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


Generated : Fri Aug 19 08:20:02 2022 Cross-referenced by PHPXref