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