[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * WordPress API for media display.
   4   *
   5   * @package WordPress
   6   * @subpackage Media
   7   */
   8  
   9  /**
  10   * Retrieve additional image sizes.
  11   *
  12   * @since 4.7.0
  13   *
  14   * @global array $_wp_additional_image_sizes
  15   *
  16   * @return array Additional images size data.
  17   */
  18  function wp_get_additional_image_sizes() {
  19      global $_wp_additional_image_sizes;
  20  
  21      if ( ! $_wp_additional_image_sizes ) {
  22          $_wp_additional_image_sizes = array();
  23      }
  24  
  25      return $_wp_additional_image_sizes;
  26  }
  27  
  28  /**
  29   * Scale down the default size of an image.
  30   *
  31   * This is so that the image is a better fit for the editor and theme.
  32   *
  33   * The `$size` parameter accepts either an array or a string. The supported string
  34   * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  35   * 128 width and 96 height in pixels. Also supported for the string value is
  36   * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
  37   * than the supported will result in the content_width size or 500 if that is
  38   * not set.
  39   *
  40   * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
  41   * called on the calculated array for width and height, respectively.
  42   *
  43   * @since 2.5.0
  44   *
  45   * @global int $content_width
  46   *
  47   * @param int          $width   Width of the image in pixels.
  48   * @param int          $height  Height of the image in pixels.
  49   * @param string|int[] $size    Optional. Image size. Accepts any registered image size name, or an array
  50   *                              of width and height values in pixels (in that order). Default 'medium'.
  51   * @param string       $context Optional. Could be 'display' (like in a theme) or 'edit'
  52   *                              (like inserting into an editor). Default null.
  53   * @return int[] {
  54   *     An array of width and height values.
  55   *
  56   *     @type int $0 The maximum width in pixels.
  57   *     @type int $1 The maximum height in pixels.
  58   * }
  59   */
  60  function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  61      global $content_width;
  62  
  63      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  64  
  65      if ( ! $context ) {
  66          $context = is_admin() ? 'edit' : 'display';
  67      }
  68  
  69      if ( is_array( $size ) ) {
  70          $max_width  = $size[0];
  71          $max_height = $size[1];
  72      } elseif ( 'thumb' === $size || 'thumbnail' === $size ) {
  73          $max_width  = (int) get_option( 'thumbnail_size_w' );
  74          $max_height = (int) get_option( 'thumbnail_size_h' );
  75          // Last chance thumbnail size defaults.
  76          if ( ! $max_width && ! $max_height ) {
  77              $max_width  = 128;
  78              $max_height = 96;
  79          }
  80      } elseif ( 'medium' === $size ) {
  81          $max_width  = (int) get_option( 'medium_size_w' );
  82          $max_height = (int) get_option( 'medium_size_h' );
  83  
  84      } elseif ( 'medium_large' === $size ) {
  85          $max_width  = (int) get_option( 'medium_large_size_w' );
  86          $max_height = (int) get_option( 'medium_large_size_h' );
  87  
  88          if ( (int) $content_width > 0 ) {
  89              $max_width = min( (int) $content_width, $max_width );
  90          }
  91      } elseif ( 'large' === $size ) {
  92          /*
  93           * We're inserting a large size image into the editor. If it's a really
  94           * big image we'll scale it down to fit reasonably within the editor
  95           * itself, and within the theme's content width if it's known. The user
  96           * can resize it in the editor if they wish.
  97           */
  98          $max_width  = (int) get_option( 'large_size_w' );
  99          $max_height = (int) get_option( 'large_size_h' );
 100  
 101          if ( (int) $content_width > 0 ) {
 102              $max_width = min( (int) $content_width, $max_width );
 103          }
 104      } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ), true ) ) {
 105          $max_width  = (int) $_wp_additional_image_sizes[ $size ]['width'];
 106          $max_height = (int) $_wp_additional_image_sizes[ $size ]['height'];
 107          // Only in admin. Assume that theme authors know what they're doing.
 108          if ( (int) $content_width > 0 && 'edit' === $context ) {
 109              $max_width = min( (int) $content_width, $max_width );
 110          }
 111      } else { // $size === 'full' has no constraint.
 112          $max_width  = $width;
 113          $max_height = $height;
 114      }
 115  
 116      /**
 117       * Filters the maximum image size dimensions for the editor.
 118       *
 119       * @since 2.5.0
 120       *
 121       * @param int[]        $max_image_size {
 122       *     An array of width and height values.
 123       *
 124       *     @type int $0 The maximum width in pixels.
 125       *     @type int $1 The maximum height in pixels.
 126       * }
 127       * @param string|int[] $size     Requested image size. Can be any registered image size name, or
 128       *                               an array of width and height values in pixels (in that order).
 129       * @param string       $context  The context the image is being resized for.
 130       *                               Possible values are 'display' (like in a theme)
 131       *                               or 'edit' (like inserting into an editor).
 132       */
 133      list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
 134  
 135      return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
 136  }
 137  
 138  /**
 139   * Retrieve width and height attributes using given width and height values.
 140   *
 141   * Both attributes are required in the sense that both parameters must have a
 142   * value, but are optional in that if you set them to false or null, then they
 143   * will not be added to the returned string.
 144   *
 145   * You can set the value using a string, but it will only take numeric values.
 146   * If you wish to put 'px' after the numbers, then it will be stripped out of
 147   * the return.
 148   *
 149   * @since 2.5.0
 150   *
 151   * @param int|string $width  Image width in pixels.
 152   * @param int|string $height Image height in pixels.
 153   * @return string HTML attributes for width and, or height.
 154   */
 155  function image_hwstring( $width, $height ) {
 156      $out = '';
 157      if ( $width ) {
 158          $out .= 'width="' . (int) $width . '" ';
 159      }
 160      if ( $height ) {
 161          $out .= 'height="' . (int) $height . '" ';
 162      }
 163      return $out;
 164  }
 165  
 166  /**
 167   * Scale an image to fit a particular size (such as 'thumb' or 'medium').
 168   *
 169   * The URL might be the original image, or it might be a resized version. This
 170   * function won't create a new resized copy, it will just return an already
 171   * resized one if it exists.
 172   *
 173   * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
 174   * resizing services for images. The hook must return an array with the same
 175   * elements that are normally returned from the function.
 176   *
 177   * @since 2.5.0
 178   *
 179   * @param int          $id   Attachment ID for image.
 180   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
 181   *                           of width and height values in pixels (in that order). Default 'medium'.
 182   * @return array|false {
 183   *     Array of image data, or boolean false if no image is available.
 184   *
 185   *     @type string $0 Image source URL.
 186   *     @type int    $1 Image width in pixels.
 187   *     @type int    $2 Image height in pixels.
 188   *     @type bool   $3 Whether the image is a resized image.
 189   * }
 190   */
 191  function image_downsize( $id, $size = 'medium' ) {
 192      $is_image = wp_attachment_is_image( $id );
 193  
 194      /**
 195       * Filters whether to preempt the output of image_downsize().
 196       *
 197       * Returning a truthy value from the filter will effectively short-circuit
 198       * down-sizing the image, returning that value instead.
 199       *
 200       * @since 2.5.0
 201       *
 202       * @param bool|array   $downsize Whether to short-circuit the image downsize.
 203       * @param int          $id       Attachment ID for image.
 204       * @param string|int[] $size     Requested image size. Can be any registered image size name, or
 205       *                               an array of width and height values in pixels (in that order).
 206       */
 207      $out = apply_filters( 'image_downsize', false, $id, $size );
 208  
 209      if ( $out ) {
 210          return $out;
 211      }
 212  
 213      $img_url          = wp_get_attachment_url( $id );
 214      $meta             = wp_get_attachment_metadata( $id );
 215      $width            = 0;
 216      $height           = 0;
 217      $is_intermediate  = false;
 218      $img_url_basename = wp_basename( $img_url );
 219  
 220      // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
 221      // Otherwise, a non-image type could be returned.
 222      if ( ! $is_image ) {
 223          if ( ! empty( $meta['sizes']['full'] ) ) {
 224              $img_url          = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
 225              $img_url_basename = $meta['sizes']['full']['file'];
 226              $width            = $meta['sizes']['full']['width'];
 227              $height           = $meta['sizes']['full']['height'];
 228          } else {
 229              return false;
 230          }
 231      }
 232  
 233      // Try for a new style intermediate size.
 234      $intermediate = image_get_intermediate_size( $id, $size );
 235  
 236      if ( $intermediate ) {
 237          $img_url         = str_replace( $img_url_basename, $intermediate['file'], $img_url );
 238          $width           = $intermediate['width'];
 239          $height          = $intermediate['height'];
 240          $is_intermediate = true;
 241      } elseif ( 'thumbnail' === $size ) {
 242          // Fall back to the old thumbnail.
 243          $thumb_file = wp_get_attachment_thumb_file( $id );
 244          $info       = null;
 245  
 246          if ( $thumb_file ) {
 247              $info = @getimagesize( $thumb_file );
 248          }
 249  
 250          if ( $thumb_file && $info ) {
 251              $img_url         = str_replace( $img_url_basename, wp_basename( $thumb_file ), $img_url );
 252              $width           = $info[0];
 253              $height          = $info[1];
 254              $is_intermediate = true;
 255          }
 256      }
 257  
 258      if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) {
 259          // Any other type: use the real image.
 260          $width  = $meta['width'];
 261          $height = $meta['height'];
 262      }
 263  
 264      if ( $img_url ) {
 265          // We have the actual image size, but might need to further constrain it if content_width is narrower.
 266          list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
 267  
 268          return array( $img_url, $width, $height, $is_intermediate );
 269      }
 270  
 271      return false;
 272  }
 273  
 274  /**
 275   * Register a new image size.
 276   *
 277   * @since 2.9.0
 278   *
 279   * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
 280   *
 281   * @param string     $name   Image size identifier.
 282   * @param int        $width  Optional. Image width in pixels. Default 0.
 283   * @param int        $height Optional. Image height in pixels. Default 0.
 284   * @param bool|array $crop   Optional. Image cropping behavior. If false, the image will be scaled (default),
 285   *                           If true, image will be cropped to the specified dimensions using center positions.
 286   *                           If an array, the image will be cropped using the array to specify the crop location.
 287   *                           Array values must be in the format: array( x_crop_position, y_crop_position ) where:
 288   *                               - x_crop_position accepts: 'left', 'center', or 'right'.
 289   *                               - y_crop_position accepts: 'top', 'center', or 'bottom'.
 290   */
 291  function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
 292      global $_wp_additional_image_sizes;
 293  
 294      $_wp_additional_image_sizes[ $name ] = array(
 295          'width'  => absint( $width ),
 296          'height' => absint( $height ),
 297          'crop'   => $crop,
 298      );
 299  }
 300  
 301  /**
 302   * Check if an image size exists.
 303   *
 304   * @since 3.9.0
 305   *
 306   * @param string $name The image size to check.
 307   * @return bool True if the image size exists, false if not.
 308   */
 309  function has_image_size( $name ) {
 310      $sizes = wp_get_additional_image_sizes();
 311      return isset( $sizes[ $name ] );
 312  }
 313  
 314  /**
 315   * Remove a new image size.
 316   *
 317   * @since 3.9.0
 318   *
 319   * @global array $_wp_additional_image_sizes
 320   *
 321   * @param string $name The image size to remove.
 322   * @return bool True if the image size was successfully removed, false on failure.
 323   */
 324  function remove_image_size( $name ) {
 325      global $_wp_additional_image_sizes;
 326  
 327      if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
 328          unset( $_wp_additional_image_sizes[ $name ] );
 329          return true;
 330      }
 331  
 332      return false;
 333  }
 334  
 335  /**
 336   * Registers an image size for the post thumbnail.
 337   *
 338   * @since 2.9.0
 339   *
 340   * @see add_image_size() for details on cropping behavior.
 341   *
 342   * @param int        $width  Image width in pixels.
 343   * @param int        $height Image height in pixels.
 344   * @param bool|array $crop   Optional. Whether to crop images to specified width and height or resize.
 345   *                           An array can specify positioning of the crop area. Default false.
 346   */
 347  function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
 348      add_image_size( 'post-thumbnail', $width, $height, $crop );
 349  }
 350  
 351  /**
 352   * Gets an img tag for an image attachment, scaling it down if requested.
 353   *
 354   * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
 355   * image without having to use regular expressions on the HTML content. The
 356   * parameters are: what WordPress will use for the class, the Attachment ID,
 357   * image align value, and the size the image should be.
 358   *
 359   * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
 360   * further manipulated by a plugin to change all attribute values and even HTML
 361   * content.
 362   *
 363   * @since 2.5.0
 364   *
 365   * @param int          $id    Attachment ID.
 366   * @param string       $alt   Image description for the alt attribute.
 367   * @param string       $title Image description for the title attribute.
 368   * @param string       $align Part of the class name for aligning the image.
 369   * @param string|int[] $size  Optional. Image size. Accepts any registered image size name, or an array of
 370   *                            width and height values in pixels (in that order). Default 'medium'.
 371   * @return string HTML IMG element for given image attachment
 372   */
 373  function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
 374  
 375      list( $img_src, $width, $height ) = image_downsize( $id, $size );
 376      $hwstring                         = image_hwstring( $width, $height );
 377  
 378      $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
 379  
 380      $size_class = is_array( $size ) ? implode( 'x', $size ) : $size;
 381      $class      = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id;
 382  
 383      /**
 384       * Filters the value of the attachment's image tag class attribute.
 385       *
 386       * @since 2.6.0
 387       *
 388       * @param string       $class CSS class name or space-separated list of classes.
 389       * @param int          $id    Attachment ID.
 390       * @param string       $align Part of the class name for aligning the image.
 391       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 392       *                            an array of width and height values in pixels (in that order).
 393       */
 394      $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
 395  
 396      $html = '<img src="' . esc_attr( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
 397  
 398      /**
 399       * Filters the HTML content for the image tag.
 400       *
 401       * @since 2.6.0
 402       *
 403       * @param string       $html  HTML content for the image.
 404       * @param int          $id    Attachment ID.
 405       * @param string       $alt   Image description for the alt attribute.
 406       * @param string       $title Image description for the title attribute.
 407       * @param string       $align Part of the class name for aligning the image.
 408       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 409       *                            an array of width and height values in pixels (in that order).
 410       */
 411      return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
 412  }
 413  
 414  /**
 415   * Calculates the new dimensions for a down-sampled image.
 416   *
 417   * If either width or height are empty, no constraint is applied on
 418   * that dimension.
 419   *
 420   * @since 2.5.0
 421   *
 422   * @param int $current_width  Current width of the image.
 423   * @param int $current_height Current height of the image.
 424   * @param int $max_width      Optional. Max width in pixels to constrain to. Default 0.
 425   * @param int $max_height     Optional. Max height in pixels to constrain to. Default 0.
 426   * @return int[] {
 427   *     An array of width and height values.
 428   *
 429   *     @type int $0 The width in pixels.
 430   *     @type int $1 The height in pixels.
 431   * }
 432   */
 433  function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
 434      if ( ! $max_width && ! $max_height ) {
 435          return array( $current_width, $current_height );
 436      }
 437  
 438      $width_ratio  = 1.0;
 439      $height_ratio = 1.0;
 440      $did_width    = false;
 441      $did_height   = false;
 442  
 443      if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
 444          $width_ratio = $max_width / $current_width;
 445          $did_width   = true;
 446      }
 447  
 448      if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
 449          $height_ratio = $max_height / $current_height;
 450          $did_height   = true;
 451      }
 452  
 453      // Calculate the larger/smaller ratios.
 454      $smaller_ratio = min( $width_ratio, $height_ratio );
 455      $larger_ratio  = max( $width_ratio, $height_ratio );
 456  
 457      if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
 458          // The larger ratio is too big. It would result in an overflow.
 459          $ratio = $smaller_ratio;
 460      } else {
 461          // The larger ratio fits, and is likely to be a more "snug" fit.
 462          $ratio = $larger_ratio;
 463      }
 464  
 465      // Very small dimensions may result in 0, 1 should be the minimum.
 466      $w = max( 1, (int) round( $current_width * $ratio ) );
 467      $h = max( 1, (int) round( $current_height * $ratio ) );
 468  
 469      /*
 470       * Sometimes, due to rounding, we'll end up with a result like this:
 471       * 465x700 in a 177x177 box is 117x176... a pixel short.
 472       * We also have issues with recursive calls resulting in an ever-changing result.
 473       * Constraining to the result of a constraint should yield the original result.
 474       * Thus we look for dimensions that are one pixel shy of the max value and bump them up.
 475       */
 476  
 477      // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
 478      if ( $did_width && $w === $max_width - 1 ) {
 479          $w = $max_width; // Round it up.
 480      }
 481  
 482      // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
 483      if ( $did_height && $h === $max_height - 1 ) {
 484          $h = $max_height; // Round it up.
 485      }
 486  
 487      /**
 488       * Filters dimensions to constrain down-sampled images to.
 489       *
 490       * @since 4.1.0
 491       *
 492       * @param int[] $dimensions     {
 493       *     An array of width and height values.
 494       *
 495       *     @type int $0 The width in pixels.
 496       *     @type int $1 The height in pixels.
 497       * }
 498       * @param int   $current_width  The current width of the image.
 499       * @param int   $current_height The current height of the image.
 500       * @param int   $max_width      The maximum width permitted.
 501       * @param int   $max_height     The maximum height permitted.
 502       */
 503      return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
 504  }
 505  
 506  /**
 507   * Retrieves calculated resize dimensions for use in WP_Image_Editor.
 508   *
 509   * Calculates dimensions and coordinates for a resized image that fits
 510   * within a specified width and height.
 511   *
 512   * Cropping behavior is dependent on the value of $crop:
 513   * 1. If false (default), images will not be cropped.
 514   * 2. If an array in the form of array( x_crop_position, y_crop_position ):
 515   *    - x_crop_position accepts 'left' 'center', or 'right'.
 516   *    - y_crop_position accepts 'top', 'center', or 'bottom'.
 517   *    Images will be cropped to the specified dimensions within the defined crop area.
 518   * 3. If true, images will be cropped to the specified dimensions using center positions.
 519   *
 520   * @since 2.5.0
 521   *
 522   * @param int        $orig_w Original width in pixels.
 523   * @param int        $orig_h Original height in pixels.
 524   * @param int        $dest_w New width in pixels.
 525   * @param int        $dest_h New height in pixels.
 526   * @param bool|array $crop   Optional. Whether to crop image to specified width and height or resize.
 527   *                           An array can specify positioning of the crop area. Default false.
 528   * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure.
 529   */
 530  function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
 531  
 532      if ( $orig_w <= 0 || $orig_h <= 0 ) {
 533          return false;
 534      }
 535      // At least one of $dest_w or $dest_h must be specific.
 536      if ( $dest_w <= 0 && $dest_h <= 0 ) {
 537          return false;
 538      }
 539  
 540      /**
 541       * Filters whether to preempt calculating the image resize dimensions.
 542       *
 543       * Returning a non-null value from the filter will effectively short-circuit
 544       * image_resize_dimensions(), returning that value instead.
 545       *
 546       * @since 3.4.0
 547       *
 548       * @param null|mixed $null   Whether to preempt output of the resize dimensions.
 549       * @param int        $orig_w Original width in pixels.
 550       * @param int        $orig_h Original height in pixels.
 551       * @param int        $dest_w New width in pixels.
 552       * @param int        $dest_h New height in pixels.
 553       * @param bool|array $crop   Whether to crop image to specified width and height or resize.
 554       *                           An array can specify positioning of the crop area. Default false.
 555       */
 556      $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
 557  
 558      if ( null !== $output ) {
 559          return $output;
 560      }
 561  
 562      // Stop if the destination size is larger than the original image dimensions.
 563      if ( empty( $dest_h ) ) {
 564          if ( $orig_w < $dest_w ) {
 565              return false;
 566          }
 567      } elseif ( empty( $dest_w ) ) {
 568          if ( $orig_h < $dest_h ) {
 569              return false;
 570          }
 571      } else {
 572          if ( $orig_w < $dest_w && $orig_h < $dest_h ) {
 573              return false;
 574          }
 575      }
 576  
 577      if ( $crop ) {
 578          /*
 579           * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h.
 580           * Note that the requested crop dimensions are used as a maximum bounding box for the original image.
 581           * If the original image's width or height is less than the requested width or height
 582           * only the greater one will be cropped.
 583           * For example when the original image is 600x300, and the requested crop dimensions are 400x400,
 584           * the resulting image will be 400x300.
 585           */
 586          $aspect_ratio = $orig_w / $orig_h;
 587          $new_w        = min( $dest_w, $orig_w );
 588          $new_h        = min( $dest_h, $orig_h );
 589  
 590          if ( ! $new_w ) {
 591              $new_w = (int) round( $new_h * $aspect_ratio );
 592          }
 593  
 594          if ( ! $new_h ) {
 595              $new_h = (int) round( $new_w / $aspect_ratio );
 596          }
 597  
 598          $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );
 599  
 600          $crop_w = round( $new_w / $size_ratio );
 601          $crop_h = round( $new_h / $size_ratio );
 602  
 603          if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
 604              $crop = array( 'center', 'center' );
 605          }
 606  
 607          list( $x, $y ) = $crop;
 608  
 609          if ( 'left' === $x ) {
 610              $s_x = 0;
 611          } elseif ( 'right' === $x ) {
 612              $s_x = $orig_w - $crop_w;
 613          } else {
 614              $s_x = floor( ( $orig_w - $crop_w ) / 2 );
 615          }
 616  
 617          if ( 'top' === $y ) {
 618              $s_y = 0;
 619          } elseif ( 'bottom' === $y ) {
 620              $s_y = $orig_h - $crop_h;
 621          } else {
 622              $s_y = floor( ( $orig_h - $crop_h ) / 2 );
 623          }
 624      } else {
 625          // Resize using $dest_w x $dest_h as a maximum bounding box.
 626          $crop_w = $orig_w;
 627          $crop_h = $orig_h;
 628  
 629          $s_x = 0;
 630          $s_y = 0;
 631  
 632          list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
 633      }
 634  
 635      if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) {
 636          // The new size has virtually the same dimensions as the original image.
 637  
 638          /**
 639           * Filters whether to proceed with making an image sub-size with identical dimensions
 640           * with the original/source image. Differences of 1px may be due to rounding and are ignored.
 641           *
 642           * @since 5.3.0
 643           *
 644           * @param bool $proceed The filtered value.
 645           * @param int  $orig_w  Original image width.
 646           * @param int  $orig_h  Original image height.
 647           */
 648          $proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h );
 649  
 650          if ( ! $proceed ) {
 651              return false;
 652          }
 653      }
 654  
 655      // The return array matches the parameters to imagecopyresampled().
 656      // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
 657      return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
 658  }
 659  
 660  /**
 661   * Resizes an image to make a thumbnail or intermediate size.
 662   *
 663   * The returned array has the file size, the image width, and image height. The
 664   * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
 665   * values of the returned array. The only parameter is the resized file path.
 666   *
 667   * @since 2.5.0
 668   *
 669   * @param string $file   File path.
 670   * @param int    $width  Image width.
 671   * @param int    $height Image height.
 672   * @param bool   $crop   Optional. Whether to crop image to specified width and height or resize.
 673   *                       Default false.
 674   * @return array|false Metadata array on success. False if no image was created.
 675   */
 676  function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
 677      if ( $width || $height ) {
 678          $editor = wp_get_image_editor( $file );
 679  
 680          if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
 681              return false;
 682          }
 683  
 684          $resized_file = $editor->save();
 685  
 686          if ( ! is_wp_error( $resized_file ) && $resized_file ) {
 687              unset( $resized_file['path'] );
 688              return $resized_file;
 689          }
 690      }
 691      return false;
 692  }
 693  
 694  /**
 695   * Helper function to test if aspect ratios for two images match.
 696   *
 697   * @since 4.6.0
 698   *
 699   * @param int $source_width  Width of the first image in pixels.
 700   * @param int $source_height Height of the first image in pixels.
 701   * @param int $target_width  Width of the second image in pixels.
 702   * @param int $target_height Height of the second image in pixels.
 703   * @return bool True if aspect ratios match within 1px. False if not.
 704   */
 705  function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
 706      /*
 707       * To test for varying crops, we constrain the dimensions of the larger image
 708       * to the dimensions of the smaller image and see if they match.
 709       */
 710      if ( $source_width > $target_width ) {
 711          $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
 712          $expected_size    = array( $target_width, $target_height );
 713      } else {
 714          $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
 715          $expected_size    = array( $source_width, $source_height );
 716      }
 717  
 718      // If the image dimensions are within 1px of the expected size, we consider it a match.
 719      $matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
 720  
 721      return $matched;
 722  }
 723  
 724  /**
 725   * Retrieves the image's intermediate size (resized) path, width, and height.
 726   *
 727   * The $size parameter can be an array with the width and height respectively.
 728   * If the size matches the 'sizes' metadata array for width and height, then it
 729   * will be used. If there is no direct match, then the nearest image size larger
 730   * than the specified size will be used. If nothing is found, then the function
 731   * will break out and return false.
 732   *
 733   * The metadata 'sizes' is used for compatible sizes that can be used for the
 734   * parameter $size value.
 735   *
 736   * The url path will be given, when the $size parameter is a string.
 737   *
 738   * If you are passing an array for the $size, you should consider using
 739   * add_image_size() so that a cropped version is generated. It's much more
 740   * efficient than having to find the closest-sized image and then having the
 741   * browser scale down the image.
 742   *
 743   * @since 2.5.0
 744   *
 745   * @param int          $post_id Attachment ID.
 746   * @param string|int[] $size    Optional. Image size. Accepts any registered image size name, or an array
 747   *                              of width and height values in pixels (in that order). Default 'thumbnail'.
 748   * @return array|false {
 749   *     Array of file relative path, width, and height on success. Additionally includes absolute
 750   *     path and URL if registered size is passed to `$size` parameter. False on failure.
 751   *
 752   *     @type string $file   Path of image relative to uploads directory.
 753   *     @type int    $width  Width of image in pixels.
 754   *     @type int    $height Height of image in pixels.
 755   *     @type string $path   Absolute filesystem path of image.
 756   *     @type string $url    URL of image.
 757   * }
 758   */
 759  function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
 760      $imagedata = wp_get_attachment_metadata( $post_id );
 761  
 762      if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
 763          return false;
 764      }
 765  
 766      $data = array();
 767  
 768      // Find the best match when '$size' is an array.
 769      if ( is_array( $size ) ) {
 770          $candidates = array();
 771  
 772          if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
 773              $imagedata['height'] = $imagedata['sizes']['full']['height'];
 774              $imagedata['width']  = $imagedata['sizes']['full']['width'];
 775          }
 776  
 777          foreach ( $imagedata['sizes'] as $_size => $data ) {
 778              // If there's an exact match to an existing image size, short circuit.
 779              if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) {
 780                  $candidates[ $data['width'] * $data['height'] ] = $data;
 781                  break;
 782              }
 783  
 784              // If it's not an exact match, consider larger sizes with the same aspect ratio.
 785              if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
 786                  // If '0' is passed to either size, we test ratios against the original file.
 787                  if ( 0 === $size[0] || 0 === $size[1] ) {
 788                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
 789                  } else {
 790                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
 791                  }
 792  
 793                  if ( $same_ratio ) {
 794                      $candidates[ $data['width'] * $data['height'] ] = $data;
 795                  }
 796              }
 797          }
 798  
 799          if ( ! empty( $candidates ) ) {
 800              // Sort the array by size if we have more than one candidate.
 801              if ( 1 < count( $candidates ) ) {
 802                  ksort( $candidates );
 803              }
 804  
 805              $data = array_shift( $candidates );
 806              /*
 807              * When the size requested is smaller than the thumbnail dimensions, we
 808              * fall back to the thumbnail size to maintain backward compatibility with
 809              * pre 4.6 versions of WordPress.
 810              */
 811          } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
 812              $data = $imagedata['sizes']['thumbnail'];
 813          } else {
 814              return false;
 815          }
 816  
 817          // Constrain the width and height attributes to the requested values.
 818          list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
 819  
 820      } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
 821          $data = $imagedata['sizes'][ $size ];
 822      }
 823  
 824      // If we still don't have a match at this point, return false.
 825      if ( empty( $data ) ) {
 826          return false;
 827      }
 828  
 829      // Include the full filesystem path of the intermediate file.
 830      if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
 831          $file_url     = wp_get_attachment_url( $post_id );
 832          $data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
 833          $data['url']  = path_join( dirname( $file_url ), $data['file'] );
 834      }
 835  
 836      /**
 837       * Filters the output of image_get_intermediate_size()
 838       *
 839       * @since 4.4.0
 840       *
 841       * @see image_get_intermediate_size()
 842       *
 843       * @param array        $data    Array of file relative path, width, and height on success. May also include
 844       *                              file absolute path and URL.
 845       * @param int          $post_id The ID of the image attachment.
 846       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
 847       *                              an array of width and height values in pixels (in that order).
 848       */
 849      return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
 850  }
 851  
 852  /**
 853   * Gets the available intermediate image size names.
 854   *
 855   * @since 3.0.0
 856   *
 857   * @return string[] An array of image size names.
 858   */
 859  function get_intermediate_image_sizes() {
 860      $default_sizes    = array( 'thumbnail', 'medium', 'medium_large', 'large' );
 861      $additional_sizes = wp_get_additional_image_sizes();
 862  
 863      if ( ! empty( $additional_sizes ) ) {
 864          $default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) );
 865      }
 866  
 867      /**
 868       * Filters the list of intermediate image sizes.
 869       *
 870       * @since 2.5.0
 871       *
 872       * @param string[] $default_sizes An array of intermediate image size names. Defaults
 873       *                                are 'thumbnail', 'medium', 'medium_large', 'large'.
 874       */
 875      return apply_filters( 'intermediate_image_sizes', $default_sizes );
 876  }
 877  
 878  /**
 879   * Returns a normalized list of all currently registered image sub-sizes.
 880   *
 881   * @since 5.3.0
 882   * @uses wp_get_additional_image_sizes()
 883   * @uses get_intermediate_image_sizes()
 884   *
 885   * @return array Associative array of the registered image sub-sizes.
 886   */
 887  function wp_get_registered_image_subsizes() {
 888      $additional_sizes = wp_get_additional_image_sizes();
 889      $all_sizes        = array();
 890  
 891      foreach ( get_intermediate_image_sizes() as $size_name ) {
 892          $size_data = array(
 893              'width'  => 0,
 894              'height' => 0,
 895              'crop'   => false,
 896          );
 897  
 898          if ( isset( $additional_sizes[ $size_name ]['width'] ) ) {
 899              // For sizes added by plugins and themes.
 900              $size_data['width'] = (int) $additional_sizes[ $size_name ]['width'];
 901          } else {
 902              // For default sizes set in options.
 903              $size_data['width'] = (int) get_option( "{$size_name}_size_w" );
 904          }
 905  
 906          if ( isset( $additional_sizes[ $size_name ]['height'] ) ) {
 907              $size_data['height'] = (int) $additional_sizes[ $size_name ]['height'];
 908          } else {
 909              $size_data['height'] = (int) get_option( "{$size_name}_size_h" );
 910          }
 911  
 912          if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) {
 913              // This size isn't set.
 914              continue;
 915          }
 916  
 917          if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
 918              $size_data['crop'] = $additional_sizes[ $size_name ]['crop'];
 919          } else {
 920              $size_data['crop'] = get_option( "{$size_name}_crop" );
 921          }
 922  
 923          if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) {
 924              $size_data['crop'] = (bool) $size_data['crop'];
 925          }
 926  
 927          $all_sizes[ $size_name ] = $size_data;
 928      }
 929  
 930      return $all_sizes;
 931  }
 932  
 933  /**
 934   * Retrieves an image to represent an attachment.
 935   *
 936   * @since 2.5.0
 937   *
 938   * @param int          $attachment_id Image attachment ID.
 939   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
 940   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
 941   * @param bool         $icon          Optional. Whether the image should fall back to a mime type icon. Default false.
 942   * @return array|false {
 943   *     Array of image data, or boolean false if no image is available.
 944   *
 945   *     @type string $0 Image source URL.
 946   *     @type int    $1 Image width in pixels.
 947   *     @type int    $2 Image height in pixels.
 948   *     @type bool   $3 Whether the image is a resized image.
 949   * }
 950   */
 951  function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
 952      // Get a thumbnail or intermediate image if there is one.
 953      $image = image_downsize( $attachment_id, $size );
 954      if ( ! $image ) {
 955          $src = false;
 956  
 957          if ( $icon ) {
 958              $src = wp_mime_type_icon( $attachment_id );
 959  
 960              if ( $src ) {
 961                  /** This filter is documented in wp-includes/post.php */
 962                  $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
 963  
 964                  $src_file               = $icon_dir . '/' . wp_basename( $src );
 965                  list( $width, $height ) = @getimagesize( $src_file );
 966              }
 967          }
 968  
 969          if ( $src && $width && $height ) {
 970              $image = array( $src, $width, $height, false );
 971          }
 972      }
 973      /**
 974       * Filters the attachment image source result.
 975       *
 976       * @since 4.3.0
 977       *
 978       * @param array|false  $image         {
 979       *     Array of image data, or boolean false if no image is available.
 980       *
 981       *     @type string $0 Image source URL.
 982       *     @type int    $1 Image width in pixels.
 983       *     @type int    $2 Image height in pixels.
 984       *     @type bool   $3 Whether the image is a resized image.
 985       * }
 986       * @param int          $attachment_id Image attachment ID.
 987       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
 988       *                                    an array of width and height values in pixels (in that order).
 989       * @param bool         $icon          Whether the image should be treated as an icon.
 990       */
 991      return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
 992  }
 993  
 994  /**
 995   * Get an HTML img element representing an image attachment.
 996   *
 997   * While `$size` will accept an array, it is better to register a size with
 998   * add_image_size() so that a cropped version is generated. It's much more
 999   * efficient than having to find the closest-sized image and then having the
1000   * browser scale down the image.
1001   *
1002   * @since 2.5.0
1003   * @since 4.4.0 The `$srcset` and `$sizes` attributes were added.
1004   * @since 5.5.0 The `$loading` attribute was added.
1005   *
1006   * @param int          $attachment_id Image attachment ID.
1007   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array
1008   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
1009   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1010   * @param string|array $attr {
1011   *     Optional. Attributes for the image markup.
1012   *
1013   *     @type string       $src     Image attachment URL.
1014   *     @type string       $class   CSS class name or space-separated list of classes.
1015   *                                 Default `attachment-$size_class size-$size_class`,
1016   *                                 where `$size_class` is the image size being requested.
1017   *     @type string       $alt     Image description for the alt attribute.
1018   *     @type string       $srcset  The 'srcset' attribute value.
1019   *     @type string       $sizes   The 'sizes' attribute value.
1020   *     @type string|false $loading The 'loading' attribute value. Passing a value of false
1021   *                                 will result in the attribute being omitted for the image.
1022   *                                 Defaults to 'lazy', depending on wp_lazy_loading_enabled().
1023   * }
1024   * @return string HTML img element or empty string on failure.
1025   */
1026  function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
1027      $html  = '';
1028      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1029  
1030      if ( $image ) {
1031          list( $src, $width, $height ) = $image;
1032  
1033          $attachment = get_post( $attachment_id );
1034          $hwstring   = image_hwstring( $width, $height );
1035          $size_class = $size;
1036  
1037          if ( is_array( $size_class ) ) {
1038              $size_class = implode( 'x', $size_class );
1039          }
1040  
1041          $default_attr = array(
1042              'src'   => $src,
1043              'class' => "attachment-$size_class size-$size_class",
1044              'alt'   => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
1045          );
1046  
1047          // Add `loading` attribute.
1048          if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
1049              $default_attr['loading'] = 'lazy';
1050          }
1051  
1052          $attr = wp_parse_args( $attr, $default_attr );
1053  
1054          // If the default value of `lazy` for the `loading` attribute is overridden
1055          // to omit the attribute for this image, ensure it is not included.
1056          if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
1057              unset( $attr['loading'] );
1058          }
1059  
1060          // Generate 'srcset' and 'sizes' if not already present.
1061          if ( empty( $attr['srcset'] ) ) {
1062              $image_meta = wp_get_attachment_metadata( $attachment_id );
1063  
1064              if ( is_array( $image_meta ) ) {
1065                  $size_array = array( absint( $width ), absint( $height ) );
1066                  $srcset     = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
1067                  $sizes      = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
1068  
1069                  if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
1070                      $attr['srcset'] = $srcset;
1071  
1072                      if ( empty( $attr['sizes'] ) ) {
1073                          $attr['sizes'] = $sizes;
1074                      }
1075                  }
1076              }
1077          }
1078  
1079          /**
1080           * Filters the list of attachment image attributes.
1081           *
1082           * @since 2.8.0
1083           *
1084           * @param string[]     $attr       Array of attribute values for the image markup, keyed by attribute name.
1085           *                                 See wp_get_attachment_image().
1086           * @param WP_Post      $attachment Image attachment post.
1087           * @param string|int[] $size       Requested image size. Can be any registered image size name, or
1088           *                                 an array of width and height values in pixels (in that order).
1089           */
1090          $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
1091  
1092          $attr = array_map( 'esc_attr', $attr );
1093          $html = rtrim( "<img $hwstring" );
1094  
1095          foreach ( $attr as $name => $value ) {
1096              $html .= " $name=" . '"' . $value . '"';
1097          }
1098  
1099          $html .= ' />';
1100      }
1101  
1102      /**
1103       * HTML img element representing an image attachment.
1104       *
1105       * @since 5.6.0
1106       *
1107       * @param string       $html          HTML img element or empty string on failure.
1108       * @param int          $attachment_id Image attachment ID.
1109       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1110       *                                    an array of width and height values in pixels (in that order).
1111       * @param bool         $icon          Whether the image should be treated as an icon.
1112       * @param string[]     $attr          Array of attribute values for the image markup, keyed by attribute name.
1113       *                                    See wp_get_attachment_image().
1114       */
1115      return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
1116  }
1117  
1118  /**
1119   * Get the URL of an image attachment.
1120   *
1121   * @since 4.4.0
1122   *
1123   * @param int          $attachment_id Image attachment ID.
1124   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1125   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
1126   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1127   * @return string|false Attachment URL or false if no image is available.
1128   */
1129  function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
1130      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1131      return isset( $image['0'] ) ? $image['0'] : false;
1132  }
1133  
1134  /**
1135   * Get the attachment path relative to the upload directory.
1136   *
1137   * @since 4.4.1
1138   * @access private
1139   *
1140   * @param string $file Attachment file name.
1141   * @return string Attachment path relative to the upload directory.
1142   */
1143  function _wp_get_attachment_relative_path( $file ) {
1144      $dirname = dirname( $file );
1145  
1146      if ( '.' === $dirname ) {
1147          return '';
1148      }
1149  
1150      if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
1151          // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
1152          $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
1153          $dirname = ltrim( $dirname, '/' );
1154      }
1155  
1156      return $dirname;
1157  }
1158  
1159  /**
1160   * Get the image size as array from its meta data.
1161   *
1162   * Used for responsive images.
1163   *
1164   * @since 4.4.0
1165   * @access private
1166   *
1167   * @param string $size_name  Image size. Accepts any registered image size name.
1168   * @param array  $image_meta The image meta data.
1169   * @return array|false {
1170   *     Array of width and height or false if the size isn't present in the meta data.
1171   *
1172   *     @type int $0 Image width.
1173   *     @type int $1 Image height.
1174   * }
1175   */
1176  function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
1177      if ( 'full' === $size_name ) {
1178          return array(
1179              absint( $image_meta['width'] ),
1180              absint( $image_meta['height'] ),
1181          );
1182      } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) {
1183          return array(
1184              absint( $image_meta['sizes'][ $size_name ]['width'] ),
1185              absint( $image_meta['sizes'][ $size_name ]['height'] ),
1186          );
1187      }
1188  
1189      return false;
1190  }
1191  
1192  /**
1193   * Retrieves the value for an image attachment's 'srcset' attribute.
1194   *
1195   * @since 4.4.0
1196   *
1197   * @see wp_calculate_image_srcset()
1198   *
1199   * @param int          $attachment_id Image attachment ID.
1200   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1201   *                                    width and height values in pixels (in that order). Default 'medium'.
1202   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1203   *                                    Default null.
1204   * @return string|false A 'srcset' value string or false.
1205   */
1206  function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
1207      $image = wp_get_attachment_image_src( $attachment_id, $size );
1208  
1209      if ( ! $image ) {
1210          return false;
1211      }
1212  
1213      if ( ! is_array( $image_meta ) ) {
1214          $image_meta = wp_get_attachment_metadata( $attachment_id );
1215      }
1216  
1217      $image_src  = $image[0];
1218      $size_array = array(
1219          absint( $image[1] ),
1220          absint( $image[2] ),
1221      );
1222  
1223      return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1224  }
1225  
1226  /**
1227   * A helper function to calculate the image sources to include in a 'srcset' attribute.
1228   *
1229   * @since 4.4.0
1230   *
1231   * @param int[]  $size_array    {
1232   *     An array of width and height values.
1233   *
1234   *     @type int $0 The width in pixels.
1235   *     @type int $1 The height in pixels.
1236   * }
1237   * @param string $image_src     The 'src' of the image.
1238   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1239   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1240   * @return string|false The 'srcset' attribute value. False on error or when only one source exists.
1241   */
1242  function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1243      /**
1244       * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
1245       *
1246       * @since 4.5.0
1247       *
1248       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1249       * @param int[]  $size_array    {
1250       *     An array of requested width and height values.
1251       *
1252       *     @type int $0 The width in pixels.
1253       *     @type int $1 The height in pixels.
1254       * }
1255       * @param string $image_src     The 'src' of the image.
1256       * @param int    $attachment_id The image attachment ID or 0 if not supplied.
1257       */
1258      $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1259  
1260      if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
1261          return false;
1262      }
1263  
1264      $image_sizes = $image_meta['sizes'];
1265  
1266      // Get the width and height of the image.
1267      $image_width  = (int) $size_array[0];
1268      $image_height = (int) $size_array[1];
1269  
1270      // Bail early if error/no width.
1271      if ( $image_width < 1 ) {
1272          return false;
1273      }
1274  
1275      $image_basename = wp_basename( $image_meta['file'] );
1276  
1277      /*
1278       * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1279       * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1280       * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1281       */
1282      if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1283          $image_sizes[] = array(
1284              'width'  => $image_meta['width'],
1285              'height' => $image_meta['height'],
1286              'file'   => $image_basename,
1287          );
1288      } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1289          return false;
1290      }
1291  
1292      // Retrieve the uploads sub-directory from the full size image.
1293      $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1294  
1295      if ( $dirname ) {
1296          $dirname = trailingslashit( $dirname );
1297      }
1298  
1299      $upload_dir    = wp_get_upload_dir();
1300      $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1301  
1302      /*
1303       * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1304       * (which is to say, when they share the domain name of the current request).
1305       */
1306      if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
1307          $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1308      }
1309  
1310      /*
1311       * Images that have been edited in WordPress after being uploaded will
1312       * contain a unique hash. Look for that hash and use it later to filter
1313       * out images that are leftovers from previous versions.
1314       */
1315      $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1316  
1317      /**
1318       * Filters the maximum image width to be included in a 'srcset' attribute.
1319       *
1320       * @since 4.4.0
1321       *
1322       * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '2048'.
1323       * @param int[] $size_array {
1324       *     An array of requested width and height values.
1325       *
1326       *     @type int $0 The width in pixels.
1327       *     @type int $1 The height in pixels.
1328       * }
1329       */
1330      $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
1331  
1332      // Array to hold URL candidates.
1333      $sources = array();
1334  
1335      /**
1336       * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1337       * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1338       * an incorrect image. See #35045.
1339       */
1340      $src_matched = false;
1341  
1342      /*
1343       * Loop through available images. Only use images that are resized
1344       * versions of the same edit.
1345       */
1346      foreach ( $image_sizes as $image ) {
1347          $is_src = false;
1348  
1349          // Check if image meta isn't corrupted.
1350          if ( ! is_array( $image ) ) {
1351              continue;
1352          }
1353  
1354          // If the file name is part of the `src`, we've confirmed a match.
1355          if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1356              $src_matched = true;
1357              $is_src      = true;
1358          }
1359  
1360          // Filter out images that are from previous edits.
1361          if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1362              continue;
1363          }
1364  
1365          /*
1366           * Filters out images that are wider than '$max_srcset_image_width' unless
1367           * that file is in the 'src' attribute.
1368           */
1369          if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1370              continue;
1371          }
1372  
1373          // If the image dimensions are within 1px of the expected size, use it.
1374          if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
1375              // Add the URL, descriptor, and value to the sources array to be returned.
1376              $source = array(
1377                  'url'        => $image_baseurl . $image['file'],
1378                  'descriptor' => 'w',
1379                  'value'      => $image['width'],
1380              );
1381  
1382              // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1383              if ( $is_src ) {
1384                  $sources = array( $image['width'] => $source ) + $sources;
1385              } else {
1386                  $sources[ $image['width'] ] = $source;
1387              }
1388          }
1389      }
1390  
1391      /**
1392       * Filters an image's 'srcset' sources.
1393       *
1394       * @since 4.4.0
1395       *
1396       * @param array  $sources {
1397       *     One or more arrays of source data to include in the 'srcset'.
1398       *
1399       *     @type array $width {
1400       *         @type string $url        The URL of an image source.
1401       *         @type string $descriptor The descriptor type used in the image candidate string,
1402       *                                  either 'w' or 'x'.
1403       *         @type int    $value      The source width if paired with a 'w' descriptor, or a
1404       *                                  pixel density value if paired with an 'x' descriptor.
1405       *     }
1406       * }
1407       * @param array $size_array     {
1408       *     An array of requested width and height values.
1409       *
1410       *     @type int $0 The width in pixels.
1411       *     @type int $1 The height in pixels.
1412       * }
1413       * @param string $image_src     The 'src' of the image.
1414       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1415       * @param int    $attachment_id Image attachment ID or 0.
1416       */
1417      $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1418  
1419      // Only return a 'srcset' value if there is more than one source.
1420      if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) {
1421          return false;
1422      }
1423  
1424      $srcset = '';
1425  
1426      foreach ( $sources as $source ) {
1427          $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
1428      }
1429  
1430      return rtrim( $srcset, ', ' );
1431  }
1432  
1433  /**
1434   * Retrieves the value for an image attachment's 'sizes' attribute.
1435   *
1436   * @since 4.4.0
1437   *
1438   * @see wp_calculate_image_sizes()
1439   *
1440   * @param int          $attachment_id Image attachment ID.
1441   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1442   *                                    width and height values in pixels (in that order). Default 'medium'.
1443   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1444   *                                    Default null.
1445   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1446   */
1447  function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1448      $image = wp_get_attachment_image_src( $attachment_id, $size );
1449  
1450      if ( ! $image ) {
1451          return false;
1452      }
1453  
1454      if ( ! is_array( $image_meta ) ) {
1455          $image_meta = wp_get_attachment_metadata( $attachment_id );
1456      }
1457  
1458      $image_src  = $image[0];
1459      $size_array = array(
1460          absint( $image[1] ),
1461          absint( $image[2] ),
1462      );
1463  
1464      return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1465  }
1466  
1467  /**
1468   * Creates a 'sizes' attribute value for an image.
1469   *
1470   * @since 4.4.0
1471   *
1472   * @param string|int[] $size          Image size. Accepts any registered image size name, or an array of
1473   *                                    width and height values in pixels (in that order).
1474   * @param string       $image_src     Optional. The URL to the image file. Default null.
1475   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1476   *                                    Default null.
1477   * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1478   *                                    is needed when using the image size name as argument for `$size`. Default 0.
1479   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1480   */
1481  function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1482      $width = 0;
1483  
1484      if ( is_array( $size ) ) {
1485          $width = absint( $size[0] );
1486      } elseif ( is_string( $size ) ) {
1487          if ( ! $image_meta && $attachment_id ) {
1488              $image_meta = wp_get_attachment_metadata( $attachment_id );
1489          }
1490  
1491          if ( is_array( $image_meta ) ) {
1492              $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1493              if ( $size_array ) {
1494                  $width = absint( $size_array[0] );
1495              }
1496          }
1497      }
1498  
1499      if ( ! $width ) {
1500          return false;
1501      }
1502  
1503      // Setup the default 'sizes' attribute.
1504      $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1505  
1506      /**
1507       * Filters the output of 'wp_calculate_image_sizes()'.
1508       *
1509       * @since 4.4.0
1510       *
1511       * @param string       $sizes         A source size value for use in a 'sizes' attribute.
1512       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1513       *                                    an array of width and height values in pixels (in that order).
1514       * @param string|null  $image_src     The URL to the image file or null.
1515       * @param array|null   $image_meta    The image meta data as returned by wp_get_attachment_metadata() or null.
1516       * @param int          $attachment_id Image attachment ID of the original image or 0.
1517       */
1518      return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1519  }
1520  
1521  /**
1522   * Determines if the image meta data is for the image source file.
1523   *
1524   * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change.
1525   * For example when the website is exported and imported at another website. Then the
1526   * attachment post IDs that are in post_content for the exported website may not match
1527   * the same attachments at the new website.
1528   *
1529   * @since 5.5.0
1530   *
1531   * @param string $image_location The full path or URI to the image file.
1532   * @param array  $image_meta     The attachment meta data as returned by 'wp_get_attachment_metadata()'.
1533   * @param int    $attachment_id  Optional. The image attachment ID. Default 0.
1534   * @return bool Whether the image meta is for this image file.
1535   */
1536  function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) {
1537      $match = false;
1538  
1539      // Ensure the $image_meta is valid.
1540      if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) {
1541          // Remove quiery args if image URI.
1542          list( $image_location ) = explode( '?', $image_location );
1543  
1544          // Check if the relative image path from the image meta is at the end of $image_location.
1545          if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) {
1546              $match = true;
1547          } else {
1548              // Retrieve the uploads sub-directory from the full size image.
1549              $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1550  
1551              if ( $dirname ) {
1552                  $dirname = trailingslashit( $dirname );
1553              }
1554  
1555              if ( ! empty( $image_meta['original_image'] ) ) {
1556                  $relative_path = $dirname . $image_meta['original_image'];
1557  
1558                  if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1559                      $match = true;
1560                  }
1561              }
1562  
1563              if ( ! $match && ! empty( $image_meta['sizes'] ) ) {
1564                  foreach ( $image_meta['sizes'] as $image_size_data ) {
1565                      $relative_path = $dirname . $image_size_data['file'];
1566  
1567                      if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1568                          $match = true;
1569                          break;
1570                      }
1571                  }
1572              }
1573          }
1574      }
1575  
1576      /**
1577       * Filters whether an image path or URI matches image meta.
1578       *
1579       * @since 5.5.0
1580       *
1581       * @param bool   $match          Whether the image relative path from the image meta
1582       *                               matches the end of the URI or path to the image file.
1583       * @param string $image_location Full path or URI to the tested image file.
1584       * @param array  $image_meta     The image meta data as returned by 'wp_get_attachment_metadata()'.
1585       * @param int    $attachment_id  The image attachment ID or 0 if not supplied.
1586       */
1587      return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id );
1588  }
1589  
1590  /**
1591   * Determines an image's width and height dimensions based on the source file.
1592   *
1593   * @since 5.5.0
1594   *
1595   * @param string $image_src     The image source file.
1596   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1597   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1598   * @return array|false Array with first element being the width and second element being the height,
1599   *                     or false if dimensions cannot be determined.
1600   */
1601  function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) {
1602      if ( ! wp_image_file_matches_image_meta( $image_src, $image_meta, $attachment_id ) ) {
1603          return false;
1604      }
1605  
1606      // Is it a full size image?
1607      if ( strpos( $image_src, $image_meta['file'] ) !== false ) {
1608          return array(
1609              (int) $image_meta['width'],
1610              (int) $image_meta['height'],
1611          );
1612      }
1613  
1614      if ( ! empty( $image_meta['sizes'] ) ) {
1615          $src_filename = wp_basename( $image_src );
1616  
1617          foreach ( $image_meta['sizes'] as $image_size_data ) {
1618              if ( $src_filename === $image_size_data['file'] ) {
1619                  return array(
1620                      (int) $image_size_data['width'],
1621                      (int) $image_size_data['height'],
1622                  );
1623              }
1624          }
1625      }
1626  
1627      return false;
1628  }
1629  
1630  /**
1631   * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1632   *
1633   * @since 4.4.0
1634   *
1635   * @see wp_calculate_image_srcset()
1636   * @see wp_calculate_image_sizes()
1637   *
1638   * @param string $image         An HTML 'img' element to be filtered.
1639   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1640   * @param int    $attachment_id Image attachment ID.
1641   * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1642   */
1643  function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1644      // Ensure the image meta exists.
1645      if ( empty( $image_meta['sizes'] ) ) {
1646          return $image;
1647      }
1648  
1649      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1650      list( $image_src ) = explode( '?', $image_src );
1651  
1652      // Return early if we couldn't get the image source.
1653      if ( ! $image_src ) {
1654          return $image;
1655      }
1656  
1657      // Bail early if an image has been inserted and later edited.
1658      if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1659          strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1660  
1661          return $image;
1662      }
1663  
1664      $width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1665      $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1666  
1667      if ( $width && $height ) {
1668          $size_array = array( $width, $height );
1669      } else {
1670          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
1671          if ( ! $size_array ) {
1672              return $image;
1673          }
1674      }
1675  
1676      $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1677  
1678      if ( $srcset ) {
1679          // Check if there is already a 'sizes' attribute.
1680          $sizes = strpos( $image, ' sizes=' );
1681  
1682          if ( ! $sizes ) {
1683              $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1684          }
1685      }
1686  
1687      if ( $srcset && $sizes ) {
1688          // Format the 'srcset' and 'sizes' string and escape attributes.
1689          $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1690  
1691          if ( is_string( $sizes ) ) {
1692              $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1693          }
1694  
1695          // Add the srcset and sizes attributes to the image markup.
1696          return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1697      }
1698  
1699      return $image;
1700  }
1701  
1702  /**
1703   * Determines whether to add the `loading` attribute to the specified tag in the specified context.
1704   *
1705   * @since 5.5.0
1706   * @since 5.7.0 Now returns `true` by default for `iframe` tags.
1707   *
1708   * @param string $tag_name The tag name.
1709   * @param string $context  Additional context, like the current filter name
1710   *                         or the function name from where this was called.
1711   * @return bool Whether to add the attribute.
1712   */
1713  function wp_lazy_loading_enabled( $tag_name, $context ) {
1714      // By default add to all 'img' and 'iframe' tags.
1715      // See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
1716      // See https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-loading
1717      $default = ( 'img' === $tag_name || 'iframe' === $tag_name );
1718  
1719      /**
1720       * Filters whether to add the `loading` attribute to the specified tag in the specified context.
1721       *
1722       * @since 5.5.0
1723       *
1724       * @param bool   $default  Default value.
1725       * @param string $tag_name The tag name.
1726       * @param string $context  Additional context, like the current filter name
1727       *                         or the function name from where this was called.
1728       */
1729      return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
1730  }
1731  
1732  /**
1733   * Filters specific tags in post content and modifies their markup.
1734   *
1735   * Modifies HTML tags in post content to include new browser and HTML technologies
1736   * that may not have existed at the time of post creation. These modifications currently
1737   * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags, as well
1738   * as adding `loading` attributes to `iframe` HTML tags.
1739   * Future similar optimizations should be added/expected here.
1740   *
1741   * @since 5.5.0
1742   * @since 5.7.0 Now supports adding `loading` attributes to `iframe` tags.
1743   *
1744   * @see wp_img_tag_add_width_and_height_attr()
1745   * @see wp_img_tag_add_srcset_and_sizes_attr()
1746   * @see wp_img_tag_add_loading_attr()
1747   * @see wp_iframe_tag_add_loading_attr()
1748   *
1749   * @param string $content The HTML content to be filtered.
1750   * @param string $context Optional. Additional context to pass to the filters.
1751   *                        Defaults to `current_filter()` when not set.
1752   * @return string Converted content with images modified.
1753   */
1754  function wp_filter_content_tags( $content, $context = null ) {
1755      if ( null === $context ) {
1756          $context = current_filter();
1757      }
1758  
1759      $add_img_loading_attr    = wp_lazy_loading_enabled( 'img', $context );
1760      $add_iframe_loading_attr = wp_lazy_loading_enabled( 'iframe', $context );
1761  
1762      if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
1763          return $content;
1764      }
1765  
1766      // List of the unique `img` tags found in $content.
1767      $images = array();
1768  
1769      // List of the unique `iframe` tags found in $content.
1770      $iframes = array();
1771  
1772      foreach ( $matches as $match ) {
1773          list( $tag, $tag_name ) = $match;
1774  
1775          switch ( $tag_name ) {
1776              case 'img':
1777                  if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) {
1778                      $attachment_id = absint( $class_id[1] );
1779  
1780                      if ( $attachment_id ) {
1781                          // If exactly the same image tag is used more than once, overwrite it.
1782                          // All identical tags will be replaced later with 'str_replace()'.
1783                          $images[ $tag ] = $attachment_id;
1784                          break;
1785                      }
1786                  }
1787                  $images[ $tag ] = 0;
1788                  break;
1789              case 'iframe':
1790                  $iframes[ $tag ] = 0;
1791                  break;
1792          }
1793      }
1794  
1795      // Reduce the array to unique attachment IDs.
1796      $attachment_ids = array_unique( array_filter( array_values( $images ) ) );
1797  
1798      if ( count( $attachment_ids ) > 1 ) {
1799          /*
1800           * Warm the object cache with post and meta information for all found
1801           * images to avoid making individual database calls.
1802           */
1803          _prime_post_caches( $attachment_ids, false, true );
1804      }
1805  
1806      foreach ( $images as $image => $attachment_id ) {
1807          $filtered_image = $image;
1808  
1809          // Add 'width' and 'height' attributes if applicable.
1810          if ( $attachment_id > 0 && false === strpos( $filtered_image, ' width=' ) && false === strpos( $filtered_image, ' height=' ) ) {
1811              $filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id );
1812          }
1813  
1814          // Add 'srcset' and 'sizes' attributes if applicable.
1815          if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
1816              $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
1817          }
1818  
1819          // Add 'loading' attribute if applicable.
1820          if ( $add_img_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
1821              $filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
1822          }
1823  
1824          if ( $filtered_image !== $image ) {
1825              $content = str_replace( $image, $filtered_image, $content );
1826          }
1827      }
1828  
1829      foreach ( $iframes as $iframe => $attachment_id ) {
1830          $filtered_iframe = $iframe;
1831  
1832          // Add 'loading' attribute if applicable.
1833          if ( $add_iframe_loading_attr && false === strpos( $filtered_iframe, ' loading=' ) ) {
1834              $filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, $context );
1835          }
1836  
1837          if ( $filtered_iframe !== $iframe ) {
1838              $content = str_replace( $iframe, $filtered_iframe, $content );
1839          }
1840      }
1841  
1842      return $content;
1843  }
1844  
1845  /**
1846   * Adds `loading` attribute to an `img` HTML tag.
1847   *
1848   * @since 5.5.0
1849   *
1850   * @param string $image   The HTML `img` tag where the attribute should be added.
1851   * @param string $context Additional context to pass to the filters.
1852   * @return string Converted `img` tag with `loading` attribute added.
1853   */
1854  function wp_img_tag_add_loading_attr( $image, $context ) {
1855      /**
1856       * Filters the `loading` attribute value to add to an image. Default `lazy`.
1857       *
1858       * Returning `false` or an empty string will not add the attribute.
1859       * Returning `true` will add the default value.
1860       *
1861       * @since 5.5.0
1862       *
1863       * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
1864       *                             the attribute being omitted for the image. Default 'lazy'.
1865       * @param string      $image   The HTML `img` tag to be filtered.
1866       * @param string      $context Additional context about how the function was called or where the img tag is.
1867       */
1868      $value = apply_filters( 'wp_img_tag_add_loading_attr', 'lazy', $image, $context );
1869  
1870      if ( $value ) {
1871          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
1872              $value = 'lazy';
1873          }
1874  
1875          // Images should have source and dimension attributes for the `loading` attribute to be added.
1876          if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) {
1877              return $image;
1878          }
1879  
1880          return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image );
1881      }
1882  
1883      return $image;
1884  }
1885  
1886  /**
1887   * Adds `width` and `height` attributes to an `img` HTML tag.
1888   *
1889   * @since 5.5.0
1890   *
1891   * @param string $image         The HTML `img` tag where the attribute should be added.
1892   * @param string $context       Additional context to pass to the filters.
1893   * @param int    $attachment_id Image attachment ID.
1894   * @return string Converted 'img' element with 'width' and 'height' attributes added.
1895   */
1896  function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
1897      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1898      list( $image_src ) = explode( '?', $image_src );
1899  
1900      // Return early if we couldn't get the image source.
1901      if ( ! $image_src ) {
1902          return $image;
1903      }
1904  
1905      /**
1906       * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
1907       *
1908       * Returning anything else than `true` will not add the attributes.
1909       *
1910       * @since 5.5.0
1911       *
1912       * @param bool   $value         The filtered value, defaults to `true`.
1913       * @param string $image         The HTML `img` tag where the attribute should be added.
1914       * @param string $context       Additional context about how the function was called or where the img tag is.
1915       * @param int    $attachment_id The image attachment ID.
1916       */
1917      $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
1918  
1919      if ( true === $add ) {
1920          $image_meta = wp_get_attachment_metadata( $attachment_id );
1921          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
1922  
1923          if ( $size_array ) {
1924              $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
1925              return str_replace( '<img', "<img {$hw}", $image );
1926          }
1927      }
1928  
1929      return $image;
1930  }
1931  
1932  /**
1933   * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
1934   *
1935   * @since 5.5.0
1936   *
1937   * @param string $image         The HTML `img` tag where the attribute should be added.
1938   * @param string $context       Additional context to pass to the filters.
1939   * @param int    $attachment_id Image attachment ID.
1940   * @return string Converted 'img' element with 'loading' attribute added.
1941   */
1942  function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
1943      /**
1944       * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
1945       *
1946       * Returning anything else than `true` will not add the attributes.
1947       *
1948       * @since 5.5.0
1949       *
1950       * @param bool   $value         The filtered value, defaults to `true`.
1951       * @param string $image         The HTML `img` tag where the attribute should be added.
1952       * @param string $context       Additional context about how the function was called or where the img tag is.
1953       * @param int    $attachment_id The image attachment ID.
1954       */
1955      $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
1956  
1957      if ( true === $add ) {
1958          $image_meta = wp_get_attachment_metadata( $attachment_id );
1959          return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
1960      }
1961  
1962      return $image;
1963  }
1964  
1965  /**
1966   * Adds `loading` attribute to an `iframe` HTML tag.
1967   *
1968   * @since 5.7.0
1969   *
1970   * @param string $iframe  The HTML `iframe` tag where the attribute should be added.
1971   * @param string $context Additional context to pass to the filters.
1972   * @return string Converted `iframe` tag with `loading` attribute added.
1973   */
1974  function wp_iframe_tag_add_loading_attr( $iframe, $context ) {
1975      /**
1976       * Filters the `loading` attribute value to add to an iframe. Default `lazy`.
1977       *
1978       * Returning `false` or an empty string will not add the attribute.
1979       * Returning `true` will add the default value.
1980       *
1981       * @since 5.7.0
1982       *
1983       * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
1984       *                             the attribute being omitted for the iframe. Default 'lazy'.
1985       * @param string      $iframe  The HTML `iframe` tag to be filtered.
1986       * @param string      $context Additional context about how the function was called or where the iframe tag is.
1987       */
1988      $value = apply_filters( 'wp_iframe_tag_add_loading_attr', 'lazy', $iframe, $context );
1989  
1990      if ( $value ) {
1991          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
1992              $value = 'lazy';
1993          }
1994  
1995          // Iframes should have source and dimension attributes for the `loading` attribute to be added.
1996          if ( false === strpos( $iframe, ' src="' ) || false === strpos( $iframe, ' width="' ) || false === strpos( $iframe, ' height="' ) ) {
1997              return $iframe;
1998          }
1999  
2000          return str_replace( '<iframe', '<iframe loading="' . esc_attr( $value ) . '"', $iframe );
2001      }
2002  
2003      return $iframe;
2004  }
2005  
2006  /**
2007   * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
2008   *
2009   * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
2010   * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
2011   *
2012   * @ignore
2013   * @since 2.9.0
2014   *
2015   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2016   * @return string[] Modified array of attributes including the new 'wp-post-image' class.
2017   */
2018  function _wp_post_thumbnail_class_filter( $attr ) {
2019      $attr['class'] .= ' wp-post-image';
2020      return $attr;
2021  }
2022  
2023  /**
2024   * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
2025   * filter hook. Internal use only.
2026   *
2027   * @ignore
2028   * @since 2.9.0
2029   *
2030   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2031   */
2032  function _wp_post_thumbnail_class_filter_add( $attr ) {
2033      add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2034  }
2035  
2036  /**
2037   * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
2038   * filter hook. Internal use only.
2039   *
2040   * @ignore
2041   * @since 2.9.0
2042   *
2043   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2044   */
2045  function _wp_post_thumbnail_class_filter_remove( $attr ) {
2046      remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2047  }
2048  
2049  add_shortcode( 'wp_caption', 'img_caption_shortcode' );
2050  add_shortcode( 'caption', 'img_caption_shortcode' );
2051  
2052  /**
2053   * Builds the Caption shortcode output.
2054   *
2055   * Allows a plugin to replace the content that would otherwise be returned. The
2056   * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
2057   * parameter and the content parameter values.
2058   *
2059   * The supported attributes for the shortcode are 'id', 'caption_id', 'align',
2060   * 'width', 'caption', and 'class'.
2061   *
2062   * @since 2.6.0
2063   * @since 3.9.0 The `class` attribute was added.
2064   * @since 5.1.0 The `caption_id` attribute was added.
2065   *
2066   * @param array  $attr {
2067   *     Attributes of the caption shortcode.
2068   *
2069   *     @type string $id         ID of the image and caption container element, i.e. `<figure>` or `<div>`.
2070   *     @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`.
2071   *     @type string $align      Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
2072   *                              'aligncenter', alignright', 'alignnone'.
2073   *     @type int    $width      The width of the caption, in pixels.
2074   *     @type string $caption    The caption text.
2075   *     @type string $class      Additional class name(s) added to the caption container.
2076   * }
2077   * @param string $content Shortcode content.
2078   * @return string HTML content to display the caption.
2079   */
2080  function img_caption_shortcode( $attr, $content = null ) {
2081      // New-style shortcode with the caption inside the shortcode with the link and image tags.
2082      if ( ! isset( $attr['caption'] ) ) {
2083          if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
2084              $content         = $matches[1];
2085              $attr['caption'] = trim( $matches[2] );
2086          }
2087      } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
2088          $attr['caption'] = wp_kses( $attr['caption'], 'post' );
2089      }
2090  
2091      /**
2092       * Filters the default caption shortcode output.
2093       *
2094       * If the filtered output isn't empty, it will be used instead of generating
2095       * the default caption template.
2096       *
2097       * @since 2.6.0
2098       *
2099       * @see img_caption_shortcode()
2100       *
2101       * @param string $output  The caption output. Default empty.
2102       * @param array  $attr    Attributes of the caption shortcode.
2103       * @param string $content The image element, possibly wrapped in a hyperlink.
2104       */
2105      $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
2106  
2107      if ( ! empty( $output ) ) {
2108          return $output;
2109      }
2110  
2111      $atts = shortcode_atts(
2112          array(
2113              'id'         => '',
2114              'caption_id' => '',
2115              'align'      => 'alignnone',
2116              'width'      => '',
2117              'caption'    => '',
2118              'class'      => '',
2119          ),
2120          $attr,
2121          'caption'
2122      );
2123  
2124      $atts['width'] = (int) $atts['width'];
2125  
2126      if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
2127          return $content;
2128      }
2129  
2130      $id          = '';
2131      $caption_id  = '';
2132      $describedby = '';
2133  
2134      if ( $atts['id'] ) {
2135          $atts['id'] = sanitize_html_class( $atts['id'] );
2136          $id         = 'id="' . esc_attr( $atts['id'] ) . '" ';
2137      }
2138  
2139      if ( $atts['caption_id'] ) {
2140          $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
2141      } elseif ( $atts['id'] ) {
2142          $atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
2143      }
2144  
2145      if ( $atts['caption_id'] ) {
2146          $caption_id  = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
2147          $describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
2148      }
2149  
2150      $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
2151  
2152      $html5 = current_theme_supports( 'html5', 'caption' );
2153      // HTML5 captions never added the extra 10px to the image width.
2154      $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
2155  
2156      /**
2157       * Filters the width of an image's caption.
2158       *
2159       * By default, the caption is 10 pixels greater than the width of the image,
2160       * to prevent post content from running up against a floated image.
2161       *
2162       * @since 3.7.0
2163       *
2164       * @see img_caption_shortcode()
2165       *
2166       * @param int    $width    Width of the caption in pixels. To remove this inline style,
2167       *                         return zero.
2168       * @param array  $atts     Attributes of the caption shortcode.
2169       * @param string $content  The image element, possibly wrapped in a hyperlink.
2170       */
2171      $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
2172  
2173      $style = '';
2174  
2175      if ( $caption_width ) {
2176          $style = 'style="width: ' . (int) $caption_width . 'px" ';
2177      }
2178  
2179      if ( $html5 ) {
2180          $html = sprintf(
2181              '<figure %s%s%sclass="%s">%s%s</figure>',
2182              $id,
2183              $describedby,
2184              $style,
2185              esc_attr( $class ),
2186              do_shortcode( $content ),
2187              sprintf(
2188                  '<figcaption %sclass="wp-caption-text">%s</figcaption>',
2189                  $caption_id,
2190                  $atts['caption']
2191              )
2192          );
2193      } else {
2194          $html = sprintf(
2195              '<div %s%sclass="%s">%s%s</div>',
2196              $id,
2197              $style,
2198              esc_attr( $class ),
2199              str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
2200              sprintf(
2201                  '<p %sclass="wp-caption-text">%s</p>',
2202                  $caption_id,
2203                  $atts['caption']
2204              )
2205          );
2206      }
2207  
2208      return $html;
2209  }
2210  
2211  add_shortcode( 'gallery', 'gallery_shortcode' );
2212  
2213  /**
2214   * Builds the Gallery shortcode output.
2215   *
2216   * This implements the functionality of the Gallery Shortcode for displaying
2217   * WordPress images on a post.
2218   *
2219   * @since 2.5.0
2220   *
2221   * @param array $attr {
2222   *     Attributes of the gallery shortcode.
2223   *
2224   *     @type string       $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
2225   *     @type string       $orderby    The field to use when ordering the images. Default 'menu_order ID'.
2226   *                                    Accepts any valid SQL ORDERBY statement.
2227   *     @type int          $id         Post ID.
2228   *     @type string       $itemtag    HTML tag to use for each image in the gallery.
2229   *                                    Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
2230   *     @type string       $icontag    HTML tag to use for each image's icon.
2231   *                                    Default 'dt', or 'div' when the theme registers HTML5 gallery support.
2232   *     @type string       $captiontag HTML tag to use for each image's caption.
2233   *                                    Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
2234   *     @type int          $columns    Number of columns of images to display. Default 3.
2235   *     @type string|int[] $size       Size of the images to display. Accepts any registered image size name, or an array
2236   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
2237   *     @type string       $ids        A comma-separated list of IDs of attachments to display. Default empty.
2238   *     @type string       $include    A comma-separated list of IDs of attachments to include. Default empty.
2239   *     @type string       $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
2240   *     @type string       $link       What to link each image to. Default empty (links to the attachment page).
2241   *                                    Accepts 'file', 'none'.
2242   * }
2243   * @return string HTML content to display gallery.
2244   */
2245  function gallery_shortcode( $attr ) {
2246      $post = get_post();
2247  
2248      static $instance = 0;
2249      $instance++;
2250  
2251      if ( ! empty( $attr['ids'] ) ) {
2252          // 'ids' is explicitly ordered, unless you specify otherwise.
2253          if ( empty( $attr['orderby'] ) ) {
2254              $attr['orderby'] = 'post__in';
2255          }
2256          $attr['include'] = $attr['ids'];
2257      }
2258  
2259      /**
2260       * Filters the default gallery shortcode output.
2261       *
2262       * If the filtered output isn't empty, it will be used instead of generating
2263       * the default gallery template.
2264       *
2265       * @since 2.5.0
2266       * @since 4.2.0 The `$instance` parameter was added.
2267       *
2268       * @see gallery_shortcode()
2269       *
2270       * @param string $output   The gallery output. Default empty.
2271       * @param array  $attr     Attributes of the gallery shortcode.
2272       * @param int    $instance Unique numeric ID of this gallery shortcode instance.
2273       */
2274      $output = apply_filters( 'post_gallery', '', $attr, $instance );
2275  
2276      if ( ! empty( $output ) ) {
2277          return $output;
2278      }
2279  
2280      $html5 = current_theme_supports( 'html5', 'gallery' );
2281      $atts  = shortcode_atts(
2282          array(
2283              'order'      => 'ASC',
2284              'orderby'    => 'menu_order ID',
2285              'id'         => $post ? $post->ID : 0,
2286              'itemtag'    => $html5 ? 'figure' : 'dl',
2287              'icontag'    => $html5 ? 'div' : 'dt',
2288              'captiontag' => $html5 ? 'figcaption' : 'dd',
2289              'columns'    => 3,
2290              'size'       => 'thumbnail',
2291              'include'    => '',
2292              'exclude'    => '',
2293              'link'       => '',
2294          ),
2295          $attr,
2296          'gallery'
2297      );
2298  
2299      $id = (int) $atts['id'];
2300  
2301      if ( ! empty( $atts['include'] ) ) {
2302          $_attachments = get_posts(
2303              array(
2304                  'include'        => $atts['include'],
2305                  'post_status'    => 'inherit',
2306                  'post_type'      => 'attachment',
2307                  'post_mime_type' => 'image',
2308                  'order'          => $atts['order'],
2309                  'orderby'        => $atts['orderby'],
2310              )
2311          );
2312  
2313          $attachments = array();
2314          foreach ( $_attachments as $key => $val ) {
2315              $attachments[ $val->ID ] = $_attachments[ $key ];
2316          }
2317      } elseif ( ! empty( $atts['exclude'] ) ) {
2318          $attachments = get_children(
2319              array(
2320                  'post_parent'    => $id,
2321                  'exclude'        => $atts['exclude'],
2322                  'post_status'    => 'inherit',
2323                  'post_type'      => 'attachment',
2324                  'post_mime_type' => 'image',
2325                  'order'          => $atts['order'],
2326                  'orderby'        => $atts['orderby'],
2327              )
2328          );
2329      } else {
2330          $attachments = get_children(
2331              array(
2332                  'post_parent'    => $id,
2333                  'post_status'    => 'inherit',
2334                  'post_type'      => 'attachment',
2335                  'post_mime_type' => 'image',
2336                  'order'          => $atts['order'],
2337                  'orderby'        => $atts['orderby'],
2338              )
2339          );
2340      }
2341  
2342      if ( empty( $attachments ) ) {
2343          return '';
2344      }
2345  
2346      if ( is_feed() ) {
2347          $output = "\n";
2348          foreach ( $attachments as $att_id => $attachment ) {
2349              if ( ! empty( $atts['link'] ) ) {
2350                  if ( 'none' === $atts['link'] ) {
2351                      $output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr );
2352                  } else {
2353                      $output .= wp_get_attachment_link( $att_id, $atts['size'], false );
2354                  }
2355              } else {
2356                  $output .= wp_get_attachment_link( $att_id, $atts['size'], true );
2357              }
2358              $output .= "\n";
2359          }
2360          return $output;
2361      }
2362  
2363      $itemtag    = tag_escape( $atts['itemtag'] );
2364      $captiontag = tag_escape( $atts['captiontag'] );
2365      $icontag    = tag_escape( $atts['icontag'] );
2366      $valid_tags = wp_kses_allowed_html( 'post' );
2367      if ( ! isset( $valid_tags[ $itemtag ] ) ) {
2368          $itemtag = 'dl';
2369      }
2370      if ( ! isset( $valid_tags[ $captiontag ] ) ) {
2371          $captiontag = 'dd';
2372      }
2373      if ( ! isset( $valid_tags[ $icontag ] ) ) {
2374          $icontag = 'dt';
2375      }
2376  
2377      $columns   = (int) $atts['columns'];
2378      $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
2379      $float     = is_rtl() ? 'right' : 'left';
2380  
2381      $selector = "gallery-{$instance}";
2382  
2383      $gallery_style = '';
2384  
2385      /**
2386       * Filters whether to print default gallery styles.
2387       *
2388       * @since 3.1.0
2389       *
2390       * @param bool $print Whether to print default gallery styles.
2391       *                    Defaults to false if the theme supports HTML5 galleries.
2392       *                    Otherwise, defaults to true.
2393       */
2394      if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
2395          $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
2396  
2397          $gallery_style = "
2398          <style{$type_attr}>
2399              #{$selector} {
2400                  margin: auto;
2401              }
2402              #{$selector} .gallery-item {
2403                  float: {$float};
2404                  margin-top: 10px;
2405                  text-align: center;
2406                  width: {$itemwidth}%;
2407              }
2408              #{$selector} img {
2409                  border: 2px solid #cfcfcf;
2410              }
2411              #{$selector} .gallery-caption {
2412                  margin-left: 0;
2413              }
2414              /* see gallery_shortcode() in wp-includes/media.php */
2415          </style>\n\t\t";
2416      }
2417  
2418      $size_class  = sanitize_html_class( is_array( $atts['size'] ) ? implode( 'x', $atts['size'] ) : $atts['size'] );
2419      $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
2420  
2421      /**
2422       * Filters the default gallery shortcode CSS styles.
2423       *
2424       * @since 2.5.0
2425       *
2426       * @param string $gallery_style Default CSS styles and opening HTML div container
2427       *                              for the gallery shortcode output.
2428       */
2429      $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
2430  
2431      $i = 0;
2432  
2433      foreach ( $attachments as $id => $attachment ) {
2434  
2435          $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
2436  
2437          if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
2438              $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
2439          } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
2440              $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
2441          } else {
2442              $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
2443          }
2444  
2445          $image_meta = wp_get_attachment_metadata( $id );
2446  
2447          $orientation = '';
2448  
2449          if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
2450              $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
2451          }
2452  
2453          $output .= "<{$itemtag} class='gallery-item'>";
2454          $output .= "
2455              <{$icontag} class='gallery-icon {$orientation}'>
2456                  $image_output
2457              </{$icontag}>";
2458  
2459          if ( $captiontag && trim( $attachment->post_excerpt ) ) {
2460              $output .= "
2461                  <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
2462                  " . wptexturize( $attachment->post_excerpt ) . "
2463                  </{$captiontag}>";
2464          }
2465  
2466          $output .= "</{$itemtag}>";
2467  
2468          if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
2469              $output .= '<br style="clear: both" />';
2470          }
2471      }
2472  
2473      if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
2474          $output .= "
2475              <br style='clear: both' />";
2476      }
2477  
2478      $output .= "
2479          </div>\n";
2480  
2481      return $output;
2482  }
2483  
2484  /**
2485   * Outputs the templates used by playlists.
2486   *
2487   * @since 3.9.0
2488   */
2489  function wp_underscore_playlist_templates() {
2490      ?>
2491  <script type="text/html" id="tmpl-wp-playlist-current-item">
2492      <# if ( data.thumb && data.thumb.src ) { #>
2493          <img src="{{ data.thumb.src }}" alt="" />
2494      <# } #>
2495      <div class="wp-playlist-caption">
2496          <span class="wp-playlist-item-meta wp-playlist-item-title">
2497          <?php
2498              /* translators: %s: Playlist item title. */
2499              printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
2500          ?>
2501          </span>
2502          <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
2503          <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
2504      </div>
2505  </script>
2506  <script type="text/html" id="tmpl-wp-playlist-item">
2507      <div class="wp-playlist-item">
2508          <a class="wp-playlist-caption" href="{{ data.src }}">
2509              {{ data.index ? ( data.index + '. ' ) : '' }}
2510              <# if ( data.caption ) { #>
2511                  {{ data.caption }}
2512              <# } else { #>
2513                  <span class="wp-playlist-item-title">
2514                  <?php
2515                      /* translators: %s: Playlist item title. */
2516                      printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
2517                  ?>
2518                  </span>
2519                  <# if ( data.artists && data.meta.artist ) { #>
2520                  <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
2521                  <# } #>
2522              <# } #>
2523          </a>
2524          <# if ( data.meta.length_formatted ) { #>
2525          <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
2526          <# } #>
2527      </div>
2528  </script>
2529      <?php
2530  }
2531  
2532  /**
2533   * Outputs and enqueue default scripts and styles for playlists.
2534   *
2535   * @since 3.9.0
2536   *
2537   * @param string $type Type of playlist. Accepts 'audio' or 'video'.
2538   */
2539  function wp_playlist_scripts( $type ) {
2540      wp_enqueue_style( 'wp-mediaelement' );
2541      wp_enqueue_script( 'wp-playlist' );
2542      ?>
2543  <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ); ?>');</script><![endif]-->
2544      <?php
2545      add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
2546      add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
2547  }
2548  
2549  /**
2550   * Builds the Playlist shortcode output.
2551   *
2552   * This implements the functionality of the playlist shortcode for displaying
2553   * a collection of WordPress audio or video files in a post.
2554   *
2555   * @since 3.9.0
2556   *
2557   * @global int $content_width
2558   *
2559   * @param array $attr {
2560   *     Array of default playlist attributes.
2561   *
2562   *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
2563   *     @type string  $order        Designates ascending or descending order of items in the playlist.
2564   *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
2565   *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
2566   *                                 passed, this defaults to the order of the $ids array ('post__in').
2567   *                                 Otherwise default is 'menu_order ID'.
2568   *     @type int     $id           If an explicit $ids array is not present, this parameter
2569   *                                 will determine which attachments are used for the playlist.
2570   *                                 Default is the current post ID.
2571   *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
2572   *                                 a playlist will be created from all $type attachments of $id.
2573   *                                 Default empty.
2574   *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
2575   *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
2576   *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
2577   *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
2578   *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
2579   *                                 thumbnail). Default true.
2580   *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
2581   * }
2582   *
2583   * @return string Playlist output. Empty string if the passed type is unsupported.
2584   */
2585  function wp_playlist_shortcode( $attr ) {
2586      global $content_width;
2587      $post = get_post();
2588  
2589      static $instance = 0;
2590      $instance++;
2591  
2592      if ( ! empty( $attr['ids'] ) ) {
2593          // 'ids' is explicitly ordered, unless you specify otherwise.
2594          if ( empty( $attr['orderby'] ) ) {
2595              $attr['orderby'] = 'post__in';
2596          }
2597          $attr['include'] = $attr['ids'];
2598      }
2599  
2600      /**
2601       * Filters the playlist output.
2602       *
2603       * Returning a non-empty value from the filter will short-circuit generation
2604       * of the default playlist output, returning the passed value instead.
2605       *
2606       * @since 3.9.0
2607       * @since 4.2.0 The `$instance` parameter was added.
2608       *
2609       * @param string $output   Playlist output. Default empty.
2610       * @param array  $attr     An array of shortcode attributes.
2611       * @param int    $instance Unique numeric ID of this playlist shortcode instance.
2612       */
2613      $output = apply_filters( 'post_playlist', '', $attr, $instance );
2614  
2615      if ( ! empty( $output ) ) {
2616          return $output;
2617      }
2618  
2619      $atts = shortcode_atts(
2620          array(
2621              'type'         => 'audio',
2622              'order'        => 'ASC',
2623              'orderby'      => 'menu_order ID',
2624              'id'           => $post ? $post->ID : 0,
2625              'include'      => '',
2626              'exclude'      => '',
2627              'style'        => 'light',
2628              'tracklist'    => true,
2629              'tracknumbers' => true,
2630              'images'       => true,
2631              'artists'      => true,
2632          ),
2633          $attr,
2634          'playlist'
2635      );
2636  
2637      $id = (int) $atts['id'];
2638  
2639      if ( 'audio' !== $atts['type'] ) {
2640          $atts['type'] = 'video';
2641      }
2642  
2643      $args = array(
2644          'post_status'    => 'inherit',
2645          'post_type'      => 'attachment',
2646          'post_mime_type' => $atts['type'],
2647          'order'          => $atts['order'],
2648          'orderby'        => $atts['orderby'],
2649      );
2650  
2651      if ( ! empty( $atts['include'] ) ) {
2652          $args['include'] = $atts['include'];
2653          $_attachments    = get_posts( $args );
2654  
2655          $attachments = array();
2656          foreach ( $_attachments as $key => $val ) {
2657              $attachments[ $val->ID ] = $_attachments[ $key ];
2658          }
2659      } elseif ( ! empty( $atts['exclude'] ) ) {
2660          $args['post_parent'] = $id;
2661          $args['exclude']     = $atts['exclude'];
2662          $attachments         = get_children( $args );
2663      } else {
2664          $args['post_parent'] = $id;
2665          $attachments         = get_children( $args );
2666      }
2667  
2668      if ( empty( $attachments ) ) {
2669          return '';
2670      }
2671  
2672      if ( is_feed() ) {
2673          $output = "\n";
2674          foreach ( $attachments as $att_id => $attachment ) {
2675              $output .= wp_get_attachment_link( $att_id ) . "\n";
2676          }
2677          return $output;
2678      }
2679  
2680      $outer = 22; // Default padding and border of wrapper.
2681  
2682      $default_width  = 640;
2683      $default_height = 360;
2684  
2685      $theme_width  = empty( $content_width ) ? $default_width : ( $content_width - $outer );
2686      $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
2687  
2688      $data = array(
2689          'type'         => $atts['type'],
2690          // Don't pass strings to JSON, will be truthy in JS.
2691          'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
2692          'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
2693          'images'       => wp_validate_boolean( $atts['images'] ),
2694          'artists'      => wp_validate_boolean( $atts['artists'] ),
2695      );
2696  
2697      $tracks = array();
2698      foreach ( $attachments as $attachment ) {
2699          $url   = wp_get_attachment_url( $attachment->ID );
2700          $ftype = wp_check_filetype( $url, wp_get_mime_types() );
2701          $track = array(
2702              'src'         => $url,
2703              'type'        => $ftype['type'],
2704              'title'       => $attachment->post_title,
2705              'caption'     => $attachment->post_excerpt,
2706              'description' => $attachment->post_content,
2707          );
2708  
2709          $track['meta'] = array();
2710          $meta          = wp_get_attachment_metadata( $attachment->ID );
2711          if ( ! empty( $meta ) ) {
2712  
2713              foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
2714                  if ( ! empty( $meta[ $key ] ) ) {
2715                      $track['meta'][ $key ] = $meta[ $key ];
2716                  }
2717              }
2718  
2719              if ( 'video' === $atts['type'] ) {
2720                  if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
2721                      $width        = $meta['width'];
2722                      $height       = $meta['height'];
2723                      $theme_height = round( ( $height * $theme_width ) / $width );
2724                  } else {
2725                      $width  = $default_width;
2726                      $height = $default_height;
2727                  }
2728  
2729                  $track['dimensions'] = array(
2730                      'original' => compact( 'width', 'height' ),
2731                      'resized'  => array(
2732                          'width'  => $theme_width,
2733                          'height' => $theme_height,
2734                      ),
2735                  );
2736              }
2737          }
2738  
2739          if ( $atts['images'] ) {
2740              $thumb_id = get_post_thumbnail_id( $attachment->ID );
2741              if ( ! empty( $thumb_id ) ) {
2742                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2743                  $track['image']               = compact( 'src', 'width', 'height' );
2744                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2745                  $track['thumb']               = compact( 'src', 'width', 'height' );
2746              } else {
2747                  $src            = wp_mime_type_icon( $attachment->ID );
2748                  $width          = 48;
2749                  $height         = 64;
2750                  $track['image'] = compact( 'src', 'width', 'height' );
2751                  $track['thumb'] = compact( 'src', 'width', 'height' );
2752              }
2753          }
2754  
2755          $tracks[] = $track;
2756      }
2757      $data['tracks'] = $tracks;
2758  
2759      $safe_type  = esc_attr( $atts['type'] );
2760      $safe_style = esc_attr( $atts['style'] );
2761  
2762      ob_start();
2763  
2764      if ( 1 === $instance ) {
2765          /**
2766           * Prints and enqueues playlist scripts, styles, and JavaScript templates.
2767           *
2768           * @since 3.9.0
2769           *
2770           * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
2771           * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2772           */
2773          do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2774      }
2775      ?>
2776  <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>">
2777      <?php if ( 'audio' === $atts['type'] ) : ?>
2778          <div class="wp-playlist-current-item"></div>
2779      <?php endif ?>
2780      <<?php echo $safe_type; ?> controls="controls" preload="none" width="<?php echo (int) $theme_width; ?>"
2781          <?php
2782          if ( 'video' === $safe_type ) {
2783              echo ' height="', (int) $theme_height, '"';
2784          }
2785          ?>
2786      ></<?php echo $safe_type; ?>>
2787      <div class="wp-playlist-next"></div>
2788      <div class="wp-playlist-prev"></div>
2789      <noscript>
2790      <ol>
2791          <?php
2792          foreach ( $attachments as $att_id => $attachment ) {
2793              printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2794          }
2795          ?>
2796      </ol>
2797      </noscript>
2798      <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ); ?></script>
2799  </div>
2800      <?php
2801      return ob_get_clean();
2802  }
2803  add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2804  
2805  /**
2806   * Provides a No-JS Flash fallback as a last resort for audio / video.
2807   *
2808   * @since 3.6.0
2809   *
2810   * @param string $url The media element URL.
2811   * @return string Fallback HTML.
2812   */
2813  function wp_mediaelement_fallback( $url ) {
2814      /**
2815       * Filters the Mediaelement fallback output for no-JS.
2816       *
2817       * @since 3.6.0
2818       *
2819       * @param string $output Fallback output for no-JS.
2820       * @param string $url    Media file URL.
2821       */
2822      return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2823  }
2824  
2825  /**
2826   * Returns a filtered list of supported audio formats.
2827   *
2828   * @since 3.6.0
2829   *
2830   * @return string[] Supported audio formats.
2831   */
2832  function wp_get_audio_extensions() {
2833      /**
2834       * Filters the list of supported audio formats.
2835       *
2836       * @since 3.6.0
2837       *
2838       * @param string[] $extensions An array of supported audio formats. Defaults are
2839       *                            'mp3', 'ogg', 'flac', 'm4a', 'wav'.
2840       */
2841      return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
2842  }
2843  
2844  /**
2845   * Returns useful keys to use to lookup data from an attachment's stored metadata.
2846   *
2847   * @since 3.9.0
2848   *
2849   * @param WP_Post $attachment The current attachment, provided for context.
2850   * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2851   * @return string[] Key/value pairs of field keys to labels.
2852   */
2853  function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2854      $fields = array(
2855          'artist' => __( 'Artist' ),
2856          'album'  => __( 'Album' ),
2857      );
2858  
2859      if ( 'display' === $context ) {
2860          $fields['genre']            = __( 'Genre' );
2861          $fields['year']             = __( 'Year' );
2862          $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2863      } elseif ( 'js' === $context ) {
2864          $fields['bitrate']      = __( 'Bitrate' );
2865          $fields['bitrate_mode'] = __( 'Bitrate Mode' );
2866      }
2867  
2868      /**
2869       * Filters the editable list of keys to look up data from an attachment's metadata.
2870       *
2871       * @since 3.9.0
2872       *
2873       * @param array   $fields     Key/value pairs of field keys to labels.
2874       * @param WP_Post $attachment Attachment object.
2875       * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
2876       */
2877      return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
2878  }
2879  /**
2880   * Builds the Audio shortcode output.
2881   *
2882   * This implements the functionality of the Audio Shortcode for displaying
2883   * WordPress mp3s in a post.
2884   *
2885   * @since 3.6.0
2886   *
2887   * @param array  $attr {
2888   *     Attributes of the audio shortcode.
2889   *
2890   *     @type string $src      URL to the source of the audio file. Default empty.
2891   *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
2892   *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
2893   *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default 'none'.
2894   *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
2895   *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
2896   * }
2897   * @param string $content Shortcode content.
2898   * @return string|void HTML content to display audio.
2899   */
2900  function wp_audio_shortcode( $attr, $content = '' ) {
2901      $post_id = get_post() ? get_the_ID() : 0;
2902  
2903      static $instance = 0;
2904      $instance++;
2905  
2906      /**
2907       * Filters the default audio shortcode output.
2908       *
2909       * If the filtered output isn't empty, it will be used instead of generating the default audio template.
2910       *
2911       * @since 3.6.0
2912       *
2913       * @param string $html     Empty variable to be replaced with shortcode markup.
2914       * @param array  $attr     Attributes of the shortcode. @see wp_audio_shortcode()
2915       * @param string $content  Shortcode content.
2916       * @param int    $instance Unique numeric ID of this audio shortcode instance.
2917       */
2918      $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
2919  
2920      if ( '' !== $override ) {
2921          return $override;
2922      }
2923  
2924      $audio = null;
2925  
2926      $default_types = wp_get_audio_extensions();
2927      $defaults_atts = array(
2928          'src'      => '',
2929          'loop'     => '',
2930          'autoplay' => '',
2931          'preload'  => 'none',
2932          'class'    => 'wp-audio-shortcode',
2933          'style'    => 'width: 100%;',
2934      );
2935      foreach ( $default_types as $type ) {
2936          $defaults_atts[ $type ] = '';
2937      }
2938  
2939      $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
2940  
2941      $primary = false;
2942      if ( ! empty( $atts['src'] ) ) {
2943          $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2944  
2945          if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
2946              return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2947          }
2948  
2949          $primary = true;
2950          array_unshift( $default_types, 'src' );
2951      } else {
2952          foreach ( $default_types as $ext ) {
2953              if ( ! empty( $atts[ $ext ] ) ) {
2954                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2955  
2956                  if ( strtolower( $type['ext'] ) === $ext ) {
2957                      $primary = true;
2958                  }
2959              }
2960          }
2961      }
2962  
2963      if ( ! $primary ) {
2964          $audios = get_attached_media( 'audio', $post_id );
2965  
2966          if ( empty( $audios ) ) {
2967              return;
2968          }
2969  
2970          $audio       = reset( $audios );
2971          $atts['src'] = wp_get_attachment_url( $audio->ID );
2972  
2973          if ( empty( $atts['src'] ) ) {
2974              return;
2975          }
2976  
2977          array_unshift( $default_types, 'src' );
2978      }
2979  
2980      /**
2981       * Filters the media library used for the audio shortcode.
2982       *
2983       * @since 3.6.0
2984       *
2985       * @param string $library Media library used for the audio shortcode.
2986       */
2987      $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
2988  
2989      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2990          wp_enqueue_style( 'wp-mediaelement' );
2991          wp_enqueue_script( 'wp-mediaelement' );
2992      }
2993  
2994      /**
2995       * Filters the class attribute for the audio shortcode output container.
2996       *
2997       * @since 3.6.0
2998       * @since 4.9.0 The `$atts` parameter was added.
2999       *
3000       * @param string $class CSS class or list of space-separated classes.
3001       * @param array  $atts  Array of audio shortcode attributes.
3002       */
3003      $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
3004  
3005      $html_atts = array(
3006          'class'    => $atts['class'],
3007          'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
3008          'loop'     => wp_validate_boolean( $atts['loop'] ),
3009          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3010          'preload'  => $atts['preload'],
3011          'style'    => $atts['style'],
3012      );
3013  
3014      // These ones should just be omitted altogether if they are blank.
3015      foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
3016          if ( empty( $html_atts[ $a ] ) ) {
3017              unset( $html_atts[ $a ] );
3018          }
3019      }
3020  
3021      $attr_strings = array();
3022  
3023      foreach ( $html_atts as $k => $v ) {
3024          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
3025      }
3026  
3027      $html = '';
3028  
3029      if ( 'mediaelement' === $library && 1 === $instance ) {
3030          $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
3031      }
3032  
3033      $html .= sprintf( '<audio %s controls="controls">', implode( ' ', $attr_strings ) );
3034  
3035      $fileurl = '';
3036      $source  = '<source type="%s" src="%s" />';
3037  
3038      foreach ( $default_types as $fallback ) {
3039          if ( ! empty( $atts[ $fallback ] ) ) {
3040              if ( empty( $fileurl ) ) {
3041                  $fileurl = $atts[ $fallback ];
3042              }
3043  
3044              $type  = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3045              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3046              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3047          }
3048      }
3049  
3050      if ( 'mediaelement' === $library ) {
3051          $html .= wp_mediaelement_fallback( $fileurl );
3052      }
3053  
3054      $html .= '</audio>';
3055  
3056      /**
3057       * Filters the audio shortcode output.
3058       *
3059       * @since 3.6.0
3060       *
3061       * @param string $html    Audio shortcode HTML output.
3062       * @param array  $atts    Array of audio shortcode attributes.
3063       * @param string $audio   Audio file.
3064       * @param int    $post_id Post ID.
3065       * @param string $library Media library used for the audio shortcode.
3066       */
3067      return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
3068  }
3069  add_shortcode( 'audio', 'wp_audio_shortcode' );
3070  
3071  /**
3072   * Returns a filtered list of supported video formats.
3073   *
3074   * @since 3.6.0
3075   *
3076   * @return string[] List of supported video formats.
3077   */
3078  function wp_get_video_extensions() {
3079      /**
3080       * Filters the list of supported video formats.
3081       *
3082       * @since 3.6.0
3083       *
3084       * @param string[] $extensions An array of supported video formats. Defaults are
3085       *                             'mp4', 'm4v', 'webm', 'ogv', 'flv'.
3086       */
3087      return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
3088  }
3089  
3090  /**
3091   * Builds the Video shortcode output.
3092   *
3093   * This implements the functionality of the Video Shortcode for displaying
3094   * WordPress mp4s in a post.
3095   *
3096   * @since 3.6.0
3097   *
3098   * @global int $content_width
3099   *
3100   * @param array  $attr {
3101   *     Attributes of the shortcode.
3102   *
3103   *     @type string $src      URL to the source of the video file. Default empty.
3104   *     @type int    $height   Height of the video embed in pixels. Default 360.
3105   *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
3106   *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
3107   *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
3108   *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
3109   *     @type string $preload  The 'preload' attribute for the `<video>` element.
3110   *                            Default 'metadata'.
3111   *     @type string $class    The 'class' attribute for the `<video>` element.
3112   *                            Default 'wp-video-shortcode'.
3113   * }
3114   * @param string $content Shortcode content.
3115   * @return string|void HTML content to display video.
3116   */
3117  function wp_video_shortcode( $attr, $content = '' ) {
3118      global $content_width;
3119      $post_id = get_post() ? get_the_ID() : 0;
3120  
3121      static $instance = 0;
3122      $instance++;
3123  
3124      /**
3125       * Filters the default video shortcode output.
3126       *
3127       * If the filtered output isn't empty, it will be used instead of generating
3128       * the default video template.
3129       *
3130       * @since 3.6.0
3131       *
3132       * @see wp_video_shortcode()
3133       *
3134       * @param string $html     Empty variable to be replaced with shortcode markup.
3135       * @param array  $attr     Attributes of the shortcode. @see wp_video_shortcode()
3136       * @param string $content  Video shortcode content.
3137       * @param int    $instance Unique numeric ID of this video shortcode instance.
3138       */
3139      $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
3140  
3141      if ( '' !== $override ) {
3142          return $override;
3143      }
3144  
3145      $video = null;
3146  
3147      $default_types = wp_get_video_extensions();
3148      $defaults_atts = array(
3149          'src'      => '',
3150          'poster'   => '',
3151          'loop'     => '',
3152          'autoplay' => '',
3153          'preload'  => 'metadata',
3154          'width'    => 640,
3155          'height'   => 360,
3156          'class'    => 'wp-video-shortcode',
3157      );
3158  
3159      foreach ( $default_types as $type ) {
3160          $defaults_atts[ $type ] = '';
3161      }
3162  
3163      $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
3164  
3165      if ( is_admin() ) {
3166          // Shrink the video so it isn't huge in the admin.
3167          if ( $atts['width'] > $defaults_atts['width'] ) {
3168              $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
3169              $atts['width']  = $defaults_atts['width'];
3170          }
3171      } else {
3172          // If the video is bigger than the theme.
3173          if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
3174              $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
3175              $atts['width']  = $content_width;
3176          }
3177      }
3178  
3179      $is_vimeo      = false;
3180      $is_youtube    = false;
3181      $yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
3182      $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
3183  
3184      $primary = false;
3185      if ( ! empty( $atts['src'] ) ) {
3186          $is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
3187          $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
3188  
3189          if ( ! $is_youtube && ! $is_vimeo ) {
3190              $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
3191  
3192              if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
3193                  return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
3194              }
3195          }
3196  
3197          if ( $is_vimeo ) {
3198              wp_enqueue_script( 'mediaelement-vimeo' );
3199          }
3200  
3201          $primary = true;
3202          array_unshift( $default_types, 'src' );
3203      } else {
3204          foreach ( $default_types as $ext ) {
3205              if ( ! empty( $atts[ $ext ] ) ) {
3206                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
3207                  if ( strtolower( $type['ext'] ) === $ext ) {
3208                      $primary = true;
3209                  }
3210              }
3211          }
3212      }
3213  
3214      if ( ! $primary ) {
3215          $videos = get_attached_media( 'video', $post_id );
3216          if ( empty( $videos ) ) {
3217              return;
3218          }
3219  
3220          $video       = reset( $videos );
3221          $atts['src'] = wp_get_attachment_url( $video->ID );
3222          if ( empty( $atts['src'] ) ) {
3223              return;
3224          }
3225  
3226          array_unshift( $default_types, 'src' );
3227      }
3228  
3229      /**
3230       * Filters the media library used for the video shortcode.
3231       *
3232       * @since 3.6.0
3233       *
3234       * @param string $library Media library used for the video shortcode.
3235       */
3236      $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
3237      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3238          wp_enqueue_style( 'wp-mediaelement' );
3239          wp_enqueue_script( 'wp-mediaelement' );
3240          wp_enqueue_script( 'mediaelement-vimeo' );
3241      }
3242  
3243      // MediaElement.js has issues with some URL formats for Vimeo and YouTube,
3244      // so update the URL to prevent the ME.js player from breaking.
3245      if ( 'mediaelement' === $library ) {
3246          if ( $is_youtube ) {
3247              // Remove `feature` query arg and force SSL - see #40866.
3248              $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
3249              $atts['src'] = set_url_scheme( $atts['src'], 'https' );
3250          } elseif ( $is_vimeo ) {
3251              // Remove all query arguments and force SSL - see #40866.
3252              $parsed_vimeo_url = wp_parse_url( $atts['src'] );
3253              $vimeo_src        = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
3254  
3255              // Add loop param for mejs bug - see #40977, not needed after #39686.
3256              $loop        = $atts['loop'] ? '1' : '0';
3257              $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
3258          }
3259      }
3260  
3261      /**
3262       * Filters the class attribute for the video shortcode output container.
3263       *
3264       * @since 3.6.0
3265       * @since 4.9.0 The `$atts` parameter was added.
3266       *
3267       * @param string $class CSS class or list of space-separated classes.
3268       * @param array  $atts  Array of video shortcode attributes.
3269       */
3270      $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
3271  
3272      $html_atts = array(
3273          'class'    => $atts['class'],
3274          'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
3275          'width'    => absint( $atts['width'] ),
3276          'height'   => absint( $atts['height'] ),
3277          'poster'   => esc_url( $atts['poster'] ),
3278          'loop'     => wp_validate_boolean( $atts['loop'] ),
3279          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3280          'preload'  => $atts['preload'],
3281      );
3282  
3283      // These ones should just be omitted altogether if they are blank.
3284      foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
3285          if ( empty( $html_atts[ $a ] ) ) {
3286              unset( $html_atts[ $a ] );
3287          }
3288      }
3289  
3290      $attr_strings = array();
3291      foreach ( $html_atts as $k => $v ) {
3292          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
3293      }
3294  
3295      $html = '';
3296  
3297      if ( 'mediaelement' === $library && 1 === $instance ) {
3298          $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
3299      }
3300  
3301      $html .= sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) );
3302  
3303      $fileurl = '';
3304      $source  = '<source type="%s" src="%s" />';
3305  
3306      foreach ( $default_types as $fallback ) {
3307          if ( ! empty( $atts[ $fallback ] ) ) {
3308              if ( empty( $fileurl ) ) {
3309                  $fileurl = $atts[ $fallback ];
3310              }
3311              if ( 'src' === $fallback && $is_youtube ) {
3312                  $type = array( 'type' => 'video/youtube' );
3313              } elseif ( 'src' === $fallback && $is_vimeo ) {
3314                  $type = array( 'type' => 'video/vimeo' );
3315              } else {
3316                  $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3317              }
3318              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3319              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3320          }
3321      }
3322  
3323      if ( ! empty( $content ) ) {
3324          if ( false !== strpos( $content, "\n" ) ) {
3325              $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
3326          }
3327          $html .= trim( $content );
3328      }
3329  
3330      if ( 'mediaelement' === $library ) {
3331          $html .= wp_mediaelement_fallback( $fileurl );
3332      }
3333      $html .= '</video>';
3334  
3335      $width_rule = '';
3336      if ( ! empty( $atts['width'] ) ) {
3337          $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
3338      }
3339      $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
3340  
3341      /**
3342       * Filters the output of the video shortcode.
3343       *
3344       * @since 3.6.0
3345       *
3346       * @param string $output  Video shortcode HTML output.
3347       * @param array  $atts    Array of video shortcode attributes.
3348       * @param string $video   Video file.
3349       * @param int    $post_id Post ID.
3350       * @param string $library Media library used for the video shortcode.
3351       */
3352      return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
3353  }
3354  add_shortcode( 'video', 'wp_video_shortcode' );
3355  
3356  /**
3357   * Displays previous image link that has the same post parent.
3358   *
3359   * @since 2.5.0
3360   *
3361   * @see adjacent_image_link()
3362   *
3363   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3364   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3365   * @param string|false $text Optional. Link text. Default false.
3366   */
3367  function previous_image_link( $size = 'thumbnail', $text = false ) {
3368      adjacent_image_link( true, $size, $text );
3369  }
3370  
3371  /**
3372   * Displays next image link that has the same post parent.
3373   *
3374   * @since 2.5.0
3375   *
3376   * @see adjacent_image_link()
3377   *
3378   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3379   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3380   * @param string|false $text Optional. Link text. Default false.
3381   */
3382  function next_image_link( $size = 'thumbnail', $text = false ) {
3383      adjacent_image_link( false, $size, $text );
3384  }
3385  
3386  /**
3387   * Displays next or previous image link that has the same post parent.
3388   *
3389   * Retrieves the current attachment object from the $post global.
3390   *
3391   * @since 2.5.0
3392   *
3393   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3394   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3395   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3396   * @param bool         $text Optional. Link text. Default false.
3397   */
3398  function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3399      $post        = get_post();
3400      $attachments = array_values(
3401          get_children(
3402              array(
3403                  'post_parent'    => $post->post_parent,
3404                  'post_status'    => 'inherit',
3405                  'post_type'      => 'attachment',
3406                  'post_mime_type' => 'image',
3407                  'order'          => 'ASC',
3408                  'orderby'        => 'menu_order ID',
3409              )
3410          )
3411      );
3412  
3413      foreach ( $attachments as $k => $attachment ) {
3414          if ( (int) $attachment->ID === (int) $post->ID ) {
3415              break;
3416          }
3417      }
3418  
3419      $output        = '';
3420      $attachment_id = 0;
3421  
3422      if ( $attachments ) {
3423          $k = $prev ? $k - 1 : $k + 1;
3424  
3425          if ( isset( $attachments[ $k ] ) ) {
3426              $attachment_id = $attachments[ $k ]->ID;
3427              $output        = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
3428          }
3429      }
3430  
3431      $adjacent = $prev ? 'previous' : 'next';
3432  
3433      /**
3434       * Filters the adjacent image link.
3435       *
3436       * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
3437       * either 'next', or 'previous'.
3438       *
3439       * @since 3.5.0
3440       *
3441       * @param string $output        Adjacent image HTML markup.
3442       * @param int    $attachment_id Attachment ID
3443       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
3444       *                              an array of width and height values in pixels (in that order).
3445       * @param string $text          Link text.
3446       */
3447      echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
3448  }
3449  
3450  /**
3451   * Retrieves taxonomies attached to given the attachment.
3452   *
3453   * @since 2.5.0
3454   * @since 4.7.0 Introduced the `$output` parameter.
3455   *
3456   * @param int|array|object $attachment Attachment ID, data array, or data object.
3457   * @param string           $output     Output type. 'names' to return an array of taxonomy names,
3458   *                                     or 'objects' to return an array of taxonomy objects.
3459   *                                     Default is 'names'.
3460   * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
3461   */
3462  function get_attachment_taxonomies( $attachment, $output = 'names' ) {
3463      if ( is_int( $attachment ) ) {
3464          $attachment = get_post( $attachment );
3465      } elseif ( is_array( $attachment ) ) {
3466          $attachment = (object) $attachment;
3467      }
3468  
3469      if ( ! is_object( $attachment ) ) {
3470          return array();
3471      }
3472  
3473      $file     = get_attached_file( $attachment->ID );
3474      $filename = wp_basename( $file );
3475  
3476      $objects = array( 'attachment' );
3477  
3478      if ( false !== strpos( $filename, '.' ) ) {
3479          $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
3480      }
3481  
3482      if ( ! empty( $attachment->post_mime_type ) ) {
3483          $objects[] = 'attachment:' . $attachment->post_mime_type;
3484  
3485          if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
3486              foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
3487                  if ( ! empty( $token ) ) {
3488                      $objects[] = "attachment:$token";
3489                  }
3490              }
3491          }
3492      }
3493  
3494      $taxonomies = array();
3495  
3496      foreach ( $objects as $object ) {
3497          $taxes = get_object_taxonomies( $object, $output );
3498  
3499          if ( $taxes ) {
3500              $taxonomies = array_merge( $taxonomies, $taxes );
3501          }
3502      }
3503  
3504      if ( 'names' === $output ) {
3505          $taxonomies = array_unique( $taxonomies );
3506      }
3507  
3508      return $taxonomies;
3509  }
3510  
3511  /**
3512   * Retrieves all of the taxonomies that are registered for attachments.
3513   *
3514   * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
3515   *
3516   * @since 3.5.0
3517   *
3518   * @see get_taxonomies()
3519   *
3520   * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
3521   *                       Default 'names'.
3522   * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.
3523   */
3524  function get_taxonomies_for_attachments( $output = 'names' ) {
3525      $taxonomies = array();
3526  
3527      foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
3528          foreach ( $taxonomy->object_type as $object_type ) {
3529              if ( 'attachment' === $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
3530                  if ( 'names' === $output ) {
3531                      $taxonomies[] = $taxonomy->name;
3532                  } else {
3533                      $taxonomies[ $taxonomy->name ] = $taxonomy;
3534                  }
3535                  break;
3536              }
3537          }
3538      }
3539  
3540      return $taxonomies;
3541  }
3542  
3543  /**
3544   * Determines whether the value is an acceptable type for GD image functions.
3545   *
3546   * In PHP 8.0, the GD extension uses GdImage objects for its data structures.
3547   * This function checks if the passed value is either a resource of type `gd`
3548   * or a GdImage object instance. Any other type will return false.
3549   *
3550   * @since 5.6.0
3551   *
3552   * @param resource|GdImage|false $image A value to check the type for.
3553   * @return bool True if $image is either a GD image resource or GdImage instance,
3554   *              false otherwise.
3555   */
3556  function is_gd_image( $image ) {
3557      if ( is_resource( $image ) && 'gd' === get_resource_type( $image )
3558          || is_object( $image ) && $image instanceof GdImage
3559      ) {
3560          return true;
3561      }
3562  
3563      return false;
3564  }
3565  
3566  /**
3567   * Create new GD image resource with transparency support
3568   *
3569   * @todo Deprecate if possible.
3570   *
3571   * @since 2.9.0
3572   *
3573   * @param int $width  Image width in pixels.
3574   * @param int $height Image height in pixels.
3575   * @return resource|GdImage|false The GD image resource or GdImage instance on success.
3576   *                                False on failure.
3577   */
3578  function wp_imagecreatetruecolor( $width, $height ) {
3579      $img = imagecreatetruecolor( $width, $height );
3580  
3581      if ( is_gd_image( $img )
3582          && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' )
3583      ) {
3584          imagealphablending( $img, false );
3585          imagesavealpha( $img, true );
3586      }
3587  
3588      return $img;
3589  }
3590  
3591  /**
3592   * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
3593   *
3594   * @since 2.9.0
3595   *
3596   * @see wp_constrain_dimensions()
3597   *
3598   * @param int $example_width  The width of an example embed.
3599   * @param int $example_height The height of an example embed.
3600   * @param int $max_width      The maximum allowed width.
3601   * @param int $max_height     The maximum allowed height.
3602   * @return int[] {
3603   *     An array of maximum width and height values.
3604   *
3605   *     @type int $0 The maximum width in pixels.
3606   *     @type int $1 The maximum height in pixels.
3607   * }
3608   */
3609  function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
3610      $example_width  = (int) $example_width;
3611      $example_height = (int) $example_height;
3612      $max_width      = (int) $max_width;
3613      $max_height     = (int) $max_height;
3614  
3615      return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
3616  }
3617  
3618  /**
3619   * Determines the maximum upload size allowed in php.ini.
3620   *
3621   * @since 2.5.0
3622   *
3623   * @return int Allowed upload size.
3624   */
3625  function wp_max_upload_size() {
3626      $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
3627      $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
3628  
3629      /**
3630       * Filters the maximum upload size allowed in php.ini.
3631       *
3632       * @since 2.5.0
3633       *
3634       * @param int $size    Max upload size limit in bytes.
3635       * @param int $u_bytes Maximum upload filesize in bytes.
3636       * @param int $p_bytes Maximum size of POST data in bytes.
3637       */
3638      return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
3639  }
3640  
3641  /**
3642   * Returns a WP_Image_Editor instance and loads file into it.
3643   *
3644   * @since 3.5.0
3645   *
3646   * @param string $path Path to the file to load.
3647   * @param array  $args Optional. Additional arguments for retrieving the image editor.
3648   *                     Default empty array.
3649   * @return WP_Image_Editor|WP_Error The WP_Image_Editor object on success,
3650   *                                  a WP_Error object otherwise.
3651   */
3652  function wp_get_image_editor( $path, $args = array() ) {
3653      $args['path'] = $path;
3654  
3655      if ( ! isset( $args['mime_type'] ) ) {
3656          $file_info = wp_check_filetype( $args['path'] );
3657  
3658          // If $file_info['type'] is false, then we let the editor attempt to
3659          // figure out the file type, rather than forcing a failure based on extension.
3660          if ( isset( $file_info ) && $file_info['type'] ) {
3661              $args['mime_type'] = $file_info['type'];
3662          }
3663      }
3664  
3665      $implementation = _wp_image_editor_choose( $args );
3666  
3667      if ( $implementation ) {
3668          $editor = new $implementation( $path );
3669          $loaded = $editor->load();
3670  
3671          if ( is_wp_error( $loaded ) ) {
3672              return $loaded;
3673          }
3674  
3675          return $editor;
3676      }
3677  
3678      return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
3679  }
3680  
3681  /**
3682   * Tests whether there is an editor that supports a given mime type or methods.
3683   *
3684   * @since 3.5.0
3685   *
3686   * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
3687   *                           Default empty array.
3688   * @return bool True if an eligible editor is found; false otherwise.
3689   */
3690  function wp_image_editor_supports( $args = array() ) {
3691      return (bool) _wp_image_editor_choose( $args );
3692  }
3693  
3694  /**
3695   * Tests which editors are capable of supporting the request.
3696   *
3697   * @ignore
3698   * @since 3.5.0
3699   *
3700   * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
3701   * @return string|false Class name for the first editor that claims to support the request.
3702   *                      False if no editor claims to support the request.
3703   */
3704  function _wp_image_editor_choose( $args = array() ) {
3705      require_once  ABSPATH . WPINC . '/class-wp-image-editor.php';
3706      require_once  ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
3707      require_once  ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
3708      /**
3709       * Filters the list of image editing library classes.
3710       *
3711       * @since 3.5.0
3712       *
3713       * @param string[] $image_editors Array of available image editor class names. Defaults are
3714       *                                'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
3715       */
3716      $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
3717  
3718      foreach ( $implementations as $implementation ) {
3719          if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) {
3720              continue;
3721          }
3722  
3723          if ( isset( $args['mime_type'] ) &&
3724              ! call_user_func(
3725                  array( $implementation, 'supports_mime_type' ),
3726                  $args['mime_type']
3727              ) ) {
3728              continue;
3729          }
3730  
3731          if ( isset( $args['methods'] ) &&
3732              array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
3733  
3734              continue;
3735          }
3736  
3737          return $implementation;
3738      }
3739  
3740      return false;
3741  }
3742  
3743  /**
3744   * Prints default Plupload arguments.
3745   *
3746   * @since 3.4.0
3747   */
3748  function wp_plupload_default_settings() {
3749      $wp_scripts = wp_scripts();
3750  
3751      $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
3752      if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) ) {
3753          return;
3754      }
3755  
3756      $max_upload_size    = wp_max_upload_size();
3757      $allowed_extensions = array_keys( get_allowed_mime_types() );
3758      $extensions         = array();
3759      foreach ( $allowed_extensions as $extension ) {
3760          $extensions = array_merge( $extensions, explode( '|', $extension ) );
3761      }
3762  
3763      /*
3764       * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
3765       * and the `flash_swf_url` and `silverlight_xap_url` are not used.
3766       */
3767      $defaults = array(
3768          'file_data_name' => 'async-upload', // Key passed to $_FILE.
3769          'url'            => admin_url( 'async-upload.php', 'relative' ),
3770          'filters'        => array(
3771              'max_file_size' => $max_upload_size . 'b',
3772              'mime_types'    => array( array( 'extensions' => implode( ',', $extensions ) ) ),
3773          ),
3774      );
3775  
3776      /*
3777       * Currently only iOS Safari supports multiple files uploading,
3778       * but iOS 7.x has a bug that prevents uploading of videos when enabled.
3779       * See #29602.
3780       */
3781      if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
3782          strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
3783  
3784          $defaults['multi_selection'] = false;
3785      }
3786  
3787      /**
3788       * Filters the Plupload default settings.
3789       *
3790       * @since 3.4.0
3791       *
3792       * @param array $defaults Default Plupload settings array.
3793       */
3794      $defaults = apply_filters( 'plupload_default_settings', $defaults );
3795  
3796      $params = array(
3797          'action' => 'upload-attachment',
3798      );
3799  
3800      /**
3801       * Filters the Plupload default parameters.
3802       *
3803       * @since 3.4.0
3804       *
3805       * @param array $params Default Plupload parameters array.
3806       */
3807      $params = apply_filters( 'plupload_default_params', $params );
3808  
3809      $params['_wpnonce'] = wp_create_nonce( 'media-form' );
3810  
3811      $defaults['multipart_params'] = $params;
3812  
3813      $settings = array(
3814          'defaults'      => $defaults,
3815          'browser'       => array(
3816              'mobile'    => wp_is_mobile(),
3817              'supported' => _device_can_upload(),
3818          ),
3819          'limitExceeded' => is_multisite() && ! is_upload_space_available(),
3820      );
3821  
3822      $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
3823  
3824      if ( $data ) {
3825          $script = "$data\n$script";
3826      }
3827  
3828      $wp_scripts->add_data( 'wp-plupload', 'data', $script );
3829  }
3830  
3831  /**
3832   * Prepares an attachment post object for JS, where it is expected
3833   * to be JSON-encoded and fit into an Attachment model.
3834   *
3835   * @since 3.5.0
3836   *
3837   * @param int|WP_Post $attachment Attachment ID or object.
3838   * @return array|void {
3839   *     Array of attachment details, or void if the parameter does not correspond to an attachment.
3840   *
3841   *     @type string $alt                   Alt text of the attachment.
3842   *     @type string $author                ID of the attachment author, as a string.
3843   *     @type string $authorName            Name of the attachment author.
3844   *     @type string $caption               Caption for the attachment.
3845   *     @type array  $compat                Containing item and meta.
3846   *     @type string $context               Context, whether it's used as the site icon for example.
3847   *     @type int    $date                  Uploaded date, timestamp in milliseconds.
3848   *     @type string $dateFormatted         Formatted date (e.g. June 29, 2018).
3849   *     @type string $description           Description of the attachment.
3850   *     @type string $editLink              URL to the edit page for the attachment.
3851   *     @type string $filename              File name of the attachment.
3852   *     @type string $filesizeHumanReadable Filesize of the attachment in human readable format (e.g. 1 MB).
3853   *     @type int    $filesizeInBytes       Filesize of the attachment in bytes.
3854   *     @type int    $height                If the attachment is an image, represents the height of the image in pixels.
3855   *     @type string $icon                  Icon URL of the attachment (e.g. /wp-includes/images/media/archive.png).
3856   *     @type int    $id                    ID of the attachment.
3857   *     @type string $link                  URL to the attachment.
3858   *     @type int    $menuOrder             Menu order of the attachment post.
3859   *     @type array  $meta                  Meta data for the attachment.
3860   *     @type string $mime                  Mime type of the attachment (e.g. image/jpeg or application/zip).
3861   *     @type int    $modified              Last modified, timestamp in milliseconds.
3862   *     @type string $name                  Name, same as title of the attachment.
3863   *     @type array  $nonces                Nonces for update, delete and edit.
3864   *     @type string $orientation           If the attachment is an image, represents the image orientation
3865   *                                         (landscape or portrait).
3866   *     @type array  $sizes                 If the attachment is an image, contains an array of arrays
3867   *                                         for the images sizes: thumbnail, medium, large, and full.
3868   *     @type string $status                Post status of the attachment (usually 'inherit').
3869   *     @type string $subtype               Mime subtype of the attachment (usually the last part, e.g. jpeg or zip).
3870   *     @type string $title                 Title of the attachment (usually slugified file name without the extension).
3871   *     @type string $type                  Type of the attachment (usually first part of the mime type, e.g. image).
3872   *     @type int    $uploadedTo            Parent post to which the attachment was uploaded.
3873   *     @type string $uploadedToLink        URL to the edit page of the parent post of the attachment.
3874   *     @type string $uploadedToTitle       Post title of the parent of the attachment.
3875   *     @type string $url                   Direct URL to the attachment file (from wp-content).
3876   *     @type int    $width                 If the attachment is an image, represents the width of the image in pixels.
3877   * }
3878   *
3879   */
3880  function wp_prepare_attachment_for_js( $attachment ) {
3881      $attachment = get_post( $attachment );
3882  
3883      if ( ! $attachment ) {
3884          return;
3885      }
3886  
3887      if ( 'attachment' !== $attachment->post_type ) {
3888          return;
3889      }
3890  
3891      $meta = wp_get_attachment_metadata( $attachment->ID );
3892      if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
3893          list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
3894      } else {
3895          list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
3896      }
3897  
3898      $attachment_url = wp_get_attachment_url( $attachment->ID );
3899      $base_url       = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
3900  
3901      $response = array(
3902          'id'            => $attachment->ID,
3903          'title'         => $attachment->post_title,
3904          'filename'      => wp_basename( get_attached_file( $attachment->ID ) ),
3905          'url'           => $attachment_url,
3906          'link'          => get_attachment_link( $attachment->ID ),
3907          'alt'           => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
3908          'author'        => $attachment->post_author,
3909          'description'   => $attachment->post_content,
3910          'caption'       => $attachment->post_excerpt,
3911          'name'          => $attachment->post_name,
3912          'status'        => $attachment->post_status,
3913          'uploadedTo'    => $attachment->post_parent,
3914          'date'          => strtotime( $attachment->post_date_gmt ) * 1000,
3915          'modified'      => strtotime( $attachment->post_modified_gmt ) * 1000,
3916          'menuOrder'     => $attachment->menu_order,
3917          'mime'          => $attachment->post_mime_type,
3918          'type'          => $type,
3919          'subtype'       => $subtype,
3920          'icon'          => wp_mime_type_icon( $attachment->ID ),
3921          'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
3922          'nonces'        => array(
3923              'update' => false,
3924              'delete' => false,
3925              'edit'   => false,
3926          ),
3927          'editLink'      => false,
3928          'meta'          => false,
3929      );
3930  
3931      $author = new WP_User( $attachment->post_author );
3932  
3933      if ( $author->exists() ) {
3934          $author_name            = $author->display_name ? $author->display_name : $author->nickname;
3935          $response['authorName'] = html_entity_decode( $author_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
3936          $response['authorLink'] = get_edit_user_link( $author->ID );
3937      } else {
3938          $response['authorName'] = __( '(no author)' );
3939      }
3940  
3941      if ( $attachment->post_parent ) {
3942          $post_parent = get_post( $attachment->post_parent );
3943          if ( $post_parent ) {
3944              $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
3945              $response['uploadedToLink']  = get_edit_post_link( $attachment->post_parent, 'raw' );
3946          }
3947      }
3948  
3949      $attached_file = get_attached_file( $attachment->ID );
3950  
3951      if ( isset( $meta['filesize'] ) ) {
3952          $bytes = $meta['filesize'];
3953      } elseif ( file_exists( $attached_file ) ) {
3954          $bytes = filesize( $attached_file );
3955      } else {
3956          $bytes = '';
3957      }
3958  
3959      if ( $bytes ) {
3960          $response['filesizeInBytes']       = $bytes;
3961          $response['filesizeHumanReadable'] = size_format( $bytes );
3962      }
3963  
3964      $context             = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
3965      $response['context'] = ( $context ) ? $context : '';
3966  
3967      if ( current_user_can( 'edit_post', $attachment->ID ) ) {
3968          $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
3969          $response['nonces']['edit']   = wp_create_nonce( 'image_editor-' . $attachment->ID );
3970          $response['editLink']         = get_edit_post_link( $attachment->ID, 'raw' );
3971      }
3972  
3973      if ( current_user_can( 'delete_post', $attachment->ID ) ) {
3974          $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
3975      }
3976  
3977      if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
3978          $sizes = array();
3979  
3980          /** This filter is documented in wp-admin/includes/media.php */
3981          $possible_sizes = apply_filters(
3982              'image_size_names_choose',
3983              array(
3984                  'thumbnail' => __( 'Thumbnail' ),
3985                  'medium'    => __( 'Medium' ),
3986                  'large'     => __( 'Large' ),
3987                  'full'      => __( 'Full Size' ),
3988              )
3989          );
3990          unset( $possible_sizes['full'] );
3991  
3992          /*
3993           * Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
3994           * First: run the image_downsize filter. If it returns something, we can use its data.
3995           * If the filter does not return something, then image_downsize() is just an expensive way
3996           * to check the image metadata, which we do second.
3997           */
3998          foreach ( $possible_sizes as $size => $label ) {
3999  
4000              /** This filter is documented in wp-includes/media.php */
4001              $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
4002  
4003              if ( $downsize ) {
4004                  if ( empty( $downsize[3] ) ) {
4005                      continue;
4006                  }
4007  
4008                  $sizes[ $size ] = array(
4009                      'height'      => $downsize[2],
4010                      'width'       => $downsize[1],
4011                      'url'         => $downsize[0],
4012                      'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
4013                  );
4014              } elseif ( isset( $meta['sizes'][ $size ] ) ) {
4015                  // Nothing from the filter, so consult image metadata if we have it.
4016                  $size_meta = $meta['sizes'][ $size ];
4017  
4018                  // We have the actual image size, but might need to further constrain it if content_width is narrower.
4019                  // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
4020                  list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
4021  
4022                  $sizes[ $size ] = array(
4023                      'height'      => $height,
4024                      'width'       => $width,
4025                      'url'         => $base_url . $size_meta['file'],
4026                      'orientation' => $height > $width ? 'portrait' : 'landscape',
4027                  );
4028              }
4029          }
4030  
4031          if ( 'image' === $type ) {
4032              if ( ! empty( $meta['original_image'] ) ) {
4033                  $response['originalImageURL']  = wp_get_original_image_url( $attachment->ID );
4034                  $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
4035              }
4036  
4037              $sizes['full'] = array( 'url' => $attachment_url );
4038  
4039              if ( isset( $meta['height'], $meta['width'] ) ) {
4040                  $sizes['full']['height']      = $meta['height'];
4041                  $sizes['full']['width']       = $meta['width'];
4042                  $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
4043              }
4044  
4045              $response = array_merge( $response, $sizes['full'] );
4046          } elseif ( $meta['sizes']['full']['file'] ) {
4047              $sizes['full'] = array(
4048                  'url'         => $base_url . $meta['sizes']['full']['file'],
4049                  'height'      => $meta['sizes']['full']['height'],
4050                  'width'       => $meta['sizes']['full']['width'],
4051                  'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape',
4052              );
4053          }
4054  
4055          $response = array_merge( $response, array( 'sizes' => $sizes ) );
4056      }
4057  
4058      if ( $meta && 'video' === $type ) {
4059          if ( isset( $meta['width'] ) ) {
4060              $response['width'] = (int) $meta['width'];
4061          }
4062          if ( isset( $meta['height'] ) ) {
4063              $response['height'] = (int) $meta['height'];
4064          }
4065      }
4066  
4067      if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
4068          if ( isset( $meta['length_formatted'] ) ) {
4069              $response['fileLength']              = $meta['length_formatted'];
4070              $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] );
4071          }
4072  
4073          $response['meta'] = array();
4074          foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
4075              $response['meta'][ $key ] = false;
4076  
4077              if ( ! empty( $meta[ $key ] ) ) {
4078                  $response['meta'][ $key ] = $meta[ $key ];
4079              }
4080          }
4081  
4082          $id = get_post_thumbnail_id( $attachment->ID );
4083          if ( ! empty( $id ) ) {
4084              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
4085              $response['image']            = compact( 'src', 'width', 'height' );
4086              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
4087              $response['thumb']            = compact( 'src', 'width', 'height' );
4088          } else {
4089              $src               = wp_mime_type_icon( $attachment->ID );
4090              $width             = 48;
4091              $height            = 64;
4092              $response['image'] = compact( 'src', 'width', 'height' );
4093              $response['thumb'] = compact( 'src', 'width', 'height' );
4094          }
4095      }
4096  
4097      if ( function_exists( 'get_compat_media_markup' ) ) {
4098          $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
4099      }
4100  
4101      if ( function_exists( 'get_media_states' ) ) {
4102          $media_states = get_media_states( $attachment );
4103          if ( ! empty( $media_states ) ) {
4104              $response['mediaStates'] = implode( ', ', $media_states );
4105          }
4106      }
4107  
4108      /**
4109       * Filters the attachment data prepared for JavaScript.
4110       *
4111       * @since 3.5.0
4112       *
4113       * @param array       $response   Array of prepared attachment data. @see wp_prepare_attachment_for_js().
4114       * @param WP_Post     $attachment Attachment object.
4115       * @param array|false $meta       Array of attachment meta data, or false if there is none.
4116       */
4117      return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
4118  }
4119  
4120  /**
4121   * Enqueues all scripts, styles, settings, and templates necessary to use
4122   * all media JS APIs.
4123   *
4124   * @since 3.5.0
4125   *
4126   * @global int       $content_width
4127   * @global wpdb      $wpdb          WordPress database abstraction object.
4128   * @global WP_Locale $wp_locale     WordPress date and time locale object.
4129   *
4130   * @param array $args {
4131   *     Arguments for enqueuing media scripts.
4132   *
4133   *     @type int|WP_Post A post object or ID.
4134   * }
4135   */
4136  function wp_enqueue_media( $args = array() ) {
4137      // Enqueue me just once per page, please.
4138      if ( did_action( 'wp_enqueue_media' ) ) {
4139          return;
4140      }
4141  
4142      global $content_width, $wpdb, $wp_locale;
4143  
4144      $defaults = array(
4145          'post' => null,
4146      );
4147      $args     = wp_parse_args( $args, $defaults );
4148  
4149      // We're going to pass the old thickbox media tabs to `media_upload_tabs`
4150      // to ensure plugins will work. We will then unset those tabs.
4151      $tabs = array(
4152          // handler action suffix => tab label
4153          'type'     => '',
4154          'type_url' => '',
4155          'gallery'  => '',
4156          'library'  => '',
4157      );
4158  
4159      /** This filter is documented in wp-admin/includes/media.php */
4160      $tabs = apply_filters( 'media_upload_tabs', $tabs );
4161      unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
4162  
4163      $props = array(
4164          'link'  => get_option( 'image_default_link_type' ), // DB default is 'file'.
4165          'align' => get_option( 'image_default_align' ),     // Empty default.
4166          'size'  => get_option( 'image_default_size' ),      // Empty default.
4167      );
4168  
4169      $exts      = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
4170      $mimes     = get_allowed_mime_types();
4171      $ext_mimes = array();
4172      foreach ( $exts as $ext ) {
4173          foreach ( $mimes as $ext_preg => $mime_match ) {
4174              if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
4175                  $ext_mimes[ $ext ] = $mime_match;
4176                  break;
4177              }
4178          }
4179      }
4180  
4181      /**
4182       * Allows showing or hiding the "Create Audio Playlist" button in the media library.
4183       *
4184       * By default, the "Create Audio Playlist" button will always be shown in
4185       * the media library.  If this filter returns `null`, a query will be run
4186       * to determine whether the media library contains any audio items.  This
4187       * was the default behavior prior to version 4.8.0, but this query is
4188       * expensive for large media libraries.
4189       *
4190       * @since 4.7.4
4191       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4192       *
4193       * @link https://core.trac.wordpress.org/ticket/31071
4194       *
4195       * @param bool|null $show Whether to show the button, or `null` to decide based
4196       *                        on whether any audio files exist in the media library.
4197       */
4198      $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
4199      if ( null === $show_audio_playlist ) {
4200          $show_audio_playlist = $wpdb->get_var(
4201              "
4202              SELECT ID
4203              FROM $wpdb->posts
4204              WHERE post_type = 'attachment'
4205              AND post_mime_type LIKE 'audio%'
4206              LIMIT 1
4207          "
4208          );
4209      }
4210  
4211      /**
4212       * Allows showing or hiding the "Create Video Playlist" button in the media library.
4213       *
4214       * By default, the "Create Video Playlist" button will always be shown in
4215       * the media library.  If this filter returns `null`, a query will be run
4216       * to determine whether the media library contains any video items.  This
4217       * was the default behavior prior to version 4.8.0, but this query is
4218       * expensive for large media libraries.
4219       *
4220       * @since 4.7.4
4221       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4222       *
4223       * @link https://core.trac.wordpress.org/ticket/31071
4224       *
4225       * @param bool|null $show Whether to show the button, or `null` to decide based
4226       *                        on whether any video files exist in the media library.
4227       */
4228      $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
4229      if ( null === $show_video_playlist ) {
4230          $show_video_playlist = $wpdb->get_var(
4231              "
4232              SELECT ID
4233              FROM $wpdb->posts
4234              WHERE post_type = 'attachment'
4235              AND post_mime_type LIKE 'video%'
4236              LIMIT 1
4237          "
4238          );
4239      }
4240  
4241      /**
4242       * Allows overriding the list of months displayed in the media library.
4243       *
4244       * By default (if this filter does not return an array), a query will be
4245       * run to determine the months that have media items.  This query can be
4246       * expensive for large media libraries, so it may be desirable for sites to
4247       * override this behavior.
4248       *
4249       * @since 4.7.4
4250       *
4251       * @link https://core.trac.wordpress.org/ticket/31071
4252       *
4253       * @param array|null $months An array of objects with `month` and `year`
4254       *                           properties, or `null` (or any other non-array value)
4255       *                           for default behavior.
4256       */
4257      $months = apply_filters( 'media_library_months_with_files', null );
4258      if ( ! is_array( $months ) ) {
4259          $months = $wpdb->get_results(
4260              $wpdb->prepare(
4261                  "
4262              SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
4263              FROM $wpdb->posts
4264              WHERE post_type = %s
4265              ORDER BY post_date DESC
4266          ",
4267                  'attachment'
4268              )
4269          );
4270      }
4271      foreach ( $months as $month_year ) {
4272          $month_year->text = sprintf(
4273              /* translators: 1: Month, 2: Year. */
4274              __( '%1$s %2$d' ),
4275              $wp_locale->get_month( $month_year->month ),
4276              $month_year->year
4277          );
4278      }
4279  
4280      $settings = array(
4281          'tabs'             => $tabs,
4282          'tabUrl'           => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ),
4283          'mimeTypes'        => wp_list_pluck( get_post_mime_types(), 0 ),
4284          /** This filter is documented in wp-admin/includes/media.php */
4285          'captions'         => ! apply_filters( 'disable_captions', '' ),
4286          'nonce'            => array(
4287              'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
4288          ),
4289          'post'             => array(
4290              'id' => 0,
4291          ),
4292          'defaultProps'     => $props,
4293          'attachmentCounts' => array(
4294              'audio' => ( $show_audio_playlist ) ? 1 : 0,
4295              'video' => ( $show_video_playlist ) ? 1 : 0,
4296          ),
4297          'oEmbedProxyUrl'   => rest_url( 'oembed/1.0/proxy' ),
4298          'embedExts'        => $exts,
4299          'embedMimes'       => $ext_mimes,
4300          'contentWidth'     => $content_width,
4301          'months'           => $months,
4302          'mediaTrash'       => MEDIA_TRASH ? 1 : 0,
4303      );
4304  
4305      $post = null;
4306      if ( isset( $args['post'] ) ) {
4307          $post             = get_post( $args['post'] );
4308          $settings['post'] = array(
4309              'id'    => $post->ID,
4310              'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
4311          );
4312  
4313          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
4314          if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
4315              if ( wp_attachment_is( 'audio', $post ) ) {
4316                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
4317              } elseif ( wp_attachment_is( 'video', $post ) ) {
4318                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
4319              }
4320          }
4321  
4322          if ( $thumbnail_support ) {
4323              $featured_image_id                   = get_post_meta( $post->ID, '_thumbnail_id', true );
4324              $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
4325          }
4326      }
4327  
4328      if ( $post ) {
4329          $post_type_object = get_post_type_object( $post->post_type );
4330      } else {
4331          $post_type_object = get_post_type_object( 'post' );
4332      }
4333  
4334      $strings = array(
4335          // Generic.
4336          'mediaFrameDefaultTitle'      => __( 'Media' ),
4337          'url'                         => __( 'URL' ),
4338          'addMedia'                    => __( 'Add media' ),
4339          'search'                      => __( 'Search' ),
4340          'select'                      => __( 'Select' ),
4341          'cancel'                      => __( 'Cancel' ),
4342          'update'                      => __( 'Update' ),
4343          'replace'                     => __( 'Replace' ),
4344          'remove'                      => __( 'Remove' ),
4345          'back'                        => __( 'Back' ),
4346          /*
4347           * translators: This is a would-be plural string used in the media manager.
4348           * If there is not a word you can use in your language to avoid issues with the
4349           * lack of plural support here, turn it into "selected: %d" then translate it.
4350           */
4351          'selected'                    => __( '%d selected' ),
4352          'dragInfo'                    => __( 'Drag and drop to reorder media files.' ),
4353  
4354          // Upload.
4355          'uploadFilesTitle'            => __( 'Upload files' ),
4356          'uploadImagesTitle'           => __( 'Upload images' ),
4357  
4358          // Library.
4359          'mediaLibraryTitle'           => __( 'Media Library' ),
4360          'insertMediaTitle'            => __( 'Add media' ),
4361          'createNewGallery'            => __( 'Create a new gallery' ),
4362          'createNewPlaylist'           => __( 'Create a new playlist' ),
4363          'createNewVideoPlaylist'      => __( 'Create a new video playlist' ),
4364          'returnToLibrary'             => __( '&#8592; Go to library' ),
4365          'allMediaItems'               => __( 'All media items' ),
4366          'allDates'                    => __( 'All dates' ),
4367          'noItemsFound'                => __( 'No items found.' ),
4368          'insertIntoPost'              => $post_type_object->labels->insert_into_item,
4369          'unattached'                  => __( 'Unattached' ),
4370          'mine'                        => _x( 'Mine', 'media items' ),
4371          'trash'                       => _x( 'Trash', 'noun' ),
4372          'uploadedToThisPost'          => $post_type_object->labels->uploaded_to_this_item,
4373          'warnDelete'                  => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4374          'warnBulkDelete'              => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4375          'warnBulkTrash'               => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
4376          'bulkSelect'                  => __( 'Bulk select' ),
4377          'trashSelected'               => __( 'Move to Trash' ),
4378          'restoreSelected'             => __( 'Restore from Trash' ),
4379          'deletePermanently'           => __( 'Delete permanently' ),
4380          'apply'                       => __( 'Apply' ),
4381          'filterByDate'                => __( 'Filter by date' ),
4382          'filterByType'                => __( 'Filter by type' ),
4383          'searchLabel'                 => __( 'Search' ),
4384          'searchMediaLabel'            => __( 'Search media' ),          // Backward compatibility pre-5.3.
4385          'searchMediaPlaceholder'      => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
4386          'mediaFound'                  => __( 'Number of media items found: %d' ),
4387          'mediaFoundHasMoreResults'    => __( 'Number of media items displayed: %d. Scroll the page for more results.' ),
4388          'noMedia'                     => __( 'No media items found.' ),
4389          'noMediaTryNewSearch'         => __( 'No media items found. Try a different search.' ),
4390  
4391          // Library Details.
4392          'attachmentDetails'           => __( 'Attachment details' ),
4393  
4394          // From URL.
4395          'insertFromUrlTitle'          => __( 'Insert from URL' ),
4396  
4397          // Featured Images.
4398          'setFeaturedImageTitle'       => $post_type_object->labels->featured_image,
4399          'setFeaturedImage'            => $post_type_object->labels->set_featured_image,
4400  
4401          // Gallery.
4402          'createGalleryTitle'          => __( 'Create gallery' ),
4403          'editGalleryTitle'            => __( 'Edit gallery' ),
4404          'cancelGalleryTitle'          => __( '&#8592; Cancel gallery' ),
4405          'insertGallery'               => __( 'Insert gallery' ),
4406          'updateGallery'               => __( 'Update gallery' ),
4407          'addToGallery'                => __( 'Add to gallery' ),
4408          'addToGalleryTitle'           => __( 'Add to gallery' ),
4409          'reverseOrder'                => __( 'Reverse order' ),
4410  
4411          // Edit Image.
4412          'imageDetailsTitle'           => __( 'Image details' ),
4413          'imageReplaceTitle'           => __( 'Replace image' ),
4414          'imageDetailsCancel'          => __( 'Cancel edit' ),
4415          'editImage'                   => __( 'Edit image' ),
4416  
4417          // Crop Image.
4418          'chooseImage'                 => __( 'Choose image' ),
4419          'selectAndCrop'               => __( 'Select and crop' ),
4420          'skipCropping'                => __( 'Skip cropping' ),
4421          'cropImage'                   => __( 'Crop image' ),
4422          'cropYourImage'               => __( 'Crop your image' ),
4423          'cropping'                    => __( 'Cropping&hellip;' ),
4424          /* translators: 1: Suggested width number, 2: Suggested height number. */
4425          'suggestedDimensions'         => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
4426          'cropError'                   => __( 'There has been an error cropping your image.' ),
4427  
4428          // Edit Audio.
4429          'audioDetailsTitle'           => __( 'Audio details' ),
4430          'audioReplaceTitle'           => __( 'Replace audio' ),
4431          'audioAddSourceTitle'         => __( 'Add audio source' ),
4432          'audioDetailsCancel'          => __( 'Cancel edit' ),
4433  
4434          // Edit Video.
4435          'videoDetailsTitle'           => __( 'Video details' ),
4436          'videoReplaceTitle'           => __( 'Replace video' ),
4437          'videoAddSourceTitle'         => __( 'Add video source' ),
4438          'videoDetailsCancel'          => __( 'Cancel edit' ),
4439          'videoSelectPosterImageTitle' => __( 'Select poster image' ),
4440          'videoAddTrackTitle'          => __( 'Add subtitles' ),
4441  
4442          // Playlist.
4443          'playlistDragInfo'            => __( 'Drag and drop to reorder tracks.' ),
4444          'createPlaylistTitle'         => __( 'Create audio playlist' ),
4445          'editPlaylistTitle'           => __( 'Edit audio playlist' ),
4446          'cancelPlaylistTitle'         => __( '&#8592; Cancel audio playlist' ),
4447          'insertPlaylist'              => __( 'Insert audio playlist' ),
4448          'updatePlaylist'              => __( 'Update audio playlist' ),
4449          'addToPlaylist'               => __( 'Add to audio playlist' ),
4450          'addToPlaylistTitle'          => __( 'Add to Audio Playlist' ),
4451  
4452          // Video Playlist.
4453          'videoPlaylistDragInfo'       => __( 'Drag and drop to reorder videos.' ),
4454          'createVideoPlaylistTitle'    => __( 'Create video playlist' ),
4455          'editVideoPlaylistTitle'      => __( 'Edit video playlist' ),
4456          'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel video playlist' ),
4457          'insertVideoPlaylist'         => __( 'Insert video playlist' ),
4458          'updateVideoPlaylist'         => __( 'Update video playlist' ),
4459          'addToVideoPlaylist'          => __( 'Add to video playlist' ),
4460          'addToVideoPlaylistTitle'     => __( 'Add to video Playlist' ),
4461  
4462          // Headings.
4463          'filterAttachments'           => __( 'Filter media' ),
4464          'attachmentsList'             => __( 'Media list' ),
4465      );
4466  
4467      /**
4468       * Filters the media view settings.
4469       *
4470       * @since 3.5.0
4471       *
4472       * @param array   $settings List of media view settings.
4473       * @param WP_Post $post     Post object.
4474       */
4475      $settings = apply_filters( 'media_view_settings', $settings, $post );
4476  
4477      /**
4478       * Filters the media view strings.
4479       *
4480       * @since 3.5.0
4481       *
4482       * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
4483       * @param WP_Post  $post    Post object.
4484       */
4485      $strings = apply_filters( 'media_view_strings', $strings, $post );
4486  
4487      $strings['settings'] = $settings;
4488  
4489      // Ensure we enqueue media-editor first, that way media-views
4490      // is registered internally before we try to localize it. See #24724.
4491      wp_enqueue_script( 'media-editor' );
4492      wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
4493  
4494      wp_enqueue_script( 'media-audiovideo' );
4495      wp_enqueue_style( 'media-views' );
4496      if ( is_admin() ) {
4497          wp_enqueue_script( 'mce-view' );
4498          wp_enqueue_script( 'image-edit' );
4499      }
4500      wp_enqueue_style( 'imgareaselect' );
4501      wp_plupload_default_settings();
4502  
4503      require_once  ABSPATH . WPINC . '/media-template.php';
4504      add_action( 'admin_footer', 'wp_print_media_templates' );
4505      add_action( 'wp_footer', 'wp_print_media_templates' );
4506      add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
4507  
4508      /**
4509       * Fires at the conclusion of wp_enqueue_media().
4510       *
4511       * @since 3.5.0
4512       */
4513      do_action( 'wp_enqueue_media' );
4514  }
4515  
4516  /**
4517   * Retrieves media attached to the passed post.
4518   *
4519   * @since 3.6.0
4520   *
4521   * @param string      $type Mime type.
4522   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4523   * @return WP_Post[] Array of media attached to the given post.
4524   */
4525  function get_attached_media( $type, $post = 0 ) {
4526      $post = get_post( $post );
4527  
4528      if ( ! $post ) {
4529          return array();
4530      }
4531  
4532      $args = array(
4533          'post_parent'    => $post->ID,
4534          'post_type'      => 'attachment',
4535          'post_mime_type' => $type,
4536          'posts_per_page' => -1,
4537          'orderby'        => 'menu_order',
4538          'order'          => 'ASC',
4539      );
4540  
4541      /**
4542       * Filters arguments used to retrieve media attached to the given post.
4543       *
4544       * @since 3.6.0
4545       *
4546       * @param array   $args Post query arguments.
4547       * @param string  $type Mime type of the desired media.
4548       * @param WP_Post $post Post object.
4549       */
4550      $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
4551  
4552      $children = get_children( $args );
4553  
4554      /**
4555       * Filters the list of media attached to the given post.
4556       *
4557       * @since 3.6.0
4558       *
4559       * @param WP_Post[] $children Array of media attached to the given post.
4560       * @param string    $type     Mime type of the media desired.
4561       * @param WP_Post   $post     Post object.
4562       */
4563      return (array) apply_filters( 'get_attached_media', $children, $type, $post );
4564  }
4565  
4566  /**
4567   * Check the content HTML for a audio, video, object, embed, or iframe tags.
4568   *
4569   * @since 3.6.0
4570   *
4571   * @param string   $content A string of HTML which might contain media elements.
4572   * @param string[] $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
4573   * @return string[] Array of found HTML media elements.
4574   */
4575  function get_media_embedded_in_content( $content, $types = null ) {
4576      $html = array();
4577  
4578      /**
4579       * Filters the embedded media types that are allowed to be returned from the content blob.
4580       *
4581       * @since 4.2.0
4582       *
4583       * @param string[] $allowed_media_types An array of allowed media types. Default media types are
4584       *                                      'audio', 'video', 'object', 'embed', and 'iframe'.
4585       */
4586      $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
4587  
4588      if ( ! empty( $types ) ) {
4589          if ( ! is_array( $types ) ) {
4590              $types = array( $types );
4591          }
4592  
4593          $allowed_media_types = array_intersect( $allowed_media_types, $types );
4594      }
4595  
4596      $tags = implode( '|', $allowed_media_types );
4597  
4598      if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
4599          foreach ( $matches[0] as $match ) {
4600              $html[] = $match;
4601          }
4602      }
4603  
4604      return $html;
4605  }
4606  
4607  /**
4608   * Retrieves galleries from the passed post's content.
4609   *
4610   * @since 3.6.0
4611   *
4612   * @param int|WP_Post $post Post ID or object.
4613   * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
4614   * @return array A list of arrays, each containing gallery data and srcs parsed
4615   *               from the expanded shortcode.
4616   */
4617  function get_post_galleries( $post, $html = true ) {
4618      $post = get_post( $post );
4619  
4620      if ( ! $post ) {
4621          return array();
4622      }
4623  
4624      if ( ! has_shortcode( $post->post_content, 'gallery' ) ) {
4625          return array();
4626      }
4627  
4628      $galleries = array();
4629      if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
4630          foreach ( $matches as $shortcode ) {
4631              if ( 'gallery' === $shortcode[2] ) {
4632                  $srcs = array();
4633  
4634                  $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
4635                  if ( ! is_array( $shortcode_attrs ) ) {
4636                      $shortcode_attrs = array();
4637                  }
4638  
4639                  // Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already.
4640                  if ( ! isset( $shortcode_attrs['id'] ) ) {
4641                      $shortcode[3] .= ' id="' . (int) $post->ID . '"';
4642                  }
4643  
4644                  $gallery = do_shortcode_tag( $shortcode );
4645                  if ( $html ) {
4646                      $galleries[] = $gallery;
4647                  } else {
4648                      preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
4649                      if ( ! empty( $src ) ) {
4650                          foreach ( $src as $s ) {
4651                              $srcs[] = $s[2];
4652                          }
4653                      }
4654  
4655                      $galleries[] = array_merge(
4656                          $shortcode_attrs,
4657                          array(
4658                              'src' => array_values( array_unique( $srcs ) ),
4659                          )
4660                      );
4661                  }
4662              }
4663          }
4664      }
4665  
4666      /**
4667       * Filters the list of all found galleries in the given post.
4668       *
4669       * @since 3.6.0
4670       *
4671       * @param array   $galleries Associative array of all found post galleries.
4672       * @param WP_Post $post      Post object.
4673       */
4674      return apply_filters( 'get_post_galleries', $galleries, $post );
4675  }
4676  
4677  /**
4678   * Check a specified post's content for gallery and, if present, return the first
4679   *
4680   * @since 3.6.0
4681   *
4682   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4683   * @param bool        $html Optional. Whether to return HTML or data. Default is true.
4684   * @return string|array Gallery data and srcs parsed from the expanded shortcode.
4685   */
4686  function get_post_gallery( $post = 0, $html = true ) {
4687      $galleries = get_post_galleries( $post, $html );
4688      $gallery   = reset( $galleries );
4689  
4690      /**
4691       * Filters the first-found post gallery.
4692       *
4693       * @since 3.6.0
4694       *
4695       * @param array       $gallery   The first-found post gallery.
4696       * @param int|WP_Post $post      Post ID or object.
4697       * @param array       $galleries Associative array of all found post galleries.
4698       */
4699      return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
4700  }
4701  
4702  /**
4703   * Retrieve the image srcs from galleries from a post's content, if present
4704   *
4705   * @since 3.6.0
4706   *
4707   * @see get_post_galleries()
4708   *
4709   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
4710   * @return array A list of lists, each containing image srcs parsed.
4711   *               from an expanded shortcode
4712   */
4713  function get_post_galleries_images( $post = 0 ) {
4714      $galleries = get_post_galleries( $post, false );
4715      return wp_list_pluck( $galleries, 'src' );
4716  }
4717  
4718  /**
4719   * Checks a post's content for galleries and return the image srcs for the first found gallery
4720   *
4721   * @since 3.6.0
4722   *
4723   * @see get_post_gallery()
4724   *
4725   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
4726   * @return string[] A list of a gallery's image srcs in order.
4727   */
4728  function get_post_gallery_images( $post = 0 ) {
4729      $gallery = get_post_gallery( $post, false );
4730      return empty( $gallery['src'] ) ? array() : $gallery['src'];
4731  }
4732  
4733  /**
4734   * Maybe attempts to generate attachment metadata, if missing.
4735   *
4736   * @since 3.9.0
4737   *
4738   * @param WP_Post $attachment Attachment object.
4739   */
4740  function wp_maybe_generate_attachment_metadata( $attachment ) {
4741      if ( empty( $attachment ) || empty( $attachment->ID ) ) {
4742          return;
4743      }
4744  
4745      $attachment_id = (int) $attachment->ID;
4746      $file          = get_attached_file( $attachment_id );
4747      $meta          = wp_get_attachment_metadata( $attachment_id );
4748  
4749      if ( empty( $meta ) && file_exists( $file ) ) {
4750          $_meta = get_post_meta( $attachment_id );
4751          $_lock = 'wp_generating_att_' . $attachment_id;
4752  
4753          if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
4754              set_transient( $_lock, $file );
4755              wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
4756              delete_transient( $_lock );
4757          }
4758      }
4759  }
4760  
4761  /**
4762   * Tries to convert an attachment URL into a post ID.
4763   *
4764   * @since 4.0.0
4765   *
4766   * @global wpdb $wpdb WordPress database abstraction object.
4767   *
4768   * @param string $url The URL to resolve.
4769   * @return int The found post ID, or 0 on failure.
4770   */
4771  function attachment_url_to_postid( $url ) {
4772      global $wpdb;
4773  
4774      $dir  = wp_get_upload_dir();
4775      $path = $url;
4776  
4777      $site_url   = parse_url( $dir['url'] );
4778      $image_path = parse_url( $path );
4779  
4780      // Force the protocols to match if needed.
4781      if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
4782          $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
4783      }
4784  
4785      if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
4786          $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
4787      }
4788  
4789      $sql = $wpdb->prepare(
4790          "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
4791          $path
4792      );
4793  
4794      $results = $wpdb->get_results( $sql );
4795      $post_id = null;
4796  
4797      if ( $results ) {
4798          // Use the first available result, but prefer a case-sensitive match, if exists.
4799          $post_id = reset( $results )->post_id;
4800  
4801          if ( count( $results ) > 1 ) {
4802              foreach ( $results as $result ) {
4803                  if ( $path === $result->meta_value ) {
4804                      $post_id = $result->post_id;
4805                      break;
4806                  }
4807              }
4808          }
4809      }
4810  
4811      /**
4812       * Filters an attachment ID found by URL.
4813       *
4814       * @since 4.2.0
4815       *
4816       * @param int|null $post_id The post_id (if any) found by the function.
4817       * @param string   $url     The URL being looked up.
4818       */
4819      return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
4820  }
4821  
4822  /**
4823   * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
4824   *
4825   * @since 4.0.0
4826   *
4827   * @return string[] The relevant CSS file URLs.
4828   */
4829  function wpview_media_sandbox_styles() {
4830      $version        = 'ver=' . get_bloginfo( 'version' );
4831      $mediaelement   = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" );
4832      $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
4833  
4834      return array( $mediaelement, $wpmediaelement );
4835  }
4836  
4837  /**
4838   * Registers the personal data exporter for media.
4839   *
4840   * @param array[] $exporters An array of personal data exporters, keyed by their ID.
4841   * @return array[] Updated array of personal data exporters.
4842   */
4843  function wp_register_media_personal_data_exporter( $exporters ) {
4844      $exporters['wordpress-media'] = array(
4845          'exporter_friendly_name' => __( 'WordPress Media' ),
4846          'callback'               => 'wp_media_personal_data_exporter',
4847      );
4848  
4849      return $exporters;
4850  }
4851  
4852  /**
4853   * Finds and exports attachments associated with an email address.
4854   *
4855   * @since 4.9.6
4856   *
4857   * @param string $email_address The attachment owner email address.
4858   * @param int    $page          Attachment page.
4859   * @return array An array of personal data.
4860   */
4861  function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
4862      // Limit us to 50 attachments at a time to avoid timing out.
4863      $number = 50;
4864      $page   = (int) $page;
4865  
4866      $data_to_export = array();
4867  
4868      $user = get_user_by( 'email', $email_address );
4869      if ( false === $user ) {
4870          return array(
4871              'data' => $data_to_export,
4872              'done' => true,
4873          );
4874      }
4875  
4876      $post_query = new WP_Query(
4877          array(
4878              'author'         => $user->ID,
4879              'posts_per_page' => $number,
4880              'paged'          => $page,
4881              'post_type'      => 'attachment',
4882              'post_status'    => 'any',
4883              'orderby'        => 'ID',
4884              'order'          => 'ASC',
4885          )
4886      );
4887  
4888      foreach ( (array) $post_query->posts as $post ) {
4889          $attachment_url = wp_get_attachment_url( $post->ID );
4890  
4891          if ( $attachment_url ) {
4892              $post_data_to_export = array(
4893                  array(
4894                      'name'  => __( 'URL' ),
4895                      'value' => $attachment_url,
4896                  ),
4897              );
4898  
4899              $data_to_export[] = array(
4900                  'group_id'          => 'media',
4901                  'group_label'       => __( 'Media' ),
4902                  'group_description' => __( 'User&#8217;s media data.' ),
4903                  'item_id'           => "post-{$post->ID}",
4904                  'data'              => $post_data_to_export,
4905              );
4906          }
4907      }