[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/includes/ -> media.php (source)

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


Generated : Tue Aug 4 08:20:02 2020 Cross-referenced by PHPXref