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