home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress2 / wp-admin / includes / media.php < prev    next >
Encoding:
PHP Script  |  2018-01-15  |  103.8 KB  |  3,267 lines

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