[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sat Dec 16 01:00:03 2017 Cross-referenced by PHPXref 0.7.1