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


Generated: Wed Aug 16 01:00:03 2017 Cross-referenced by PHPXref 0.7.1