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


Generated : Fri Apr 24 08:20:12 2026 Cross-referenced by PHPXref