[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/includes/ -> media.php (source)

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


Generated: Sat Nov 25 01:00:03 2017 Cross-referenced by PHPXref 0.7.1