]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/media.php
c6b2dcd1ba4fb25271de5e637dcc9ce793268eb2
[autoinstalls/wordpress.git] / wp-admin / includes / media.php
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  */
16 function 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          * Filters 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  * @global wpdb $wpdb WordPress database abstraction object.
40  *
41  * @param array $tabs
42  * @return array $tabs with gallery if post has image attachment
43  */
44 function update_gallery_tab($tabs) {
45         global $wpdb;
46
47         if ( !isset($_REQUEST['post_id']) ) {
48                 unset($tabs['gallery']);
49                 return $tabs;
50         }
51
52         $post_id = intval($_REQUEST['post_id']);
53
54         if ( $post_id )
55                 $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 ) ) );
56
57         if ( empty($attachments) ) {
58                 unset($tabs['gallery']);
59                 return $tabs;
60         }
61
62         $tabs['gallery'] = sprintf(__('Gallery (%s)'), "<span id='attachments-count'>$attachments</span>");
63
64         return $tabs;
65 }
66
67 /**
68  * Outputs the legacy media upload tabs UI.
69  *
70  * @since 2.5.0
71  *
72  * @global string $redir_tab
73  */
74 function the_media_upload_tabs() {
75         global $redir_tab;
76         $tabs = media_upload_tabs();
77         $default = 'type';
78
79         if ( !empty($tabs) ) {
80                 echo "<ul id='sidemenu'>\n";
81                 if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) ) {
82                         $current = $redir_tab;
83                 } elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) ) {
84                         $current = $_GET['tab'];
85                 } else {
86                         /** This filter is documented in wp-admin/media-upload.php */
87                         $current = apply_filters( 'media_upload_default_tab', $default );
88                 }
89
90                 foreach ( $tabs as $callback => $text ) {
91                         $class = '';
92
93                         if ( $current == $callback )
94                                 $class = " class='current'";
95
96                         $href = add_query_arg(array('tab' => $callback, 's' => false, 'paged' => false, 'post_mime_type' => false, 'm' => false));
97                         $link = "<a href='" . esc_url($href) . "'$class>$text</a>";
98                         echo "\t<li id='" . esc_attr("tab-$callback") . "'>$link</li>\n";
99                 }
100                 echo "</ul>\n";
101         }
102 }
103
104 /**
105  * Retrieves the image HTML to send to the editor.
106  *
107  * @since 2.5.0
108  *
109  * @param int          $id      Image attachment id.
110  * @param string       $caption Image caption.
111  * @param string       $title   Image title attribute.
112  * @param string       $align   Image CSS alignment property.
113  * @param string       $url     Optional. Image src URL. Default empty.
114  * @param bool|string  $rel     Optional. Value for rel attribute or whether to add a default value. Default false.
115  * @param string|array $size    Optional. Image size. Accepts any valid image size, or an array of width
116  *                              and height values in pixels (in that order). Default 'medium'.
117  * @param string       $alt     Optional. Image alt attribute. Default empty.
118  * @return string The HTML output to insert into the editor.
119  */
120 function get_image_send_to_editor( $id, $caption, $title, $align, $url = '', $rel = false, $size = 'medium', $alt = '' ) {
121
122         $html = get_image_tag( $id, $alt, '', $align, $size );
123
124         if ( $rel ) {
125                 if ( is_string( $rel ) ) {
126                         $rel = ' rel="' . esc_attr( $rel ) . '"';
127                 } else {
128                         $rel = ' rel="attachment wp-att-' . intval( $id ) . '"';
129                 }
130         } else {
131                 $rel = '';
132         }
133
134         if ( $url )
135                 $html = '<a href="' . esc_attr( $url ) . '"' . $rel . '>' . $html . '</a>';
136
137         /**
138          * Filters the image HTML markup to send to the editor.
139          *
140          * @since 2.5.0
141          *
142          * @param string       $html    The image HTML markup to send.
143          * @param int          $id      The attachment id.
144          * @param string       $caption The image caption.
145          * @param string       $title   The image title.
146          * @param string       $align   The image alignment.
147          * @param string       $url     The image source URL.
148          * @param string|array $size    Size of image. Image size or array of width and height values
149          *                              (in that order). Default 'medium'.
150          * @param string       $alt     The image alternative, or alt, text.
151          */
152         $html = apply_filters( 'image_send_to_editor', $html, $id, $caption, $title, $align, $url, $size, $alt );
153
154         return $html;
155 }
156
157 /**
158  * Adds image shortcode with caption to editor
159  *
160  * @since 2.6.0
161  *
162  * @param string $html
163  * @param integer $id
164  * @param string $caption image caption
165  * @param string $title image title attribute
166  * @param string $align image css alignment property
167  * @param string $url image src url
168  * @param string $size image size (thumbnail, medium, large, full or added with add_image_size() )
169  * @param string $alt image alt attribute
170  * @return string
171  */
172 function image_add_caption( $html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
173
174         /**
175          * Filters the caption text.
176          *
177          * Note: If the caption text is empty, the caption shortcode will not be appended
178          * to the image HTML when inserted into the editor.
179          *
180          * Passing an empty value also prevents the {@see 'image_add_caption_shortcode'}
181          * Filters from being evaluated at the end of image_add_caption().
182          *
183          * @since 4.1.0
184          *
185          * @param string $caption The original caption text.
186          * @param int    $id      The attachment ID.
187          */
188         $caption = apply_filters( 'image_add_caption_text', $caption, $id );
189
190         /**
191          * Filters whether to disable captions.
192          *
193          * Prevents image captions from being appended to image HTML when inserted into the editor.
194          *
195          * @since 2.6.0
196          *
197          * @param bool $bool Whether to disable appending captions. Returning true to the filter
198          *                   will disable captions. Default empty string.
199          */
200         if ( empty($caption) || apply_filters( 'disable_captions', '' ) )
201                 return $html;
202
203         $id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';
204
205         if ( ! preg_match( '/width=["\']([0-9]+)/', $html, $matches ) )
206                 return $html;
207
208         $width = $matches[1];
209
210         $caption = str_replace( array("\r\n", "\r"), "\n", $caption);
211         $caption = preg_replace_callback( '/<[a-zA-Z0-9]+(?: [^<>]+>)*/', '_cleanup_image_add_caption', $caption );
212
213         // Convert any remaining line breaks to <br>.
214         $caption = preg_replace( '/[ \n\t]*\n[ \t]*/', '<br />', $caption );
215
216         $html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html );
217         if ( empty($align) )
218                 $align = 'none';
219
220         $shcode = '[caption id="' . $id . '" align="align' . $align     . '" width="' . $width . '"]' . $html . ' ' . $caption . '[/caption]';
221
222         /**
223          * Filters the image HTML markup including the caption shortcode.
224          *
225          * @since 2.6.0
226          *
227          * @param string $shcode The image HTML markup with caption shortcode.
228          * @param string $html   The image HTML markup.
229          */
230         return apply_filters( 'image_add_caption_shortcode', $shcode, $html );
231 }
232
233 /**
234  * Private preg_replace callback used in image_add_caption()
235  *
236  * @access private
237  * @since 3.4.0
238  */
239 function _cleanup_image_add_caption( $matches ) {
240         // Remove any line breaks from inside the tags.
241         return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
242 }
243
244 /**
245  * Adds image html to editor
246  *
247  * @since 2.5.0
248  *
249  * @param string $html
250  */
251 function media_send_to_editor($html) {
252 ?>
253 <script type="text/javascript">
254 var win = window.dialogArguments || opener || parent || top;
255 win.send_to_editor( <?php echo wp_json_encode( $html ); ?> );
256 </script>
257 <?php
258         exit;
259 }
260
261 /**
262  * Save a file submitted from a POST request and create an attachment post for it.
263  *
264  * @since 2.5.0
265  *
266  * @param string $file_id   Index of the `$_FILES` array that the file was sent. Required.
267  * @param int    $post_id   The post ID of a post to attach the media item to. Required, but can
268  *                          be set to 0, creating a media item that has no relationship to a post.
269  * @param array  $post_data Overwrite some of the attachment. Optional.
270  * @param array  $overrides Override the wp_handle_upload() behavior. Optional.
271  * @return int|WP_Error ID of the attachment or a WP_Error object on failure.
272  */
273 function media_handle_upload($file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false )) {
274
275         $time = current_time('mysql');
276         if ( $post = get_post($post_id) ) {
277                 if ( substr( $post->post_date, 0, 4 ) > 0 )
278                         $time = $post->post_date;
279         }
280
281         $name = $_FILES[$file_id]['name'];
282         $file = wp_handle_upload($_FILES[$file_id], $overrides, $time);
283
284         if ( isset($file['error']) )
285                 return new WP_Error( 'upload_error', $file['error'] );
286
287         $name_parts = pathinfo($name);
288         $name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
289
290         $url = $file['url'];
291         $type = $file['type'];
292         $file = $file['file'];
293         $title = sanitize_title( $name );
294         $content = '';
295         $excerpt = '';
296
297         if ( preg_match( '#^audio#', $type ) ) {
298                 $meta = wp_read_audio_metadata( $file );
299
300                 if ( ! empty( $meta['title'] ) ) {
301                         $title = $meta['title'];
302                 }
303
304                 if ( ! empty( $title ) ) {
305
306                         if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
307                                 /* translators: 1: audio track title, 2: album title, 3: artist name */
308                                 $content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] );
309                         } elseif ( ! empty( $meta['album'] ) ) {
310                                 /* translators: 1: audio track title, 2: album title */
311                                 $content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] );
312                         } elseif ( ! empty( $meta['artist'] ) ) {
313                                 /* translators: 1: audio track title, 2: artist name */
314                                 $content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] );
315                         } else {
316                                 $content .= sprintf( __( '"%s".' ), $title );
317                         }
318
319                 } elseif ( ! empty( $meta['album'] ) ) {
320
321                         if ( ! empty( $meta['artist'] ) ) {
322                                 /* translators: 1: audio album title, 2: artist name */
323                                 $content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] );
324                         } else {
325                                 $content .= $meta['album'] . '.';
326                         }
327
328                 } elseif ( ! empty( $meta['artist'] ) ) {
329
330                         $content .= $meta['artist'] . '.';
331
332                 }
333
334                 if ( ! empty( $meta['year'] ) )
335                         $content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] );
336
337                 if ( ! empty( $meta['track_number'] ) ) {
338                         $track_number = explode( '/', $meta['track_number'] );
339                         if ( isset( $track_number[1] ) )
340                                 $content .= ' ' . sprintf( __( 'Track %1$s of %2$s.' ), number_format_i18n( $track_number[0] ), number_format_i18n( $track_number[1] ) );
341                         else
342                                 $content .= ' ' . sprintf( __( 'Track %1$s.' ), number_format_i18n( $track_number[0] ) );
343                 }
344
345                 if ( ! empty( $meta['genre'] ) )
346                         $content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] );
347
348         // Use image exif/iptc data for title and caption defaults if possible.
349         } elseif ( 0 === strpos( $type, 'image/' ) && $image_meta = @wp_read_image_metadata( $file ) ) {
350                 if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
351                         $title = $image_meta['title'];
352                 }
353
354                 if ( trim( $image_meta['caption'] ) ) {
355                         $excerpt = $image_meta['caption'];
356                 }
357         }
358
359         // Construct the attachment array
360         $attachment = array_merge( array(
361                 'post_mime_type' => $type,
362                 'guid' => $url,
363                 'post_parent' => $post_id,
364                 'post_title' => $title,
365                 'post_content' => $content,
366                 'post_excerpt' => $excerpt,
367         ), $post_data );
368
369         // This should never be set as it would then overwrite an existing attachment.
370         unset( $attachment['ID'] );
371
372         // Save the data
373         $id = wp_insert_attachment($attachment, $file, $post_id);
374         if ( !is_wp_error($id) ) {
375                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
376         }
377
378         return $id;
379
380 }
381
382 /**
383  * Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
384  *
385  * @since 2.6.0
386  *
387  * @param array  $file_array Array similar to a `$_FILES` upload array.
388  * @param int    $post_id    The post ID the media is associated with.
389  * @param string $desc       Optional. Description of the side-loaded file. Default null.
390  * @param array  $post_data  Optional. Post data to override. Default empty array.
391  * @return int|object The ID of the attachment or a WP_Error on failure.
392  */
393 function media_handle_sideload( $file_array, $post_id, $desc = null, $post_data = array() ) {
394         $overrides = array('test_form'=>false);
395
396         $time = current_time( 'mysql' );
397         if ( $post = get_post( $post_id ) ) {
398                 if ( substr( $post->post_date, 0, 4 ) > 0 )
399                         $time = $post->post_date;
400         }
401
402         $file = wp_handle_sideload( $file_array, $overrides, $time );
403         if ( isset($file['error']) )
404                 return new WP_Error( 'upload_error', $file['error'] );
405
406         $url = $file['url'];
407         $type = $file['type'];
408         $file = $file['file'];
409         $title = preg_replace('/\.[^.]+$/', '', basename($file));
410         $content = '';
411
412         // Use image exif/iptc data for title and caption defaults if possible.
413         if ( $image_meta = @wp_read_image_metadata($file) ) {
414                 if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
415                         $title = $image_meta['title'];
416                 if ( trim( $image_meta['caption'] ) )
417                         $content = $image_meta['caption'];
418         }
419
420         if ( isset( $desc ) )
421                 $title = $desc;
422
423         // Construct the attachment array.
424         $attachment = array_merge( array(
425                 'post_mime_type' => $type,
426                 'guid' => $url,
427                 'post_parent' => $post_id,
428                 'post_title' => $title,
429                 'post_content' => $content,
430         ), $post_data );
431
432         // This should never be set as it would then overwrite an existing attachment.
433         unset( $attachment['ID'] );
434
435         // Save the attachment metadata
436         $id = wp_insert_attachment($attachment, $file, $post_id);
437         if ( !is_wp_error($id) )
438                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
439
440         return $id;
441 }
442
443 /**
444  * Adds the iframe to display content for the media upload page
445  *
446  * @since 2.5.0
447  *
448  * @global int $body_id
449  *
450  * @param string|callable $content_func
451  */
452 function wp_iframe($content_func /* ... */) {
453         _wp_admin_html_begin();
454 ?>
455 <title><?php bloginfo('name') ?> &rsaquo; <?php _e('Uploads'); ?> &#8212; <?php _e('WordPress'); ?></title>
456 <?php
457
458 wp_enqueue_style( 'colors' );
459 // Check callback name for 'media'
460 if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) )
461         || ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) ) )
462         wp_enqueue_style( 'deprecated-media' );
463 wp_enqueue_style( 'ie' );
464 ?>
465 <script type="text/javascript">
466 addLoadEvent = 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();}}};
467 var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup',
468 isRtl = <?php echo (int) is_rtl(); ?>;
469 </script>
470 <?php
471         /** This action is documented in wp-admin/admin-header.php */
472         do_action( 'admin_enqueue_scripts', 'media-upload-popup' );
473
474         /**
475          * Fires when admin styles enqueued for the legacy (pre-3.5.0) media upload popup are printed.
476          *
477          * @since 2.9.0
478          */
479         do_action( 'admin_print_styles-media-upload-popup' );
480
481         /** This action is documented in wp-admin/admin-header.php */
482         do_action( 'admin_print_styles' );
483
484         /**
485          * Fires when admin scripts enqueued for the legacy (pre-3.5.0) media upload popup are printed.
486          *
487          * @since 2.9.0
488          */
489         do_action( 'admin_print_scripts-media-upload-popup' );
490
491         /** This action is documented in wp-admin/admin-header.php */
492         do_action( 'admin_print_scripts' );
493
494         /**
495          * Fires when scripts enqueued for the admin header for the legacy (pre-3.5.0)
496          * media upload popup are printed.
497          *
498          * @since 2.9.0
499          */
500         do_action( 'admin_head-media-upload-popup' );
501
502         /** This action is documented in wp-admin/admin-header.php */
503         do_action( 'admin_head' );
504
505 if ( is_string( $content_func ) ) {
506         /**
507          * Fires in the admin header for each specific form tab in the legacy
508          * (pre-3.5.0) media upload popup.
509          *
510          * The dynamic portion of the hook, `$content_func`, refers to the form
511          * callback for the media upload type. Possible values include
512          * 'media_upload_type_form', 'media_upload_type_url_form', and
513          * 'media_upload_library_form'.
514          *
515          * @since 2.5.0
516          */
517         do_action( "admin_head_{$content_func}" );
518 }
519 ?>
520 </head>
521 <body<?php if ( isset($GLOBALS['body_id']) ) echo ' id="' . $GLOBALS['body_id'] . '"'; ?> class="wp-core-ui no-js">
522 <script type="text/javascript">
523 document.body.className = document.body.className.replace('no-js', 'js');
524 </script>
525 <?php
526         $args = func_get_args();
527         $args = array_slice($args, 1);
528         call_user_func_array($content_func, $args);
529
530         /** This action is documented in wp-admin/admin-footer.php */
531         do_action( 'admin_print_footer_scripts' );
532 ?>
533 <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
534 </body>
535 </html>
536 <?php
537 }
538
539 /**
540  * Adds the media button to the editor
541  *
542  * @since 2.5.0
543  *
544  * @global int $post_ID
545  *
546  * @staticvar int $instance
547  *
548  * @param string $editor_id
549  */
550 function media_buttons($editor_id = 'content') {
551         static $instance = 0;
552         $instance++;
553
554         $post = get_post();
555         if ( ! $post && ! empty( $GLOBALS['post_ID'] ) )
556                 $post = $GLOBALS['post_ID'];
557
558         wp_enqueue_media( array(
559                 'post' => $post
560         ) );
561
562         $img = '<span class="wp-media-buttons-icon"></span> ';
563
564         $id_attribute = $instance === 1 ? ' id="insert-media-button"' : '';
565         printf( '<button type="button"%s class="button insert-media add_media" data-editor="%s">%s</button>',
566                 $id_attribute,
567                 esc_attr( $editor_id ),
568                 $img . __( 'Add Media' )
569         );
570         /**
571          * Filters the legacy (pre-3.5.0) media buttons.
572          *
573          * Use {@see 'media_buttons'} action instead.
574          *
575          * @since 2.5.0
576          * @deprecated 3.5.0 Use {@see 'media_buttons'} action instead.
577          *
578          * @param string $string Media buttons context. Default empty.
579          */
580         $legacy_filter = apply_filters( 'media_buttons_context', '' );
581
582         if ( $legacy_filter ) {
583                 // #WP22559. Close <a> if a plugin started by closing <a> to open their own <a> tag.
584                 if ( 0 === stripos( trim( $legacy_filter ), '</a>' ) )
585                         $legacy_filter .= '</a>';
586                 echo $legacy_filter;
587         }
588 }
589
590 /**
591  *
592  * @global int $post_ID
593  * @param string $type
594  * @param int $post_id
595  * @param string $tab
596  * @return string
597  */
598 function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) {
599         global $post_ID;
600
601         if ( empty( $post_id ) )
602                 $post_id = $post_ID;
603
604         $upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url('media-upload.php') );
605
606         if ( $type && 'media' != $type )
607                 $upload_iframe_src = add_query_arg('type', $type, $upload_iframe_src);
608
609         if ( ! empty( $tab ) )
610                 $upload_iframe_src = add_query_arg('tab', $tab, $upload_iframe_src);
611
612         /**
613          * Filters the upload iframe source URL for a specific media type.
614          *
615          * The dynamic portion of the hook name, `$type`, refers to the type
616          * of media uploaded.
617          *
618          * @since 3.0.0
619          *
620          * @param string $upload_iframe_src The upload iframe source URL by type.
621          */
622         $upload_iframe_src = apply_filters( $type . '_upload_iframe_src', $upload_iframe_src );
623
624         return add_query_arg('TB_iframe', true, $upload_iframe_src);
625 }
626
627 /**
628  * Handles form submissions for the legacy media uploader.
629  *
630  * @since 2.5.0
631  *
632  * @return mixed void|object WP_Error on failure
633  */
634 function media_upload_form_handler() {
635         check_admin_referer('media-form');
636
637         $errors = null;
638
639         if ( isset($_POST['send']) ) {
640                 $keys = array_keys( $_POST['send'] );
641                 $send_id = (int) reset( $keys );
642         }
643
644         if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
645                 $post = $_post = get_post($attachment_id, ARRAY_A);
646
647                 if ( !current_user_can( 'edit_post', $attachment_id ) )
648                         continue;
649
650                 if ( isset($attachment['post_content']) )
651                         $post['post_content'] = $attachment['post_content'];
652                 if ( isset($attachment['post_title']) )
653                         $post['post_title'] = $attachment['post_title'];
654                 if ( isset($attachment['post_excerpt']) )
655                         $post['post_excerpt'] = $attachment['post_excerpt'];
656                 if ( isset($attachment['menu_order']) )
657                         $post['menu_order'] = $attachment['menu_order'];
658
659                 if ( isset($send_id) && $attachment_id == $send_id ) {
660                         if ( isset($attachment['post_parent']) )
661                                 $post['post_parent'] = $attachment['post_parent'];
662                 }
663
664                 /**
665                  * Filters the attachment fields to be saved.
666                  *
667                  * @since 2.5.0
668                  *
669                  * @see wp_get_attachment_metadata()
670                  *
671                  * @param array $post       An array of post data.
672                  * @param array $attachment An array of attachment metadata.
673                  */
674                 $post = apply_filters( 'attachment_fields_to_save', $post, $attachment );
675
676                 if ( isset($attachment['image_alt']) ) {
677                         $image_alt = wp_unslash( $attachment['image_alt'] );
678                         if ( $image_alt != get_post_meta($attachment_id, '_wp_attachment_image_alt', true) ) {
679                                 $image_alt = wp_strip_all_tags( $image_alt, true );
680
681                                 // Update_meta expects slashed.
682                                 update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
683                         }
684                 }
685
686                 if ( isset($post['errors']) ) {
687                         $errors[$attachment_id] = $post['errors'];
688                         unset($post['errors']);
689                 }
690
691                 if ( $post != $_post )
692                         wp_update_post($post);
693
694                 foreach ( get_attachment_taxonomies($post) as $t ) {
695                         if ( isset($attachment[$t]) )
696                                 wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false);
697                 }
698         }
699
700         if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?>
701                 <script type="text/javascript">
702                 var win = window.dialogArguments || opener || parent || top;
703                 win.tb_remove();
704                 </script>
705                 <?php
706                 exit;
707         }
708
709         if ( isset($send_id) ) {
710                 $attachment = wp_unslash( $_POST['attachments'][$send_id] );
711
712                 $html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
713                 if ( !empty($attachment['url']) ) {
714                         $rel = '';
715                         if ( strpos($attachment['url'], 'attachment_id') || get_attachment_link($send_id) == $attachment['url'] )
716                                 $rel = " rel='attachment wp-att-" . esc_attr($send_id) . "'";
717                         $html = "<a href='{$attachment['url']}'$rel>$html</a>";
718                 }
719
720                 /**
721                  * Filters the HTML markup for a media item sent to the editor.
722                  *
723                  * @since 2.5.0
724                  *
725                  * @see wp_get_attachment_metadata()
726                  *
727                  * @param string $html       HTML markup for a media item sent to the editor.
728                  * @param int    $send_id    The first key from the $_POST['send'] data.
729                  * @param array  $attachment Array of attachment metadata.
730                  */
731                 $html = apply_filters( 'media_send_to_editor', $html, $send_id, $attachment );
732                 return media_send_to_editor($html);
733         }
734
735         return $errors;
736 }
737
738 /**
739  * Handles the process of uploading media.
740  *
741  * @since 2.5.0
742  *
743  * @return null|string
744  */
745 function wp_media_upload_handler() {
746         $errors = array();
747         $id = 0;
748
749         if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
750                 check_admin_referer('media-form');
751                 // Upload File button was clicked
752                 $id = media_handle_upload('async-upload', $_REQUEST['post_id']);
753                 unset($_FILES);
754                 if ( is_wp_error($id) ) {
755                         $errors['upload_error'] = $id;
756                         $id = false;
757                 }
758         }
759
760         if ( !empty($_POST['insertonlybutton']) ) {
761                 $src = $_POST['src'];
762                 if ( !empty($src) && !strpos($src, '://') )
763                         $src = "http://$src";
764
765                 if ( isset( $_POST['media_type'] ) && 'image' != $_POST['media_type'] ) {
766                         $title = esc_html( wp_unslash( $_POST['title'] ) );
767                         if ( empty( $title ) )
768                                 $title = esc_html( basename( $src ) );
769
770                         if ( $title && $src )
771                                 $html = "<a href='" . esc_url($src) . "'>$title</a>";
772
773                         $type = 'file';
774                         if ( ( $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ) ) && ( $ext_type = wp_ext2type( $ext ) )
775                                 && ( 'audio' == $ext_type || 'video' == $ext_type ) )
776                                         $type = $ext_type;
777
778                         /**
779                          * Filters the URL sent to the editor for a specific media type.
780                          *
781                          * The dynamic portion of the hook name, `$type`, refers to the type
782                          * of media being sent.
783                          *
784                          * @since 3.3.0
785                          *
786                          * @param string $html  HTML markup sent to the editor.
787                          * @param string $src   Media source URL.
788                          * @param string $title Media title.
789                          */
790                         $html = apply_filters( $type . '_send_to_editor_url', $html, esc_url_raw( $src ), $title );
791                 } else {
792                         $align = '';
793                         $alt = esc_attr( wp_unslash( $_POST['alt'] ) );
794                         if ( isset($_POST['align']) ) {
795                                 $align = esc_attr( wp_unslash( $_POST['align'] ) );
796                                 $class = " class='align$align'";
797                         }
798                         if ( !empty($src) )
799                                 $html = "<img src='" . esc_url($src) . "' alt='$alt'$class />";
800
801                         /**
802                          * Filters the image URL sent to the editor.
803                          *
804                          * @since 2.8.0
805                          *
806                          * @param string $html  HTML markup sent to the editor for an image.
807                          * @param string $src   Image source URL.
808                          * @param string $alt   Image alternate, or alt, text.
809                          * @param string $align The image alignment. Default 'alignnone'. Possible values include
810                          *                      'alignleft', 'aligncenter', 'alignright', 'alignnone'.
811                          */
812                         $html = apply_filters( 'image_send_to_editor_url', $html, esc_url_raw( $src ), $alt, $align );
813                 }
814
815                 return media_send_to_editor($html);
816         }
817
818         if ( isset( $_POST['save'] ) ) {
819                 $errors['upload_notice'] = __('Saved.');
820                 wp_enqueue_script( 'admin-gallery' );
821                 return wp_iframe( 'media_upload_gallery_form', $errors );
822
823         } elseif ( ! empty( $_POST ) ) {
824                 $return = media_upload_form_handler();
825
826                 if ( is_string($return) )
827                         return $return;
828                 if ( is_array($return) )
829                         $errors = $return;
830         }
831
832         if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) {
833                 $type = 'image';
834                 if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ) ) )
835                         $type = $_GET['type'];
836                 return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id );
837         }
838
839         return wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
840 }
841
842 /**
843  * Downloads an image from the specified URL and attaches it to a post.
844  *
845  * @since 2.6.0
846  * @since 4.2.0 Introduced the `$return` parameter.
847  *
848  * @param string $file    The URL of the image to download.
849  * @param int    $post_id The post ID the media is to be associated with.
850  * @param string $desc    Optional. Description of the image.
851  * @param string $return  Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'.
852  * @return string|WP_Error Populated HTML img tag on success, WP_Error object otherwise.
853  */
854 function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) {
855         if ( ! empty( $file ) ) {
856
857                 // Set variables for storage, fix file filename for query strings.
858                 preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
859                 if ( ! $matches ) {
860                         return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
861                 }
862
863                 $file_array = array();
864                 $file_array['name'] = basename( $matches[0] );
865
866                 // Download file to temp location.
867                 $file_array['tmp_name'] = download_url( $file );
868
869                 // If error storing temporarily, return the error.
870                 if ( is_wp_error( $file_array['tmp_name'] ) ) {
871                         return $file_array['tmp_name'];
872                 }
873
874                 // Do the validation and storage stuff.
875                 $id = media_handle_sideload( $file_array, $post_id, $desc );
876
877                 // If error storing permanently, unlink.
878                 if ( is_wp_error( $id ) ) {
879                         @unlink( $file_array['tmp_name'] );
880                         return $id;
881                 }
882
883                 $src = wp_get_attachment_url( $id );
884         }
885
886         // Finally, check to make sure the file has been saved, then return the HTML.
887         if ( ! empty( $src ) ) {
888                 if ( $return === 'src' ) {
889                         return $src;
890                 }
891
892                 $alt = isset( $desc ) ? esc_attr( $desc ) : '';
893                 $html = "<img src='$src' alt='$alt' />";
894                 return $html;
895         } else {
896                 return new WP_Error( 'image_sideload_failed' );
897         }
898 }
899
900 /**
901  * Retrieves the legacy media uploader form in an iframe.
902  *
903  * @since 2.5.0
904  *
905  * @return string|null
906  */
907 function media_upload_gallery() {
908         $errors = array();
909
910         if ( !empty($_POST) ) {
911                 $return = media_upload_form_handler();
912
913                 if ( is_string($return) )
914                         return $return;
915                 if ( is_array($return) )
916                         $errors = $return;
917         }
918
919         wp_enqueue_script('admin-gallery');
920         return wp_iframe( 'media_upload_gallery_form', $errors );
921 }
922
923 /**
924  * Retrieves the legacy media library form in an iframe.
925  *
926  * @since 2.5.0
927  *
928  * @return string|null
929  */
930 function media_upload_library() {
931         $errors = array();
932         if ( !empty($_POST) ) {
933                 $return = media_upload_form_handler();
934
935                 if ( is_string($return) )
936                         return $return;
937                 if ( is_array($return) )
938                         $errors = $return;
939         }
940
941         return wp_iframe( 'media_upload_library_form', $errors );
942 }
943
944 /**
945  * Retrieve HTML for the image alignment radio buttons with the specified one checked.
946  *
947  * @since 2.7.0
948  *
949  * @param WP_Post $post
950  * @param string $checked
951  * @return string
952  */
953 function image_align_input_fields( $post, $checked = '' ) {
954
955         if ( empty($checked) )
956                 $checked = get_user_setting('align', 'none');
957
958         $alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right'));
959         if ( !array_key_exists( (string) $checked, $alignments ) )
960                 $checked = 'none';
961
962         $out = array();
963         foreach ( $alignments as $name => $label ) {
964                 $name = esc_attr($name);
965                 $out[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'".
966                         ( $checked == $name ? " checked='checked'" : "" ) .
967                         " /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
968         }
969         return join("\n", $out);
970 }
971
972 /**
973  * Retrieve HTML for the size radio buttons with the specified one checked.
974  *
975  * @since 2.7.0
976  *
977  * @param WP_Post $post
978  * @param bool|string $check
979  * @return array
980  */
981 function image_size_input_fields( $post, $check = '' ) {
982         /**
983          * Filters the names and labels of the default image sizes.
984          *
985          * @since 3.3.0
986          *
987          * @param array $size_names Array of image sizes and their names. Default values
988          *                          include 'Thumbnail', 'Medium', 'Large', 'Full Size'.
989          */
990         $size_names = apply_filters( 'image_size_names_choose', array(
991                 'thumbnail' => __( 'Thumbnail' ),
992                 'medium'    => __( 'Medium' ),
993                 'large'     => __( 'Large' ),
994                 'full'      => __( 'Full Size' )
995         ) );
996
997         if ( empty( $check ) ) {
998                 $check = get_user_setting('imgsize', 'medium');
999         }
1000         $out = array();
1001
1002         foreach ( $size_names as $size => $label ) {
1003                 $downsize = image_downsize( $post->ID, $size );
1004                 $checked = '';
1005
1006                 // Is this size selectable?
1007                 $enabled = ( $downsize[3] || 'full' == $size );
1008                 $css_id = "image-size-{$size}-{$post->ID}";
1009
1010                 // If this size is the default but that's not available, don't select it.
1011                 if ( $size == $check ) {
1012                         if ( $enabled ) {
1013                                 $checked = " checked='checked'";
1014                         } else {
1015                                 $check = '';
1016                         }
1017                 } elseif ( ! $check && $enabled && 'thumbnail' != $size ) {
1018                         /*
1019                          * If $check is not enabled, default to the first available size
1020                          * that's bigger than a thumbnail.
1021                          */
1022                         $check = $size;
1023                         $checked = " checked='checked'";
1024                 }
1025
1026                 $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 />";
1027
1028                 $html .= "<label for='{$css_id}'>$label</label>";
1029
1030                 // Only show the dimensions if that choice is available.
1031                 if ( $enabled ) {
1032                         $html .= " <label for='{$css_id}' class='help'>" . sprintf( "(%d&nbsp;&times;&nbsp;%d)", $downsize[1], $downsize[2] ). "</label>";
1033                 }
1034                 $html .= '</div>';
1035
1036                 $out[] = $html;
1037         }
1038
1039         return array(
1040                 'label' => __( 'Size' ),
1041                 'input' => 'html',
1042                 'html'  => join( "\n", $out ),
1043         );
1044 }
1045
1046 /**
1047  * Retrieve HTML for the Link URL buttons with the default link type as specified.
1048  *
1049  * @since 2.7.0
1050  *
1051  * @param WP_Post $post
1052  * @param string $url_type
1053  * @return string
1054  */
1055 function image_link_input_fields($post, $url_type = '') {
1056
1057         $file = wp_get_attachment_url($post->ID);
1058         $link = get_attachment_link($post->ID);
1059
1060         if ( empty($url_type) )
1061                 $url_type = get_user_setting('urlbutton', 'post');
1062
1063         $url = '';
1064         if ( $url_type == 'file' )
1065                 $url = $file;
1066         elseif ( $url_type == 'post' )
1067                 $url = $link;
1068
1069         return "
1070         <input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr($url) . "' /><br />
1071         <button type='button' class='button urlnone' data-link-url=''>" . __('None') . "</button>
1072         <button type='button' class='button urlfile' data-link-url='" . esc_attr($file) . "'>" . __('File URL') . "</button>
1073         <button type='button' class='button urlpost' data-link-url='" . esc_attr($link) . "'>" . __('Attachment Post URL') . "</button>
1074 ";
1075 }
1076
1077 /**
1078  * Output a textarea element for inputting an attachment caption.
1079  *
1080  * @since 3.4.0
1081  *
1082  * @param WP_Post $edit_post Attachment WP_Post object.
1083  * @return string HTML markup for the textarea element.
1084  */
1085 function wp_caption_input_textarea($edit_post) {
1086         // Post data is already escaped.
1087         $name = "attachments[{$edit_post->ID}][post_excerpt]";
1088
1089         return '<textarea name="' . $name . '" id="' . $name . '">' . $edit_post->post_excerpt . '</textarea>';
1090 }
1091
1092 /**
1093  * Retrieves the image attachment fields to edit form fields.
1094  *
1095  * @since 2.5.0
1096  *
1097  * @param array $form_fields
1098  * @param object $post
1099  * @return array
1100  */
1101 function image_attachment_fields_to_edit($form_fields, $post) {
1102         return $form_fields;
1103 }
1104
1105 /**
1106  * Retrieves the single non-image attachment fields to edit form fields.
1107  *
1108  * @since 2.5.0
1109  *
1110  * @param array   $form_fields An array of attachment form fields.
1111  * @param WP_Post $post        The WP_Post attachment object.
1112  * @return array Filtered attachment form fields.
1113  */
1114 function media_single_attachment_fields_to_edit( $form_fields, $post ) {
1115         unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']);
1116         return $form_fields;
1117 }
1118
1119 /**
1120  * Retrieves the post non-image attachment fields to edito form fields.
1121  *
1122  * @since 2.8.0
1123  *
1124  * @param array   $form_fields An array of attachment form fields.
1125  * @param WP_Post $post        The WP_Post attachment object.
1126  * @return array Filtered attachment form fields.
1127  */
1128 function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
1129         unset($form_fields['image_url']);
1130         return $form_fields;
1131 }
1132
1133 /**
1134  * Filters input from media_upload_form_handler() and assigns a default
1135  * post_title from the file name if none supplied.
1136  *
1137  * Illustrates the use of the {@see 'attachment_fields_to_save'} filter
1138  * which can be used to add default values to any field before saving to DB.
1139  *
1140  * @since 2.5.0
1141  *
1142  * @param array $post       The WP_Post attachment object converted to an array.
1143  * @param array $attachment An array of attachment metadata.
1144  * @return array Filtered attachment post object.
1145  */
1146 function image_attachment_fields_to_save( $post, $attachment ) {
1147         if ( substr( $post['post_mime_type'], 0, 5 ) == 'image' ) {
1148                 if ( strlen( trim( $post['post_title'] ) ) == 0 ) {
1149                         $attachment_url = ( isset( $post['attachment_url'] ) ) ? $post['attachment_url'] : $post['guid'];
1150                         $post['post_title'] = preg_replace( '/\.\w+$/', '', wp_basename( $attachment_url ) );
1151                         $post['errors']['post_title']['errors'][] = __( 'Empty Title filled from filename.' );
1152                 }
1153         }
1154
1155         return $post;
1156 }
1157
1158 /**
1159  * Retrieves the media element HTML to send to the editor.
1160  *
1161  * @since 2.5.0
1162  *
1163  * @param string $html
1164  * @param integer $attachment_id
1165  * @param array $attachment
1166  * @return string
1167  */
1168 function image_media_send_to_editor($html, $attachment_id, $attachment) {
1169         $post = get_post($attachment_id);
1170         if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
1171                 $url = $attachment['url'];
1172                 $align = !empty($attachment['align']) ? $attachment['align'] : 'none';
1173                 $size = !empty($attachment['image-size']) ? $attachment['image-size'] : 'medium';
1174                 $alt = !empty($attachment['image_alt']) ? $attachment['image_alt'] : '';
1175                 $rel = ( strpos( $url, 'attachment_id') || $url === get_attachment_link( $attachment_id ) );
1176
1177                 return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt);
1178         }
1179
1180         return $html;
1181 }
1182
1183 /**
1184  * Retrieves the attachment fields to edit form fields.
1185  *
1186  * @since 2.5.0
1187  *
1188  * @param WP_Post $post
1189  * @param array $errors
1190  * @return array
1191  */
1192 function get_attachment_fields_to_edit($post, $errors = null) {
1193         if ( is_int($post) )
1194                 $post = get_post($post);
1195         if ( is_array($post) )
1196                 $post = new WP_Post( (object) $post );
1197
1198         $image_url = wp_get_attachment_url($post->ID);
1199
1200         $edit_post = sanitize_post($post, 'edit');
1201
1202         $form_fields = array(
1203                 'post_title'   => array(
1204                         'label'      => __('Title'),
1205                         'value'      => $edit_post->post_title
1206                 ),
1207                 'image_alt'   => array(),
1208                 'post_excerpt' => array(
1209                         'label'      => __('Caption'),
1210                         'input'      => 'html',
1211                         'html'       => wp_caption_input_textarea($edit_post)
1212                 ),
1213                 'post_content' => array(
1214                         'label'      => __('Description'),
1215                         'value'      => $edit_post->post_content,
1216                         'input'      => 'textarea'
1217                 ),
1218                 'url'          => array(
1219                         'label'      => __('Link URL'),
1220                         'input'      => 'html',
1221                         'html'       => image_link_input_fields($post, get_option('image_default_link_type')),
1222                         'helps'      => __('Enter a link URL or click above for presets.')
1223                 ),
1224                 'menu_order'   => array(
1225                         'label'      => __('Order'),
1226                         'value'      => $edit_post->menu_order
1227                 ),
1228                 'image_url'     => array(
1229                         'label'      => __('File URL'),
1230                         'input'      => 'html',
1231                         'html'       => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr($image_url) . "' /><br />",
1232                         'value'      => wp_get_attachment_url($post->ID),
1233                         'helps'      => __('Location of the uploaded file.')
1234                 )
1235         );
1236
1237         foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
1238                 $t = (array) get_taxonomy($taxonomy);
1239                 if ( ! $t['public'] || ! $t['show_ui'] )
1240                         continue;
1241                 if ( empty($t['label']) )
1242                         $t['label'] = $taxonomy;
1243                 if ( empty($t['args']) )
1244                         $t['args'] = array();
1245
1246                 $terms = get_object_term_cache($post->ID, $taxonomy);
1247                 if ( false === $terms )
1248                         $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
1249
1250                 $values = array();
1251
1252                 foreach ( $terms as $term )
1253                         $values[] = $term->slug;
1254                 $t['value'] = join(', ', $values);
1255
1256                 $form_fields[$taxonomy] = $t;
1257         }
1258
1259         // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
1260         // The recursive merge is easily traversed with array casting: foreach ( (array) $things as $thing )
1261         $form_fields = array_merge_recursive($form_fields, (array) $errors);
1262
1263         // This was formerly in image_attachment_fields_to_edit().
1264         if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
1265                 $alt = get_post_meta($post->ID, '_wp_attachment_image_alt', true);
1266                 if ( empty($alt) )
1267                         $alt = '';
1268
1269                 $form_fields['post_title']['required'] = true;
1270
1271                 $form_fields['image_alt'] = array(
1272                         'value' => $alt,
1273                         'label' => __('Alternative Text'),
1274                         'helps' => __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;')
1275                 );
1276
1277                 $form_fields['align'] = array(
1278                         'label' => __('Alignment'),
1279                         'input' => 'html',
1280                         'html'  => image_align_input_fields($post, get_option('image_default_align')),
1281                 );
1282
1283                 $form_fields['image-size'] = image_size_input_fields( $post, get_option('image_default_size', 'medium') );
1284
1285         } else {
1286                 unset( $form_fields['image_alt'] );
1287         }
1288
1289         /**
1290          * Filters the attachment fields to edit.
1291          *
1292          * @since 2.5.0
1293          *
1294          * @param array   $form_fields An array of attachment form fields.
1295          * @param WP_Post $post        The WP_Post attachment object.
1296          */
1297         $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1298
1299         return $form_fields;
1300 }
1301
1302 /**
1303  * Retrieve HTML for media items of post gallery.
1304  *
1305  * The HTML markup retrieved will be created for the progress of SWF Upload
1306  * component. Will also create link for showing and hiding the form to modify
1307  * the image attachment.
1308  *
1309  * @since 2.5.0
1310  *
1311  * @global WP_Query $wp_the_query
1312  *
1313  * @param int $post_id Optional. Post ID.
1314  * @param array $errors Errors for attachment, if any.
1315  * @return string
1316  */
1317 function get_media_items( $post_id, $errors ) {
1318         $attachments = array();
1319         if ( $post_id ) {
1320                 $post = get_post($post_id);
1321                 if ( $post && $post->post_type == 'attachment' )
1322                         $attachments = array($post->ID => $post);
1323                 else
1324                         $attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') );
1325         } else {
1326                 if ( is_array($GLOBALS['wp_the_query']->posts) )
1327                         foreach ( $GLOBALS['wp_the_query']->posts as $attachment )
1328                                 $attachments[$attachment->ID] = $attachment;
1329         }
1330
1331         $output = '';
1332         foreach ( (array) $attachments as $id => $attachment ) {
1333                 if ( $attachment->post_status == 'trash' )
1334                         continue;
1335                 if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) )
1336                         $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>";
1337         }
1338
1339         return $output;
1340 }
1341
1342 /**
1343  * Retrieve HTML form for modifying the image attachment.
1344  *
1345  * @since 2.5.0
1346  *
1347  * @global string $redir_tab
1348  *
1349  * @param int $attachment_id Attachment ID for modification.
1350  * @param string|array $args Optional. Override defaults.
1351  * @return string HTML form for attachment.
1352  */
1353 function get_media_item( $attachment_id, $args = null ) {
1354         global $redir_tab;
1355
1356         if ( ( $attachment_id = intval( $attachment_id ) ) && $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true ) )
1357                 $thumb_url = $thumb_url[0];
1358         else
1359                 $thumb_url = false;
1360
1361         $post = get_post( $attachment_id );
1362         $current_post_id = !empty( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0;
1363
1364         $default_args = array(
1365                 'errors' => null,
1366                 'send' => $current_post_id ? post_type_supports( get_post_type( $current_post_id ), 'editor' ) : true,
1367                 'delete' => true,
1368                 'toggle' => true,
1369                 'show_title' => true
1370         );
1371         $args = wp_parse_args( $args, $default_args );
1372
1373         /**
1374          * Filters the arguments used to retrieve an image for the edit image form.
1375          *
1376          * @since 3.1.0
1377          *
1378          * @see get_media_item
1379          *
1380          * @param array $args An array of arguments.
1381          */
1382         $r = apply_filters( 'get_media_item_args', $args );
1383
1384         $toggle_on  = __( 'Show' );
1385         $toggle_off = __( 'Hide' );
1386
1387         $file = get_attached_file( $post->ID );
1388         $filename = esc_html( wp_basename( $file ) );
1389         $title = esc_attr( $post->post_title );
1390
1391         $post_mime_types = get_post_mime_types();
1392         $keys = array_keys( wp_match_mime_types( array_keys( $post_mime_types ), $post->post_mime_type ) );
1393         $type = reset( $keys );
1394         $type_html = "<input type='hidden' id='type-of-$attachment_id' value='" . esc_attr( $type ) . "' />";
1395
1396         $form_fields = get_attachment_fields_to_edit( $post, $r['errors'] );
1397
1398         if ( $r['toggle'] ) {
1399                 $class = empty( $r['errors'] ) ? 'startclosed' : 'startopen';
1400                 $toggle_links = "
1401         <a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
1402         <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
1403         } else {
1404                 $class = '';
1405                 $toggle_links = '';
1406         }
1407
1408         $display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case
1409         $display_title = $r['show_title'] ? "<div class='filename new'><span class='title'>" . wp_html_excerpt( $display_title, 60, '&hellip;' ) . "</span></div>" : '';
1410
1411         $gallery = ( ( isset( $_REQUEST['tab'] ) && 'gallery' == $_REQUEST['tab'] ) || ( isset( $redir_tab ) && 'gallery' == $redir_tab ) );
1412         $order = '';
1413
1414         foreach ( $form_fields as $key => $val ) {
1415                 if ( 'menu_order' == $key ) {
1416                         if ( $gallery )
1417                                 $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>";
1418                         else
1419                                 $order = "<input type='hidden' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ) . "' />";
1420
1421                         unset( $form_fields['menu_order'] );
1422                         break;
1423                 }
1424         }
1425
1426         $media_dims = '';
1427         $meta = wp_get_attachment_metadata( $post->ID );
1428         if ( isset( $meta['width'], $meta['height'] ) )
1429                 $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
1430
1431         /**
1432          * Filters the media metadata.
1433          *
1434          * @since 2.5.0
1435          *
1436          * @param string  $media_dims The HTML markup containing the media dimensions.
1437          * @param WP_Post $post       The WP_Post attachment object.
1438          */
1439         $media_dims = apply_filters( 'media_meta', $media_dims, $post );
1440
1441         $image_edit_button = '';
1442         if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
1443                 $nonce = wp_create_nonce( "image_editor-$post->ID" );
1444                 $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>";
1445         }
1446
1447         $attachment_url = get_permalink( $attachment_id );
1448
1449         $item = "
1450         $type_html
1451         $toggle_links
1452         $order
1453         $display_title
1454         <table class='slidetoggle describe $class'>
1455                 <thead class='media-item-info' id='media-head-$post->ID'>
1456                 <tr>
1457                         <td class='A1B1' id='thumbnail-head-$post->ID'>
1458                         <p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p>
1459                         <p>$image_edit_button</p>
1460                         </td>
1461                         <td>
1462                         <p><strong>" . __('File name:') . "</strong> $filename</p>
1463                         <p><strong>" . __('File type:') . "</strong> $post->post_mime_type</p>
1464                         <p><strong>" . __('Upload date:') . "</strong> " . mysql2date( __( 'F j, Y' ), $post->post_date ). '</p>';
1465                         if ( !empty( $media_dims ) )
1466                                 $item .= "<p><strong>" . __('Dimensions:') . "</strong> $media_dims</p>\n";
1467
1468                         $item .= "</td></tr>\n";
1469
1470         $item .= "
1471                 </thead>
1472                 <tbody>
1473                 <tr><td colspan='2' class='imgedit-response' id='imgedit-response-$post->ID'></td></tr>\n
1474                 <tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-$post->ID'></td></tr>\n
1475                 <tr><td colspan='2'><p class='media-types media-types-required-info'>" . sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . "</p></td></tr>\n";
1476
1477         $defaults = array(
1478                 'input'      => 'text',
1479                 'required'   => false,
1480                 'value'      => '',
1481                 'extra_rows' => array(),
1482         );
1483
1484         if ( $r['send'] ) {
1485                 $r['send'] = get_submit_button( __( 'Insert into Post' ), 'button', "send[$attachment_id]", false );
1486         }
1487
1488         $delete = empty( $r['delete'] ) ? '' : $r['delete'];
1489         if ( $delete && current_user_can( 'delete_post', $attachment_id ) ) {
1490                 if ( !EMPTY_TRASH_DAYS ) {
1491                         $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>';
1492                 } elseif ( !MEDIA_TRASH ) {
1493                         $delete = "<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __( 'Delete' ) . "</a>
1494                          <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'>" .
1495                          /* translators: %s: file name */
1496                         '<p>' . sprintf( __( 'You are about to delete %s.' ), '<strong>' . $filename . '</strong>' ) . "</p>
1497                          <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>
1498                          <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">" . __( 'Cancel' ) . "</a>
1499                          </div>";
1500                 } else {
1501                         $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>
1502                         <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>";
1503                 }
1504         } else {
1505                 $delete = '';
1506         }
1507
1508         $thumbnail = '';
1509         $calling_post_id = 0;
1510         if ( isset( $_GET['post_id'] ) ) {
1511                 $calling_post_id = absint( $_GET['post_id'] );
1512         } elseif ( isset( $_POST ) && count( $_POST ) ) {// Like for async-upload where $_GET['post_id'] isn't set
1513                 $calling_post_id = $post->post_parent;
1514         }
1515         if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) )
1516                 && post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) {
1517
1518                 $calling_post = get_post( $calling_post_id );
1519                 $calling_post_type_object = get_post_type_object( $calling_post->post_type );
1520
1521                 $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$calling_post_id" );
1522                 $thumbnail = "<a class='wp-post-thumbnail' id='wp-post-thumbnail-" . $attachment_id . "' href='#' onclick='WPSetAsThumbnail(\"$attachment_id\", \"$ajax_nonce\");return false;'>" . esc_html( $calling_post_type_object->labels->use_featured_image ) . "</a>";
1523         }
1524
1525         if ( ( $r['send'] || $thumbnail || $delete ) && !isset( $form_fields['buttons'] ) ) {
1526                 $form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>" . $r['send'] . " $thumbnail $delete</td></tr>\n" );
1527         }
1528         $hidden_fields = array();
1529
1530         foreach ( $form_fields as $id => $field ) {
1531                 if ( $id[0] == '_' )
1532                         continue;
1533
1534                 if ( !empty( $field['tr'] ) ) {
1535                         $item .= $field['tr'];
1536                         continue;
1537                 }
1538
1539                 $field = array_merge( $defaults, $field );
1540                 $name = "attachments[$attachment_id][$id]";
1541
1542                 if ( $field['input'] == 'hidden' ) {
1543                         $hidden_fields[$name] = $field['value'];
1544                         continue;
1545                 }
1546
1547                 $required      = $field['required'] ? '<span class="required">*</span>' : '';
1548                 $required_attr = $field['required'] ? ' required' : '';
1549                 $aria_required = $field['required'] ? " aria-required='true'" : '';
1550                 $class  = $id;
1551                 $class .= $field['required'] ? ' form-required' : '';
1552
1553                 $item .= "\t\t<tr class='$class'>\n\t\t\t<th scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}{$required}</span><br class='clear' /></label></th>\n\t\t\t<td class='field'>";
1554                 if ( !empty( $field[ $field['input'] ] ) )
1555                         $item .= $field[ $field['input'] ];
1556                 elseif ( $field['input'] == 'textarea' ) {
1557                         if ( 'post_content' == $id && user_can_richedit() ) {
1558                                 // Sanitize_post() skips the post_content when user_can_richedit.
1559                                 $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1560                         }
1561                         // Post_excerpt is already escaped by sanitize_post() in get_attachment_fields_to_edit().
1562                         $item .= "<textarea id='$name' name='$name'{$required_attr}{$aria_required}>" . $field['value'] . '</textarea>';
1563                 } else {
1564                         $item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "'{$required_attr}{$aria_required} />";
1565                 }
1566                 if ( !empty( $field['helps'] ) )
1567                         $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1568                 $item .= "</td>\n\t\t</tr>\n";
1569
1570                 $extra_rows = array();
1571
1572                 if ( !empty( $field['errors'] ) )
1573                         foreach ( array_unique( (array) $field['errors'] ) as $error )
1574                                 $extra_rows['error'][] = $error;
1575
1576                 if ( !empty( $field['extra_rows'] ) )
1577                         foreach ( $field['extra_rows'] as $class => $rows )
1578                                 foreach ( (array) $rows as $html )
1579                                         $extra_rows[$class][] = $html;
1580
1581                 foreach ( $extra_rows as $class => $rows )
1582                         foreach ( $rows as $html )
1583                                 $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1584         }
1585
1586         if ( !empty( $form_fields['_final'] ) )
1587                 $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1588         $item .= "\t</tbody>\n";
1589         $item .= "\t</table>\n";
1590
1591         foreach ( $hidden_fields as $name => $value )
1592                 $item .= "\t<input type='hidden' name='$name' id='$name' value='" . esc_attr( $value ) . "' />\n";
1593
1594         if ( $post->post_parent < 1 && isset( $_REQUEST['post_id'] ) ) {
1595                 $parent = (int) $_REQUEST['post_id'];
1596                 $parent_name = "attachments[$attachment_id][post_parent]";
1597                 $item .= "\t<input type='hidden' name='$parent_name' id='$parent_name' value='$parent' />\n";
1598         }
1599
1600         return $item;
1601 }
1602
1603 /**
1604  * @since 3.5.0
1605  *
1606  * @param int   $attachment_id
1607  * @param array $args
1608  * @return array
1609  */
1610 function get_compat_media_markup( $attachment_id, $args = null ) {
1611         $post = get_post( $attachment_id );
1612
1613         $default_args = array(
1614                 'errors' => null,
1615                 'in_modal' => false,
1616         );
1617
1618         $user_can_edit = current_user_can( 'edit_post', $attachment_id );
1619
1620         $args = wp_parse_args( $args, $default_args );
1621
1622         /** This filter is documented in wp-admin/includes/media.php */
1623         $args = apply_filters( 'get_media_item_args', $args );
1624
1625         $form_fields = array();
1626
1627         if ( $args['in_modal'] ) {
1628                 foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
1629                         $t = (array) get_taxonomy($taxonomy);
1630                         if ( ! $t['public'] || ! $t['show_ui'] )
1631                                 continue;
1632                         if ( empty($t['label']) )
1633                                 $t['label'] = $taxonomy;
1634                         if ( empty($t['args']) )
1635                                 $t['args'] = array();
1636
1637                         $terms = get_object_term_cache($post->ID, $taxonomy);
1638                         if ( false === $terms )
1639                                 $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
1640
1641                         $values = array();
1642
1643                         foreach ( $terms as $term )
1644                                 $values[] = $term->slug;
1645                         $t['value'] = join(', ', $values);
1646                         $t['taxonomy'] = true;
1647
1648                         $form_fields[$taxonomy] = $t;
1649                 }
1650         }
1651
1652         // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
1653         // The recursive merge is easily traversed with array casting: foreach ( (array) $things as $thing )
1654         $form_fields = array_merge_recursive($form_fields, (array) $args['errors'] );
1655
1656         /** This filter is documented in wp-admin/includes/media.php */
1657         $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1658
1659         unset( $form_fields['image-size'], $form_fields['align'], $form_fields['image_alt'],
1660                 $form_fields['post_title'], $form_fields['post_excerpt'], $form_fields['post_content'],
1661                 $form_fields['url'], $form_fields['menu_order'], $form_fields['image_url'] );
1662
1663         /** This filter is documented in wp-admin/includes/media.php */
1664         $media_meta = apply_filters( 'media_meta', '', $post );
1665
1666         $defaults = array(
1667                 'input'         => 'text',
1668                 'required'      => false,
1669                 'value'         => '',
1670                 'extra_rows'    => array(),
1671                 'show_in_edit'  => true,
1672                 'show_in_modal' => true,
1673         );
1674
1675         $hidden_fields = array();
1676
1677         $item = '';
1678         foreach ( $form_fields as $id => $field ) {
1679                 if ( $id[0] == '_' )
1680                         continue;
1681
1682                 $name = "attachments[$attachment_id][$id]";
1683                 $id_attr = "attachments-$attachment_id-$id";
1684
1685                 if ( !empty( $field['tr'] ) ) {
1686                         $item .= $field['tr'];
1687                         continue;
1688                 }
1689
1690                 $field = array_merge( $defaults, $field );
1691
1692                 if ( ( ! $field['show_in_edit'] && ! $args['in_modal'] ) || ( ! $field['show_in_modal'] && $args['in_modal'] ) )
1693                         continue;
1694
1695                 if ( $field['input'] == 'hidden' ) {
1696                         $hidden_fields[$name] = $field['value'];
1697                         continue;
1698                 }
1699
1700                 $readonly      = ! $user_can_edit && ! empty( $field['taxonomy'] ) ? " readonly='readonly' " : '';
1701                 $required      = $field['required'] ? '<span class="required">*</span>' : '';
1702                 $required_attr = $field['required'] ? ' required' : '';
1703                 $aria_required = $field['required'] ? " aria-required='true'" : '';
1704                 $class  = 'compat-field-' . $id;
1705                 $class .= $field['required'] ? ' form-required' : '';
1706
1707                 $item .= "\t\t<tr class='$class'>";
1708                 $item .= "\t\t\t<th scope='row' class='label'><label for='$id_attr'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label>";
1709                 $item .= "</th>\n\t\t\t<td class='field'>";
1710
1711                 if ( !empty( $field[ $field['input'] ] ) )
1712                         $item .= $field[ $field['input'] ];
1713                 elseif ( $field['input'] == 'textarea' ) {
1714                         if ( 'post_content' == $id && user_can_richedit() ) {
1715                                 // sanitize_post() skips the post_content when user_can_richedit.
1716                                 $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1717                         }
1718                         $item .= "<textarea id='$id_attr' name='$name'{$required_attr}{$aria_required}>" . $field['value'] . '</textarea>';
1719                 } else {
1720                         $item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly{$required_attr}{$aria_required} />";
1721                 }
1722                 if ( !empty( $field['helps'] ) )
1723                         $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1724                 $item .= "</td>\n\t\t</tr>\n";
1725
1726                 $extra_rows = array();
1727
1728                 if ( !empty( $field['errors'] ) )
1729                         foreach ( array_unique( (array) $field['errors'] ) as $error )
1730                                 $extra_rows['error'][] = $error;
1731
1732                 if ( !empty( $field['extra_rows'] ) )
1733                         foreach ( $field['extra_rows'] as $class => $rows )
1734                                 foreach ( (array) $rows as $html )
1735                                         $extra_rows[$class][] = $html;
1736
1737                 foreach ( $extra_rows as $class => $rows )
1738                         foreach ( $rows as $html )
1739                                 $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1740         }
1741
1742         if ( !empty( $form_fields['_final'] ) )
1743                 $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1744
1745         if ( $item ) {
1746                 $item = '<p class="media-types media-types-required-info">' .
1747                         sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . '</p>
1748                         <table class="compat-attachment-fields">' . $item . '</table>';
1749         }
1750
1751         foreach ( $hidden_fields as $hidden_field => $value ) {
1752                 $item .= '<input type="hidden" name="' . esc_attr( $hidden_field ) . '" value="' . esc_attr( $value ) . '" />' . "\n";
1753         }
1754
1755         if ( $item )
1756                 $item = '<input type="hidden" name="attachments[' . $attachment_id . '][menu_order]" value="' . esc_attr( $post->menu_order ) . '" />' . $item;
1757
1758         return array(
1759                 'item'   => $item,
1760                 'meta'   => $media_meta,
1761         );
1762 }
1763
1764 /**
1765  * Outputs the legacy media upload header.
1766  *
1767  * @since 2.5.0
1768  */
1769 function media_upload_header() {
1770         $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
1771
1772         echo '<script type="text/javascript">post_id = ' . $post_id . ';</script>';
1773         if ( empty( $_GET['chromeless'] ) ) {
1774                 echo '<div id="media-upload-header">';
1775                 the_media_upload_tabs();
1776                 echo '</div>';
1777         }
1778 }
1779
1780 /**
1781  * Outputs the legacy media upload form.
1782  *
1783  * @since 2.5.0
1784  *
1785  * @global string $type
1786  * @global string $tab
1787  * @global bool   $is_IE
1788  * @global bool   $is_opera
1789  *
1790  * @param array $errors
1791  */
1792 function media_upload_form( $errors = null ) {
1793         global $type, $tab, $is_IE, $is_opera;
1794
1795         if ( ! _device_can_upload() ) {
1796                 echo '<p>' . sprintf( __('The web browser on your device cannot be used to upload files. You may be able to use the <a href="%s">native app for your device</a> instead.'), 'https://apps.wordpress.org/' ) . '</p>';
1797                 return;
1798         }
1799
1800         $upload_action_url = admin_url('async-upload.php');
1801         $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
1802         $_type = isset($type) ? $type : '';
1803         $_tab = isset($tab) ? $tab : '';
1804
1805         $max_upload_size = wp_max_upload_size();
1806         if ( ! $max_upload_size ) {
1807                 $max_upload_size = 0;
1808         }
1809 ?>
1810
1811 <div id="media-upload-notice"><?php
1812
1813         if (isset($errors['upload_notice']) )
1814                 echo $errors['upload_notice'];
1815
1816 ?></div>
1817 <div id="media-upload-error"><?php
1818
1819         if (isset($errors['upload_error']) && is_wp_error($errors['upload_error']))
1820                 echo $errors['upload_error']->get_error_message();
1821
1822 ?></div>
1823 <?php
1824 if ( is_multisite() && !is_upload_space_available() ) {
1825         /**
1826          * Fires when an upload will exceed the defined upload space quota for a network site.
1827          *
1828          * @since 3.5.0
1829          */
1830         do_action( 'upload_ui_over_quota' );
1831         return;
1832 }
1833
1834 /**
1835  * Fires just before the legacy (pre-3.5.0) upload interface is loaded.
1836  *
1837  * @since 2.6.0
1838  */
1839 do_action( 'pre-upload-ui' );
1840
1841 $post_params = array(
1842         "post_id" => $post_id,
1843         "_wpnonce" => wp_create_nonce('media-form'),
1844         "type" => $_type,
1845         "tab" => $_tab,
1846         "short" => "1",
1847 );
1848
1849 /**
1850  * Filters the media upload post parameters.
1851  *
1852  * @since 3.1.0 As 'swfupload_post_params'
1853  * @since 3.3.0
1854  *
1855  * @param array $post_params An array of media upload parameters used by Plupload.
1856  */
1857 $post_params = apply_filters( 'upload_post_params', $post_params );
1858
1859 $plupload_init = array(
1860         'runtimes'            => 'html5,flash,silverlight,html4',
1861         'browse_button'       => 'plupload-browse-button',
1862         'container'           => 'plupload-upload-ui',
1863         'drop_element'        => 'drag-drop-area',
1864         'file_data_name'      => 'async-upload',
1865         'url'                 => $upload_action_url,
1866         'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
1867         'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
1868         'filters' => array(
1869                 'max_file_size'   => $max_upload_size . 'b',
1870         ),
1871         'multipart_params'    => $post_params,
1872 );
1873
1874 // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
1875 // when enabled. See #29602.
1876 if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
1877         strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
1878
1879         $plupload_init['multi_selection'] = false;
1880 }
1881
1882 /**
1883  * Filters the default Plupload settings.
1884  *
1885  * @since 3.3.0
1886  *
1887  * @param array $plupload_init An array of default settings used by Plupload.
1888  */
1889 $plupload_init = apply_filters( 'plupload_init', $plupload_init );
1890
1891 ?>
1892
1893 <script type="text/javascript">
1894 <?php
1895 // Verify size is an int. If not return default value.
1896 $large_size_h = absint( get_option('large_size_h') );
1897 if( !$large_size_h )
1898         $large_size_h = 1024;
1899 $large_size_w = absint( get_option('large_size_w') );
1900 if( !$large_size_w )
1901         $large_size_w = 1024;
1902 ?>
1903 var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>,
1904 wpUploaderInit = <?php echo wp_json_encode( $plupload_init ); ?>;
1905 </script>
1906
1907 <div id="plupload-upload-ui" class="hide-if-no-js">
1908 <?php
1909 /**
1910  * Fires before the upload interface loads.
1911  *
1912  * @since 2.6.0 As 'pre-flash-upload-ui'
1913  * @since 3.3.0
1914  */
1915 do_action( 'pre-plupload-upload-ui' ); ?>
1916 <div id="drag-drop-area">
1917         <div class="drag-drop-inside">
1918         <p class="drag-drop-info"><?php _e('Drop files here'); ?></p>
1919         <p><?php _ex('or', 'Uploader: Drop files here - or - Select Files'); ?></p>
1920         <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e('Select Files'); ?>" class="button" /></p>
1921         </div>
1922 </div>
1923 <?php
1924 /**
1925  * Fires after the upload interface loads.
1926  *
1927  * @since 2.6.0 As 'post-flash-upload-ui'
1928  * @since 3.3.0
1929  */
1930 do_action( 'post-plupload-upload-ui' ); ?>
1931 </div>
1932
1933 <div id="html-upload-ui" class="hide-if-js">
1934         <?php
1935         /**
1936          * Fires before the upload button in the media upload interface.
1937          *
1938          * @since 2.6.0
1939          */
1940         do_action( 'pre-html-upload-ui' );
1941         ?>
1942         <p id="async-upload-wrap">
1943                 <label class="screen-reader-text" for="async-upload"><?php _e('Upload'); ?></label>
1944                 <input type="file" name="async-upload" id="async-upload" />
1945                 <?php submit_button( __( 'Upload' ), 'primary', 'html-upload', false ); ?>
1946                 <a href="#" onclick="try{top.tb_remove();}catch(e){}; return false;"><?php _e('Cancel'); ?></a>
1947         </p>
1948         <div class="clear"></div>
1949 <?php
1950 /**
1951  * Fires after the upload button in the media upload interface.
1952  *
1953  * @since 2.6.0
1954  */
1955 do_action( 'post-html-upload-ui' );
1956 ?>
1957 </div>
1958
1959 <p class="max-upload-size"><?php printf( __( 'Maximum upload file size: %s.' ), esc_html( size_format( $max_upload_size ) ) ); ?></p>
1960 <?php
1961
1962         /**
1963          * Fires on the post upload UI screen.
1964          *
1965          * Legacy (pre-3.5.0) media workflow hook.
1966          *
1967          * @since 2.6.0
1968          */
1969         do_action( 'post-upload-ui' );
1970 }
1971
1972 /**
1973  * Outputs the legacy media upload form for a given media type.
1974  *
1975  * @since 2.5.0
1976  *
1977  * @param string $type
1978  * @param object $errors
1979  * @param integer $id
1980  */
1981 function media_upload_type_form($type = 'file', $errors = null, $id = null) {
1982
1983         media_upload_header();
1984
1985         $post_id = isset( $_REQUEST['post_id'] )? intval( $_REQUEST['post_id'] ) : 0;
1986
1987         $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
1988
1989         /**
1990          * Filters the media upload form action URL.
1991          *
1992          * @since 2.6.0
1993          *
1994          * @param string $form_action_url The media upload form action URL.
1995          * @param string $type            The type of media. Default 'file'.
1996          */
1997         $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
1998         $form_class = 'media-upload-form type-form validate';
1999
2000         if ( get_user_setting('uploader') )
2001                 $form_class .= ' html-uploader';
2002 ?>
2003
2004 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
2005 <?php submit_button( '', 'hidden', 'save', false ); ?>
2006 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2007 <?php wp_nonce_field('media-form'); ?>
2008
2009 <h3 class="media-title"><?php _e('Add media files from your computer'); ?></h3>
2010
2011 <?php media_upload_form( $errors ); ?>
2012
2013 <script type="text/javascript">
2014 jQuery(function($){
2015         var preloaded = $(".media-item.preloaded");
2016         if ( preloaded.length > 0 ) {
2017                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2018         }
2019         updateMediaForm();
2020 });
2021 </script>
2022 <div id="media-items"><?php
2023
2024 if ( $id ) {
2025         if ( !is_wp_error($id) ) {
2026                 add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
2027                 echo get_media_items( $id, $errors );
2028         } else {
2029                 echo '<div id="media-upload-error">'.esc_html($id->get_error_message()).'</div></div>';
2030                 exit;
2031         }
2032 }
2033 ?></div>
2034
2035 <p class="savebutton ml-submit">
2036 <?php submit_button( __( 'Save all changes' ), 'button', 'save', false ); ?>
2037 </p>
2038 </form>
2039 <?php
2040 }
2041
2042 /**
2043  * Outputs the legacy media upload form for external media.
2044  *
2045  * @since 2.7.0
2046  *
2047  * @param string $type
2048  * @param object $errors
2049  * @param integer $id
2050  */
2051 function media_upload_type_url_form($type = null, $errors = null, $id = null) {
2052         if ( null === $type )
2053                 $type = 'image';
2054
2055         media_upload_header();
2056
2057         $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2058
2059         $form_action_url = admin_url("media-upload.php?type=$type&tab=type&post_id=$post_id");
2060         /** This filter is documented in wp-admin/includes/media.php */
2061         $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2062         $form_class = 'media-upload-form type-form validate';
2063
2064         if ( get_user_setting('uploader') )
2065                 $form_class .= ' html-uploader';
2066 ?>
2067
2068 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
2069 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2070 <?php wp_nonce_field('media-form'); ?>
2071
2072 <h3 class="media-title"><?php _e('Insert media from another website'); ?></h3>
2073
2074 <script type="text/javascript">
2075 var addExtImage = {
2076
2077         width : '',
2078         height : '',
2079         align : 'alignnone',
2080
2081         insert : function() {
2082                 var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = '';
2083
2084                 if ( '' == f.src.value || '' == t.width )
2085                         return false;
2086
2087                 if ( f.alt.value )
2088                         alt = f.alt.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2089
2090 <?php
2091         /** This filter is documented in wp-admin/includes/media.php */
2092         if ( ! apply_filters( 'disable_captions', '' ) ) {
2093                 ?>
2094                 if ( f.caption.value ) {
2095                         caption = f.caption.value.replace(/\r\n|\r/g, '\n');
2096                         caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
2097                                 return a.replace(/[\r\n\t]+/, ' ');
2098                         });
2099
2100                         caption = caption.replace(/\s*\n\s*/g, '<br />');
2101                 }
2102 <?php } ?>
2103
2104                 cls = caption ? '' : ' class="'+t.align+'"';
2105
2106                 html = '<img alt="'+alt+'" src="'+f.src.value+'"'+cls+' width="'+t.width+'" height="'+t.height+'" />';
2107
2108                 if ( f.url.value ) {
2109                         url = f.url.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2110                         html = '<a href="'+url+'">'+html+'</a>';
2111                 }
2112
2113                 if ( caption )
2114                         html = '[caption id="" align="'+t.align+'" width="'+t.width+'"]'+html+caption+'[/caption]';
2115
2116                 var win = window.dialogArguments || opener || parent || top;
2117                 win.send_to_editor(html);
2118                 return false;
2119         },
2120
2121         resetImageData : function() {
2122                 var t = addExtImage;
2123
2124                 t.width = t.height = '';
2125                 document.getElementById('go_button').style.color = '#bbb';
2126                 if ( ! document.forms[0].src.value )
2127                         document.getElementById('status_img').innerHTML = '';
2128                 else document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/no.png' ) ); ?>" alt="" />';
2129         },
2130
2131         updateImageData : function() {
2132                 var t = addExtImage;
2133
2134                 t.width = t.preloadImg.width;
2135                 t.height = t.preloadImg.height;
2136                 document.getElementById('go_button').style.color = '#333';
2137                 document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/yes.png' ) ); ?>" alt="" />';
2138         },
2139
2140         getImageData : function() {
2141                 if ( jQuery('table.describe').hasClass('not-image') )
2142                         return;
2143
2144                 var t = addExtImage, src = document.forms[0].src.value;
2145
2146                 if ( ! src ) {
2147                         t.resetImageData();
2148                         return false;
2149                 }
2150
2151                 document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" alt="" width="16" height="16" />';
2152                 t.preloadImg = new Image();
2153                 t.preloadImg.onload = t.updateImageData;
2154                 t.preloadImg.onerror = t.resetImageData;
2155                 t.preloadImg.src = src;
2156         }
2157 };
2158
2159 jQuery(document).ready( function($) {
2160         $('.media-types input').click( function() {
2161                 $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
2162         });
2163 });
2164 </script>
2165
2166 <div id="media-items">
2167 <div class="media-item media-blank">
2168 <?php
2169 /**
2170  * Filters the insert media from URL form HTML.
2171  *
2172  * @since 3.3.0
2173  *
2174  * @param string $form_html The insert from URL form HTML.
2175  */
2176 echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) );
2177 ?>
2178 </div>
2179 </div>
2180 </form>
2181 <?php
2182 }
2183
2184 /**
2185  * Adds gallery form to upload iframe
2186  *
2187  * @since 2.5.0
2188  *
2189  * @global string $redir_tab
2190  * @global string $type
2191  * @global string $tab
2192  *
2193  * @param array $errors
2194  */
2195 function media_upload_gallery_form($errors) {
2196         global $redir_tab, $type;
2197
2198         $redir_tab = 'gallery';
2199         media_upload_header();
2200
2201         $post_id = intval($_REQUEST['post_id']);
2202         $form_action_url = admin_url("media-upload.php?type=$type&tab=gallery&post_id=$post_id");
2203         /** This filter is documented in wp-admin/includes/media.php */
2204         $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2205         $form_class = 'media-upload-form validate';
2206
2207         if ( get_user_setting('uploader') )
2208                 $form_class .= ' html-uploader';
2209 ?>
2210
2211 <script type="text/javascript">
2212 jQuery(function($){
2213         var preloaded = $(".media-item.preloaded");
2214         if ( preloaded.length > 0 ) {
2215                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2216                 updateMediaForm();
2217         }
2218 });
2219 </script>
2220 <div id="sort-buttons" class="hide-if-no-js">
2221 <span>
2222 <?php _e('All Tabs:'); ?>
2223 <a href="#" id="showall"><?php _e('Show'); ?></a>
2224 <a href="#" id="hideall" style="display:none;"><?php _e('Hide'); ?></a>
2225 </span>
2226 <?php _e('Sort Order:'); ?>
2227 <a href="#" id="asc"><?php _e('Ascending'); ?></a> |
2228 <a href="#" id="desc"><?php _e('Descending'); ?></a> |
2229 <a href="#" id="clear"><?php _ex('Clear', 'verb'); ?></a>
2230 </div>
2231 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
2232 <?php wp_nonce_field('media-form'); ?>
2233 <?php //media_upload_form( $errors ); ?>
2234 <table class="widefat">
2235 <thead><tr>
2236 <th><?php _e('Media'); ?></th>
2237 <th class="order-head"><?php _e('Order'); ?></th>
2238 <th class="actions-head"><?php _e('Actions'); ?></th>
2239 </tr></thead>
2240 </table>
2241 <div id="media-items">
2242 <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?>
2243 <?php echo get_media_items($post_id, $errors); ?>
2244 </div>
2245
2246 <p class="ml-submit">
2247 <?php submit_button( __( 'Save all changes' ), 'button savebutton', 'save', false, array( 'id' => 'save-all', 'style' => 'display: none;' ) ); ?>
2248 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2249 <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
2250 <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
2251 </p>
2252
2253 <div id="gallery-settings" style="display:none;">
2254 <div class="title"><?php _e('Gallery Settings'); ?></div>
2255 <table id="basic" class="describe"><tbody>
2256         <tr>
2257         <th scope="row" class="label">
2258                 <label>
2259                 <span class="alignleft"><?php _e('Link thumbnails to:'); ?></span>
2260                 </label>
2261         </th>
2262         <td class="field">
2263                 <input type="radio" name="linkto" id="linkto-file" value="file" />
2264                 <label for="linkto-file" class="radio"><?php _e('Image File'); ?></label>
2265
2266                 <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" />
2267                 <label for="linkto-post" class="radio"><?php _e('Attachment Page'); ?></label>
2268         </td>
2269         </tr>
2270
2271         <tr>
2272         <th scope="row" class="label">
2273                 <label>
2274                 <span class="alignleft"><?php _e('Order images by:'); ?></span>
2275                 </label>
2276         </th>
2277         <td class="field">
2278                 <select id="orderby" name="orderby">
2279                         <option value="menu_order" selected="selected"><?php _e('Menu order'); ?></option>
2280                         <option value="title"><?php _e('Title'); ?></option>
2281                         <option value="post_date"><?php _e('Date/Time'); ?></option>
2282                         <option value="rand"><?php _e('Random'); ?></option>
2283                 </select>
2284         </td>
2285         </tr>
2286
2287         <tr>
2288         <th scope="row" class="label">
2289                 <label>
2290                 <span class="alignleft"><?php _e('Order:'); ?></span>
2291                 </label>
2292         </th>
2293         <td class="field">
2294                 <input type="radio" checked="checked" name="order" id="order-asc" value="asc" />
2295                 <label for="order-asc" class="radio"><?php _e('Ascending'); ?></label>
2296
2297                 <input type="radio" name="order" id="order-desc" value="desc" />
2298                 <label for="order-desc" class="radio"><?php _e('Descending'); ?></label>
2299         </td>
2300         </tr>
2301
2302         <tr>
2303         <th scope="row" class="label">
2304                 <label>
2305                 <span class="alignleft"><?php _e('Gallery columns:'); ?></span>
2306                 </label>
2307         </th>
2308         <td class="field">
2309                 <select id="columns" name="columns">
2310                         <option value="1">1</option>
2311                         <option value="2">2</option>
2312                         <option value="3" selected="selected">3</option>
2313                         <option value="4">4</option>
2314                         <option value="5">5</option>
2315                         <option value="6">6</option>
2316                         <option value="7">7</option>
2317                         <option value="8">8</option>
2318                         <option value="9">9</option>
2319                 </select>
2320         </td>
2321         </tr>
2322 </tbody></table>
2323
2324 <p class="ml-submit">
2325 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" />
2326 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="update-gallery" id="update-gallery" value="<?php esc_attr_e( 'Update gallery settings' ); ?>" />
2327 </p>
2328 </div>
2329 </form>
2330 <?php
2331 }
2332
2333 /**
2334  * Outputs the legacy media upload form for the media library.
2335  *
2336  * @since 2.5.0
2337  *
2338  * @global wpdb      $wpdb
2339  * @global WP_Query  $wp_query
2340  * @global WP_Locale $wp_locale
2341  * @global string    $type
2342  * @global string    $tab
2343  * @global array     $post_mime_types
2344  *
2345  * @param array $errors
2346  */
2347 function media_upload_library_form($errors) {
2348         global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;
2349
2350         media_upload_header();
2351
2352         $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2353
2354         $form_action_url = admin_url("media-upload.php?type=$type&tab=library&post_id=$post_id");
2355         /** This filter is documented in wp-admin/includes/media.php */
2356         $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2357         $form_class = 'media-upload-form validate';
2358
2359         if ( get_user_setting('uploader') )
2360                 $form_class .= ' html-uploader';
2361
2362         $q = $_GET;
2363         $q['posts_per_page'] = 10;
2364         $q['paged'] = isset( $q['paged'] ) ? intval( $q['paged'] ) : 0;
2365         if ( $q['paged'] < 1 ) {
2366                 $q['paged'] = 1;
2367         }
2368         $q['offset'] = ( $q['paged'] - 1 ) * 10;
2369         if ( $q['offset'] < 1 ) {
2370                 $q['offset'] = 0;
2371         }
2372
2373         list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query( $q );
2374
2375 ?>
2376
2377 <form id="filter" method="get">
2378 <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
2379 <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
2380 <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" />
2381 <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" />
2382 <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" />
2383
2384 <p id="media-search" class="search-box">
2385         <label class="screen-reader-text" for="media-search-input"><?php _e('Search Media');?>:</label>
2386         <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" />
2387         <?php submit_button( __( 'Search Media' ), 'button', '', false ); ?>
2388 </p>
2389
2390 <ul class="subsubsub">
2391 <?php
2392 $type_links = array();
2393 $_num_posts = (array) wp_count_attachments();
2394 $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
2395 foreach ( $matches as $_type => $reals )
2396         foreach ( $reals as $real )
2397                 if ( isset($num_posts[$_type]) )
2398                         $num_posts[$_type] += $_num_posts[$real];
2399                 else
2400                         $num_posts[$_type] = $_num_posts[$real];
2401 // If available type specified by media button clicked, filter by that type
2402 if ( empty($_GET['post_mime_type']) && !empty($num_posts[$type]) ) {
2403         $_GET['post_mime_type'] = $type;
2404         list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
2405 }
2406 if ( empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all' )
2407         $class = ' class="current"';
2408 else
2409         $class = '';
2410 $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type'=>'all', 'paged'=>false, 'm'=>false))) . '"' . $class . '>' . __('All Types') . '</a>';
2411 foreach ( $post_mime_types as $mime_type => $label ) {
2412         $class = '';
2413
2414         if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
2415                 continue;
2416
2417         if ( isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
2418                 $class = ' class="current"';
2419
2420         $type_links[] = '<li><a href="' . esc_url(add_query_arg(array('post_mime_type'=>$mime_type, 'paged'=>false))) . '"' . $class . '>' . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), '<span id="' . $mime_type . '-counter">' . number_format_i18n( $num_posts[$mime_type] ) . '</span>') . '</a>';
2421 }
2422 /**
2423  * Filters the media upload mime type list items.
2424  *
2425  * Returned values should begin with an `<li>` tag.
2426  *
2427  * @since 3.1.0
2428  *
2429  * @param array $type_links An array of list items containing mime type link HTML.
2430  */
2431 echo implode(' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>';
2432 unset($type_links);
2433 ?>
2434 </ul>
2435
2436 <div class="tablenav">
2437
2438 <?php
2439 $page_links = paginate_links( array(
2440         'base' => add_query_arg( 'paged', '%#%' ),
2441         'format' => '',
2442         'prev_text' => __('&laquo;'),
2443         'next_text' => __('&raquo;'),
2444         'total' => ceil($wp_query->found_posts / 10),
2445         'current' => $q['paged'],
2446 ));
2447
2448 if ( $page_links )
2449         echo "<div class='tablenav-pages'>$page_links</div>";
2450 ?>
2451
2452 <div class="alignleft actions">
2453 <?php
2454
2455 $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC";
2456
2457 $arc_result = $wpdb->get_results( $arc_query );
2458
2459 $month_count = count($arc_result);
2460 $selected_month = isset( $_GET['m'] ) ? $_GET['m'] : 0;
2461
2462 if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { ?>
2463 <select name='m'>
2464 <option<?php selected( $selected_month, 0 ); ?> value='0'><?php _e( 'All dates' ); ?></option>
2465 <?php
2466 foreach ($arc_result as $arc_row) {
2467         if ( $arc_row->yyear == 0 )
2468                 continue;
2469         $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );
2470
2471         if ( $arc_row->yyear . $arc_row->mmonth == $selected_month )
2472                 $default = ' selected="selected"';
2473         else
2474                 $default = '';
2475
2476         echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>";
2477         echo esc_html( $wp_locale->get_month($arc_row->mmonth) . " $arc_row->yyear" );
2478         echo "</option>\n";
2479 }
2480 ?>
2481 </select>
2482 <?php } ?>
2483
2484 <?php submit_button( __( 'Filter &#187;' ), 'button', 'post-query-submit', false ); ?>
2485
2486 </div>
2487
2488 <br class="clear" />
2489 </div>
2490 </form>
2491
2492 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="library-form">
2493
2494 <?php wp_nonce_field('media-form'); ?>
2495 <?php //media_upload_form( $errors ); ?>
2496
2497 <script type="text/javascript">
2498 <!--
2499 jQuery(function($){
2500         var preloaded = $(".media-item.preloaded");
2501         if ( preloaded.length > 0 ) {
2502                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2503                 updateMediaForm();
2504         }
2505 });
2506 -->
2507 </script>
2508
2509 <div id="media-items">
2510 <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?>
2511 <?php echo get_media_items(null, $errors); ?>
2512 </div>
2513 <p class="ml-submit">
2514 <?php submit_button( __( 'Save all changes' ), 'button savebutton', 'save', false ); ?>
2515 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2516 </p>
2517 </form>
2518 <?php
2519 }
2520
2521 /**
2522  * Creates the form for external url
2523  *
2524  * @since 2.7.0
2525  *
2526  * @param string $default_view
2527  * @return string the form html
2528  */
2529 function wp_media_insert_url_form( $default_view = 'image' ) {
2530         /** This filter is documented in wp-admin/includes/media.php */
2531         if ( ! apply_filters( 'disable_captions', '' ) ) {
2532                 $caption = '
2533                 <tr class="image-only">
2534                         <th scope="row" class="label">
2535                                 <label for="caption"><span class="alignleft">' . __('Image Caption') . '</span></label>
2536                         </th>
2537                         <td class="field"><textarea id="caption" name="caption"></textarea></td>
2538                 </tr>
2539 ';
2540         } else {
2541                 $caption = '';
2542         }
2543
2544         $default_align = get_option('image_default_align');
2545         if ( empty($default_align) )
2546                 $default_align = 'none';
2547
2548         if ( 'image' == $default_view ) {
2549                 $view = 'image-only';
2550                 $table_class = '';
2551         } else {
2552                 $view = $table_class = 'not-image';
2553         }
2554
2555         return '
2556         <p class="media-types"><label><input type="radio" name="media_type" value="image" id="image-only"' . checked( 'image-only', $view, false ) . ' /> ' . __( 'Image' ) . '</label> &nbsp; &nbsp; <label><input type="radio" name="media_type" value="generic" id="not-image"' . checked( 'not-image', $view, false ) . ' /> ' . __( 'Audio, Video, or Other File' ) . '</label></p>
2557         <p class="media-types media-types-required-info">' . sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) . '</p>
2558         <table class="describe ' . $table_class . '"><tbody>
2559                 <tr>
2560                         <th scope="row" class="label" style="width:130px;">
2561                                 <label for="src"><span class="alignleft">' . __( 'URL' ) . '</span> <span class="required">*</span></label>
2562                                 <span class="alignright" id="status_img"></span>
2563                         </th>
2564                         <td class="field"><input id="src" name="src" value="" type="text" required aria-required="true" onblur="addExtImage.getImageData()" /></td>
2565                 </tr>
2566
2567                 <tr>
2568                         <th scope="row" class="label">
2569                                 <label for="title"><span class="alignleft">' . __( 'Title' ) . '</span> <span class="required">*</span></label>
2570                         </th>
2571                         <td class="field"><input id="title" name="title" value="" type="text" required aria-required="true" /></td>
2572                 </tr>
2573
2574                 <tr class="not-image"><td></td><td><p class="help">' . __('Link text, e.g. &#8220;Ransom Demands (PDF)&#8221;') . '</p></td></tr>
2575
2576                 <tr class="image-only">
2577                         <th scope="row" class="label">
2578                                 <label for="alt"><span class="alignleft">' . __('Alternative Text') . '</span></label>
2579                         </th>
2580                         <td class="field"><input id="alt" name="alt" value="" type="text" aria-required="true" />
2581                         <p class="help">' . __('Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;') . '</p></td>
2582                 </tr>
2583                 ' . $caption . '
2584                 <tr class="align image-only">
2585                         <th scope="row" class="label"><p><label for="align">' . __('Alignment') . '</label></p></th>
2586                         <td class="field">
2587                                 <input name="align" id="align-none" value="none" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'none' ? ' checked="checked"' : '').' />
2588                                 <label for="align-none" class="align image-align-none-label">' . __('None') . '</label>
2589                                 <input name="align" id="align-left" value="left" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'left' ? ' checked="checked"' : '').' />
2590                                 <label for="align-left" class="align image-align-left-label">' . __('Left') . '</label>
2591                                 <input name="align" id="align-center" value="center" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'center' ? ' checked="checked"' : '').' />
2592                                 <label for="align-center" class="align image-align-center-label">' . __('Center') . '</label>
2593                                 <input name="align" id="align-right" value="right" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ($default_align == 'right' ? ' checked="checked"' : '').' />
2594                                 <label for="align-right" class="align image-align-right-label">' . __('Right') . '</label>
2595                         </td>
2596                 </tr>
2597
2598                 <tr class="image-only">
2599                         <th scope="row" class="label">
2600                                 <label for="url"><span class="alignleft">' . __('Link Image To:') . '</span></label>
2601                         </th>
2602                         <td class="field"><input id="url" name="url" value="" type="text" /><br />
2603
2604                         <button type="button" class="button" value="" onclick="document.forms[0].url.value=null">' . __('None') . '</button>
2605                         <button type="button" class="button" value="" onclick="document.forms[0].url.value=document.forms[0].src.value">' . __('Link to image') . '</button>
2606                         <p class="help">' . __('Enter a link URL or click above for presets.') . '</p></td>
2607                 </tr>
2608                 <tr class="image-only">
2609                         <td></td>
2610                         <td>
2611                                 <input type="button" class="button" id="go_button" style="color:#bbb;" onclick="addExtImage.insert()" value="' . esc_attr__('Insert into Post') . '" />
2612                         </td>
2613                 </tr>
2614                 <tr class="not-image">
2615                         <td></td>
2616                         <td>
2617                                 ' . get_submit_button( __( 'Insert into Post' ), 'button', 'insertonlybutton', false ) . '
2618                         </td>
2619                 </tr>
2620         </tbody></table>
2621 ';
2622
2623 }
2624
2625 /**
2626  * Displays the multi-file uploader message.
2627  *
2628  * @since 2.6.0
2629  *
2630  * @global int $post_ID
2631  */
2632 function media_upload_flash_bypass() {
2633         $browser_uploader = admin_url( 'media-new.php?browser-uploader' );
2634
2635         if ( $post = get_post() )
2636                 $browser_uploader .= '&amp;post_id=' . intval( $post->ID );
2637         elseif ( ! empty( $GLOBALS['post_ID'] ) )
2638                 $browser_uploader .= '&amp;post_id=' . intval( $GLOBALS['post_ID'] );
2639
2640         ?>
2641         <p class="upload-flash-bypass">
2642         <?php printf( __( 'You are using the multi-file uploader. Problems? Try the <a href="%1$s" target="%2$s">browser uploader</a> instead.' ), $browser_uploader, '_blank' ); ?>
2643         </p>
2644         <?php
2645 }
2646
2647 /**
2648  * Displays the browser's built-in uploader message.
2649  *
2650  * @since 2.6.0
2651  */
2652 function media_upload_html_bypass() {
2653         ?>
2654         <p class="upload-html-bypass hide-if-no-js">
2655            <?php _e('You are using the browser&#8217;s built-in file uploader. The WordPress uploader includes multiple file selection and drag and drop capability. <a href="#">Switch to the multi-file uploader</a>.'); ?>
2656         </p>
2657         <?php
2658 }
2659
2660 /**
2661  * Used to display a "After a file has been uploaded..." help message.
2662  *
2663  * @since 3.3.0
2664  */
2665 function media_upload_text_after() {}
2666
2667 /**
2668  * Displays the checkbox to scale images.
2669  *
2670  * @since 3.3.0
2671  */
2672 function media_upload_max_image_resize() {
2673         $checked = get_user_setting('upload_resize') ? ' checked="true"' : '';
2674         $a = $end = '';
2675
2676         if ( current_user_can( 'manage_options' ) ) {
2677                 $a = '<a href="' . esc_url( admin_url( 'options-media.php' ) ) . '" target="_blank">';
2678                 $end = '</a>';
2679         }
2680 ?>
2681 <p class="hide-if-no-js"><label>
2682 <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> />
2683 <?php
2684         /* translators: %1$s is link start tag, %2$s is link end tag, %3$d is width, %4$d is height*/
2685         printf( __( 'Scale images to match the large size selected in %1$simage options%2$s (%3$d &times; %4$d).' ), $a, $end, (int) get_option( 'large_size_w', '1024' ), (int) get_option( 'large_size_h', '1024' ) );
2686 ?>
2687 </label></p>
2688 <?php
2689 }
2690
2691 /**
2692  * Displays the out of storage quota message in Multisite.
2693  *
2694  * @since 3.5.0
2695  */
2696 function multisite_over_quota_message() {
2697         echo '<p>' . sprintf( __( 'Sorry, you have used all of your storage quota of %s MB.' ), get_space_allowed() ) . '</p>';
2698 }
2699
2700 /**
2701  * Displays the image and editor in the post editor
2702  *
2703  * @since 3.5.0
2704  *
2705  * @param WP_Post $post A post object.
2706  */
2707 function edit_form_image_editor( $post ) {
2708         $open = isset( $_GET['image-editor'] );
2709         if ( $open )
2710                 require_once ABSPATH . 'wp-admin/includes/image-edit.php';
2711
2712         $thumb_url = false;
2713         if ( $attachment_id = intval( $post->ID ) )
2714                 $thumb_url = wp_get_attachment_image_src( $attachment_id, array( 900, 450 ), true );
2715
2716         $alt_text = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
2717
2718         $att_url = wp_get_attachment_url( $post->ID ); ?>
2719         <div class="wp_attachment_holder wp-clearfix">
2720         <?php
2721         if ( wp_attachment_is_image( $post->ID ) ) :
2722                 $image_edit_button = '';
2723                 if ( wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
2724                         $nonce = wp_create_nonce( "image_editor-$post->ID" );
2725                         $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>";
2726                 }
2727         ?>
2728
2729                 <div class="imgedit-response" id="imgedit-response-<?php echo $attachment_id; ?>"></div>
2730
2731                 <div<?php if ( $open ) echo ' style="display:none"'; ?> class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
2732                         <p id="thumbnail-head-<?php echo $attachment_id; ?>"><img class="thumbnail" src="<?php echo set_url_scheme( $thumb_url[0] ); ?>" style="max-width:100%" alt="" /></p>
2733                         <p><?php echo $image_edit_button; ?></p>
2734                 </div>
2735                 <div<?php if ( ! $open ) echo ' style="display:none"'; ?> class="image-editor" id="image-editor-<?php echo $attachment_id; ?>">
2736                         <?php if ( $open ) wp_image_editor( $attachment_id ); ?>
2737                 </div>
2738         <?php
2739         elseif ( $attachment_id && wp_attachment_is( 'audio', $post ) ):
2740
2741                 wp_maybe_generate_attachment_metadata( $post );
2742
2743                 echo wp_audio_shortcode( array( 'src' => $att_url ) );
2744
2745         elseif ( $attachment_id && wp_attachment_is( 'video', $post ) ):
2746
2747                 wp_maybe_generate_attachment_metadata( $post );
2748
2749                 $meta = wp_get_attachment_metadata( $attachment_id );
2750                 $w = ! empty( $meta['width'] ) ? min( $meta['width'], 640 ) : 0;
2751                 $h = ! empty( $meta['height'] ) ? $meta['height'] : 0;
2752                 if ( $h && $w < $meta['width'] ) {
2753                         $h = round( ( $meta['height'] * $w ) / $meta['width'] );
2754                 }
2755
2756                 $attr = array( 'src' => $att_url );
2757                 if ( ! empty( $w ) && ! empty( $h ) ) {
2758                         $attr['width'] = $w;
2759                         $attr['height'] = $h;
2760                 }
2761
2762                 $thumb_id = get_post_thumbnail_id( $attachment_id );
2763                 if ( ! empty( $thumb_id ) ) {
2764                         $attr['poster'] = wp_get_attachment_url( $thumb_id );
2765                 }
2766
2767                 echo wp_video_shortcode( $attr );
2768
2769         else :
2770
2771                 /**
2772                  * Fires when an attachment type can't be rendered in the edit form.
2773                  *
2774                  * @since 4.6.0
2775                  *
2776                  * @param WP_Post $post A post object.
2777                  */
2778                 do_action( 'wp_edit_form_attachment_display', $post );
2779
2780         endif; ?>
2781         </div>
2782         <div class="wp_attachment_details edit-form-section">
2783                 <p>
2784                         <label for="attachment_caption"><strong><?php _e( 'Caption' ); ?></strong></label><br />
2785                         <textarea class="widefat" name="excerpt" id="attachment_caption"><?php echo $post->post_excerpt; ?></textarea>
2786                 </p>
2787
2788
2789         <?php if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) : ?>
2790                 <p>
2791                         <label for="attachment_alt"><strong><?php _e( 'Alternative Text' ); ?></strong></label><br />
2792                         <input type="text" class="widefat" name="_wp_attachment_image_alt" id="attachment_alt" value="<?php echo esc_attr( $alt_text ); ?>" />
2793                 </p>
2794         <?php endif; ?>
2795
2796         <?php
2797                 $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
2798                 $editor_args = array(
2799                         'textarea_name' => 'content',
2800                         'textarea_rows' => 5,
2801                         'media_buttons' => false,
2802                         'tinymce' => false,
2803                         'quicktags' => $quicktags_settings,
2804                 );
2805         ?>
2806
2807         <label for="attachment_content"><strong><?php _e( 'Description' ); ?></strong><?php
2808         if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
2809                 echo ': ' . __( 'Displayed on attachment pages.' );
2810         } ?></label>
2811         <?php wp_editor( $post->post_content, 'attachment_content', $editor_args ); ?>
2812
2813         </div>
2814         <?php
2815         $extras = get_compat_media_markup( $post->ID );
2816         echo $extras['item'];
2817         echo '<input type="hidden" id="image-edit-context" value="edit-attachment" />' . "\n";
2818 }
2819
2820 /**
2821  * Displays non-editable attachment metadata in the publish meta box.
2822  *
2823  * @since 3.5.0
2824  */
2825 function attachment_submitbox_metadata() {
2826         $post = get_post();
2827
2828         $file = get_attached_file( $post->ID );
2829         $filename = esc_html( wp_basename( $file ) );
2830
2831         $media_dims = '';
2832         $meta = wp_get_attachment_metadata( $post->ID );
2833         if ( isset( $meta['width'], $meta['height'] ) )
2834                 $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
2835         /** This filter is documented in wp-admin/includes/media.php */
2836         $media_dims = apply_filters( 'media_meta', $media_dims, $post );
2837
2838         $att_url = wp_get_attachment_url( $post->ID );
2839 ?>
2840         <div class="misc-pub-section misc-pub-attachment">
2841                 <label for="attachment_url"><?php _e( 'File URL:' ); ?></label>
2842                 <input type="text" class="widefat urlfield" readonly="readonly" name="attachment_url" id="attachment_url" value="<?php echo esc_attr( $att_url ); ?>" />
2843         </div>
2844         <div class="misc-pub-section misc-pub-filename">
2845                 <?php _e( 'File name:' ); ?> <strong><?php echo $filename; ?></strong>
2846         </div>
2847         <div class="misc-pub-section misc-pub-filetype">
2848                 <?php _e( 'File type:' ); ?> <strong><?php
2849                         if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) {
2850                                 echo esc_html( strtoupper( $matches[1] ) );
2851                                 list( $mime_type ) = explode( '/', $post->post_mime_type );
2852                                 if ( $mime_type !== 'image' && ! empty( $meta['mime_type'] ) ) {
2853                                         if ( $meta['mime_type'] !== "$mime_type/" . strtolower( $matches[1] ) ) {
2854                                                 echo ' (' . $meta['mime_type'] . ')';
2855                                         }
2856                                 }
2857                         } else {
2858                                 echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) );
2859                         }
2860                 ?></strong>
2861         </div>
2862
2863         <?php
2864                 $file_size = false;
2865
2866                 if ( isset( $meta['filesize'] ) )
2867                         $file_size = $meta['filesize'];
2868                 elseif ( file_exists( $file ) )
2869                         $file_size = filesize( $file );
2870
2871                 if ( ! empty( $file_size ) ) : ?>
2872                         <div class="misc-pub-section misc-pub-filesize">
2873                                 <?php _e( 'File size:' ); ?> <strong><?php echo size_format( $file_size ); ?></strong>
2874                         </div>
2875                         <?php
2876                 endif;
2877
2878         if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
2879
2880                 /**
2881                  * Filters the audio and video metadata fields to be shown in the publish meta box.
2882                  *
2883                  * The key for each item in the array should correspond to an attachment
2884                  * metadata key, and the value should be the desired label.
2885                  *
2886                  * @since 3.7.0
2887                  *
2888                  * @param array $fields An array of the attachment metadata keys and labels.
2889                  */
2890                 $fields = apply_filters( 'media_submitbox_misc_sections', array(
2891                         'length_formatted' => __( 'Length:' ),
2892                         'bitrate'          => __( 'Bitrate:' ),
2893                 ) );
2894
2895                 foreach ( $fields as $key => $label ) {
2896                         if ( empty( $meta[ $key ] ) ) {
2897                                 continue;
2898                         }
2899         ?>
2900                 <div class="misc-pub-section misc-pub-mime-meta misc-pub-<?php echo sanitize_html_class( $key ); ?>">
2901                         <?php echo $label ?> <strong><?php
2902                                 switch ( $key ) {
2903                                         case 'bitrate' :
2904                                                 echo round( $meta['bitrate'] / 1000 ) . 'kb/s';
2905                                                 if ( ! empty( $meta['bitrate_mode'] ) ) {
2906                                                         echo ' ' . strtoupper( esc_html( $meta['bitrate_mode'] ) );
2907                                                 }
2908                                                 break;
2909                                         default:
2910                                                 echo esc_html( $meta[ $key ] );
2911                                                 break;
2912                                 }
2913                         ?></strong>
2914                 </div>
2915         <?php
2916                 }
2917
2918                 /**
2919                  * Filters the audio attachment metadata fields to be shown in the publish meta box.
2920                  *
2921                  * The key for each item in the array should correspond to an attachment
2922                  * metadata key, and the value should be the desired label.
2923                  *
2924                  * @since 3.7.0
2925                  *
2926                  * @param array $fields An array of the attachment metadata keys and labels.
2927                  */
2928                 $audio_fields = apply_filters( 'audio_submitbox_misc_sections', array(
2929                         'dataformat' => __( 'Audio Format:' ),
2930                         'codec'      => __( 'Audio Codec:' )
2931                 ) );
2932
2933                 foreach ( $audio_fields as $key => $label ) {
2934                         if ( empty( $meta['audio'][ $key ] ) ) {
2935                                 continue;
2936                         }
2937         ?>
2938                 <div class="misc-pub-section misc-pub-audio misc-pub-<?php echo sanitize_html_class( $key ); ?>">
2939                         <?php echo $label; ?> <strong><?php echo esc_html( $meta['audio'][$key] ); ?></strong>
2940                 </div>
2941         <?php
2942                 }
2943
2944         }
2945
2946         if ( $media_dims ) : ?>
2947         <div class="misc-pub-section misc-pub-dimensions">
2948                 <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong>
2949         </div>
2950 <?php
2951         endif;
2952 }
2953
2954 /**
2955  * Parse ID3v2, ID3v1, and getID3 comments to extract usable data
2956  *
2957  * @since 3.6.0
2958  *
2959  * @param array $metadata An existing array with data
2960  * @param array $data Data supplied by ID3 tags
2961  */
2962 function wp_add_id3_tag_data( &$metadata, $data ) {
2963         foreach ( array( 'id3v2', 'id3v1' ) as $version ) {
2964                 if ( ! empty( $data[$version]['comments'] ) ) {
2965                         foreach ( $data[$version]['comments'] as $key => $list ) {
2966                                 if ( 'length' !== $key && ! empty( $list ) ) {
2967                                         $metadata[$key] = reset( $list );
2968                                         // Fix bug in byte stream analysis.
2969                                         if ( 'terms_of_use' === $key && 0 === strpos( $metadata[$key], 'yright notice.' ) )
2970                                                 $metadata[$key] = 'Cop' . $metadata[$key];
2971                                 }
2972                         }
2973                         break;
2974                 }
2975         }
2976
2977         if ( ! empty( $data['id3v2']['APIC'] ) ) {
2978                 $image = reset( $data['id3v2']['APIC']);
2979                 if ( ! empty( $image['data'] ) ) {
2980                         $metadata['image'] = array(
2981                                 'data' => $image['data'],
2982                                 'mime' => $image['image_mime'],
2983                                 'width' => $image['image_width'],
2984                                 'height' => $image['image_height']
2985                         );
2986                 }
2987         } elseif ( ! empty( $data['comments']['picture'] ) ) {
2988                 $image = reset( $data['comments']['picture'] );
2989                 if ( ! empty( $image['data'] ) ) {
2990                         $metadata['image'] = array(
2991                                 'data' => $image['data'],
2992                                 'mime' => $image['image_mime']
2993                         );
2994                 }
2995         }
2996 }
2997
2998 /**
2999  * Retrieve metadata from a video file's ID3 tags
3000  *
3001  * @since 3.6.0
3002  *
3003  * @param string $file Path to file.
3004  * @return array|bool Returns array of metadata, if found.
3005  */
3006 function wp_read_video_metadata( $file ) {
3007         if ( ! file_exists( $file ) ) {
3008                 return false;
3009         }
3010
3011         $metadata = array();
3012
3013         if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3014                 define( 'GETID3_TEMP_DIR', get_temp_dir() );
3015         }
3016
3017         if ( ! class_exists( 'getID3', false ) ) {
3018                 require( ABSPATH . WPINC . '/ID3/getid3.php' );
3019         }
3020         $id3 = new getID3();
3021         $data = $id3->analyze( $file );
3022
3023         if ( isset( $data['video']['lossless'] ) )
3024                 $metadata['lossless'] = $data['video']['lossless'];
3025         if ( ! empty( $data['video']['bitrate'] ) )
3026                 $metadata['bitrate'] = (int) $data['video']['bitrate'];
3027         if ( ! empty( $data['video']['bitrate_mode'] ) )
3028                 $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
3029         if ( ! empty( $data['filesize'] ) )
3030                 $metadata['filesize'] = (int) $data['filesize'];
3031         if ( ! empty( $data['mime_type'] ) )
3032                 $metadata['mime_type'] = $data['mime_type'];
3033         if ( ! empty( $data['playtime_seconds'] ) )
3034                 $metadata['length'] = (int) round( $data['playtime_seconds'] );
3035         if ( ! empty( $data['playtime_string'] ) )
3036                 $metadata['length_formatted'] = $data['playtime_string'];
3037         if ( ! empty( $data['video']['resolution_x'] ) )
3038                 $metadata['width'] = (int) $data['video']['resolution_x'];
3039         if ( ! empty( $data['video']['resolution_y'] ) )
3040                 $metadata['height'] = (int) $data['video']['resolution_y'];
3041         if ( ! empty( $data['fileformat'] ) )
3042                 $metadata['fileformat'] = $data['fileformat'];
3043         if ( ! empty( $data['video']['dataformat'] ) )
3044                 $metadata['dataformat'] = $data['video']['dataformat'];
3045         if ( ! empty( $data['video']['encoder'] ) )
3046                 $metadata['encoder'] = $data['video']['encoder'];
3047         if ( ! empty( $data['video']['codec'] ) )
3048                 $metadata['codec'] = $data['video']['codec'];
3049
3050         if ( ! empty( $data['audio'] ) ) {
3051                 unset( $data['audio']['streams'] );
3052                 $metadata['audio'] = $data['audio'];
3053         }
3054
3055         wp_add_id3_tag_data( $metadata, $data );
3056
3057         return $metadata;
3058 }
3059
3060 /**
3061  * Retrieve metadata from a audio file's ID3 tags
3062  *
3063  * @since 3.6.0
3064  *
3065  * @param string $file Path to file.
3066  * @return array|bool Returns array of metadata, if found.
3067  */
3068 function wp_read_audio_metadata( $file ) {
3069         if ( ! file_exists( $file ) ) {
3070                 return false;
3071         }
3072         $metadata = array();
3073
3074         if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3075                 define( 'GETID3_TEMP_DIR', get_temp_dir() );
3076         }
3077
3078         if ( ! class_exists( 'getID3', false ) ) {
3079                 require( ABSPATH . WPINC . '/ID3/getid3.php' );
3080         }
3081         $id3 = new getID3();
3082         $data = $id3->analyze( $file );
3083
3084         if ( ! empty( $data['audio'] ) ) {
3085                 unset( $data['audio']['streams'] );
3086                 $metadata = $data['audio'];
3087         }
3088
3089         if ( ! empty( $data['fileformat'] ) )
3090                 $metadata['fileformat'] = $data['fileformat'];
3091         if ( ! empty( $data['filesize'] ) )
3092                 $metadata['filesize'] = (int) $data['filesize'];
3093         if ( ! empty( $data['mime_type'] ) )
3094                 $metadata['mime_type'] = $data['mime_type'];
3095         if ( ! empty( $data['playtime_seconds'] ) )
3096                 $metadata['length'] = (int) round( $data['playtime_seconds'] );
3097         if ( ! empty( $data['playtime_string'] ) )
3098                 $metadata['length_formatted'] = $data['playtime_string'];
3099
3100         wp_add_id3_tag_data( $metadata, $data );
3101
3102         return $metadata;
3103 }
3104
3105 /**
3106  * Encapsulate logic for Attach/Detach actions
3107  *
3108  * @since 4.2.0
3109  *
3110  * @global wpdb $wpdb WordPress database abstraction object.
3111  *
3112  * @param int    $parent_id Attachment parent ID.
3113  * @param string $action    Optional. Attach/detach action. Accepts 'attach' or 'detach'.
3114  *                          Default 'attach'.
3115  */
3116 function wp_media_attach_action( $parent_id, $action = 'attach' ) {
3117         global $wpdb;
3118
3119         if ( ! $parent_id ) {
3120                 return;
3121         }
3122
3123         if ( ! current_user_can( 'edit_post', $parent_id ) ) {
3124                 wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
3125         }
3126         $ids = array();
3127         foreach ( (array) $_REQUEST['media'] as $att_id ) {
3128                 $att_id = (int) $att_id;
3129
3130                 if ( ! current_user_can( 'edit_post', $att_id ) ) {
3131                         continue;
3132                 }
3133
3134                 $ids[] = $att_id;
3135         }
3136
3137         if ( ! empty( $ids ) ) {
3138                 $ids_string = implode( ',', $ids );
3139                 if ( 'attach' === $action ) {
3140                         $result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
3141                 } else {
3142                         $result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
3143                 }
3144
3145                 foreach ( $ids as $att_id ) {
3146                         clean_attachment_cache( $att_id );
3147                 }
3148         }
3149
3150         if ( isset( $result ) ) {
3151                 $location = 'upload.php';
3152                 if ( $referer = wp_get_referer() ) {
3153                         if ( false !== strpos( $referer, 'upload.php' ) ) {
3154                                 $location = remove_query_arg( array( 'attached', 'detach' ), $referer );
3155                         }
3156                 }
3157
3158                 $key = 'attach' === $action ? 'attached' : 'detach';
3159                 $location = add_query_arg( array( $key => $result ), $location );
3160                 wp_redirect( $location );
3161                 exit;
3162         }
3163 }