[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7