PageRenderTime 327ms CodeModel.GetById 101ms app.highlight 133ms RepoModel.GetById 38ms app.codeStats 1ms

/APP/wp-admin/includes/media.php

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

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