PageRenderTime 244ms CodeModel.GetById 80ms app.highlight 113ms RepoModel.GetById 28ms app.codeStats 1ms

/wp-admin/includes/media.php

https://github.com/dipakdotyadav/WordPress
PHP | 2399 lines | 2340 code | 18 blank | 41 comment | 11 complexity | 56dec3757c6f2fd72482c2e9583e9f5c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * WordPress Administration Media API.
   4 *
   5 * @package WordPress
   6 * @subpackage Administration
   7 */
   8
   9/**
  10 * Defines the default media upload tabs
  11 *
  12 * @since 2.5.0
  13 *
  14 * @return array default tabs
  15 */
  16function media_upload_tabs() {
  17	$_default_tabs = array(
  18		'type' => __('From Computer'), // handler action suffix => tab text
  19		'type_url' => __('From URL'),
  20		'gallery' => __('Gallery'),
  21		'library' => __('Media Library')
  22	);
  23
  24	return apply_filters('media_upload_tabs', $_default_tabs);
  25}
  26
  27/**
  28 * Adds the gallery tab back to the tabs array if post has image attachments
  29 *
  30 * @since 2.5.0
  31 *
  32 * @param array $tabs
  33 * @return array $tabs with gallery if post has image attachment
  34 */
  35function update_gallery_tab($tabs) {
  36	global $wpdb;
  37
  38	if ( !isset($_REQUEST['post_id']) ) {
  39		unset($tabs['gallery']);
  40		return $tabs;
  41	}
  42
  43	$post_id = intval($_REQUEST['post_id']);
  44
  45	if ( $post_id )
  46		$attachments = intval( $wpdb->get_var( $wpdb->prepare( "SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent = %d", $post_id ) ) );
  47
  48	if ( empty($attachments) ) {
  49		unset($tabs['gallery']);
  50		return $tabs;
  51	}
  52
  53	$tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>$attachments</span>");
  54
  55	return $tabs;
  56}
  57add_filter('media_upload_tabs', 'update_gallery_tab');
  58
  59/**
  60 * {@internal Missing Short Description}}
  61 *
  62 * @since 2.5.0
  63 */
  64function the_media_upload_tabs() {
  65	global $redir_tab;
  66	$tabs = media_upload_tabs();
  67	$default = 'type';
  68
  69	if ( !empty($tabs) ) {
  70		echo "<ul id='sidemenu'>\n";
  71		if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) )
  72			$current = $redir_tab;
  73		elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) )
  74			$current = $_GET['tab'];
  75		else
  76			$current = apply_filters('media_upload_default_tab', $default);
  77
  78		foreach ( $tabs as $callback => $text ) {
  79			$class = '';
  80
  81			if ( $current == $callback )
  82				$class = " class='current'";
  83
  84			$href = add_query_arg(array('tab' => $callback, 's' => false, 'paged' => false, 'post_mime_type' => false, 'm' => false));
  85			$link = "<a href='" . esc_url($href) . "'$class>$text</a>";
  86			echo "\t<li id='" . esc_attr("tab-$callback") . "'>$link</li>\n";
  87		}
  88		echo "</ul>\n";
  89	}
  90}
  91
  92/**
  93 * {@internal Missing Short Description}}
  94 *
  95 * @since 2.5.0
  96 *
  97 * @param integer $id image attachment id
  98 * @param string $caption image caption
  99 * @param string $alt image alt attribute
 100 * @param string $title image title attribute
 101 * @param string $align image css alignment property
 102 * @param string $url image src url
 103 * @param string|bool $rel image rel attribute
 104 * @param string $size image size (thumbnail, medium, large, full or added  with add_image_size() )
 105 * @return string the html to insert into editor
 106 */
 107function get_image_send_to_editor($id, $caption, $title, $align, $url='', $rel = false, $size='medium', $alt = '') {
 108
 109	$html = get_image_tag($id, $alt, '', $align, $size);
 110
 111	$rel = $rel ? ' rel="attachment wp-att-' . esc_attr($id).'"' : '';
 112
 113	if ( $url )
 114		$html = '<a href="' . esc_attr($url) . "\"$rel>$html</a>";
 115
 116	$html = apply_filters( 'image_send_to_editor', $html, $id, $caption, $title, $align, $url, $size, $alt );
 117
 118	return $html;
 119}
 120
 121/**
 122 * Adds image shortcode with caption to editor
 123 *
 124 * @since 2.6.0
 125 *
 126 * @param string $html
 127 * @param integer $id
 128 * @param string $caption image caption
 129 * @param string $alt image alt attribute
 130 * @param string $title image title attribute
 131 * @param string $align image css alignment property
 132 * @param string $url image src url
 133 * @param string $size image size (thumbnail, medium, large, full or added with add_image_size() )
 134 * @return string
 135 */
 136function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
 137
 138	if ( empty($caption) || apply_filters( 'disable_captions', '' ) )
 139		return $html;
 140
 141	$id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';
 142
 143	if ( ! preg_match( '/width=["\']([0-9]+)/', $html, $matches ) )
 144		return $html;
 145
 146	$width = $matches[1];
 147
 148	$caption = str_replace( array("\r\n", "\r"), "\n", $caption);
 149	$caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption );
 150	// convert any remaining line breaks to <br>
 151	$caption = preg_replace( '/[ \n\t]*\n[ \t]*/', '<br />', $caption );
 152
 153	$html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html );
 154	if ( empty($align) )
 155		$align = 'none';
 156
 157	$shcode = '[caption id="' . $id . '" align="align' . $align	. '" width="' . $width . '"]' . $html . ' ' . $caption . '[/caption]';
 158
 159	return apply_filters( 'image_add_caption_shortcode', $shcode, $html );
 160}
 161add_filter( 'image_send_to_editor', 'image_add_caption', 20, 8 );
 162
 163/**
 164 * Private preg_replace callback used in image_add_caption()
 165 *
 166 * @access private
 167 * @since 3.4.0
 168 */
 169function _cleanup_image_add_caption( $matches ) {
 170	// remove any line breaks from inside the tags
 171	return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
 172}
 173
 174/**
 175 * Adds image html to editor
 176 *
 177 * @since 2.5.0
 178 *
 179 * @param string $html
 180 */
 181function media_send_to_editor($html) {
 182?>
 183<script type="text/javascript">
 184/* <![CDATA[ */
 185var win = window.dialogArguments || opener || parent || top;
 186win.send_to_editor('<?php echo addslashes($html); ?>');
 187/* ]]> */
 188</script>
 189<?php
 190	exit;
 191}
 192
 193/**
 194 * This handles the file upload POST itself, creating the attachment post.
 195 *
 196 * @since 2.5.0
 197 *
 198 * @param string $file_id Index into the {@link $_FILES} array of the upload
 199 * @param int $post_id The post ID the media is associated with
 200 * @param array $post_data allows you to overwrite some of the attachment
 201 * @param array $overrides allows you to override the {@link wp_handle_upload()} behavior
 202 * @return int the ID of the attachment
 203 */
 204function media_handle_upload($file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false )) {
 205
 206	$time = current_time('mysql');
 207	if ( $post = get_post($post_id) ) {
 208		if ( substr( $post->post_date, 0, 4 ) > 0 )
 209			$time = $post->post_date;
 210	}
 211
 212	$name = $_FILES[$file_id]['name'];
 213	$file = wp_handle_upload($_FILES[$file_id], $overrides, $time);
 214
 215	if ( isset($file['error']) )
 216		return new WP_Error( 'upload_error', $file['error'] );
 217
 218	$name_parts = pathinfo($name);
 219	$name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
 220
 221	$url = $file['url'];
 222	$type = $file['type'];
 223	$file = $file['file'];
 224	$title = $name;
 225	$content = '';
 226
 227	// use image exif/iptc data for title and caption defaults if possible
 228	if ( $image_meta = @wp_read_image_metadata($file) ) {
 229		if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
 230			$title = $image_meta['title'];
 231		if ( trim( $image_meta['caption'] ) )
 232			$content = $image_meta['caption'];
 233	}
 234
 235	// Construct the attachment array
 236	$attachment = array_merge( array(
 237		'post_mime_type' => $type,
 238		'guid' => $url,
 239		'post_parent' => $post_id,
 240		'post_title' => $title,
 241		'post_content' => $content,
 242	), $post_data );
 243
 244	// This should never be set as it would then overwrite an existing attachment.
 245	if ( isset( $attachment['ID'] ) )
 246		unset( $attachment['ID'] );
 247
 248	// Save the data
 249	$id = wp_insert_attachment($attachment, $file, $post_id);
 250	if ( !is_wp_error($id) ) {
 251		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
 252	}
 253
 254	return $id;
 255
 256}
 257
 258/**
 259 * This handles a sideloaded file in the same way as an uploaded file is handled by {@link media_handle_upload()}
 260 *
 261 * @since 2.6.0
 262 *
 263 * @param array $file_array Array similar to a {@link $_FILES} upload array
 264 * @param int $post_id The post ID the media is associated with
 265 * @param string $desc Description of the sideloaded file
 266 * @param array $post_data allows you to overwrite some of the attachment
 267 * @return int|object The ID of the attachment or a WP_Error on failure
 268 */
 269function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) {
 270	$overrides = array('test_form'=>false);
 271
 272	$time = current_time( 'mysql' );
 273	if ( $post = get_post( $post_id ) ) {
 274		if ( substr( $post->post_date, 0, 4 ) > 0 )
 275			$time = $post->post_date;
 276	}
 277
 278	$file = wp_handle_sideload( $file_array, $overrides, $time );
 279	if ( isset($file['error']) )
 280		return new WP_Error( 'upload_error', $file['error'] );
 281
 282	$url = $file['url'];
 283	$type = $file['type'];
 284	$file = $file['file'];
 285	$title = preg_replace('/\.[^.]+$/', '', basename($file));
 286	$content = '';
 287
 288	// use image exif/iptc data for title and caption defaults if possible
 289	if ( $image_meta = @wp_read_image_metadata($file) ) {
 290		if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
 291			$title = $image_meta['title'];
 292		if ( trim( $image_meta['caption'] ) )
 293			$content = $image_meta['caption'];
 294	}
 295
 296	if ( isset( $desc ) )
 297		$title = $desc;
 298
 299	// Construct the attachment array
 300	$attachment = array_merge( array(
 301		'post_mime_type' => $type,
 302		'guid' => $url,
 303		'post_parent' => $post_id,
 304		'post_title' => $title,
 305		'post_content' => $content,
 306	), $post_data );
 307
 308	// This should never be set as it would then overwrite an existing attachment.
 309	if ( isset( $attachment['ID'] ) )
 310		unset( $attachment['ID'] );
 311
 312	// Save the attachment metadata
 313	$id = wp_insert_attachment($attachment, $file, $post_id);
 314	if ( !is_wp_error($id) )
 315		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
 316
 317	return $id;
 318}
 319
 320/**
 321 * Adds the iframe to display content for the media upload page
 322 *
 323 * @since 2.5.0
 324 *
 325 * @param array $content_func
 326 */
 327function wp_iframe($content_func /* ... */) {
 328	_wp_admin_html_begin();
 329?>
 330<title><?php bloginfo('name') ?> &rsaquo; <?php _e('Uploads'); ?> &#8212; <?php _e('WordPress'); ?></title>
 331<?php
 332
 333wp_enqueue_style( 'colors' );
 334// Check callback name for 'media'
 335if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) )
 336	|| ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) ) )
 337	wp_enqueue_style( 'media' );
 338wp_enqueue_style( 'ie' );
 339?>
 340<script type="text/javascript">
 341//<![CDATA[
 342addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
 343var userSettings = {'url':'<?php echo SITECOOKIEPATH; ?>','uid':'<?php if ( ! isset($current_user) ) $current_user = wp_get_current_user(); echo $current_user->ID; ?>','time':'<?php echo time(); ?>'};
 344var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup',
 345isRtl = <?php echo (int) is_rtl(); ?>;
 346//]]>
 347</script>
 348<?php
 349do_action('admin_enqueue_scripts', 'media-upload-popup');
 350do_action('admin_print_styles-media-upload-popup');
 351do_action('admin_print_styles');
 352do_action('admin_print_scripts-media-upload-popup');
 353do_action('admin_print_scripts');
 354do_action('admin_head-media-upload-popup');
 355do_action('admin_head');
 356
 357if ( is_string($content_func) )
 358	do_action( "admin_head_{$content_func}" );
 359?>
 360</head>
 361<body<?php if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?> class="wp-core-ui no-js">
 362<script type="text/javascript">
 363document.body.className = document.body.className.replace('no-js', 'js');
 364</script>
 365<?php
 366	$args = func_get_args();
 367	$args = array_slice($args, 1);
 368	call_user_func_array($content_func, $args);
 369
 370	do_action('admin_print_footer_scripts');
 371?>
 372<script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
 373</body>
 374</html>
 375<?php
 376}
 377
 378/**
 379 * Adds the media button to the editor
 380 *
 381 * @since 2.5.0
 382 *
 383 * @param string $editor_id
 384 */
 385function media_buttons($editor_id = 'content') {
 386	$post = get_post();
 387	if ( ! $post && ! empty( $GLOBALS['post_ID'] ) )
 388		$post = $GLOBALS['post_ID'];
 389
 390	wp_enqueue_media( array(
 391		'post' => $post
 392	) );
 393
 394	$img = '<span class="wp-media-buttons-icon"></span> ';
 395
 396	echo '<a href="#" id="insert-media-button" class="button insert-media add_media" data-editor="' . esc_attr( $editor_id ) . '" title="' . esc_attr__( 'Add Media' ) . '">' . $img . __( 'Add Media' ) . '</a>';
 397
 398	// Don't use this filter. Want to add a button? Use the media_buttons action.
 399	$legacy_filter = apply_filters('media_buttons_context', ''); // deprecated
 400
 401	if ( $legacy_filter ) {
 402		// #WP22559. Close <a> if a plugin started by closing <a> to open their own <a> tag.
 403		if ( 0 === stripos( trim( $legacy_filter ), '</a>' ) )
 404			$legacy_filter .= '</a>';
 405		echo $legacy_filter;
 406	}
 407}
 408add_action( 'media_buttons', 'media_buttons' );
 409
 410function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) {
 411	global $post_ID;
 412
 413	if ( empty( $post_id ) )
 414		$post_id = $post_ID;
 415
 416	$upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url('media-upload.php') );
 417
 418	if ( $type && 'media' != $type )
 419		$upload_iframe_src = add_query_arg('type', $type, $upload_iframe_src);
 420
 421	if ( ! empty( $tab ) )
 422		$upload_iframe_src = add_query_arg('tab', $tab, $upload_iframe_src);
 423
 424	$upload_iframe_src = apply_filters($type . '_upload_iframe_src', $upload_iframe_src);
 425
 426	return add_query_arg('TB_iframe', true, $upload_iframe_src);
 427}
 428
 429/**
 430 * {@internal Missing Short Description}}
 431 *
 432 * @since 2.5.0
 433 *
 434 * @return mixed void|object WP_Error on failure
 435 */
 436function media_upload_form_handler() {
 437	check_admin_referer('media-form');
 438
 439	$errors = null;
 440
 441	if ( isset($_POST['send']) ) {
 442		$keys = array_keys($_POST['send']);
 443		$send_id = (int) array_shift($keys);
 444	}
 445
 446	if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
 447		$post = $_post = get_post($attachment_id, ARRAY_A);
 448		$post_type_object = get_post_type_object( $post[ 'post_type' ] );
 449
 450		if ( !current_user_can( $post_type_object->cap->edit_post, $attachment_id ) )
 451			continue;
 452
 453		if ( isset($attachment['post_content']) )
 454			$post['post_content'] = $attachment['post_content'];
 455		if ( isset($attachment['post_title']) )
 456			$post['post_title'] = $attachment['post_title'];
 457		if ( isset($attachment['post_excerpt']) )
 458			$post['post_excerpt'] = $attachment['post_excerpt'];
 459		if ( isset($attachment['menu_order']) )
 460			$post['menu_order'] = $attachment['menu_order'];
 461
 462		if ( isset($send_id) && $attachment_id == $send_id ) {
 463			if ( isset($attachment['post_parent']) )
 464				$post['post_parent'] = $attachment['post_parent'];
 465		}
 466
 467		$post = apply_filters('attachment_fields_to_save', $post, $attachment);
 468
 469		if ( isset($attachment['image_alt']) ) {
 470			$image_alt = wp_unslash( $attachment['image_alt'] );
 471			if ( $image_alt != get_post_meta($attachment_id, '_wp_attachment_image_alt', true) ) {
 472				$image_alt = wp_strip_all_tags( $image_alt, true );
 473				// update_meta expects slashed
 474				update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
 475			}
 476		}
 477
 478		if ( isset($post['errors']) ) {
 479			$errors[$attachment_id] = $post['errors'];
 480			unset($post['errors']);
 481		}
 482
 483		if ( $post != $_post )
 484			wp_update_post($post);
 485
 486		foreach ( get_attachment_taxonomies($post) as $t ) {
 487			if ( isset($attachment[$t]) )
 488				wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false);
 489		}
 490	}
 491
 492	if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?>
 493		<script type="text/javascript">
 494		/* <![CDATA[ */
 495		var win = window.dialogArguments || opener || parent || top;
 496		win.tb_remove();
 497		/* ]]> */
 498		</script>
 499		<?php
 500		exit;
 501	}
 502
 503	if ( isset($send_id) ) {
 504		$attachment = wp_unslash( $_POST['attachments'][$send_id] );
 505
 506		$html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
 507		if ( !empty($attachment['url']) ) {
 508			$rel = '';
 509			if ( strpos($attachment['url'], 'attachment_id') || get_attachment_link($send_id) == $attachment['url'] )
 510				$rel = " rel='attachment wp-att-" . esc_attr($send_id) . "'";
 511			$html = "<a href='{$attachment['url']}'$rel>$html</a>";
 512		}
 513
 514		$html = apply_filters('media_send_to_editor', $html, $send_id, $attachment);
 515		return media_send_to_editor($html);
 516	}
 517
 518	return $errors;
 519}
 520
 521/**
 522 * {@internal Missing Short Description}}
 523 *
 524 * @since 2.5.0
 525 *
 526 * @return mixed
 527 */
 528function wp_media_upload_handler() {
 529	$errors = array();
 530	$id = 0;
 531
 532	if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
 533		check_admin_referer('media-form');
 534		// Upload File button was clicked
 535		$id = media_handle_upload('async-upload', $_REQUEST['post_id']);
 536		unset($_FILES);
 537		if ( is_wp_error($id) ) {
 538			$errors['upload_error'] = $id;
 539			$id = false;
 540		}
 541	}
 542
 543	if ( !empty($_POST['insertonlybutton']) ) {
 544		$src = $_POST['src'];
 545		if ( !empty($src) && !strpos($src, '://') )
 546			$src = "http://$src";
 547
 548		if ( isset( $_POST['media_type'] ) && 'image' != $_POST['media_type'] ) {
 549			$title = esc_html( wp_unslash( $_POST['title'] ) );
 550			if ( empty( $title ) )
 551				$title = esc_html( basename( $src ) );
 552
 553			if ( $title && $src )
 554				$html = "<a href='" . esc_url($src) . "'>$title</a>";
 555
 556			$type = 'file';
 557			if ( ( $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ) ) && ( $ext_type = wp_ext2type( $ext ) )
 558				&& ( 'audio' == $ext_type || 'video' == $ext_type ) )
 559					$type = $ext_type;
 560
 561			$html = apply_filters( $type . '_send_to_editor_url', $html, esc_url_raw( $src ), $title );
 562		} else {
 563			$align = '';
 564			$alt = esc_attr( wp_unslash( $_POST['alt'] ) );
 565			if ( isset($_POST['align']) ) {
 566				$align = esc_attr( wp_unslash( $_POST['align'] ) );
 567				$class = " class='align$align'";
 568			}
 569			if ( !empty($src) )
 570				$html = "<img src='" . esc_url($src) . "' alt='$alt'$class />";
 571
 572			$html = apply_filters( 'image_send_to_editor_url', $html, esc_url_raw( $src ), $alt, $align );
 573		}
 574
 575		return media_send_to_editor($html);
 576	}
 577
 578	if ( !empty($_POST) ) {
 579		$return = media_upload_form_handler();
 580
 581		if ( is_string($return) )
 582			return $return;
 583		if ( is_array($return) )
 584			$errors = $return;
 585	}
 586
 587	if ( isset($_POST['save']) ) {
 588		$errors['upload_notice'] = __('Saved.');
 589		return media_upload_gallery();
 590	}
 591
 592	if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) {
 593		$type = 'image';
 594		if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ) ) )
 595			$type = $_GET['type'];
 596		return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id );
 597	}
 598
 599	return wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
 600}
 601
 602/**
 603 * Download an image from the specified URL and attach it to a post.
 604 *
 605 * @since 2.6.0
 606 *
 607 * @param string $file The URL of the image to download
 608 * @param int $post_id The post ID the media is to be associated with
 609 * @param string $desc Optional. Description of the image
 610 * @return string|WP_Error Populated HTML img tag on success
 611 */
 612function media_sideload_image($file, $post_id, $desc = null) {
 613	if ( ! empty($file) ) {
 614		// Download file to temp location
 615		$tmp = download_url( $file );
 616
 617		// Set variables for storage
 618		// fix file filename for query strings
 619		preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
 620		$file_array['name'] = basename($matches[0]);
 621		$file_array['tmp_name'] = $tmp;
 622
 623		// If error storing temporarily, unlink
 624		if ( is_wp_error( $tmp ) ) {
 625			@unlink($file_array['tmp_name']);
 626			$file_array['tmp_name'] = '';
 627		}
 628
 629		// do the validation and storage stuff
 630		$id = media_handle_sideload( $file_array, $post_id, $desc );
 631		// If error storing permanently, unlink
 632		if ( is_wp_error($id) ) {
 633			@unlink($file_array['tmp_name']);
 634			return $id;
 635		}
 636
 637		$src = wp_get_attachment_url( $id );
 638	}
 639
 640	// Finally check to make sure the file has been saved, then return the html
 641	if ( ! empty($src) ) {
 642		$alt = isset($desc) ? esc_attr($desc) : '';
 643		$html = "<img src='$src' alt='$alt' />";
 644		return $html;
 645	}
 646}
 647
 648/**
 649 * {@internal Missing Short Description}}
 650 *
 651 * @since 2.5.0
 652 *
 653 * @return unknown
 654 */
 655function media_upload_gallery() {
 656	$errors = array();
 657
 658	if ( !empty($_POST) ) {
 659		$return = media_upload_form_handler();
 660
 661		if ( is_string($return) )
 662			return $return;
 663		if ( is_array($return) )
 664			$errors = $return;
 665	}
 666
 667	wp_enqueue_script('admin-gallery');
 668	return wp_iframe( 'media_upload_gallery_form', $errors );
 669}
 670
 671/**
 672 * {@internal Missing Short Description}}
 673 *
 674 * @since 2.5.0
 675 *
 676 * @return unknown
 677 */
 678function media_upload_library() {
 679	$errors = array();
 680	if ( !empty($_POST) ) {
 681		$return = media_upload_form_handler();
 682
 683		if ( is_string($return) )
 684			return $return;
 685		if ( is_array($return) )
 686			$errors = $return;
 687	}
 688
 689	return wp_iframe( 'media_upload_library_form', $errors );
 690}
 691
 692/**
 693 * Retrieve HTML for the image alignment radio buttons with the specified one checked.
 694 *
 695 * @since 2.7.0
 696 *
 697 * @param object $post
 698 * @param string $checked
 699 * @return string
 700 */
 701function image_align_input_fields( $post, $checked = '' ) {
 702
 703	if ( empty($checked) )
 704		$checked = get_user_setting('align', 'none');
 705
 706	$alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right'));
 707	if ( !array_key_exists( (string) $checked, $alignments ) )
 708		$checked = 'none';
 709
 710	$out = array();
 711	foreach ( $alignments as $name => $label ) {
 712		$name = esc_attr($name);
 713		$out[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'".
 714		 	( $checked == $name ? " checked='checked'" : "" ) .
 715			" /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
 716	}
 717	return join("\n", $out);
 718}
 719
 720/**
 721 * Retrieve HTML for the size radio buttons with the specified one checked.
 722 *
 723 * @since 2.7.0
 724 *
 725 * @param object $post
 726 * @param bool|string $check
 727 * @return array
 728 */
 729function image_size_input_fields( $post, $check = '' ) {
 730
 731		// get a list of the actual pixel dimensions of each possible intermediate version of this image
 732		$size_names = apply_filters( 'image_size_names_choose', array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size')) );
 733
 734		if ( empty($check) )
 735			$check = get_user_setting('imgsize', 'medium');
 736
 737		foreach ( $size_names as $size => $label ) {
 738			$downsize = image_downsize($post->ID, $size);
 739			$checked = '';
 740
 741			// is this size selectable?
 742			$enabled = ( $downsize[3] || 'full' == $size );
 743			$css_id = "image-size-{$size}-{$post->ID}";
 744			// if this size is the default but that's not available, don't select it
 745			if ( $size == $check ) {
 746				if ( $enabled )
 747					$checked = " checked='checked'";
 748				else
 749					$check = '';
 750			} elseif ( !$check && $enabled && 'thumbnail' != $size ) {
 751				// if $check is not enabled, default to the first available size that's bigger than a thumbnail
 752				$check = $size;
 753				$checked = " checked='checked'";
 754			}
 755
 756			$html = "<div class='image-size-item'><input type='radio' " . disabled( $enabled, false, false ) . "name='attachments[$post->ID][image-size]' id='{$css_id}' value='{$size}'$checked />";
 757
 758			$html .= "<label for='{$css_id}'>$label</label>";
 759			// only show the dimensions if that choice is available
 760			if ( $enabled )
 761				$html .= " <label for='{$css_id}' class='help'>" . sprintf( "(%d&nbsp;&times;&nbsp;%d)", $downsize[1], $downsize[2] ). "</label>";
 762
 763			$html .= '</div>';
 764
 765			$out[] = $html;
 766		}
 767
 768		return array(
 769			'label' => __('Size'),
 770			'input' => 'html',
 771			'html'  => join("\n", $out),
 772		);
 773}
 774
 775/**
 776 * Retrieve HTML for the Link URL buttons with the default link type as specified.
 777 *
 778 * @since 2.7.0
 779 *
 780 * @param object $post
 781 * @param string $url_type
 782 * @return string
 783 */
 784function image_link_input_fields($post, $url_type = '') {
 785
 786	$file = wp_get_attachment_url($post->ID);
 787	$link = get_attachment_link($post->ID);
 788
 789	if ( empty($url_type) )
 790		$url_type = get_user_setting('urlbutton', 'post');
 791
 792	$url = '';
 793	if ( $url_type == 'file' )
 794		$url = $file;
 795	elseif ( $url_type == 'post' )
 796		$url = $link;
 797
 798	return "
 799	<input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr($url) . "' /><br />
 800	<button type='button' class='button urlnone' data-link-url=''>" . __('None') . "</button>
 801	<button type='button' class='button urlfile' data-link-url='" . esc_attr($file) . "'>" . __('File URL') . "</button>
 802	<button type='button' class='button urlpost' data-link-url='" . esc_attr($link) . "'>" . __('Attachment Post URL') . "</button>
 803";
 804}
 805
 806function wp_caption_input_textarea($edit_post) {
 807	// post data is already escaped
 808	$name = "attachments[{$edit_post->ID}][post_excerpt]";
 809
 810	return '<textarea name="' . $name . '" id="' . $name . '">' . $edit_post->post_excerpt . '</textarea>';
 811}
 812
 813/**
 814 * {@internal Missing Short Description}}
 815 *
 816 * @since 2.5.0
 817 *
 818 * @param array $form_fields
 819 * @param object $post
 820 * @return array
 821 */
 822function image_attachment_fields_to_edit($form_fields, $post) {
 823	return $form_fields;
 824}
 825
 826/**
 827 * {@internal Missing Short Description}}
 828 *
 829 * @since 2.5.0
 830 *
 831 * @param array $form_fields
 832 * @param object $post {@internal $post not used}}
 833 * @return array
 834 */
 835function media_single_attachment_fields_to_edit( $form_fields, $post ) {
 836	unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']);
 837	return $form_fields;
 838}
 839
 840/**
 841 * {@internal Missing Short Description}}
 842 *
 843 * @since 2.8.0
 844 *
 845 * @param array $form_fields
 846 * @param object $post {@internal $post not used}}
 847 * @return array
 848 */
 849function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
 850	unset($form_fields['image_url']);
 851	return $form_fields;
 852}
 853
 854/**
 855 * Filters input from media_upload_form_handler() and assigns a default
 856 * post_title from the file name if none supplied.
 857 *
 858 * Illustrates the use of the attachment_fields_to_save filter
 859 * which can be used to add default values to any field before saving to DB.
 860 *
 861 * @since 2.5.0
 862 *
 863 * @param object $post
 864 * @param array $attachment {@internal $attachment not used}}
 865 * @return array
 866 */
 867function image_attachment_fields_to_save($post, $attachment) {
 868	if ( substr($post['post_mime_type'], 0, 5) == 'image' ) {
 869		if ( strlen(trim($post['post_title'])) == 0 ) {
 870			$post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid']));
 871			$post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.');
 872		}
 873	}
 874
 875	return $post;
 876}
 877
 878add_filter('attachment_fields_to_save', 'image_attachment_fields_to_save', 10, 2);
 879
 880/**
 881 * {@internal Missing Short Description}}
 882 *
 883 * @since 2.5.0
 884 *
 885 * @param string $html
 886 * @param integer $attachment_id
 887 * @param array $attachment
 888 * @return array
 889 */
 890function image_media_send_to_editor($html, $attachment_id, $attachment) {
 891	$post = get_post($attachment_id);
 892	if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
 893		$url = $attachment['url'];
 894		$align = !empty($attachment['align']) ? $attachment['align'] : 'none';
 895		$size = !empty($attachment['image-size']) ? $attachment['image-size'] : 'medium';
 896		$alt = !empty($attachment['image_alt']) ? $attachment['image_alt'] : '';
 897		$rel = ( $url == get_attachment_link($attachment_id) );
 898
 899		return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt);
 900	}
 901
 902	return $html;
 903}
 904
 905add_filter('media_send_to_editor', 'image_media_send_to_editor', 10, 3);
 906
 907/**
 908 * {@internal Missing Short Description}}
 909 *
 910 * @since 2.5.0
 911 *
 912 * @param object $post
 913 * @param array $errors
 914 * @return array
 915 */
 916function get_attachment_fields_to_edit($post, $errors = null) {
 917	if ( is_int($post) )
 918		$post = get_post($post);
 919	if ( is_array($post) )
 920		$post = new WP_Post( (object) $post );
 921
 922	$image_url = wp_get_attachment_url($post->ID);
 923
 924	$edit_post = sanitize_post($post, 'edit');
 925
 926	$form_fields = array(
 927		'post_title'   => array(
 928			'label'      => __('Title'),
 929			'value'      => $edit_post->post_title
 930		),
 931		'image_alt'   => array(),
 932		'post_excerpt' => array(
 933			'label'      => __('Caption'),
 934			'input'      => 'html',
 935			'html'       => wp_caption_input_textarea($edit_post)
 936		),
 937		'post_content' => array(
 938			'label'      => __('Description'),
 939			'value'      => $edit_post->post_content,
 940			'input'      => 'textarea'
 941		),
 942		'url'          => array(
 943			'label'      => __('Link URL'),
 944			'input'      => 'html',
 945			'html'       => image_link_input_fields($post, get_option('image_default_link_type')),
 946			'helps'      => __('Enter a link URL or click above for presets.')
 947		),
 948		'menu_order'   => array(
 949			'label'      => __('Order'),
 950			'value'      => $edit_post->menu_order
 951		),
 952		'image_url'	=> array(
 953			'label'      => __('File URL'),
 954			'input'      => 'html',
 955			'html'       => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr($image_url) . "' /><br />",
 956			'value'      => wp_get_attachment_url($post->ID),
 957			'helps'      => __('Location of the uploaded file.')
 958		)
 959	);
 960
 961	foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
 962		$t = (array) get_taxonomy($taxonomy);
 963		if ( ! $t['public'] || ! $t['show_ui'] )
 964			continue;
 965		if ( empty($t['label']) )
 966			$t['label'] = $taxonomy;
 967		if ( empty($t['args']) )
 968			$t['args'] = array();
 969
 970		$terms = get_object_term_cache($post->ID, $taxonomy);
 971		if ( false === $terms )
 972			$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
 973
 974		$values = array();
 975
 976		foreach ( $terms as $term )
 977			$values[] = $term->slug;
 978		$t['value'] = join(', ', $values);
 979
 980		$form_fields[$taxonomy] = $t;
 981	}
 982
 983	// Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
 984	// The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
 985	$form_fields = array_merge_recursive($form_fields, (array) $errors);
 986
 987	// This was formerly in image_attachment_fields_to_edit().
 988	if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
 989		$alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true);
 990		if ( empty($alt) )
 991			$alt = '';
 992
 993		$form_fields['post_title']['required'] = true;
 994
 995		$form_fields['image_alt'] = array(
 996			'value' => $alt,
 997			'label' => __('Alternative Text'),
 998			'helps' => __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;')
 999		);
1000
1001		$form_fields['align'] = array(
1002			'label' => __('Alignment'),
1003			'input' => 'html',
1004			'html'  => image_align_input_fields($post, get_option('image_default_align')),
1005		);
1006
1007		$form_fields['image-size'] = image_size_input_fields( $post, get_option('image_default_size', 'medium') );
1008
1009	} else {
1010		unset( $form_fields['image_alt'] );
1011	}
1012
1013	$form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post);
1014
1015	return $form_fields;
1016}
1017
1018/**
1019 * Retrieve HTML for media items of post gallery.
1020 *
1021 * The HTML markup retrieved will be created for the progress of SWF Upload
1022 * component. Will also create link for showing and hiding the form to modify
1023 * the image attachment.
1024 *
1025 * @since 2.5.0
1026 *
1027 * @param int $post_id Optional. Post ID.
1028 * @param array $errors Errors for attachment, if any.
1029 * @return string
1030 */
1031function get_media_items( $post_id, $errors ) {
1032	$attachments = array();
1033	if ( $post_id ) {
1034		$post = get_post($post_id);
1035		if ( $post && $post->post_type == 'attachment' )
1036			$attachments = array($post->ID => $post);
1037		else
1038			$attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') );
1039	} else {
1040		if ( is_array($GLOBALS['wp_the_query']->posts) )
1041			foreach ( $GLOBALS['wp_the_query']->posts as $attachment )
1042				$attachments[$attachment->ID] = $attachment;
1043	}
1044
1045	$output = '';
1046	foreach ( (array) $attachments as $id => $attachment ) {
1047		if ( $attachment->post_status == 'trash' )
1048			continue;
1049		if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) )
1050			$output .= "\n<div id='media-item-$id' class='media-item child-of-$attachment->post_parent preloaded'><div class='progress hidden'><div class='bar'></div></div><div id='media-upload-error-$id' class='hidden'></div><div class='filename hidden'></div>$item\n</div>";
1051	}
1052
1053	return $output;
1054}
1055
1056/**
1057 * Retrieve HTML form for modifying the image attachment.
1058 *
1059 * @since 2.5.0
1060 *
1061 * @param int $attachment_id Attachment ID for modification.
1062 * @param string|array $args Optional. Override defaults.
1063 * @return string HTML form for attachment.
1064 */
1065function get_media_item( $attachment_id, $args = null ) {
1066	global $redir_tab;
1067
1068	if ( ( $attachment_id = intval( $attachment_id ) ) && $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true ) )
1069		$thumb_url = $thumb_url[0];
1070	else
1071		$thumb_url = false;
1072
1073	$post = get_post( $attachment_id );
1074	$current_post_id = !empty( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0;
1075
1076	$default_args = array( 'errors' => null, 'send' => $current_post_id ? post_type_supports( get_post_type( $current_post_id ), 'editor' ) : true, 'delete' => true, 'toggle' => true, 'show_title' => true );
1077	$args = wp_parse_args( $args, $default_args );
1078	$args = apply_filters( 'get_media_item_args', $args );
1079	extract( $args, EXTR_SKIP );
1080
1081	$toggle_on  = __( 'Show' );
1082	$toggle_off = __( 'Hide' );
1083
1084	$filename = esc_html( wp_basename( $post->guid ) );
1085	$title = esc_attr( $post->post_title );
1086
1087	if ( $_tags = get_the_tags( $attachment_id ) ) {
1088		foreach ( $_tags as $tag )
1089			$tags[] = $tag->name;
1090		$tags = esc_attr( join( ', ', $tags ) );
1091	}
1092
1093	$post_mime_types = get_post_mime_types();
1094	$keys = array_keys( wp_match_mime_types( array_keys( $post_mime_types ), $post->post_mime_type ) );
1095	$type = array_shift( $keys );
1096	$type_html = "<input type='hidden' id='type-of-$attachment_id' value='" . esc_attr( $type ) . "' />";
1097
1098	$form_fields = get_attachment_fields_to_edit( $post, $errors );
1099
1100	if ( $toggle ) {
1101		$class = empty( $errors ) ? 'startclosed' : 'startopen';
1102		$toggle_links = "
1103	<a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
1104	<a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
1105	} else {
1106		$class = '';
1107		$toggle_links = '';
1108	}
1109
1110	$display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case
1111	$display_title = $show_title ? "<div class='filename new'><span class='title'>" . wp_html_excerpt( $display_title, 60 ) . "</span></div>" : '';
1112
1113	$gallery = ( ( isset( $_REQUEST['tab'] ) && 'gallery' == $_REQUEST['tab'] ) || ( isset( $redir_tab ) && 'gallery' == $redir_tab ) );
1114	$order = '';
1115
1116	foreach ( $form_fields as $key => $val ) {
1117		if ( 'menu_order' == $key ) {
1118			if ( $gallery )
1119				$order = "<div class='menu_order'> <input class='menu_order_input' type='text' id='attachments[$attachment_id][menu_order]' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ). "' /></div>";
1120			else
1121				$order = "<input type='hidden' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ) . "' />";
1122
1123			unset( $form_fields['menu_order'] );
1124			break;
1125		}
1126	}
1127
1128	$media_dims = '';
1129	$meta = wp_get_attachment_metadata( $post->ID );
1130	if ( is_array( $meta ) && array_key_exists( 'width', $meta ) && array_key_exists( 'height', $meta ) )
1131		$media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
1132	$media_dims = apply_filters( 'media_meta', $media_dims, $post );
1133
1134	$image_edit_button = '';
1135	if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
1136		$nonce = wp_create_nonce( "image_editor-$post->ID" );
1137		$image_edit_button = "<input type='button' id='imgedit-open-btn-$post->ID' onclick='imageEdit.open( $post->ID, \"$nonce\" )' class='button' value='" . esc_attr__( 'Edit Image' ) . "' /> <span class='spinner'></span>";
1138	}
1139
1140	$attachment_url = get_permalink( $attachment_id );
1141
1142	$item = "
1143	$type_html
1144	$toggle_links
1145	$order
1146	$display_title
1147	<table class='slidetoggle describe $class'>
1148		<thead class='media-item-info' id='media-head-$post->ID'>
1149		<tr valign='top'>
1150			<td class='A1B1' id='thumbnail-head-$post->ID'>
1151			<p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p>
1152			<p>$image_edit_button</p>
1153			</td>
1154			<td>
1155			<p><strong>" . __('File name:') . "</strong> $filename</p>
1156			<p><strong>" . __('File type:') . "</strong> $post->post_mime_type</p>
1157			<p><strong>" . __('Upload date:') . "</strong> " . mysql2date( get_option('date_format'), $post->post_date ). '</p>';
1158			if ( !empty( $media_dims ) )
1159				$item .= "<p><strong>" . __('Dimensions:') . "</strong> $media_dims</p>\n";
1160
1161			$item .= "</td></tr>\n";
1162
1163	$item .= "
1164		</thead>
1165		<tbody>
1166		<tr><td colspan='2' class='imgedit-response' id='imgedit-response-$post->ID'></td></tr>
1167		<tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-$post->ID'></td></tr>\n";
1168
1169	$defaults = array(
1170		'input'      => 'text',
1171		'required'   => false,
1172		'value'      => '',
1173		'extra_rows' => array(),
1174	);
1175
1176	if ( $send )
1177		$send = get_submit_button( __( 'Insert into Post' ), 'button', "send[$attachment_id]", false );
1178	if ( $delete && current_user_can( 'delete_post', $attachment_id ) ) {
1179		if ( !EMPTY_TRASH_DAYS ) {
1180			$delete = "<a href='" . wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete-permanently'>" . __( 'Delete Permanently' ) . '</a>';
1181		} elseif ( !MEDIA_TRASH ) {
1182			$delete = "<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __( 'Delete' ) . "</a>
1183			 <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'><p>" . sprintf( __( 'You are about to delete <strong>%s</strong>.' ), $filename ) . "</p>
1184			 <a href='" . wp_nonce_url( "post.php?action=delete&amp;post=$attachment_id", 'delete-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='button'>" . __( 'Continue' ) . "</a>
1185			 <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">" . __( 'Cancel' ) . "</a>
1186			 </div>";
1187		} else {
1188			$delete = "<a href='" . wp_nonce_url( "post.php?action=trash&amp;post=$attachment_id", 'trash-post_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete'>" . __( 'Move to Trash' ) . "</a>
1189			<a href='" . wp_nonce_url( "post.php?action=untrash&amp;post=$attachment_id", 'untrash-post_' . $attachment_id ) . "' id='undo[$attachment_id]' class='undo hidden'>" . __( 'Undo' ) . "</a>";
1190		}
1191	} else {
1192		$delete = '';
1193	}
1194
1195	$thumbnail = '';
1196	$calling_post_id = 0;
1197	if ( isset( $_GET['post_id'] ) )
1198		$calling_post_id = absint( $_GET['post_id'] );
1199	elseif ( isset( $_POST ) && count( $_POST ) ) // Like for async-upload where $_GET['post_id'] isn't set
1200		$calling_post_id = $post->post_parent;
1201	if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) )
1202		&& post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) {
1203		$ajax_nonce = wp_create_nonce( "set_post_thumbnail-$calling_post_id" );
1204		$thumbnail = "<a class='wp-post-thumbnail' id='wp-post-thumbnail-" . $attachment_id . "' href='#' onclick='WPSetAsThumbnail(\"$attachment_id\", \"$ajax_nonce\");return false;'>" . esc_html__( "Use as featured image" ) . "</a>";
1205	}
1206
1207	if ( ( $send || $thumbnail || $delete ) && !isset( $form_fields['buttons'] ) )
1208		$form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send $thumbnail $delete</td></tr>\n" );
1209
1210	$hidden_fields = array();
1211
1212	foreach ( $form_fields as $id => $field ) {
1213		if ( $id[0] == '_' )
1214			continue;
1215
1216		if ( !empty( $field['tr'] ) ) {
1217			$item .= $field['tr'];
1218			continue;
1219		}
1220
1221		$field = array_merge( $defaults, $field );
1222		$name = "attachments[$attachment_id][$id]";
1223
1224		if ( $field['input'] == 'hidden' ) {
1225			$hidden_fields[$name] = $field['value'];
1226			continue;
1227		}
1228
1229		$required      = $field['required'] ? '<span class="alignright"><abbr title="required" class="required">*</abbr></span>' : '';
1230		$aria_required = $field['required'] ? " aria-required='true' " : '';
1231		$class  = $id;
1232		$class .= $field['required'] ? ' form-required' : '';
1233
1234		$item .= "\t\t<tr class='$class'>\n\t\t\t<th valign='top' scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label></th>\n\t\t\t<td class='field'>";
1235		if ( !empty( $field[ $field['input'] ] ) )
1236			$item .= $field[ $field['input'] ];
1237		elseif ( $field['input'] == 'textarea' ) {
1238			if ( 'post_content' == $id && user_can_richedit() ) {
1239				// sanitize_post() skips the post_content when user_can_richedit
1240				$field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1241			}
1242			// post_excerpt is already escaped by sanitize_post() in get_attachment_fields_to_edit()
1243			$item .= "<textarea id='$name' name='$name' $aria_required>" . $field['value'] . '</textarea>';
1244		} else {
1245			$item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "' $aria_required />";
1246		}
1247		if ( !empty( $field['helps'] ) )
1248			$item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1249		$item .= "</td>\n\t\t</tr>\n";
1250
1251		$extra_rows = array();
1252
1253		if ( !empty( $field['errors'] ) )
1254			foreach ( array_unique( (array) $field['errors'] ) as $error )
1255				$extra_rows['error'][] = $error;
1256
1257		if ( !empty( $field['extra_rows'] ) )
1258			foreach ( $field['extra_rows'] as $class => $rows )
1259				foreach ( (array) $rows as $html )
1260					$extra_rows[$class][] = $html;
1261
1262		foreach ( $extra_rows as $class => $rows )
1263			foreach ( $rows as $html )
1264				$item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1265	}
1266
1267	if ( !empty( $form_fields['_final'] ) )
1268		$item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1269	$item .= "\t</tbody>\n";
1270	$item .= "\t</table>\n";
1271
1272	foreach ( $hidden_fields as $name => $value )
1273		$item .= "\t<input type='hidden' name='$name' id='$name' value='" . esc_attr( $value ) . "' />\n";
1274
1275	if ( $post->post_parent < 1 && isset( $_REQUEST['post_id'] ) ) {
1276		$parent = (int) $_REQUEST['post_id'];
1277		$parent_name = "attachments[$attachment_id][post_parent]";
1278		$item .= "\t<input type='hidden' name='$parent_name' id='$parent_name' value='$parent' />\n";
1279	}
1280
1281	return $item;
1282}
1283
1284function get_compat_media_markup( $attachment_id, $args = null ) {
1285	$post = get_post( $attachment_id );
1286
1287	$default_args = array(
1288		'errors' => null,
1289		'in_modal' => false,
1290	);
1291
1292	$user_can_edit = current_user_can( 'edit_post', $attachment_id );
1293
1294	$args = wp_parse_args( $args, $default_args );
1295	$args = apply_filters( 'get_media_item_args', $args );
1296
1297	$form_fields = array();
1298
1299	if ( $args['in_modal'] ) {
1300		foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
1301			$t = (array) get_taxonomy($taxonomy);
1302			if ( ! $t['public'] || ! $t['show_ui'] )
1303				continue;
1304			if ( empty($t['label']) )
1305				$t['label'] = $taxonomy;
1306			if ( empty($t['args']) )
1307				$t['args'] = array();
1308
1309			$terms = get_object_term_cache($post->ID, $taxonomy);
1310			if ( false === $terms )
1311				$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
1312
1313			$values = array();
1314
1315			foreach ( $terms as $term )
1316				$values[] = $term->slug;
1317			$t['value'] = join(', ', $values);
1318			$t['taxonomy'] = true;
1319
1320			$form_fields[$taxonomy] = $t;
1321		}
1322	}
1323
1324	// Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
1325	// The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
1326	$form_fields = array_merge_recursive($form_fields, (array) $args['errors'] );
1327
1328	$form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1329
1330	unset( $form_fields['image-size'], $form_fields['align'], $form_fields['image_alt'],
1331		$form_fields['post_title'], $form_fields['post_excerpt'], $form_fields['post_content'],
1332		$form_fields['url'], $form_fields['menu_order'], $form_fields['image_url'] );
1333
1334	$media_meta = apply_filters( 'media_meta', '', $post );
1335
1336	$defaults = array(
1337		'input'         => 'text',
1338 		'required'      => false,
1339 		'value'         => '',
1340 		'extra_rows'    => array(),
1341 		'show_in_edit'  => true,
1342 		'show_in_modal' => true,
1343	);
1344
1345	$hidden_fields = array();
1346
1347	$item = '';
1348	foreach ( $form_fields as $id => $field ) {
1349		if ( $id[0] == '_' )
1350			continue;
1351
1352		$name = "attachments[$attachment_id][$id]";
1353		$id_attr = "attachments-$attachment_id-$id";
1354
1355		if ( !empty( $field['tr'] ) ) {
1356			$item .= $field['tr'];
1357			continue;
1358		}
1359
1360		$field = array_merge( $defaults, $field );
1361
1362		if ( ( ! $field['show_in_edit'] && ! $args['in_modal'] ) || ( ! $field['show_in_modal'] && $args['in_modal'] ) )
1363			continue;
1364
1365		if ( $field['input'] == 'hidden' ) {
1366			$hidden_fields[$name] = $field['value'];
1367			continue;
1368		}
1369
1370		$readonly      = ! $user_can_edit && ! empty( $field['taxonomy'] ) ? " readonly='readonly' " : '';
1371		$required      = $field['required'] ? '<span class="alignright"><abbr title="required" class="required">*</abbr></span>' : '';
1372		$aria_required = $field['required'] ? " aria-required='true' " : '';
1373		$class  = 'compat-field-' . $id;
1374		$class .= $field['required'] ? ' form-required' : '';
1375
1376		$item .= "\t\t<tr class='$class'>";
1377		$item .= "\t\t\t<th valign='top' scope='row' class='label'><label for='$id_attr'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label>";
1378		$item .= "</th>\n\t\t\t<td class='field'>";
1379
1380		if ( !empty( $field[ $field['input'] ] ) )
1381			$item .= $field[ $field['input'] ];
1382		elseif ( $field['input'] == 'textarea' ) {
1383			if ( 'post_content' == $id && user_can_richedit() ) {
1384				// sanitize_post() skips the post_content when user_can_richedit
1385				$field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1386			}
1387			$item .= "<textarea id='$id_attr' name='$name' $aria_required>" . $field['value'] . '</textarea>';
1388		} else {
1389			$item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly $aria_required />";
1390		}
1391		if ( !empty( $field['helps'] ) )
1392			$item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1393		$item .= "</td>\n\t\t</tr>\n";
1394
1395		$extra_rows = array();
1396
1397		if ( !empty( $field['errors'] ) )
1398			foreach ( array_unique( (array) $field['errors'] ) as $error )
1399				$extra_rows['error'][] = $error;
1400
1401		if ( !empty( $field['extra_rows'] ) )
1402			foreach ( $field['extra_rows'] as $class => $rows )
1403				foreach ( (array) $rows as $html )
1404					$extra_rows[$class][] = $html;
1405
1406		foreach ( $extra_rows as $class => $rows )
1407			foreach ( $rows as $html )
1408				$item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1409	}
1410
1411	if ( !empty( $form_fields['_final'] ) )
1412		$item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1413	if ( $item )
1414		$item = '<table class="compat-attachment-fields">' . $item . '</table>';
1415
1416	foreach ( $hidden_fields as $hidden_field => $value ) {
1417		$item .= '<input type="hidden" name="' . esc_attr( $hidden_field ) . '" value="' . esc_attr( $value ) . '" />' . "\n";
1418	}
1419
1420	if ( $item )
1421		$item = '<input type="hidden" name="attachments[' . $attachment_id . '][menu_order]" value="' . esc_attr( $post->menu_order ) . '" />' . $item;
1422
1423	return array(
1424		'item'   => $item,
1425		'meta'   => $media_meta,
1426	);
1427}
1428
1429/**
1430 * {@internal Missing Short Description}}
1431 *
1432 * @since 2.5.0
1433 */
1434function media_upload_header() {
1435	$post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
1436	echo '<script type="text/javascript">post_id = ' . $post_id . ";</script>\n";
1437	if ( empty( $_GET['chromeless'] ) ) {
1438		echo '<div id="media-upload-header">';
1439		the_media_upload_tabs();
1440		echo '</div>';
1441	}
1442}
1443
1444/**
1445 * {@internal Missing Short Description}}
1446 *
1447 * @since 2.5.0
1448 *
1449 * @param unknown_type $errors
1450 */
1451function media_upload_form( $errors = null ) {
1452	global $type, $tab, $pagenow, $is_IE, $is_opera;
1453
1454	if ( ! _device_can_upload() ) {
1455		echo '<p>' . __('The web browser on your device cannot be used to upload files. You may be able to use the <a href="http://wordpress.org/extend/mobile/">native app for your device</a> instead.') . '</p>';
1456		return;
1457	}
1458
1459	$upload_action_url = admin_url('async-upload.php');
1460	$post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
1461	$_type = isset($type) ? $type : '';
1462	$_tab = isset($tab) ? $tab : '';
1463
1464	$upload_size_unit = $max_upload_size = wp_max_upload_size();
1465	$sizes = array( 'KB', 'MB', 'GB' );
1466
1467	for ( $u = -1; $upload_size_unit > 1024 && $u < count( $sizes ) - 1; $u++ ) {
1468		$upload_size_unit /= 1024;
1469	}
1470
1471	if ( $u < 0 ) {
1472		$upload_size_unit = 0;
1473		$u = 0;
1474	} else {
1475		$upload_size_unit = (int) $upload_size_unit;
1476	}
1477?>
1478
1479<div id="media-upload-notice"><?php
1480
1481	if (isset($errors['upload_notice']) )
1482		echo $errors['upload_notice'];
1483
1484?></div>
1485<div id="media-upload-error"><?php
1486
1487	if (isset($errors['upload_error']) && is_wp_error($errors['upload_error']))
1488		echo $errors['upload_error']->get_error_message();
1489
1490?></div>
1491<?php
1492if ( is_multisite() && !is_upload_space_available() ) {
1493	do_action( 'upload_ui_over_quota' );
1494	return;
1495}
1496
1497do_action('pre-upload-ui');
1498
1499$post_params = array(
1500		"post_id" => $post_id,
1501		"_wpnonce" => wp_create_nonce('media-form'),
1502		"type" => $_type,
1503		"tab" => $_tab,
1504		"short" => "1",
1505);
1506
1507$post_params = apply_filters( 'upload_post_params', $post_params ); // hook change! old name: 'swfupload_post_params'
1508
1509$plupload_init = array(
1510	'runtimes' => 'html5,silverlight,flash,html4',
1511	'browse_button' => 'plupload-browse-button',
1512	'container' => 'plupload-upload-ui',
1513	'drop_element' => 'drag-drop-area',
1514	'file_data_name' => 'async-upload',
1515	'multiple_queues' => true,
1516	'max_file_size' => $max_upload_size . 'b',
1517	'url' => $upload_action_url,
1518	'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
1519	'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
1520	'filters' => array( array('title' => __( 'Allowed Files' ), 'extensions' => '*') ),
1521	'multipart' => true,
1522	'urlstream_upload' => true,
1523	'multipart_params' => $post_params
1524);
1525
1526// Multi-file …

Large files files are truncated, but you can click here to view the full file