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


Generated : Fri Sep 11 08:20:31 2026 Cross-referenced by PHPXref