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


Generated : Sat Dec 2 08:20:01 2023 Cross-referenced by PHPXref