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


Generated: Mon Jul 27 03:55:52 2015 Hosted by follow the white rabbit.