[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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 string[] 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 string[] $_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 = 1 === $instance ? ' 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_deprecated( 'media_buttons_context', array( '' ), '3.5.0', 'media_buttons' );
 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 ( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) !== $image_alt ) {
 771                      $image_alt = wp_strip_all_tags( $image_alt, true );
 772  
 773                      // update_post_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'] ) && 'type_url' === $_GET['tab'] ) {
 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   * @since 5.4.0 The original URL of the attachment is stored in the `_source_url`
 971   *              post meta value.
 972   *
 973   * @param string $file    The URL of the image to download.
 974   * @param int    $post_id Optional. The post ID the media is to be associated with.
 975   * @param string $desc    Optional. Description of the image.
 976   * @param string $return  Optional. Accepts 'html' (image tag html) or 'src' (URL),
 977   *                        or 'id' (attachment ID). Default 'html'.
 978   * @return string|WP_Error Populated HTML img tag on success, WP_Error object otherwise.
 979   */
 980  function media_sideload_image( $file, $post_id = 0, $desc = null, $return = 'html' ) {
 981      if ( ! empty( $file ) ) {
 982  
 983          // Set variables for storage, fix file filename for query strings.
 984          preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
 985  
 986          if ( ! $matches ) {
 987              return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL.' ) );
 988          }
 989  
 990          $file_array         = array();
 991          $file_array['name'] = wp_basename( $matches[0] );
 992  
 993          // Download file to temp location.
 994          $file_array['tmp_name'] = download_url( $file );
 995  
 996          // If error storing temporarily, return the error.
 997          if ( is_wp_error( $file_array['tmp_name'] ) ) {
 998              return $file_array['tmp_name'];
 999          }
1000  
1001          // Do the validation and storage stuff.
1002          $id = media_handle_sideload( $file_array, $post_id, $desc );
1003  
1004          // If error storing permanently, unlink.
1005          if ( is_wp_error( $id ) ) {
1006              @unlink( $file_array['tmp_name'] );
1007              return $id;
1008          }
1009  
1010          // Store the original attachment source in meta.
1011          add_post_meta( $id, '_source_url', $file );
1012  
1013          // If attachment id was requested, return it.
1014          if ( 'id' === $return ) {
1015              return $id;
1016          }
1017  
1018          $src = wp_get_attachment_url( $id );
1019      }
1020  
1021      // Finally, check to make sure the file has been saved, then return the HTML.
1022      if ( ! empty( $src ) ) {
1023          if ( 'src' === $return ) {
1024              return $src;
1025          }
1026  
1027          $alt  = isset( $desc ) ? esc_attr( $desc ) : '';
1028          $html = "<img src='$src' alt='$alt' />";
1029  
1030          return $html;
1031      } else {
1032          return new WP_Error( 'image_sideload_failed' );
1033      }
1034  }
1035  
1036  /**
1037   * Retrieves the legacy media uploader form in an iframe.
1038   *
1039   * @since 2.5.0
1040   *
1041   * @return string|null
1042   */
1043  function media_upload_gallery() {
1044      $errors = array();
1045  
1046      if ( ! empty( $_POST ) ) {
1047          $return = media_upload_form_handler();
1048  
1049          if ( is_string( $return ) ) {
1050              return $return;
1051          }
1052  
1053          if ( is_array( $return ) ) {
1054              $errors = $return;
1055          }
1056      }
1057  
1058      wp_enqueue_script( 'admin-gallery' );
1059      return wp_iframe( 'media_upload_gallery_form', $errors );
1060  }
1061  
1062  /**
1063   * Retrieves the legacy media library form in an iframe.
1064   *
1065   * @since 2.5.0
1066   *
1067   * @return string|null
1068   */
1069  function media_upload_library() {
1070      $errors = array();
1071  
1072      if ( ! empty( $_POST ) ) {
1073          $return = media_upload_form_handler();
1074  
1075          if ( is_string( $return ) ) {
1076              return $return;
1077          }
1078          if ( is_array( $return ) ) {
1079              $errors = $return;
1080          }
1081      }
1082  
1083      return wp_iframe( 'media_upload_library_form', $errors );
1084  }
1085  
1086  /**
1087   * Retrieve HTML for the image alignment radio buttons with the specified one checked.
1088   *
1089   * @since 2.7.0
1090   *
1091   * @param WP_Post $post
1092   * @param string $checked
1093   * @return string
1094   */
1095  function image_align_input_fields( $post, $checked = '' ) {
1096  
1097      if ( empty( $checked ) ) {
1098          $checked = get_user_setting( 'align', 'none' );
1099      }
1100  
1101      $alignments = array(
1102          'none'   => __( 'None' ),
1103          'left'   => __( 'Left' ),
1104          'center' => __( 'Center' ),
1105          'right'  => __( 'Right' ),
1106      );
1107  
1108      if ( ! array_key_exists( (string) $checked, $alignments ) ) {
1109          $checked = 'none';
1110      }
1111  
1112      $out = array();
1113  
1114      foreach ( $alignments as $name => $label ) {
1115          $name  = esc_attr( $name );
1116          $out[] = "<input type='radio' name='attachments[{$post->ID}][align]' id='image-align-{$name}-{$post->ID}' value='$name'" .
1117              ( $checked == $name ? " checked='checked'" : '' ) .
1118              " /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
1119      }
1120  
1121      return join( "\n", $out );
1122  }
1123  
1124  /**
1125   * Retrieve HTML for the size radio buttons with the specified one checked.
1126   *
1127   * @since 2.7.0
1128   *
1129   * @param WP_Post $post
1130   * @param bool|string $check
1131   * @return array
1132   */
1133  function image_size_input_fields( $post, $check = '' ) {
1134      /**
1135       * Filters the names and labels of the default image sizes.
1136       *
1137       * @since 3.3.0
1138       *
1139       * @param string[] $size_names Array of image size labels keyed by their name. Default values
1140       *                             include 'Thumbnail', 'Medium', 'Large', and 'Full Size'.
1141       */
1142      $size_names = apply_filters(
1143          'image_size_names_choose',
1144          array(
1145              'thumbnail' => __( 'Thumbnail' ),
1146              'medium'    => __( 'Medium' ),
1147              'large'     => __( 'Large' ),
1148              'full'      => __( 'Full Size' ),
1149          )
1150      );
1151  
1152      if ( empty( $check ) ) {
1153          $check = get_user_setting( 'imgsize', 'medium' );
1154      }
1155  
1156      $out = array();
1157  
1158      foreach ( $size_names as $size => $label ) {
1159          $downsize = image_downsize( $post->ID, $size );
1160          $checked  = '';
1161  
1162          // Is this size selectable?
1163          $enabled = ( $downsize[3] || 'full' == $size );
1164          $css_id  = "image-size-{$size}-{$post->ID}";
1165  
1166          // If this size is the default but that's not available, don't select it.
1167          if ( $size == $check ) {
1168              if ( $enabled ) {
1169                  $checked = " checked='checked'";
1170              } else {
1171                  $check = '';
1172              }
1173          } elseif ( ! $check && $enabled && 'thumbnail' != $size ) {
1174              /*
1175               * If $check is not enabled, default to the first available size
1176               * that's bigger than a thumbnail.
1177               */
1178              $check   = $size;
1179              $checked = " checked='checked'";
1180          }
1181  
1182          $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 />";
1183  
1184          $html .= "<label for='{$css_id}'>$label</label>";
1185  
1186          // Only show the dimensions if that choice is available.
1187          if ( $enabled ) {
1188              $html .= " <label for='{$css_id}' class='help'>" . sprintf( '(%d&nbsp;&times;&nbsp;%d)', $downsize[1], $downsize[2] ) . '</label>';
1189          }
1190          $html .= '</div>';
1191  
1192          $out[] = $html;
1193      }
1194  
1195      return array(
1196          'label' => __( 'Size' ),
1197          'input' => 'html',
1198          'html'  => join( "\n", $out ),
1199      );
1200  }
1201  
1202  /**
1203   * Retrieve HTML for the Link URL buttons with the default link type as specified.
1204   *
1205   * @since 2.7.0
1206   *
1207   * @param WP_Post $post
1208   * @param string $url_type
1209   * @return string
1210   */
1211  function image_link_input_fields( $post, $url_type = '' ) {
1212  
1213      $file = wp_get_attachment_url( $post->ID );
1214      $link = get_attachment_link( $post->ID );
1215  
1216      if ( empty( $url_type ) ) {
1217          $url_type = get_user_setting( 'urlbutton', 'post' );
1218      }
1219  
1220      $url = '';
1221  
1222      if ( 'file' === $url_type ) {
1223          $url = $file;
1224      } elseif ( 'post' === $url_type ) {
1225          $url = $link;
1226      }
1227  
1228      return "
1229      <input type='text' class='text urlfield' name='attachments[$post->ID][url]' value='" . esc_attr( $url ) . "' /><br />
1230      <button type='button' class='button urlnone' data-link-url=''>" . __( 'None' ) . "</button>
1231      <button type='button' class='button urlfile' data-link-url='" . esc_attr( $file ) . "'>" . __( 'File URL' ) . "</button>
1232      <button type='button' class='button urlpost' data-link-url='" . esc_attr( $link ) . "'>" . __( 'Attachment Post URL' ) . '</button>
1233  ';
1234  }
1235  
1236  /**
1237   * Output a textarea element for inputting an attachment caption.
1238   *
1239   * @since 3.4.0
1240   *
1241   * @param WP_Post $edit_post Attachment WP_Post object.
1242   * @return string HTML markup for the textarea element.
1243   */
1244  function wp_caption_input_textarea( $edit_post ) {
1245      // Post data is already escaped.
1246      $name = "attachments[{$edit_post->ID}][post_excerpt]";
1247  
1248      return '<textarea name="' . $name . '" id="' . $name . '">' . $edit_post->post_excerpt . '</textarea>';
1249  }
1250  
1251  /**
1252   * Retrieves the image attachment fields to edit form fields.
1253   *
1254   * @since 2.5.0
1255   *
1256   * @param array $form_fields
1257   * @param object $post
1258   * @return array
1259   */
1260  function image_attachment_fields_to_edit( $form_fields, $post ) {
1261      return $form_fields;
1262  }
1263  
1264  /**
1265   * Retrieves the single non-image attachment fields to edit form fields.
1266   *
1267   * @since 2.5.0
1268   *
1269   * @param array   $form_fields An array of attachment form fields.
1270   * @param WP_Post $post        The WP_Post attachment object.
1271   * @return array Filtered attachment form fields.
1272   */
1273  function media_single_attachment_fields_to_edit( $form_fields, $post ) {
1274      unset( $form_fields['url'], $form_fields['align'], $form_fields['image-size'] );
1275      return $form_fields;
1276  }
1277  
1278  /**
1279   * Retrieves the post non-image attachment fields to edit form fields.
1280   *
1281   * @since 2.8.0
1282   *
1283   * @param array   $form_fields An array of attachment form fields.
1284   * @param WP_Post $post        The WP_Post attachment object.
1285   * @return array Filtered attachment form fields.
1286   */
1287  function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
1288      unset( $form_fields['image_url'] );
1289      return $form_fields;
1290  }
1291  
1292  /**
1293   * Filters input from media_upload_form_handler() and assigns a default
1294   * post_title from the file name if none supplied.
1295   *
1296   * Illustrates the use of the {@see 'attachment_fields_to_save'} filter
1297   * which can be used to add default values to any field before saving to DB.
1298   *
1299   * @since 2.5.0
1300   *
1301   * @param array $post       The WP_Post attachment object converted to an array.
1302   * @param array $attachment An array of attachment metadata.
1303   * @return array Filtered attachment post object.
1304   */
1305  function image_attachment_fields_to_save( $post, $attachment ) {
1306      if ( substr( $post['post_mime_type'], 0, 5 ) == 'image' ) {
1307          if ( strlen( trim( $post['post_title'] ) ) == 0 ) {
1308              $attachment_url                           = ( isset( $post['attachment_url'] ) ) ? $post['attachment_url'] : $post['guid'];
1309              $post['post_title']                       = preg_replace( '/\.\w+$/', '', wp_basename( $attachment_url ) );
1310              $post['errors']['post_title']['errors'][] = __( 'Empty Title filled from filename.' );
1311          }
1312      }
1313  
1314      return $post;
1315  }
1316  
1317  /**
1318   * Retrieves the media element HTML to send to the editor.
1319   *
1320   * @since 2.5.0
1321   *
1322   * @param string $html
1323   * @param integer $attachment_id
1324   * @param array $attachment
1325   * @return string
1326   */
1327  function image_media_send_to_editor( $html, $attachment_id, $attachment ) {
1328      $post = get_post( $attachment_id );
1329  
1330      if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) {
1331          $url   = $attachment['url'];
1332          $align = ! empty( $attachment['align'] ) ? $attachment['align'] : 'none';
1333          $size  = ! empty( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium';
1334          $alt   = ! empty( $attachment['image_alt'] ) ? $attachment['image_alt'] : '';
1335          $rel   = ( strpos( $url, 'attachment_id' ) || get_attachment_link( $attachment_id ) === $url );
1336  
1337          return get_image_send_to_editor( $attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size, $alt );
1338      }
1339  
1340      return $html;
1341  }
1342  
1343  /**
1344   * Retrieves the attachment fields to edit form fields.
1345   *
1346   * @since 2.5.0
1347   *
1348   * @param WP_Post $post
1349   * @param array $errors
1350   * @return array
1351   */
1352  function get_attachment_fields_to_edit( $post, $errors = null ) {
1353      if ( is_int( $post ) ) {
1354          $post = get_post( $post );
1355      }
1356  
1357      if ( is_array( $post ) ) {
1358          $post = new WP_Post( (object) $post );
1359      }
1360  
1361      $image_url = wp_get_attachment_url( $post->ID );
1362  
1363      $edit_post = sanitize_post( $post, 'edit' );
1364  
1365      $form_fields = array(
1366          'post_title'   => array(
1367              'label' => __( 'Title' ),
1368              'value' => $edit_post->post_title,
1369          ),
1370          'image_alt'    => array(),
1371          'post_excerpt' => array(
1372              'label' => __( 'Caption' ),
1373              'input' => 'html',
1374              'html'  => wp_caption_input_textarea( $edit_post ),
1375          ),
1376          'post_content' => array(
1377              'label' => __( 'Description' ),
1378              'value' => $edit_post->post_content,
1379              'input' => 'textarea',
1380          ),
1381          'url'          => array(
1382              'label' => __( 'Link URL' ),
1383              'input' => 'html',
1384              'html'  => image_link_input_fields( $post, get_option( 'image_default_link_type' ) ),
1385              'helps' => __( 'Enter a link URL or click above for presets.' ),
1386          ),
1387          'menu_order'   => array(
1388              'label' => __( 'Order' ),
1389              'value' => $edit_post->menu_order,
1390          ),
1391          'image_url'    => array(
1392              'label' => __( 'File URL' ),
1393              'input' => 'html',
1394              'html'  => "<input type='text' class='text urlfield' readonly='readonly' name='attachments[$post->ID][url]' value='" . esc_attr( $image_url ) . "' /><br />",
1395              'value' => wp_get_attachment_url( $post->ID ),
1396              'helps' => __( 'Location of the uploaded file.' ),
1397          ),
1398      );
1399  
1400      foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
1401          $t = (array) get_taxonomy( $taxonomy );
1402  
1403          if ( ! $t['public'] || ! $t['show_ui'] ) {
1404              continue;
1405          }
1406  
1407          if ( empty( $t['label'] ) ) {
1408              $t['label'] = $taxonomy;
1409          }
1410  
1411          if ( empty( $t['args'] ) ) {
1412              $t['args'] = array();
1413          }
1414  
1415          $terms = get_object_term_cache( $post->ID, $taxonomy );
1416  
1417          if ( false === $terms ) {
1418              $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
1419          }
1420  
1421          $values = array();
1422  
1423          foreach ( $terms as $term ) {
1424              $values[] = $term->slug;
1425          }
1426  
1427          $t['value'] = join( ', ', $values );
1428  
1429          $form_fields[ $taxonomy ] = $t;
1430      }
1431  
1432      /*
1433       * Merge default fields with their errors, so any key passed with the error
1434       * (e.g. 'error', 'helps', 'value') will replace the default.
1435       * The recursive merge is easily traversed with array casting:
1436       * foreach ( (array) $things as $thing )
1437       */
1438      $form_fields = array_merge_recursive( $form_fields, (array) $errors );
1439  
1440      // This was formerly in image_attachment_fields_to_edit().
1441      if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) {
1442          $alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
1443  
1444          if ( empty( $alt ) ) {
1445              $alt = '';
1446          }
1447  
1448          $form_fields['post_title']['required'] = true;
1449  
1450          $form_fields['image_alt'] = array(
1451              'value' => $alt,
1452              'label' => __( 'Alternative Text' ),
1453              'helps' => __( 'Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;' ),
1454          );
1455  
1456          $form_fields['align'] = array(
1457              'label' => __( 'Alignment' ),
1458              'input' => 'html',
1459              'html'  => image_align_input_fields( $post, get_option( 'image_default_align' ) ),
1460          );
1461  
1462          $form_fields['image-size'] = image_size_input_fields( $post, get_option( 'image_default_size', 'medium' ) );
1463  
1464      } else {
1465          unset( $form_fields['image_alt'] );
1466      }
1467  
1468      /**
1469       * Filters the attachment fields to edit.
1470       *
1471       * @since 2.5.0
1472       *
1473       * @param array   $form_fields An array of attachment form fields.
1474       * @param WP_Post $post        The WP_Post attachment object.
1475       */
1476      $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1477  
1478      return $form_fields;
1479  }
1480  
1481  /**
1482   * Retrieve HTML for media items of post gallery.
1483   *
1484   * The HTML markup retrieved will be created for the progress of SWF Upload
1485   * component. Will also create link for showing and hiding the form to modify
1486   * the image attachment.
1487   *
1488   * @since 2.5.0
1489   *
1490   * @global WP_Query $wp_the_query WordPress Query object.
1491   *
1492   * @param int $post_id Optional. Post ID.
1493   * @param array $errors Errors for attachment, if any.
1494   * @return string
1495   */
1496  function get_media_items( $post_id, $errors ) {
1497      $attachments = array();
1498  
1499      if ( $post_id ) {
1500          $post = get_post( $post_id );
1501  
1502          if ( $post && 'attachment' === $post->post_type ) {
1503              $attachments = array( $post->ID => $post );
1504          } else {
1505              $attachments = get_children(
1506                  array(
1507                      'post_parent' => $post_id,
1508                      'post_type'   => 'attachment',
1509                      'orderby'     => 'menu_order ASC, ID',
1510                      'order'       => 'DESC',
1511                  )
1512              );
1513          }
1514      } else {
1515          if ( is_array( $GLOBALS['wp_the_query']->posts ) ) {
1516              foreach ( $GLOBALS['wp_the_query']->posts as $attachment ) {
1517                  $attachments[ $attachment->ID ] = $attachment;
1518              }
1519          }
1520      }
1521  
1522      $output = '';
1523      foreach ( (array) $attachments as $id => $attachment ) {
1524          if ( 'trash' === $attachment->post_status ) {
1525              continue;
1526          }
1527  
1528          $item = get_media_item( $id, array( 'errors' => isset( $errors[ $id ] ) ? $errors[ $id ] : null ) );
1529  
1530          if ( $item ) {
1531              $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>";
1532          }
1533      }
1534  
1535      return $output;
1536  }
1537  
1538  /**
1539   * Retrieve HTML form for modifying the image attachment.
1540   *
1541   * @since 2.5.0
1542   *
1543   * @global string $redir_tab
1544   *
1545   * @param int $attachment_id Attachment ID for modification.
1546   * @param string|array $args Optional. Override defaults.
1547   * @return string HTML form for attachment.
1548   */
1549  function get_media_item( $attachment_id, $args = null ) {
1550      global $redir_tab;
1551  
1552      $thumb_url     = false;
1553      $attachment_id = intval( $attachment_id );
1554  
1555      if ( $attachment_id ) {
1556          $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true );
1557  
1558          if ( $thumb_url ) {
1559              $thumb_url = $thumb_url[0];
1560          }
1561      }
1562  
1563      $post            = get_post( $attachment_id );
1564      $current_post_id = ! empty( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0;
1565  
1566      $default_args = array(
1567          'errors'     => null,
1568          'send'       => $current_post_id ? post_type_supports( get_post_type( $current_post_id ), 'editor' ) : true,
1569          'delete'     => true,
1570          'toggle'     => true,
1571          'show_title' => true,
1572      );
1573  
1574      $parsed_args = wp_parse_args( $args, $default_args );
1575  
1576      /**
1577       * Filters the arguments used to retrieve an image for the edit image form.
1578       *
1579       * @since 3.1.0
1580       *
1581       * @see get_media_item
1582       *
1583       * @param array $parsed_args An array of arguments.
1584       */
1585      $parsed_args = apply_filters( 'get_media_item_args', $parsed_args );
1586  
1587      $toggle_on  = __( 'Show' );
1588      $toggle_off = __( 'Hide' );
1589  
1590      $file     = get_attached_file( $post->ID );
1591      $filename = esc_html( wp_basename( $file ) );
1592      $title    = esc_attr( $post->post_title );
1593  
1594      $post_mime_types = get_post_mime_types();
1595      $keys            = array_keys( wp_match_mime_types( array_keys( $post_mime_types ), $post->post_mime_type ) );
1596      $type            = reset( $keys );
1597      $type_html       = "<input type='hidden' id='type-of-$attachment_id' value='" . esc_attr( $type ) . "' />";
1598  
1599      $form_fields = get_attachment_fields_to_edit( $post, $parsed_args['errors'] );
1600  
1601      if ( $parsed_args['toggle'] ) {
1602          $class        = empty( $parsed_args['errors'] ) ? 'startclosed' : 'startopen';
1603          $toggle_links = "
1604          <a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
1605          <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
1606      } else {
1607          $class        = '';
1608          $toggle_links = '';
1609      }
1610  
1611      $display_title = ( ! empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case.
1612      $display_title = $parsed_args['show_title'] ? "<div class='filename new'><span class='title'>" . wp_html_excerpt( $display_title, 60, '&hellip;' ) . '</span></div>' : '';
1613  
1614      $gallery = ( ( isset( $_REQUEST['tab'] ) && 'gallery' == $_REQUEST['tab'] ) || ( isset( $redir_tab ) && 'gallery' == $redir_tab ) );
1615      $order   = '';
1616  
1617      foreach ( $form_fields as $key => $val ) {
1618          if ( 'menu_order' == $key ) {
1619              if ( $gallery ) {
1620                  $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>";
1621              } else {
1622                  $order = "<input type='hidden' name='attachments[$attachment_id][menu_order]' value='" . esc_attr( $val['value'] ) . "' />";
1623              }
1624  
1625              unset( $form_fields['menu_order'] );
1626              break;
1627          }
1628      }
1629  
1630      $media_dims = '';
1631      $meta       = wp_get_attachment_metadata( $post->ID );
1632  
1633      if ( isset( $meta['width'], $meta['height'] ) ) {
1634          $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
1635      }
1636  
1637      /**
1638       * Filters the media metadata.
1639       *
1640       * @since 2.5.0
1641       *
1642       * @param string  $media_dims The HTML markup containing the media dimensions.
1643       * @param WP_Post $post       The WP_Post attachment object.
1644       */
1645      $media_dims = apply_filters( 'media_meta', $media_dims, $post );
1646  
1647      $image_edit_button = '';
1648  
1649      if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
1650          $nonce             = wp_create_nonce( "image_editor-$post->ID" );
1651          $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>";
1652      }
1653  
1654      $attachment_url = get_permalink( $attachment_id );
1655  
1656      $item = "
1657          $type_html
1658          $toggle_links
1659          $order
1660          $display_title
1661          <table class='slidetoggle describe $class'>
1662              <thead class='media-item-info' id='media-head-$post->ID'>
1663              <tr>
1664              <td class='A1B1' id='thumbnail-head-$post->ID'>
1665              <p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p>
1666              <p>$image_edit_button</p>
1667              </td>
1668              <td>
1669              <p><strong>" . __( 'File name:' ) . "</strong> $filename</p>
1670              <p><strong>" . __( 'File type:' ) . "</strong> $post->post_mime_type</p>
1671              <p><strong>" . __( 'Upload date:' ) . '</strong> ' . mysql2date( __( 'F j, Y' ), $post->post_date ) . '</p>';
1672  
1673      if ( ! empty( $media_dims ) ) {
1674          $item .= '<p><strong>' . __( 'Dimensions:' ) . "</strong> $media_dims</p>\n";
1675      }
1676  
1677      $item .= "</td></tr>\n";
1678  
1679      $item .= "
1680          </thead>
1681          <tbody>
1682          <tr><td colspan='2' class='imgedit-response' id='imgedit-response-$post->ID'></td></tr>\n
1683          <tr><td style='display:none' colspan='2' class='image-editor' id='image-editor-$post->ID'></td></tr>\n
1684          <tr><td colspan='2'><p class='media-types media-types-required-info'>" .
1685              /* translators: %s: Asterisk symbol (*). */
1686              sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) .
1687          "</p></td></tr>\n";
1688  
1689      $defaults = array(
1690          'input'      => 'text',
1691          'required'   => false,
1692          'value'      => '',
1693          'extra_rows' => array(),
1694      );
1695  
1696      if ( $parsed_args['send'] ) {
1697          $parsed_args['send'] = get_submit_button( __( 'Insert into Post' ), '', "send[$attachment_id]", false );
1698      }
1699  
1700      $delete = empty( $parsed_args['delete'] ) ? '' : $parsed_args['delete'];
1701      if ( $delete && current_user_can( 'delete_post', $attachment_id ) ) {
1702          if ( ! EMPTY_TRASH_DAYS ) {
1703              $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>';
1704          } elseif ( ! MEDIA_TRASH ) {
1705              $delete = "<a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\">" . __( 'Delete' ) . "</a>
1706                  <div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'>" .
1707                  /* translators: %s: File name. */
1708                  '<p>' . sprintf( __( 'You are about to delete %s.' ), '<strong>' . $filename . '</strong>' ) . "</p>
1709                  <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>
1710                  <a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\">" . __( 'Cancel' ) . '</a>
1711                  </div>';
1712          } else {
1713              $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>
1714              <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>';
1715          }
1716      } else {
1717          $delete = '';
1718      }
1719  
1720      $thumbnail       = '';
1721      $calling_post_id = 0;
1722  
1723      if ( isset( $_GET['post_id'] ) ) {
1724          $calling_post_id = absint( $_GET['post_id'] );
1725      } elseif ( isset( $_POST ) && count( $_POST ) ) {// Like for async-upload where $_GET['post_id'] isn't set.
1726          $calling_post_id = $post->post_parent;
1727      }
1728  
1729      if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) )
1730          && post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) {
1731  
1732          $calling_post             = get_post( $calling_post_id );
1733          $calling_post_type_object = get_post_type_object( $calling_post->post_type );
1734  
1735          $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$calling_post_id" );
1736          $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>';
1737      }
1738  
1739      if ( ( $parsed_args['send'] || $thumbnail || $delete ) && ! isset( $form_fields['buttons'] ) ) {
1740          $form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>" . $parsed_args['send'] . " $thumbnail $delete</td></tr>\n" );
1741      }
1742  
1743      $hidden_fields = array();
1744  
1745      foreach ( $form_fields as $id => $field ) {
1746          if ( '_' === $id[0] ) {
1747              continue;
1748          }
1749  
1750          if ( ! empty( $field['tr'] ) ) {
1751              $item .= $field['tr'];
1752              continue;
1753          }
1754  
1755          $field = array_merge( $defaults, $field );
1756          $name  = "attachments[$attachment_id][$id]";
1757  
1758          if ( 'hidden' === $field['input'] ) {
1759              $hidden_fields[ $name ] = $field['value'];
1760              continue;
1761          }
1762  
1763          $required      = $field['required'] ? '<span class="required">*</span>' : '';
1764          $required_attr = $field['required'] ? ' required' : '';
1765          $class         = $id;
1766          $class        .= $field['required'] ? ' form-required' : '';
1767  
1768          $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'>";
1769  
1770          if ( ! empty( $field[ $field['input'] ] ) ) {
1771              $item .= $field[ $field['input'] ];
1772          } elseif ( 'textarea' === $field['input'] ) {
1773              if ( 'post_content' == $id && user_can_richedit() ) {
1774                  // Sanitize_post() skips the post_content when user_can_richedit.
1775                  $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1776              }
1777              // Post_excerpt is already escaped by sanitize_post() in get_attachment_fields_to_edit().
1778              $item .= "<textarea id='$name' name='$name'{$required_attr}>" . $field['value'] . '</textarea>';
1779          } else {
1780              $item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "'{$required_attr} />";
1781          }
1782  
1783          if ( ! empty( $field['helps'] ) ) {
1784              $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1785          }
1786          $item .= "</td>\n\t\t</tr>\n";
1787  
1788          $extra_rows = array();
1789  
1790          if ( ! empty( $field['errors'] ) ) {
1791              foreach ( array_unique( (array) $field['errors'] ) as $error ) {
1792                  $extra_rows['error'][] = $error;
1793              }
1794          }
1795  
1796          if ( ! empty( $field['extra_rows'] ) ) {
1797              foreach ( $field['extra_rows'] as $class => $rows ) {
1798                  foreach ( (array) $rows as $html ) {
1799                      $extra_rows[ $class ][] = $html;
1800                  }
1801              }
1802          }
1803  
1804          foreach ( $extra_rows as $class => $rows ) {
1805              foreach ( $rows as $html ) {
1806                  $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
1807              }
1808          }
1809      }
1810  
1811      if ( ! empty( $form_fields['_final'] ) ) {
1812          $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
1813      }
1814  
1815      $item .= "\t</tbody>\n";
1816      $item .= "\t</table>\n";
1817  
1818      foreach ( $hidden_fields as $name => $value ) {
1819          $item .= "\t<input type='hidden' name='$name' id='$name' value='" . esc_attr( $value ) . "' />\n";
1820      }
1821  
1822      if ( $post->post_parent < 1 && isset( $_REQUEST['post_id'] ) ) {
1823          $parent      = (int) $_REQUEST['post_id'];
1824          $parent_name = "attachments[$attachment_id][post_parent]";
1825          $item       .= "\t<input type='hidden' name='$parent_name' id='$parent_name' value='$parent' />\n";
1826      }
1827  
1828      return $item;
1829  }
1830  
1831  /**
1832   * @since 3.5.0
1833   *
1834   * @param int   $attachment_id
1835   * @param array $args
1836   * @return array
1837   */
1838  function get_compat_media_markup( $attachment_id, $args = null ) {
1839      $post = get_post( $attachment_id );
1840  
1841      $default_args = array(
1842          'errors'   => null,
1843          'in_modal' => false,
1844      );
1845  
1846      $user_can_edit = current_user_can( 'edit_post', $attachment_id );
1847  
1848      $args = wp_parse_args( $args, $default_args );
1849  
1850      /** This filter is documented in wp-admin/includes/media.php */
1851      $args = apply_filters( 'get_media_item_args', $args );
1852  
1853      $form_fields = array();
1854  
1855      if ( $args['in_modal'] ) {
1856          foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
1857              $t = (array) get_taxonomy( $taxonomy );
1858  
1859              if ( ! $t['public'] || ! $t['show_ui'] ) {
1860                  continue;
1861              }
1862  
1863              if ( empty( $t['label'] ) ) {
1864                  $t['label'] = $taxonomy;
1865              }
1866  
1867              if ( empty( $t['args'] ) ) {
1868                  $t['args'] = array();
1869              }
1870  
1871              $terms = get_object_term_cache( $post->ID, $taxonomy );
1872  
1873              if ( false === $terms ) {
1874                  $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
1875              }
1876  
1877              $values = array();
1878  
1879              foreach ( $terms as $term ) {
1880                  $values[] = $term->slug;
1881              }
1882  
1883              $t['value']    = join( ', ', $values );
1884              $t['taxonomy'] = true;
1885  
1886              $form_fields[ $taxonomy ] = $t;
1887          }
1888      }
1889  
1890      /*
1891       * Merge default fields with their errors, so any key passed with the error
1892       * (e.g. 'error', 'helps', 'value') will replace the default.
1893       * The recursive merge is easily traversed with array casting:
1894       * foreach ( (array) $things as $thing )
1895       */
1896      $form_fields = array_merge_recursive( $form_fields, (array) $args['errors'] );
1897  
1898      /** This filter is documented in wp-admin/includes/media.php */
1899      $form_fields = apply_filters( 'attachment_fields_to_edit', $form_fields, $post );
1900  
1901      unset(
1902          $form_fields['image-size'],
1903          $form_fields['align'],
1904          $form_fields['image_alt'],
1905          $form_fields['post_title'],
1906          $form_fields['post_excerpt'],
1907          $form_fields['post_content'],
1908          $form_fields['url'],
1909          $form_fields['menu_order'],
1910          $form_fields['image_url']
1911      );
1912  
1913      /** This filter is documented in wp-admin/includes/media.php */
1914      $media_meta = apply_filters( 'media_meta', '', $post );
1915  
1916      $defaults = array(
1917          'input'         => 'text',
1918          'required'      => false,
1919          'value'         => '',
1920          'extra_rows'    => array(),
1921          'show_in_edit'  => true,
1922          'show_in_modal' => true,
1923      );
1924  
1925      $hidden_fields = array();
1926  
1927      $item = '';
1928  
1929      foreach ( $form_fields as $id => $field ) {
1930          if ( '_' === $id[0] ) {
1931              continue;
1932          }
1933  
1934          $name    = "attachments[$attachment_id][$id]";
1935          $id_attr = "attachments-$attachment_id-$id";
1936  
1937          if ( ! empty( $field['tr'] ) ) {
1938              $item .= $field['tr'];
1939              continue;
1940          }
1941  
1942          $field = array_merge( $defaults, $field );
1943  
1944          if ( ( ! $field['show_in_edit'] && ! $args['in_modal'] ) || ( ! $field['show_in_modal'] && $args['in_modal'] ) ) {
1945              continue;
1946          }
1947  
1948          if ( 'hidden' === $field['input'] ) {
1949              $hidden_fields[ $name ] = $field['value'];
1950              continue;
1951          }
1952  
1953          $readonly      = ! $user_can_edit && ! empty( $field['taxonomy'] ) ? " readonly='readonly' " : '';
1954          $required      = $field['required'] ? '<span class="required">*</span>' : '';
1955          $required_attr = $field['required'] ? ' required' : '';
1956          $class         = 'compat-field-' . $id;
1957          $class        .= $field['required'] ? ' form-required' : '';
1958  
1959          $item .= "\t\t<tr class='$class'>";
1960          $item .= "\t\t\t<th scope='row' class='label'><label for='$id_attr'><span class='alignleft'>{$field['label']}</span>$required<br class='clear' /></label>";
1961          $item .= "</th>\n\t\t\t<td class='field'>";
1962  
1963          if ( ! empty( $field[ $field['input'] ] ) ) {
1964              $item .= $field[ $field['input'] ];
1965          } elseif ( 'textarea' === $field['input'] ) {
1966              if ( 'post_content' == $id && user_can_richedit() ) {
1967                  // sanitize_post() skips the post_content when user_can_richedit.
1968                  $field['value'] = htmlspecialchars( $field['value'], ENT_QUOTES );
1969              }
1970              $item .= "<textarea id='$id_attr' name='$name'{$required_attr}>" . $field['value'] . '</textarea>';
1971          } else {
1972              $item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly{$required_attr} />";
1973          }
1974  
1975          if ( ! empty( $field['helps'] ) ) {
1976              $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
1977          }
1978  
1979          $item .= "</td>\n\t\t</tr>\n";
1980  
1981          $extra_rows = array();
1982  
1983          if ( ! empty( $field['errors'] ) ) {
1984              foreach ( array_unique( (array) $field['errors'] ) as $error ) {
1985                  $extra_rows['error'][] = $error;
1986              }
1987          }
1988  
1989          if ( ! empty( $field['extra_rows'] ) ) {
1990              foreach ( $field['extra_rows'] as $class => $rows ) {
1991                  foreach ( (array) $rows as $html ) {
1992                      $extra_rows[ $class ][] = $html;
1993                  }
1994              }
1995          }
1996  
1997          foreach ( $extra_rows as $class => $rows ) {
1998              foreach ( $rows as $html ) {
1999                  $item .= "\t\t<tr><td></td><td class='$class'>$html</td></tr>\n";
2000              }
2001          }
2002      }
2003  
2004      if ( ! empty( $form_fields['_final'] ) ) {
2005          $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
2006      }
2007  
2008      if ( $item ) {
2009          $item = '<p class="media-types media-types-required-info">' .
2010              /* translators: %s: Asterisk symbol (*). */
2011              sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) .
2012              '</p>' .
2013              '<table class="compat-attachment-fields">' . $item . '</table>';
2014      }
2015  
2016      foreach ( $hidden_fields as $hidden_field => $value ) {
2017          $item .= '<input type="hidden" name="' . esc_attr( $hidden_field ) . '" value="' . esc_attr( $value ) . '" />' . "\n";
2018      }
2019  
2020      if ( $item ) {
2021          $item = '<input type="hidden" name="attachments[' . $attachment_id . '][menu_order]" value="' . esc_attr( $post->menu_order ) . '" />' . $item;
2022      }
2023  
2024      return array(
2025          'item' => $item,
2026          'meta' => $media_meta,
2027      );
2028  }
2029  
2030  /**
2031   * Outputs the legacy media upload header.
2032   *
2033   * @since 2.5.0
2034   */
2035  function media_upload_header() {
2036      $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2037  
2038      echo '<script type="text/javascript">post_id = ' . $post_id . ';</script>';
2039  
2040      if ( empty( $_GET['chromeless'] ) ) {
2041          echo '<div id="media-upload-header">';
2042          the_media_upload_tabs();
2043          echo '</div>';
2044      }
2045  }
2046  
2047  /**
2048   * Outputs the legacy media upload form.
2049   *
2050   * @since 2.5.0
2051   *
2052   * @global string $type
2053   * @global string $tab
2054   * @global bool   $is_IE
2055   * @global bool   $is_opera
2056   *
2057   * @param array $errors
2058   */
2059  function media_upload_form( $errors = null ) {
2060      global $type, $tab, $is_IE, $is_opera;
2061  
2062      if ( ! _device_can_upload() ) {
2063          echo '<p>' . sprintf(
2064              /* translators: %s: https://apps.wordpress.org/ */
2065              __( '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.' ),
2066              'https://apps.wordpress.org/'
2067          ) . '</p>';
2068          return;
2069      }
2070  
2071      $upload_action_url = admin_url( 'async-upload.php' );
2072      $post_id           = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2073      $_type             = isset( $type ) ? $type : '';
2074      $_tab              = isset( $tab ) ? $tab : '';
2075  
2076      $max_upload_size = wp_max_upload_size();
2077      if ( ! $max_upload_size ) {
2078          $max_upload_size = 0;
2079      }
2080  
2081      ?>
2082      <div id="media-upload-notice">
2083      <?php
2084  
2085      if ( isset( $errors['upload_notice'] ) ) {
2086          echo $errors['upload_notice'];
2087      }
2088  
2089      ?>
2090      </div>
2091      <div id="media-upload-error">
2092      <?php
2093  
2094      if ( isset( $errors['upload_error'] ) && is_wp_error( $errors['upload_error'] ) ) {
2095          echo $errors['upload_error']->get_error_message();
2096      }
2097  
2098      ?>
2099      </div>
2100      <?php
2101  
2102      if ( is_multisite() && ! is_upload_space_available() ) {
2103          /**
2104           * Fires when an upload will exceed the defined upload space quota for a network site.
2105           *
2106           * @since 3.5.0
2107           */
2108          do_action( 'upload_ui_over_quota' );
2109          return;
2110      }
2111  
2112      /**
2113       * Fires just before the legacy (pre-3.5.0) upload interface is loaded.
2114       *
2115       * @since 2.6.0
2116       */
2117      do_action( 'pre-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2118  
2119      $post_params = array(
2120          'post_id'  => $post_id,
2121          '_wpnonce' => wp_create_nonce( 'media-form' ),
2122          'type'     => $_type,
2123          'tab'      => $_tab,
2124          'short'    => '1',
2125      );
2126  
2127      /**
2128       * Filters the media upload post parameters.
2129       *
2130       * @since 3.1.0 As 'swfupload_post_params'
2131       * @since 3.3.0
2132       *
2133       * @param array $post_params An array of media upload parameters used by Plupload.
2134       */
2135      $post_params = apply_filters( 'upload_post_params', $post_params );
2136  
2137      /*
2138      * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
2139      * and the `flash_swf_url` and `silverlight_xap_url` are not used.
2140      */
2141      $plupload_init = array(
2142          'browse_button'    => 'plupload-browse-button',
2143          'container'        => 'plupload-upload-ui',
2144          'drop_element'     => 'drag-drop-area',
2145          'file_data_name'   => 'async-upload',
2146          'url'              => $upload_action_url,
2147          'filters'          => array( 'max_file_size' => $max_upload_size . 'b' ),
2148          'multipart_params' => $post_params,
2149      );
2150  
2151      /*
2152       * Currently only iOS Safari supports multiple files uploading,
2153       * but iOS 7.x has a bug that prevents uploading of videos when enabled.
2154       * See #29602.
2155       */
2156      if (
2157          wp_is_mobile() &&
2158          strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2159          strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false
2160      ) {
2161          $plupload_init['multi_selection'] = false;
2162      }
2163  
2164      /**
2165       * Filters the default Plupload settings.
2166       *
2167       * @since 3.3.0
2168       *
2169       * @param array $plupload_init An array of default settings used by Plupload.
2170       */
2171      $plupload_init = apply_filters( 'plupload_init', $plupload_init );
2172  
2173      ?>
2174      <script type="text/javascript">
2175      <?php
2176      // Verify size is an int. If not return default value.
2177      $large_size_h = absint( get_option( 'large_size_h' ) );
2178  
2179      if ( ! $large_size_h ) {
2180          $large_size_h = 1024;
2181      }
2182  
2183      $large_size_w = absint( get_option( 'large_size_w' ) );
2184  
2185      if ( ! $large_size_w ) {
2186          $large_size_w = 1024;
2187      }
2188  
2189      ?>
2190      var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>,
2191      wpUploaderInit = <?php echo wp_json_encode( $plupload_init ); ?>;
2192      </script>
2193  
2194      <div id="plupload-upload-ui" class="hide-if-no-js">
2195      <?php
2196      /**
2197       * Fires before the upload interface loads.
2198       *
2199       * @since 2.6.0 As 'pre-flash-upload-ui'
2200       * @since 3.3.0
2201       */
2202      do_action( 'pre-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2203  
2204      ?>
2205      <div id="drag-drop-area">
2206          <div class="drag-drop-inside">
2207          <p class="drag-drop-info"><?php _e( 'Drop files to upload' ); ?></p>
2208          <p><?php _ex( 'or', 'Uploader: Drop files here - or - Select Files' ); ?></p>
2209          <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e( 'Select Files' ); ?>" class="button" /></p>
2210          </div>
2211      </div>
2212      <?php
2213      /**
2214       * Fires after the upload interface loads.
2215       *
2216       * @since 2.6.0 As 'post-flash-upload-ui'
2217       * @since 3.3.0
2218       */
2219      do_action( 'post-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2220      ?>
2221      </div>
2222  
2223      <div id="html-upload-ui" class="hide-if-js">
2224      <?php
2225      /**
2226       * Fires before the upload button in the media upload interface.
2227       *
2228       * @since 2.6.0
2229       */
2230      do_action( 'pre-html-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2231  
2232      ?>
2233      <p id="async-upload-wrap">
2234          <label class="screen-reader-text" for="async-upload"><?php _e( 'Upload' ); ?></label>
2235          <input type="file" name="async-upload" id="async-upload" />
2236          <?php submit_button( __( 'Upload' ), 'primary', 'html-upload', false ); ?>
2237          <a href="#" onclick="try{top.tb_remove();}catch(e){}; return false;"><?php _e( 'Cancel' ); ?></a>
2238      </p>
2239      <div class="clear"></div>
2240      <?php
2241      /**
2242       * Fires after the upload button in the media upload interface.
2243       *
2244       * @since 2.6.0
2245       */
2246      do_action( 'post-html-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2247  
2248      ?>
2249      </div>
2250  
2251  <p class="max-upload-size">
2252      <?php
2253      /* translators: %s: Maximum allowed file size. */
2254      printf( __( 'Maximum upload file size: %s.' ), esc_html( size_format( $max_upload_size ) ) );
2255      ?>
2256  </p>
2257      <?php
2258  
2259      /**
2260       * Fires on the post upload UI screen.
2261       *
2262       * Legacy (pre-3.5.0) media workflow hook.
2263       *
2264       * @since 2.6.0
2265       */
2266      do_action( 'post-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
2267  }
2268  
2269  /**
2270   * Outputs the legacy media upload form for a given media type.
2271   *
2272   * @since 2.5.0
2273   *
2274   * @param string $type
2275   * @param object $errors
2276   * @param integer $id
2277   */
2278  function media_upload_type_form( $type = 'file', $errors = null, $id = null ) {
2279  
2280      media_upload_header();
2281  
2282      $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2283  
2284      $form_action_url = admin_url( "media-upload.php?type=$type&tab=type&post_id=$post_id" );
2285  
2286      /**
2287       * Filters the media upload form action URL.
2288       *
2289       * @since 2.6.0
2290       *
2291       * @param string $form_action_url The media upload form action URL.
2292       * @param string $type            The type of media. Default 'file'.
2293       */
2294      $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2295      $form_class      = 'media-upload-form type-form validate';
2296  
2297      if ( get_user_setting( 'uploader' ) ) {
2298          $form_class .= ' html-uploader';
2299      }
2300  
2301      ?>
2302      <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">
2303          <?php submit_button( '', 'hidden', 'save', false ); ?>
2304      <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2305          <?php wp_nonce_field( 'media-form' ); ?>
2306  
2307      <h3 class="media-title"><?php _e( 'Add media files from your computer' ); ?></h3>
2308  
2309      <?php media_upload_form( $errors ); ?>
2310  
2311      <script type="text/javascript">
2312      jQuery(function($){
2313          var preloaded = $(".media-item.preloaded");
2314          if ( preloaded.length > 0 ) {
2315              preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2316          }
2317          updateMediaForm();
2318      });
2319      </script>
2320      <div id="media-items">
2321      <?php
2322  
2323      if ( $id ) {
2324          if ( ! is_wp_error( $id ) ) {
2325              add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 );
2326              echo get_media_items( $id, $errors );
2327          } else {
2328              echo '<div id="media-upload-error">' . esc_html( $id->get_error_message() ) . '</div></div>';
2329              exit;
2330          }
2331      }
2332  
2333      ?>
2334      </div>
2335  
2336      <p class="savebutton ml-submit">
2337          <?php submit_button( __( 'Save all changes' ), '', 'save', false ); ?>
2338      </p>
2339      </form>
2340      <?php
2341  }
2342  
2343  /**
2344   * Outputs the legacy media upload form for external media.
2345   *
2346   * @since 2.7.0
2347   *
2348   * @param string $type
2349   * @param object $errors
2350   * @param integer $id
2351   */
2352  function media_upload_type_url_form( $type = null, $errors = null, $id = null ) {
2353      if ( null === $type ) {
2354          $type = 'image';
2355      }
2356  
2357      media_upload_header();
2358  
2359      $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2360  
2361      $form_action_url = admin_url( "media-upload.php?type=$type&tab=type&post_id=$post_id" );
2362      /** This filter is documented in wp-admin/includes/media.php */
2363      $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2364      $form_class      = 'media-upload-form type-form validate';
2365  
2366      if ( get_user_setting( 'uploader' ) ) {
2367          $form_class .= ' html-uploader';
2368      }
2369  
2370      ?>
2371      <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">
2372      <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2373          <?php wp_nonce_field( 'media-form' ); ?>
2374  
2375      <h3 class="media-title"><?php _e( 'Insert media from another website' ); ?></h3>
2376  
2377      <script type="text/javascript">
2378      var addExtImage = {
2379  
2380      width : '',
2381      height : '',
2382      align : 'alignnone',
2383  
2384      insert : function() {
2385          var t = this, html, f = document.forms[0], cls, title = '', alt = '', caption = '';
2386  
2387          if ( '' == f.src.value || '' == t.width )
2388              return false;
2389  
2390          if ( f.alt.value )
2391              alt = f.alt.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2392  
2393          <?php
2394          /** This filter is documented in wp-admin/includes/media.php */
2395          if ( ! apply_filters( 'disable_captions', '' ) ) {
2396              ?>
2397              if ( f.caption.value ) {
2398                  caption = f.caption.value.replace(/\r\n|\r/g, '\n');
2399                  caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
2400                      return a.replace(/[\r\n\t]+/, ' ');
2401                  });
2402  
2403                  caption = caption.replace(/\s*\n\s*/g, '<br />');
2404              }
2405              <?php
2406          }
2407  
2408          ?>
2409          cls = caption ? '' : ' class="'+t.align+'"';
2410  
2411          html = '<img alt="'+alt+'" src="'+f.src.value+'"'+cls+' width="'+t.width+'" height="'+t.height+'" />';
2412  
2413          if ( f.url.value ) {
2414              url = f.url.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2415              html = '<a href="'+url+'">'+html+'</a>';
2416          }
2417  
2418          if ( caption )
2419              html = '[caption id="" align="'+t.align+'" width="'+t.width+'"]'+html+caption+'[/caption]';
2420  
2421          var win = window.dialogArguments || opener || parent || top;
2422          win.send_to_editor(html);
2423          return false;
2424      },
2425  
2426      resetImageData : function() {
2427          var t = addExtImage;
2428  
2429          t.width = t.height = '';
2430          document.getElementById('go_button').style.color = '#bbb';
2431          if ( ! document.forms[0].src.value )
2432              document.getElementById('status_img').innerHTML = '';
2433          else document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/no.png' ) ); ?>" alt="" />';
2434      },
2435  
2436      updateImageData : function() {
2437          var t = addExtImage;
2438  
2439          t.width = t.preloadImg.width;
2440          t.height = t.preloadImg.height;
2441          document.getElementById('go_button').style.color = '#333';
2442          document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/yes.png' ) ); ?>" alt="" />';
2443      },
2444  
2445      getImageData : function() {
2446          if ( jQuery('table.describe').hasClass('not-image') )
2447              return;
2448  
2449          var t = addExtImage, src = document.forms[0].src.value;
2450  
2451          if ( ! src ) {
2452              t.resetImageData();
2453              return false;
2454          }
2455  
2456          document.getElementById('status_img').innerHTML = '<img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" alt="" width="16" height="16" />';
2457          t.preloadImg = new Image();
2458          t.preloadImg.onload = t.updateImageData;
2459          t.preloadImg.onerror = t.resetImageData;
2460          t.preloadImg.src = src;
2461      }
2462      };
2463  
2464      jQuery(document).ready( function($) {
2465          $('.media-types input').click( function() {
2466              $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
2467          });
2468      });
2469      </script>
2470  
2471      <div id="media-items">
2472      <div class="media-item media-blank">
2473      <?php
2474      /**
2475       * Filters the insert media from URL form HTML.
2476       *
2477       * @since 3.3.0
2478       *
2479       * @param string $form_html The insert from URL form HTML.
2480       */
2481      echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) );
2482  
2483      ?>
2484      </div>
2485      </div>
2486      </form>
2487      <?php
2488  }
2489  
2490  /**
2491   * Adds gallery form to upload iframe
2492   *
2493   * @since 2.5.0
2494   *
2495   * @global string $redir_tab
2496   * @global string $type
2497   * @global string $tab
2498   *
2499   * @param array $errors
2500   */
2501  function media_upload_gallery_form( $errors ) {
2502      global $redir_tab, $type;
2503  
2504      $redir_tab = 'gallery';
2505      media_upload_header();
2506  
2507      $post_id         = intval( $_REQUEST['post_id'] );
2508      $form_action_url = admin_url( "media-upload.php?type=$type&tab=gallery&post_id=$post_id" );
2509      /** This filter is documented in wp-admin/includes/media.php */
2510      $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2511      $form_class      = 'media-upload-form validate';
2512  
2513      if ( get_user_setting( 'uploader' ) ) {
2514          $form_class .= ' html-uploader';
2515      }
2516  
2517      ?>
2518      <script type="text/javascript">
2519      jQuery(function($){
2520          var preloaded = $(".media-item.preloaded");
2521          if ( preloaded.length > 0 ) {
2522              preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2523              updateMediaForm();
2524          }
2525      });
2526      </script>
2527      <div id="sort-buttons" class="hide-if-no-js">
2528      <span>
2529          <?php _e( 'All Tabs:' ); ?>
2530      <a href="#" id="showall"><?php _e( 'Show' ); ?></a>
2531      <a href="#" id="hideall" style="display:none;"><?php _e( 'Hide' ); ?></a>
2532      </span>
2533          <?php _e( 'Sort Order:' ); ?>
2534      <a href="#" id="asc"><?php _e( 'Ascending' ); ?></a> |
2535      <a href="#" id="desc"><?php _e( 'Descending' ); ?></a> |
2536      <a href="#" id="clear"><?php _ex( 'Clear', 'verb' ); ?></a>
2537      </div>
2538      <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
2539          <?php wp_nonce_field( 'media-form' ); ?>
2540          <?php // media_upload_form( $errors ); ?>
2541      <table class="widefat">
2542      <thead><tr>
2543      <th><?php _e( 'Media' ); ?></th>
2544      <th class="order-head"><?php _e( 'Order' ); ?></th>
2545      <th class="actions-head"><?php _e( 'Actions' ); ?></th>
2546      </tr></thead>
2547      </table>
2548      <div id="media-items">
2549          <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
2550          <?php echo get_media_items( $post_id, $errors ); ?>
2551      </div>
2552  
2553      <p class="ml-submit">
2554          <?php
2555          submit_button(
2556              __( 'Save all changes' ),
2557              'savebutton',
2558              'save',
2559              false,
2560              array(
2561                  'id'    => 'save-all',
2562                  'style' => 'display: none;',
2563              )
2564          );
2565          ?>
2566      <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2567      <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
2568      <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
2569      </p>
2570  
2571      <div id="gallery-settings" style="display:none;">
2572      <div class="title"><?php _e( 'Gallery Settings' ); ?></div>
2573      <table id="basic" class="describe"><tbody>
2574          <tr>
2575          <th scope="row" class="label">
2576              <label>
2577              <span class="alignleft"><?php _e( 'Link thumbnails to:' ); ?></span>
2578              </label>
2579          </th>
2580          <td class="field">
2581              <input type="radio" name="linkto" id="linkto-file" value="file" />
2582              <label for="linkto-file" class="radio"><?php _e( 'Image File' ); ?></label>
2583  
2584              <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" />
2585              <label for="linkto-post" class="radio"><?php _e( 'Attachment Page' ); ?></label>
2586          </td>
2587          </tr>
2588  
2589          <tr>
2590          <th scope="row" class="label">
2591              <label>
2592              <span class="alignleft"><?php _e( 'Order images by:' ); ?></span>
2593              </label>
2594          </th>
2595          <td class="field">
2596              <select id="orderby" name="orderby">
2597                  <option value="menu_order" selected="selected"><?php _e( 'Menu order' ); ?></option>
2598                  <option value="title"><?php _e( 'Title' ); ?></option>
2599                  <option value="post_date"><?php _e( 'Date/Time' ); ?></option>
2600                  <option value="rand"><?php _e( 'Random' ); ?></option>
2601              </select>
2602          </td>
2603          </tr>
2604  
2605          <tr>
2606          <th scope="row" class="label">
2607              <label>
2608              <span class="alignleft"><?php _e( 'Order:' ); ?></span>
2609              </label>
2610          </th>
2611          <td class="field">
2612              <input type="radio" checked="checked" name="order" id="order-asc" value="asc" />
2613              <label for="order-asc" class="radio"><?php _e( 'Ascending' ); ?></label>
2614  
2615              <input type="radio" name="order" id="order-desc" value="desc" />
2616              <label for="order-desc" class="radio"><?php _e( 'Descending' ); ?></label>
2617          </td>
2618          </tr>
2619  
2620          <tr>
2621          <th scope="row" class="label">
2622              <label>
2623              <span class="alignleft"><?php _e( 'Gallery columns:' ); ?></span>
2624              </label>
2625          </th>
2626          <td class="field">
2627              <select id="columns" name="columns">
2628                  <option value="1">1</option>
2629                  <option value="2">2</option>
2630                  <option value="3" selected="selected">3</option>
2631                  <option value="4">4</option>
2632                  <option value="5">5</option>
2633                  <option value="6">6</option>
2634                  <option value="7">7</option>
2635                  <option value="8">8</option>
2636                  <option value="9">9</option>
2637              </select>
2638          </td>
2639          </tr>
2640      </tbody></table>
2641  
2642      <p class="ml-submit">
2643      <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" />
2644      <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' ); ?>" />
2645      </p>
2646      </div>
2647      </form>
2648      <?php
2649  }
2650  
2651  /**
2652   * Outputs the legacy media upload form for the media library.
2653   *
2654   * @since 2.5.0
2655   *
2656   * @global wpdb      $wpdb            WordPress database abstraction object.
2657   * @global WP_Query  $wp_query        WordPress Query object.
2658   * @global WP_Locale $wp_locale       WordPress date and time locale object.
2659   * @global string    $type
2660   * @global string    $tab
2661   * @global array     $post_mime_types
2662   *
2663   * @param array $errors
2664   */
2665  function media_upload_library_form( $errors ) {
2666      global $wpdb, $wp_query, $wp_locale, $type, $tab, $post_mime_types;
2667  
2668      media_upload_header();
2669  
2670      $post_id = isset( $_REQUEST['post_id'] ) ? intval( $_REQUEST['post_id'] ) : 0;
2671  
2672      $form_action_url = admin_url( "media-upload.php?type=$type&tab=library&post_id=$post_id" );
2673      /** This filter is documented in wp-admin/includes/media.php */
2674      $form_action_url = apply_filters( 'media_upload_form_url', $form_action_url, $type );
2675      $form_class      = 'media-upload-form validate';
2676  
2677      if ( get_user_setting( 'uploader' ) ) {
2678          $form_class .= ' html-uploader';
2679      }
2680  
2681      $q                   = $_GET;
2682      $q['posts_per_page'] = 10;
2683      $q['paged']          = isset( $q['paged'] ) ? intval( $q['paged'] ) : 0;
2684      if ( $q['paged'] < 1 ) {
2685          $q['paged'] = 1;
2686      }
2687      $q['offset'] = ( $q['paged'] - 1 ) * 10;
2688      if ( $q['offset'] < 1 ) {
2689          $q['offset'] = 0;
2690      }
2691  
2692      list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query( $q );
2693  
2694      ?>
2695      <form id="filter" method="get">
2696      <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
2697      <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
2698      <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" />
2699      <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" />
2700      <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" />
2701  
2702      <p id="media-search" class="search-box">
2703          <label class="screen-reader-text" for="media-search-input"><?php _e( 'Search Media' ); ?>:</label>
2704          <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" />
2705          <?php submit_button( __( 'Search Media' ), '', '', false ); ?>
2706      </p>
2707  
2708      <ul class="subsubsub">
2709          <?php
2710          $type_links = array();
2711          $_num_posts = (array) wp_count_attachments();
2712          $matches    = wp_match_mime_types( array_keys( $post_mime_types ), array_keys( $_num_posts ) );
2713          foreach ( $matches as $_type => $reals ) {
2714              foreach ( $reals as $real ) {
2715                  if ( isset( $num_posts[ $_type ] ) ) {
2716                      $num_posts[ $_type ] += $_num_posts[ $real ];
2717                  } else {
2718                      $num_posts[ $_type ] = $_num_posts[ $real ];
2719                  }
2720              }
2721          }
2722          // If available type specified by media button clicked, filter by that type.
2723          if ( empty( $_GET['post_mime_type'] ) && ! empty( $num_posts[ $type ] ) ) {
2724              $_GET['post_mime_type']                        = $type;
2725              list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
2726          }
2727          if ( empty( $_GET['post_mime_type'] ) || 'all' === $_GET['post_mime_type'] ) {
2728              $class = ' class="current"';
2729          } else {
2730              $class = '';
2731          }
2732          $type_links[] = '<li><a href="' . esc_url(
2733              add_query_arg(
2734                  array(
2735                      'post_mime_type' => 'all',
2736                      'paged'          => false,
2737                      'm'              => false,
2738                  )
2739              )
2740          ) . '"' . $class . '>' . __( 'All Types' ) . '</a>';
2741          foreach ( $post_mime_types as $mime_type => $label ) {
2742              $class = '';
2743  
2744              if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) {
2745                  continue;
2746              }
2747  
2748              if ( isset( $_GET['post_mime_type'] ) && wp_match_mime_types( $mime_type, $_GET['post_mime_type'] ) ) {
2749                  $class = ' class="current"';
2750              }
2751  
2752              $type_links[] = '<li><a href="' . esc_url(
2753                  add_query_arg(
2754                      array(
2755                          'post_mime_type' => $mime_type,
2756                          'paged'          => false,
2757                      )
2758                  )
2759              ) . '"' . $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>';
2760          }
2761          /**
2762           * Filters the media upload mime type list items.
2763           *
2764           * Returned values should begin with an `<li>` tag.
2765           *
2766           * @since 3.1.0
2767           *
2768           * @param string[] $type_links An array of list items containing mime type link HTML.
2769           */
2770          echo implode( ' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>';
2771          unset( $type_links );
2772          ?>
2773      </ul>
2774  
2775      <div class="tablenav">
2776  
2777          <?php
2778          $page_links = paginate_links(
2779              array(
2780                  'base'      => add_query_arg( 'paged', '%#%' ),
2781                  'format'    => '',
2782                  'prev_text' => __( '&laquo;' ),
2783                  'next_text' => __( '&raquo;' ),
2784                  'total'     => ceil( $wp_query->found_posts / 10 ),
2785                  'current'   => $q['paged'],
2786              )
2787          );
2788  
2789          if ( $page_links ) {
2790              echo "<div class='tablenav-pages'>$page_links</div>";
2791          }
2792          ?>
2793  
2794      <div class="alignleft actions">
2795          <?php
2796  
2797          $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";
2798  
2799          $arc_result = $wpdb->get_results( $arc_query );
2800  
2801          $month_count    = count( $arc_result );
2802          $selected_month = isset( $_GET['m'] ) ? $_GET['m'] : 0;
2803  
2804          if ( $month_count && ! ( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) {
2805              ?>
2806              <select name='m'>
2807              <option<?php selected( $selected_month, 0 ); ?> value='0'><?php _e( 'All dates' ); ?></option>
2808              <?php
2809  
2810              foreach ( $arc_result as $arc_row ) {
2811                  if ( 0 == $arc_row->yyear ) {
2812                      continue;
2813                  }
2814  
2815                  $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );
2816  
2817                  if ( $arc_row->yyear . $arc_row->mmonth == $selected_month ) {
2818                      $default = ' selected="selected"';
2819                  } else {
2820                      $default = '';
2821                  }
2822  
2823                  echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>";
2824                  echo esc_html( $wp_locale->get_month( $arc_row->mmonth ) . " $arc_row->yyear" );
2825                  echo "</option>\n";
2826              }
2827  
2828              ?>
2829              </select>
2830          <?php } ?>
2831  
2832          <?php submit_button( __( 'Filter &#187;' ), '', 'post-query-submit', false ); ?>
2833  
2834      </div>
2835  
2836      <br class="clear" />
2837      </div>
2838      </form>
2839  
2840      <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="library-form">
2841      <?php wp_nonce_field( 'media-form' ); ?>
2842      <?php // media_upload_form( $errors ); ?>
2843  
2844      <script type="text/javascript">
2845      jQuery(function($){
2846          var preloaded = $(".media-item.preloaded");
2847          if ( preloaded.length > 0 ) {
2848              preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
2849              updateMediaForm();
2850          }
2851      });
2852      </script>
2853  
2854      <div id="media-items">
2855          <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
2856          <?php echo get_media_items( null, $errors ); ?>
2857      </div>
2858      <p class="ml-submit">
2859          <?php submit_button( __( 'Save all changes' ), 'savebutton', 'save', false ); ?>
2860      <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
2861      </p>
2862      </form>
2863      <?php
2864  }
2865  
2866  /**
2867   * Creates the form for external url
2868   *
2869   * @since 2.7.0
2870   *
2871   * @param string $default_view
2872   * @return string the form html
2873   */
2874  function wp_media_insert_url_form( $default_view = 'image' ) {
2875      /** This filter is documented in wp-admin/includes/media.php */
2876      if ( ! apply_filters( 'disable_captions', '' ) ) {
2877          $caption = '
2878          <tr class="image-only">
2879              <th scope="row" class="label">
2880                  <label for="caption"><span class="alignleft">' . __( 'Image Caption' ) . '</span></label>
2881              </th>
2882              <td class="field"><textarea id="caption" name="caption"></textarea></td>
2883          </tr>';
2884      } else {
2885          $caption = '';
2886      }
2887  
2888      $default_align = get_option( 'image_default_align' );
2889  
2890      if ( empty( $default_align ) ) {
2891          $default_align = 'none';
2892      }
2893  
2894      if ( 'image' == $default_view ) {
2895          $view        = 'image-only';
2896          $table_class = '';
2897      } else {
2898          $view        = 'not-image';
2899          $table_class = $view;
2900      }
2901  
2902      return '
2903      <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>
2904      <p class="media-types media-types-required-info">' .
2905          /* translators: %s: Asterisk symbol (*). */
2906          sprintf( __( 'Required fields are marked %s' ), '<span class="required">*</span>' ) .
2907      '</p>
2908      <table class="describe ' . $table_class . '"><tbody>
2909          <tr>
2910              <th scope="row" class="label" style="width:130px;">
2911                  <label for="src"><span class="alignleft">' . __( 'URL' ) . '</span> <span class="required">*</span></label>
2912                  <span class="alignright" id="status_img"></span>
2913              </th>
2914              <td class="field"><input id="src" name="src" value="" type="text" required onblur="addExtImage.getImageData()" /></td>
2915          </tr>
2916  
2917          <tr>
2918              <th scope="row" class="label">
2919                  <label for="title"><span class="alignleft">' . __( 'Title' ) . '</span> <span class="required">*</span></label>
2920              </th>
2921              <td class="field"><input id="title" name="title" value="" type="text" required /></td>
2922          </tr>
2923  
2924          <tr class="not-image"><td></td><td><p class="help">' . __( 'Link text, e.g. &#8220;Ransom Demands (PDF)&#8221;' ) . '</p></td></tr>
2925  
2926          <tr class="image-only">
2927              <th scope="row" class="label">
2928                  <label for="alt"><span class="alignleft">' . __( 'Alternative Text' ) . '</span></label>
2929              </th>
2930              <td class="field"><input id="alt" name="alt" value="" type="text" required />
2931              <p class="help">' . __( 'Alt text for the image, e.g. &#8220;The Mona Lisa&#8221;' ) . '</p></td>
2932          </tr>
2933          ' . $caption . '
2934          <tr class="align image-only">
2935              <th scope="row" class="label"><p><label for="align">' . __( 'Alignment' ) . '</label></p></th>
2936              <td class="field">
2937                  <input name="align" id="align-none" value="none" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ( 'none' === $default_align ? ' checked="checked"' : '' ) . ' />
2938                  <label for="align-none" class="align image-align-none-label">' . __( 'None' ) . '</label>
2939                  <input name="align" id="align-left" value="left" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ( 'left' === $default_align ? ' checked="checked"' : '' ) . ' />
2940                  <label for="align-left" class="align image-align-left-label">' . __( 'Left' ) . '</label>
2941                  <input name="align" id="align-center" value="center" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ( 'center' === $default_align ? ' checked="checked"' : '' ) . ' />
2942                  <label for="align-center" class="align image-align-center-label">' . __( 'Center' ) . '</label>
2943                  <input name="align" id="align-right" value="right" onclick="addExtImage.align=\'align\'+this.value" type="radio"' . ( 'right' === $default_align ? ' checked="checked"' : '' ) . ' />
2944                  <label for="align-right" class="align image-align-right-label">' . __( 'Right' ) . '</label>
2945              </td>
2946          </tr>
2947  
2948          <tr class="image-only">
2949              <th scope="row" class="label">
2950                  <label for="url"><span class="alignleft">' . __( 'Link Image To:' ) . '</span></label>
2951              </th>
2952              <td class="field"><input id="url" name="url" value="" type="text" /><br />
2953  
2954              <button type="button" class="button" value="" onclick="document.forms[0].url.value=null">' . __( 'None' ) . '</button>
2955              <button type="button" class="button" value="" onclick="document.forms[0].url.value=document.forms[0].src.value">' . __( 'Link to image' ) . '</button>
2956              <p class="help">' . __( 'Enter a link URL or click above for presets.' ) . '</p></td>
2957          </tr>
2958          <tr class="image-only">
2959              <td></td>
2960              <td>
2961                  <input type="button" class="button" id="go_button" style="color:#bbb;" onclick="addExtImage.insert()" value="' . esc_attr__( 'Insert into Post' ) . '" />
2962              </td>
2963          </tr>
2964          <tr class="not-image">
2965              <td></td>
2966              <td>
2967                  ' . get_submit_button( __( 'Insert into Post' ), '', 'insertonlybutton', false ) . '
2968              </td>
2969          </tr>
2970      </tbody></table>';
2971  }
2972  
2973  /**
2974   * Displays the multi-file uploader message.
2975   *
2976   * @since 2.6.0
2977   *
2978   * @global int $post_ID
2979   */
2980  function media_upload_flash_bypass() {
2981      $browser_uploader = admin_url( 'media-new.php?browser-uploader' );
2982  
2983      $post = get_post();
2984      if ( $post ) {
2985          $browser_uploader .= '&amp;post_id=' . intval( $post->ID );
2986      } elseif ( ! empty( $GLOBALS['post_ID'] ) ) {
2987          $browser_uploader .= '&amp;post_id=' . intval( $GLOBALS['post_ID'] );
2988      }
2989  
2990      ?>
2991      <p class="upload-flash-bypass">
2992      <?php
2993          printf(
2994              /* translators: 1: URL to browser uploader, 2: Additional link attributes. */
2995              __( 'You are using the multi-file uploader. Problems? Try the <a href="%1$s" %2$s>browser uploader</a> instead.' ),
2996              $browser_uploader,
2997              'target="_blank"'
2998          );
2999      ?>
3000      </p>
3001      <?php
3002  }
3003  
3004  /**
3005   * Displays the browser's built-in uploader message.
3006   *
3007   * @since 2.6.0
3008   */
3009  function media_upload_html_bypass() {
3010      ?>
3011      <p class="upload-html-bypass hide-if-no-js">
3012          <?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>.' ); ?>
3013      </p>
3014      <?php
3015  }
3016  
3017  /**
3018   * Used to display a "After a file has been uploaded..." help message.
3019   *
3020   * @since 3.3.0
3021   */
3022  function media_upload_text_after() {}
3023  
3024  /**
3025   * Displays the checkbox to scale images.
3026   *
3027   * @since 3.3.0
3028   */
3029  function media_upload_max_image_resize() {
3030      $checked = get_user_setting( 'upload_resize' ) ? ' checked="true"' : '';
3031      $a       = '';
3032      $end     = '';
3033  
3034      if ( current_user_can( 'manage_options' ) ) {
3035          $a   = '<a href="' . esc_url( admin_url( 'options-media.php' ) ) . '" target="_blank">';
3036          $end = '</a>';
3037      }
3038  
3039      ?>
3040      <p class="hide-if-no-js"><label>
3041      <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> />
3042      <?php
3043      /* translators: 1: Link start tag, 2: Link end tag, 3: Width, 4: Height. */
3044      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' ) );
3045  
3046      ?>
3047      </label></p>
3048      <?php
3049  }
3050  
3051  /**
3052   * Displays the out of storage quota message in Multisite.
3053   *
3054   * @since 3.5.0
3055   */
3056  function multisite_over_quota_message() {
3057      echo '<p>' . sprintf(
3058          /* translators: %s: Allowed space allocation. */
3059          __( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
3060          size_format( get_space_allowed() * MB_IN_BYTES )
3061      ) . '</p>';
3062  }
3063  
3064  /**
3065   * Displays the image and editor in the post editor
3066   *
3067   * @since 3.5.0
3068   *
3069   * @param WP_Post $post A post object.
3070   */
3071  function edit_form_image_editor( $post ) {
3072      $open = isset( $_GET['image-editor'] );
3073  
3074      if ( $open ) {
3075          require_once  ABSPATH . 'wp-admin/includes/image-edit.php';
3076      }
3077  
3078      $thumb_url     = false;
3079      $attachment_id = intval( $post->ID );
3080  
3081      if ( $attachment_id ) {
3082          $thumb_url = wp_get_attachment_image_src( $attachment_id, array( 900, 450 ), true );
3083      }
3084  
3085      $alt_text = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
3086  
3087      $att_url = wp_get_attachment_url( $post->ID );
3088      ?>
3089      <div class="wp_attachment_holder wp-clearfix">
3090      <?php
3091  
3092      if ( wp_attachment_is_image( $post->ID ) ) :
3093          $image_edit_button = '';
3094          if ( wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
3095              $nonce             = wp_create_nonce( "image_editor-$post->ID" );
3096              $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>";
3097          }
3098  
3099          $open_style     = '';
3100          $not_open_style = '';
3101  
3102          if ( $open ) {
3103              $open_style = ' style="display:none"';
3104          } else {
3105              $not_open_style = ' style="display:none"';
3106          }
3107  
3108          ?>
3109          <div class="imgedit-response" id="imgedit-response-<?php echo $attachment_id; ?>"></div>
3110  
3111          <div<?php echo $open_style; ?> class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
3112              <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>
3113              <p><?php echo $image_edit_button; ?></p>
3114          </div>
3115          <div<?php echo $not_open_style; ?> class="image-editor" id="image-editor-<?php echo $attachment_id; ?>">
3116          <?php
3117  
3118          if ( $open ) {
3119              wp_image_editor( $attachment_id );
3120          }
3121  
3122          ?>
3123          </div>
3124          <?php
3125      elseif ( $attachment_id && wp_attachment_is( 'audio', $post ) ) :
3126  
3127          wp_maybe_generate_attachment_metadata( $post );
3128  
3129          echo wp_audio_shortcode( array( 'src' => $att_url ) );
3130  
3131      elseif ( $attachment_id && wp_attachment_is( 'video', $post ) ) :
3132  
3133          wp_maybe_generate_attachment_metadata( $post );
3134  
3135          $meta = wp_get_attachment_metadata( $attachment_id );
3136          $w    = ! empty( $meta['width'] ) ? min( $meta['width'], 640 ) : 0;
3137          $h    = ! empty( $meta['height'] ) ? $meta['height'] : 0;
3138  
3139          if ( $h && $w < $meta['width'] ) {
3140              $h = round( ( $meta['height'] * $w ) / $meta['width'] );
3141          }
3142  
3143          $attr = array( 'src' => $att_url );
3144  
3145          if ( ! empty( $w ) && ! empty( $h ) ) {
3146              $attr['width']  = $w;
3147              $attr['height'] = $h;
3148          }
3149  
3150          $thumb_id = get_post_thumbnail_id( $attachment_id );
3151  
3152          if ( ! empty( $thumb_id ) ) {
3153              $attr['poster'] = wp_get_attachment_url( $thumb_id );
3154          }
3155  
3156          echo wp_video_shortcode( $attr );
3157  
3158      elseif ( isset( $thumb_url[0] ) ) :
3159          ?>
3160          <div class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
3161              <p id="thumbnail-head-<?php echo $attachment_id; ?>">
3162                  <img class="thumbnail" src="<?php echo set_url_scheme( $thumb_url[0] ); ?>" style="max-width:100%" alt="" />
3163              </p>
3164          </div>
3165          <?php
3166  
3167      else :
3168  
3169          /**
3170           * Fires when an attachment type can't be rendered in the edit form.
3171           *
3172           * @since 4.6.0
3173           *
3174           * @param WP_Post $post A post object.
3175           */
3176          do_action( 'wp_edit_form_attachment_display', $post );
3177  
3178      endif;
3179  
3180      ?>
3181      </div>
3182      <div class="wp_attachment_details edit-form-section">
3183      <?php if ( 'image' === substr( $post->post_mime_type, 0, 5 ) ) : ?>
3184          <p class="attachment-alt-text">
3185              <label for="attachment_alt"><strong><?php _e( 'Alternative Text' ); ?></strong></label><br />
3186              <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 ); ?>" />
3187          </p>
3188          <p class="attachment-alt-text-description" id="alt-text-description">
3189          <?php
3190  
3191          printf(
3192              /* translators: 1: Link to tutorial, 2: Additional link attributes, 3: Accessibility text. */
3193              __( '<a href="%1$s" %2$s>Describe the purpose of the image%3$s</a>. Leave empty if the image is purely decorative.' ),
3194              esc_url( 'https://www.w3.org/WAI/tutorials/images/decision-tree' ),
3195              'target="_blank" rel="noopener noreferrer"',
3196              sprintf(
3197                  '<span class="screen-reader-text"> %s</span>',
3198                  /* translators: Accessibility text. */
3199                  __( '(opens in a new tab)' )
3200              )
3201          );
3202  
3203          ?>
3204          </p>
3205      <?php endif; ?>
3206  
3207          <p>
3208              <label for="attachment_caption"><strong><?php _e( 'Caption' ); ?></strong></label><br />
3209              <textarea class="widefat" name="excerpt" id="attachment_caption"><?php echo $post->post_excerpt; ?></textarea>
3210          </p>
3211  
3212      <?php
3213  
3214      $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
3215      $editor_args        = array(
3216          'textarea_name' => 'content',
3217          'textarea_rows' => 5,
3218          'media_buttons' => false,
3219          'tinymce'       => false,
3220          'quicktags'     => $quicktags_settings,
3221      );
3222  
3223      ?>
3224  
3225      <label for="attachment_content" class="attachment-content-description"><strong><?php _e( 'Description' ); ?></strong>
3226      <?php
3227  
3228      if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
3229          echo ': ' . __( 'Displayed on attachment pages.' );
3230      }
3231  
3232      ?>
3233      </label>
3234      <?php wp_editor( $post->post_content, 'attachment_content', $editor_args ); ?>
3235  
3236      </div>
3237      <?php
3238  
3239      $extras = get_compat_media_markup( $post->ID );
3240      echo $extras['item'];
3241      echo '<input type="hidden" id="image-edit-context" value="edit-attachment" />' . "\n";
3242  }
3243  
3244  /**
3245   * Displays non-editable attachment metadata in the publish meta box.
3246   *
3247   * @since 3.5.0
3248   */
3249  function attachment_submitbox_metadata() {
3250      $post          = get_post();
3251      $attachment_id = $post->ID;
3252  
3253      $file     = get_attached_file( $attachment_id );
3254      $filename = esc_html( wp_basename( $file ) );
3255  
3256      $media_dims = '';
3257      $meta       = wp_get_attachment_metadata( $attachment_id );
3258  
3259      if ( isset( $meta['width'], $meta['height'] ) ) {
3260          $media_dims .= "<span id='media-dims-$attachment_id'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
3261      }
3262      /** This filter is documented in wp-admin/includes/media.php */
3263      $media_dims = apply_filters( 'media_meta', $media_dims, $post );
3264  
3265      $att_url = wp_get_attachment_url( $attachment_id );
3266  
3267      ?>
3268      <div class="misc-pub-section misc-pub-attachment">
3269          <label for="attachment_url"><?php _e( 'File URL:' ); ?></label>
3270          <input type="text" class="widefat urlfield" readonly="readonly" name="attachment_url" id="attachment_url" value="<?php echo esc_attr( $att_url ); ?>" />
3271      </div>
3272      <div class="misc-pub-section misc-pub-filename">
3273          <?php _e( 'File name:' ); ?> <strong><?php echo $filename; ?></strong>
3274      </div>
3275      <div class="misc-pub-section misc-pub-filetype">
3276          <?php _e( 'File type:' ); ?>
3277          <strong>
3278          <?php
3279  
3280          if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) {
3281              echo esc_html( strtoupper( $matches[1] ) );
3282              list( $mime_type ) = explode( '/', $post->post_mime_type );
3283              if ( 'image' !== $mime_type && ! empty( $meta['mime_type'] ) ) {
3284                  if ( "$mime_type/" . strtolower( $matches[1] ) !== $meta['mime_type'] ) {
3285                      echo ' (' . $meta['mime_type'] . ')';
3286                  }
3287              }
3288          } else {
3289              echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) );
3290          }
3291  
3292          ?>
3293          </strong>
3294      </div>
3295  
3296      <?php
3297  
3298      $file_size = false;
3299  
3300      if ( isset( $meta['filesize'] ) ) {
3301          $file_size = $meta['filesize'];
3302      } elseif ( file_exists( $file ) ) {
3303          $file_size = filesize( $file );
3304      }
3305  
3306      if ( ! empty( $file_size ) ) {
3307          ?>
3308          <div class="misc-pub-section misc-pub-filesize">
3309              <?php _e( 'File size:' ); ?> <strong><?php echo size_format( $file_size ); ?></strong>
3310          </div>
3311          <?php
3312      }
3313  
3314      if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
3315          $fields = array(
3316              'length_formatted' => __( 'Length:' ),
3317              'bitrate'          => __( 'Bitrate:' ),
3318          );
3319  
3320          /**
3321           * Filters the audio and video metadata fields to be shown in the publish meta box.
3322           *
3323           * The key for each item in the array should correspond to an attachment
3324           * metadata key, and the value should be the desired label.
3325           *
3326           * @since 3.7.0
3327           * @since 4.9.0 Added the `$post` parameter.
3328           *
3329           * @param array   $fields An array of the attachment metadata keys and labels.
3330           * @param WP_Post $post   WP_Post object for the current attachment.
3331           */
3332          $fields = apply_filters( 'media_submitbox_misc_sections', $fields, $post );
3333  
3334          foreach ( $fields as $key => $label ) {
3335              if ( empty( $meta[ $key ] ) ) {
3336                  continue;
3337              }
3338  
3339              ?>
3340              <div class="misc-pub-section misc-pub-mime-meta misc-pub-<?php echo sanitize_html_class( $key ); ?>">
3341                  <?php echo $label; ?>
3342                  <strong>
3343                  <?php
3344  
3345                  switch ( $key ) {
3346                      case 'bitrate':
3347                          echo round( $meta['bitrate'] / 1000 ) . 'kb/s';
3348                          if ( ! empty( $meta['bitrate_mode'] ) ) {
3349                              echo ' ' . strtoupper( esc_html( $meta['bitrate_mode'] ) );
3350                          }
3351                          break;
3352                      default:
3353                          echo esc_html( $meta[ $key ] );
3354                          break;
3355                  }
3356  
3357                  ?>
3358                  </strong>
3359              </div>
3360              <?php
3361          }
3362  
3363          $fields = array(
3364              'dataformat' => __( 'Audio Format:' ),
3365              'codec'      => __( 'Audio Codec:' ),
3366          );
3367  
3368          /**
3369           * Filters the audio attachment metadata fields to be shown in the publish meta box.
3370           *
3371           * The key for each item in the array should correspond to an attachment
3372           * metadata key, and the value should be the desired label.
3373           *
3374           * @since 3.7.0
3375           * @since 4.9.0 Added the `$post` parameter.
3376           *
3377           * @param array   $fields An array of the attachment metadata keys and labels.
3378           * @param WP_Post $post   WP_Post object for the current attachment.
3379           */
3380          $audio_fields = apply_filters( 'audio_submitbox_misc_sections', $fields, $post );
3381  
3382          foreach ( $audio_fields as $key => $label ) {
3383              if ( empty( $meta['audio'][ $key ] ) ) {
3384                  continue;
3385              }
3386  
3387              ?>
3388              <div class="misc-pub-section misc-pub-audio misc-pub-<?php echo sanitize_html_class( $key ); ?>">
3389                  <?php echo $label; ?> <strong><?php echo esc_html( $meta['audio'][ $key ] ); ?></strong>
3390              </div>
3391              <?php
3392          }
3393      }
3394  
3395      if ( $media_dims ) {
3396          ?>
3397          <div class="misc-pub-section misc-pub-dimensions">
3398              <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong>
3399          </div>
3400          <?php
3401      }
3402  
3403      if ( ! empty( $meta['original_image'] ) ) {
3404          ?>
3405          <div class="misc-pub-section misc-pub-original-image">
3406              <?php _e( 'Original image:' ); ?>
3407              <a href="<?php echo esc_url( wp_get_original_image_url( $attachment_id ) ); ?>">
3408                  <?php echo esc_html( wp_basename( wp_get_original_image_path( $attachment_id ) ) ); ?>
3409              </a>
3410          </div>
3411          <?php
3412      }
3413  }
3414  
3415  /**
3416   * Parse ID3v2, ID3v1, and getID3 comments to extract usable data
3417   *
3418   * @since 3.6.0
3419   *
3420   * @param array $metadata An existing array with data
3421   * @param array $data Data supplied by ID3 tags
3422   */
3423  function wp_add_id3_tag_data( &$metadata, $data ) {
3424      foreach ( array( 'id3v2', 'id3v1' ) as $version ) {
3425          if ( ! empty( $data[ $version ]['comments'] ) ) {
3426              foreach ( $data[ $version ]['comments'] as $key => $list ) {
3427                  if ( 'length' !== $key && ! empty( $list ) ) {
3428                      $metadata[ $key ] = wp_kses_post( reset( $list ) );
3429                      // Fix bug in byte stream analysis.
3430                      if ( 'terms_of_use' === $key && 0 === strpos( $metadata[ $key ], 'yright notice.' ) ) {
3431                          $metadata[ $key ] = 'Cop' . $metadata[ $key ];
3432                      }
3433                  }
3434              }
3435              break;
3436          }
3437      }
3438  
3439      if ( ! empty( $data['id3v2']['APIC'] ) ) {
3440          $image = reset( $data['id3v2']['APIC'] );
3441          if ( ! empty( $image['data'] ) ) {
3442              $metadata['image'] = array(
3443                  'data'   => $image['data'],
3444                  'mime'   => $image['image_mime'],
3445                  'width'  => $image['image_width'],
3446                  'height' => $image['image_height'],
3447              );
3448          }
3449      } elseif ( ! empty( $data['comments']['picture'] ) ) {
3450          $image = reset( $data['comments']['picture'] );
3451          if ( ! empty( $image['data'] ) ) {
3452              $metadata['image'] = array(
3453                  'data' => $image['data'],
3454                  'mime' => $image['image_mime'],
3455              );
3456          }
3457      }
3458  }
3459  
3460  /**
3461   * Retrieve metadata from a video file's ID3 tags
3462   *
3463   * @since 3.6.0
3464   *
3465   * @param string $file Path to file.
3466   * @return array|bool Returns array of metadata, if found.
3467   */
3468  function wp_read_video_metadata( $file ) {
3469      if ( ! file_exists( $file ) ) {
3470          return false;
3471      }
3472  
3473      $metadata = array();
3474  
3475      if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3476          define( 'GETID3_TEMP_DIR', get_temp_dir() );
3477      }
3478  
3479      if ( ! class_exists( 'getID3', false ) ) {
3480          require ABSPATH . WPINC . '/ID3/getid3.php';
3481      }
3482  
3483      $id3  = new getID3();
3484      $data = $id3->analyze( $file );
3485  
3486      if ( isset( $data['video']['lossless'] ) ) {
3487          $metadata['lossless'] = $data['video']['lossless'];
3488      }
3489  
3490      if ( ! empty( $data['video']['bitrate'] ) ) {
3491          $metadata['bitrate'] = (int) $data['video']['bitrate'];
3492      }
3493  
3494      if ( ! empty( $data['video']['bitrate_mode'] ) ) {
3495          $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
3496      }
3497  
3498      if ( ! empty( $data['filesize'] ) ) {
3499          $metadata['filesize'] = (int) $data['filesize'];
3500      }
3501  
3502      if ( ! empty( $data['mime_type'] ) ) {
3503          $metadata['mime_type'] = $data['mime_type'];
3504      }
3505  
3506      if ( ! empty( $data['playtime_seconds'] ) ) {
3507          $metadata['length'] = (int) round( $data['playtime_seconds'] );
3508      }
3509  
3510      if ( ! empty( $data['playtime_string'] ) ) {
3511          $metadata['length_formatted'] = $data['playtime_string'];
3512      }
3513  
3514      if ( ! empty( $data['video']['resolution_x'] ) ) {
3515          $metadata['width'] = (int) $data['video']['resolution_x'];
3516      }
3517  
3518      if ( ! empty( $data['video']['resolution_y'] ) ) {
3519          $metadata['height'] = (int) $data['video']['resolution_y'];
3520      }
3521  
3522      if ( ! empty( $data['fileformat'] ) ) {
3523          $metadata['fileformat'] = $data['fileformat'];
3524      }
3525  
3526      if ( ! empty( $data['video']['dataformat'] ) ) {
3527          $metadata['dataformat'] = $data['video']['dataformat'];
3528      }
3529  
3530      if ( ! empty( $data['video']['encoder'] ) ) {
3531          $metadata['encoder'] = $data['video']['encoder'];
3532      }
3533  
3534      if ( ! empty( $data['video']['codec'] ) ) {
3535          $metadata['codec'] = $data['video']['codec'];
3536      }
3537  
3538      if ( ! empty( $data['audio'] ) ) {
3539          unset( $data['audio']['streams'] );
3540          $metadata['audio'] = $data['audio'];
3541      }
3542  
3543      if ( empty( $metadata['created_timestamp'] ) ) {
3544          $created_timestamp = wp_get_media_creation_timestamp( $data );
3545  
3546          if ( false !== $created_timestamp ) {
3547              $metadata['created_timestamp'] = $created_timestamp;
3548          }
3549      }
3550  
3551      wp_add_id3_tag_data( $metadata, $data );
3552  
3553      $file_format = isset( $metadata['fileformat'] ) ? $metadata['fileformat'] : null;
3554  
3555      /**
3556       * Filters the array of metadata retrieved from a video.
3557       *
3558       * In core, usually this selection is what is stored.
3559       * More complete data can be parsed from the `$data` parameter.
3560       *
3561       * @since 4.9.0
3562       *
3563       * @param array  $metadata       Filtered Video metadata.
3564       * @param string $file           Path to video file.
3565       * @param string $file_format    File format of video, as analyzed by getID3.
3566       * @param string $data           Raw metadata from getID3.
3567       */
3568      return apply_filters( 'wp_read_video_metadata', $metadata, $file, $file_format, $data );
3569  }
3570  
3571  /**
3572   * Retrieve metadata from an audio file's ID3 tags.
3573   *
3574   * @since 3.6.0
3575   *
3576   * @param string $file Path to file.
3577   * @return array|bool Returns array of metadata, if found.
3578   */
3579  function wp_read_audio_metadata( $file ) {
3580      if ( ! file_exists( $file ) ) {
3581          return false;
3582      }
3583  
3584      $metadata = array();
3585  
3586      if ( ! defined( 'GETID3_TEMP_DIR' ) ) {
3587          define( 'GETID3_TEMP_DIR', get_temp_dir() );
3588      }
3589  
3590      if ( ! class_exists( 'getID3', false ) ) {
3591          require ABSPATH . WPINC . '/ID3/getid3.php';
3592      }
3593  
3594      $id3  = new getID3();
3595      $data = $id3->analyze( $file );
3596  
3597      if ( ! empty( $data['audio'] ) ) {
3598          unset( $data['audio']['streams'] );
3599          $metadata = $data['audio'];
3600      }
3601  
3602      if ( ! empty( $data['fileformat'] ) ) {
3603          $metadata['fileformat'] = $data['fileformat'];
3604      }
3605  
3606      if ( ! empty( $data['filesize'] ) ) {
3607          $metadata['filesize'] = (int) $data['filesize'];
3608      }
3609  
3610      if ( ! empty( $data['mime_type'] ) ) {
3611          $metadata['mime_type'] = $data['mime_type'];
3612      }
3613  
3614      if ( ! empty( $data['playtime_seconds'] ) ) {
3615          $metadata['length'] = (int) round( $data['playtime_seconds'] );
3616      }
3617  
3618      if ( ! empty( $data['playtime_string'] ) ) {
3619          $metadata['length_formatted'] = $data['playtime_string'];
3620      }
3621  
3622      if ( empty( $metadata['created_timestamp'] ) ) {
3623          $created_timestamp = wp_get_media_creation_timestamp( $data );
3624  
3625          if ( false !== $created_timestamp ) {
3626              $metadata['created_timestamp'] = $created_timestamp;
3627          }
3628      }
3629  
3630      wp_add_id3_tag_data( $metadata, $data );
3631  
3632      return $metadata;
3633  }
3634  
3635  /**
3636   * Parse creation date from media metadata.
3637   *
3638   * The getID3 library doesn't have a standard method for getting creation dates,
3639   * so the location of this data can vary based on the MIME type.
3640   *
3641   * @since 4.9.0
3642   *
3643   * @link https://github.com/JamesHeinrich/getID3/blob/master/structure.txt
3644   *
3645   * @param array $metadata The metadata returned by getID3::analyze().
3646   * @return int|bool A UNIX timestamp for the media's creation date if available
3647   *                  or a boolean FALSE if a timestamp could not be determined.
3648   */
3649  function wp_get_media_creation_timestamp( $metadata ) {
3650      $creation_date = false;
3651  
3652      if ( empty( $metadata['fileformat'] ) ) {
3653          return $creation_date;
3654      }
3655  
3656      switch ( $metadata['fileformat'] ) {
3657          case 'asf':
3658              if ( isset( $metadata['asf']['file_properties_object']['creation_date_unix'] ) ) {
3659                  $creation_date = (int) $metadata['asf']['file_properties_object']['creation_date_unix'];
3660              }
3661              break;
3662  
3663          case 'matroska':
3664          case 'webm':
3665              if ( isset( $metadata['matroska']['comments']['creation_time']['0'] ) ) {
3666                  $creation_date = strtotime( $metadata['matroska']['comments']['creation_time']['0'] );
3667              } elseif ( isset( $metadata['matroska']['info']['0']['DateUTC_unix'] ) ) {
3668                  $creation_date = (int) $metadata['matroska']['info']['0']['DateUTC_unix'];
3669              }
3670              break;
3671  
3672          case 'quicktime':
3673          case 'mp4':
3674              if ( isset( $metadata['quicktime']['moov']['subatoms']['0']['creation_time_unix'] ) ) {
3675                  $creation_date = (int) $metadata['quicktime']['moov']['subatoms']['0']['creation_time_unix'];
3676              }
3677              break;
3678      }
3679  
3680      return $creation_date;
3681  }
3682  
3683  /**
3684   * Encapsulate logic for Attach/Detach actions
3685   *
3686   * @since 4.2.0
3687   *
3688   * @global wpdb $wpdb WordPress database abstraction object.
3689   *
3690   * @param int    $parent_id Attachment parent ID.
3691   * @param string $action    Optional. Attach/detach action. Accepts 'attach' or 'detach'.
3692   *                          Default 'attach'.
3693   */
3694  function wp_media_attach_action( $parent_id, $action = 'attach' ) {
3695      global $wpdb;
3696  
3697      if ( ! $parent_id ) {
3698          return;
3699      }
3700  
3701      if ( ! current_user_can( 'edit_post', $parent_id ) ) {
3702          wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
3703      }
3704  
3705      $ids = array();
3706  
3707      foreach ( (array) $_REQUEST['media'] as $att_id ) {
3708          $att_id = (int) $att_id;
3709  
3710          if ( ! current_user_can( 'edit_post', $att_id ) ) {
3711              continue;
3712          }
3713  
3714          $ids[] = $att_id;
3715      }
3716  
3717      if ( ! empty( $ids ) ) {
3718          $ids_string = implode( ',', $ids );
3719  
3720          if ( 'attach' === $action ) {
3721              $result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
3722          } else {
3723              $result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
3724          }
3725  
3726          foreach ( $ids as $att_id ) {
3727              clean_attachment_cache( $att_id );
3728          }
3729      }
3730  
3731      if ( isset( $result ) ) {
3732          $location = 'upload.php';
3733          $referer  = wp_get_referer();
3734  
3735          if ( $referer ) {
3736              if ( false !== strpos( $referer, 'upload.php' ) ) {
3737                  $location = remove_query_arg( array( 'attached', 'detach' ), $referer );
3738              }
3739          }
3740  
3741          $key      = 'attach' === $action ? 'attached' : 'detach';
3742          $location = add_query_arg( array( $key => $result ), $location );
3743  
3744          wp_redirect( $location );
3745          exit;
3746      }
3747  }


Generated : Wed Apr 1 08:20:01 2020 Cross-referenced by PHPXref