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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7