[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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  // Don't load directly.
  10  if ( ! defined( 'ABSPATH' ) ) {
  11      die( '-1' );
  12  }
  13  
  14  /**
  15   * Retrieves additional image sizes.
  16   *
  17   * @since 4.7.0
  18   *
  19   * @global array $_wp_additional_image_sizes
  20   *
  21   * @return array Additional images size data.
  22   */
  23  function wp_get_additional_image_sizes() {
  24      global $_wp_additional_image_sizes;
  25  
  26      if ( ! $_wp_additional_image_sizes ) {
  27          $_wp_additional_image_sizes = array();
  28      }
  29  
  30      return $_wp_additional_image_sizes;
  31  }
  32  
  33  /**
  34   * Scales down the default size of an image.
  35   *
  36   * This is so that the image is a better fit for the editor and theme.
  37   *
  38   * The `$size` parameter accepts either an array or a string. The supported string
  39   * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  40   * 128 width and 96 height in pixels. Also supported for the string value is
  41   * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
  42   * than the supported will result in the content_width size or 500 if that is
  43   * not set.
  44   *
  45   * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
  46   * called on the calculated array for width and height, respectively.
  47   *
  48   * @since 2.5.0
  49   *
  50   * @global int $content_width
  51   *
  52   * @param int          $width   Width of the image in pixels.
  53   * @param int          $height  Height of the image in pixels.
  54   * @param string|int[] $size    Optional. Image size. Accepts any registered image size name, or an array
  55   *                              of width and height values in pixels (in that order). Default 'medium'.
  56   * @param string       $context Optional. Could be 'display' (like in a theme) or 'edit'
  57   *                              (like inserting into an editor). Default null.
  58   * @return int[] {
  59   *     An array of width and height values.
  60   *
  61   *     @type int $0 The maximum width in pixels.
  62   *     @type int $1 The maximum height in pixels.
  63   * }
  64   */
  65  function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  66      global $content_width;
  67  
  68      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  69  
  70      if ( ! $context ) {
  71          $context = is_admin() ? 'edit' : 'display';
  72      }
  73  
  74      if ( is_array( $size ) ) {
  75          $max_width  = $size[0];
  76          $max_height = $size[1];
  77      } elseif ( 'thumb' === $size || 'thumbnail' === $size ) {
  78          $max_width  = (int) get_option( 'thumbnail_size_w' );
  79          $max_height = (int) get_option( 'thumbnail_size_h' );
  80          // Last chance thumbnail size defaults.
  81          if ( ! $max_width && ! $max_height ) {
  82              $max_width  = 128;
  83              $max_height = 96;
  84          }
  85      } elseif ( 'medium' === $size ) {
  86          $max_width  = (int) get_option( 'medium_size_w' );
  87          $max_height = (int) get_option( 'medium_size_h' );
  88  
  89      } elseif ( 'medium_large' === $size ) {
  90          $max_width  = (int) get_option( 'medium_large_size_w' );
  91          $max_height = (int) get_option( 'medium_large_size_h' );
  92  
  93          if ( (int) $content_width > 0 ) {
  94              $max_width = min( (int) $content_width, $max_width );
  95          }
  96      } elseif ( 'large' === $size ) {
  97          /*
  98           * We're inserting a large size image into the editor. If it's a really
  99           * big image we'll scale it down to fit reasonably within the editor
 100           * itself, and within the theme's content width if it's known. The user
 101           * can resize it in the editor if they wish.
 102           */
 103          $max_width  = (int) get_option( 'large_size_w' );
 104          $max_height = (int) get_option( 'large_size_h' );
 105  
 106          if ( (int) $content_width > 0 ) {
 107              $max_width = min( (int) $content_width, $max_width );
 108          }
 109      } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ), true ) ) {
 110          $max_width  = (int) $_wp_additional_image_sizes[ $size ]['width'];
 111          $max_height = (int) $_wp_additional_image_sizes[ $size ]['height'];
 112          // Only in admin. Assume that theme authors know what they're doing.
 113          if ( (int) $content_width > 0 && 'edit' === $context ) {
 114              $max_width = min( (int) $content_width, $max_width );
 115          }
 116      } else { // $size === 'full' has no constraint.
 117          $max_width  = $width;
 118          $max_height = $height;
 119      }
 120  
 121      /**
 122       * Filters the maximum image size dimensions for the editor.
 123       *
 124       * @since 2.5.0
 125       *
 126       * @param int[]        $max_image_size {
 127       *     An array of width and height values.
 128       *
 129       *     @type int $0 The maximum width in pixels.
 130       *     @type int $1 The maximum height in pixels.
 131       * }
 132       * @param string|int[] $size     Requested image size. Can be any registered image size name, or
 133       *                               an array of width and height values in pixels (in that order).
 134       * @param string       $context  The context the image is being resized for.
 135       *                               Possible values are 'display' (like in a theme)
 136       *                               or 'edit' (like inserting into an editor).
 137       */
 138      list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
 139  
 140      return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
 141  }
 142  
 143  /**
 144   * Retrieves width and height attributes using given width and height values.
 145   *
 146   * Both attributes are required in the sense that both parameters must have a
 147   * value, but are optional in that if you set them to false or null, then they
 148   * will not be added to the returned string.
 149   *
 150   * You can set the value using a string, but it will only take numeric values.
 151   * If you wish to put 'px' after the numbers, then it will be stripped out of
 152   * the return.
 153   *
 154   * @since 2.5.0
 155   *
 156   * @param int|string $width  Image width in pixels.
 157   * @param int|string $height Image height in pixels.
 158   * @return string HTML attributes for width and, or height.
 159   */
 160  function image_hwstring( $width, $height ) {
 161      $out = '';
 162      if ( $width ) {
 163          $out .= 'width="' . (int) $width . '" ';
 164      }
 165      if ( $height ) {
 166          $out .= 'height="' . (int) $height . '" ';
 167      }
 168      return $out;
 169  }
 170  
 171  /**
 172   * Scales an image to fit a particular size (such as 'thumb' or 'medium').
 173   *
 174   * The URL might be the original image, or it might be a resized version. This
 175   * function won't create a new resized copy, it will just return an already
 176   * resized one if it exists.
 177   *
 178   * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
 179   * resizing services for images. The hook must return an array with the same
 180   * elements that are normally returned from the function.
 181   *
 182   * @since 2.5.0
 183   *
 184   * @param int          $id   Attachment ID for image.
 185   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
 186   *                           of width and height values in pixels (in that order). Default 'medium'.
 187   * @return array|false {
 188   *     Array of image data, or boolean false if no image is available.
 189   *
 190   *     @type string $0 Image source URL.
 191   *     @type int    $1 Image width in pixels.
 192   *     @type int    $2 Image height in pixels.
 193   *     @type bool   $3 Whether the image is a resized image.
 194   * }
 195   */
 196  function image_downsize( $id, $size = 'medium' ) {
 197      $is_image = wp_attachment_is_image( $id );
 198  
 199      /**
 200       * Filters whether to preempt the output of image_downsize().
 201       *
 202       * Returning a truthy value from the filter will effectively short-circuit
 203       * down-sizing the image, returning that value instead.
 204       *
 205       * @since 2.5.0
 206       *
 207       * @param bool|array   $downsize Whether to short-circuit the image downsize.
 208       * @param int          $id       Attachment ID for image.
 209       * @param string|int[] $size     Requested image size. Can be any registered image size name, or
 210       *                               an array of width and height values in pixels (in that order).
 211       */
 212      $out = apply_filters( 'image_downsize', false, $id, $size );
 213  
 214      if ( $out ) {
 215          return $out;
 216      }
 217  
 218      $img_url          = wp_get_attachment_url( $id );
 219      $meta             = wp_get_attachment_metadata( $id );
 220      $width            = 0;
 221      $height           = 0;
 222      $is_intermediate  = false;
 223      $img_url_basename = wp_basename( $img_url );
 224  
 225      /*
 226       * If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
 227       * Otherwise, a non-image type could be returned.
 228       */
 229      if ( ! $is_image ) {
 230          if ( ! empty( $meta['sizes']['full'] ) ) {
 231              $img_url          = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
 232              $img_url_basename = $meta['sizes']['full']['file'];
 233              $width            = $meta['sizes']['full']['width'];
 234              $height           = $meta['sizes']['full']['height'];
 235          } else {
 236              return false;
 237          }
 238      }
 239  
 240      // Try for a new style intermediate size.
 241      $intermediate = image_get_intermediate_size( $id, $size );
 242  
 243      if ( $intermediate ) {
 244          $img_url         = str_replace( $img_url_basename, $intermediate['file'], $img_url );
 245          $width           = $intermediate['width'];
 246          $height          = $intermediate['height'];
 247          $is_intermediate = true;
 248      } elseif ( 'thumbnail' === $size && ! empty( $meta['thumb'] ) && is_string( $meta['thumb'] ) ) {
 249          // Fall back to the old thumbnail.
 250          $imagefile = get_attached_file( $id );
 251          $thumbfile = str_replace( wp_basename( $imagefile ), wp_basename( $meta['thumb'] ), $imagefile );
 252  
 253          if ( file_exists( $thumbfile ) ) {
 254              $info = wp_getimagesize( $thumbfile );
 255  
 256              if ( $info ) {
 257                  $img_url         = str_replace( $img_url_basename, wp_basename( $thumbfile ), $img_url );
 258                  $width           = $info[0];
 259                  $height          = $info[1];
 260                  $is_intermediate = true;
 261              }
 262          }
 263      }
 264  
 265      if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) {
 266          // Any other type: use the real image.
 267          $width  = $meta['width'];
 268          $height = $meta['height'];
 269      }
 270  
 271      if ( $img_url ) {
 272          // We have the actual image size, but might need to further constrain it if content_width is narrower.
 273          list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
 274  
 275          return array( $img_url, $width, $height, $is_intermediate );
 276      }
 277  
 278      return false;
 279  }
 280  
 281  /**
 282   * Registers a new image size.
 283   *
 284   * @since 2.9.0
 285   *
 286   * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
 287   *
 288   * @param string     $name   Image size identifier.
 289   * @param int        $width  Optional. Image width in pixels. Default 0.
 290   * @param int        $height Optional. Image height in pixels. Default 0.
 291   * @param bool|array $crop   {
 292   *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 293   *     If true, image will be cropped to the specified dimensions using center positions.
 294   *     If an array, the image will be cropped using the array to specify the crop location:
 295   *
 296   *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 297   *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 298   * }
 299   */
 300  function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
 301      global $_wp_additional_image_sizes;
 302  
 303      $_wp_additional_image_sizes[ $name ] = array(
 304          'width'  => absint( $width ),
 305          'height' => absint( $height ),
 306          'crop'   => $crop,
 307      );
 308  }
 309  
 310  /**
 311   * Checks if an image size exists.
 312   *
 313   * @since 3.9.0
 314   *
 315   * @param string $name The image size to check.
 316   * @return bool True if the image size exists, false if not.
 317   */
 318  function has_image_size( $name ) {
 319      $sizes = wp_get_additional_image_sizes();
 320      return isset( $sizes[ $name ] );
 321  }
 322  
 323  /**
 324   * Removes a new image size.
 325   *
 326   * @since 3.9.0
 327   *
 328   * @global array $_wp_additional_image_sizes
 329   *
 330   * @param string $name The image size to remove.
 331   * @return bool True if the image size was successfully removed, false on failure.
 332   */
 333  function remove_image_size( $name ) {
 334      global $_wp_additional_image_sizes;
 335  
 336      if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
 337          unset( $_wp_additional_image_sizes[ $name ] );
 338          return true;
 339      }
 340  
 341      return false;
 342  }
 343  
 344  /**
 345   * Registers an image size for the post thumbnail.
 346   *
 347   * @since 2.9.0
 348   *
 349   * @see add_image_size() for details on cropping behavior.
 350   *
 351   * @param int        $width  Image width in pixels.
 352   * @param int        $height Image height in pixels.
 353   * @param bool|array $crop   {
 354   *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 355   *     If true, image will be cropped to the specified dimensions using center positions.
 356   *     If an array, the image will be cropped using the array to specify the crop location:
 357   *
 358   *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 359   *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 360   * }
 361   */
 362  function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
 363      add_image_size( 'post-thumbnail', $width, $height, $crop );
 364  }
 365  
 366  /**
 367   * Gets an img tag for an image attachment, scaling it down if requested.
 368   *
 369   * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
 370   * image without having to use regular expressions on the HTML content. The
 371   * parameters are: what WordPress will use for the class, the Attachment ID,
 372   * image align value, and the size the image should be.
 373   *
 374   * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
 375   * further manipulated by a plugin to change all attribute values and even HTML
 376   * content.
 377   *
 378   * @since 2.5.0
 379   *
 380   * @param int          $id    Attachment ID.
 381   * @param string       $alt   Image description for the alt attribute.
 382   * @param string       $title Image description for the title attribute.
 383   * @param string       $align Part of the class name for aligning the image.
 384   * @param string|int[] $size  Optional. Image size. Accepts any registered image size name, or an array of
 385   *                            width and height values in pixels (in that order). Default 'medium'.
 386   * @return string HTML IMG element for given image attachment.
 387   */
 388  function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
 389  
 390      list( $img_src, $width, $height ) = image_downsize( $id, $size );
 391      $hwstring                         = image_hwstring( $width, $height );
 392  
 393      $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
 394  
 395      $size_class = is_array( $size ) ? implode( 'x', $size ) : $size;
 396      $class      = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id;
 397  
 398      /**
 399       * Filters the value of the attachment's image tag class attribute.
 400       *
 401       * @since 2.6.0
 402       *
 403       * @param string       $class CSS class name or space-separated list of classes.
 404       * @param int          $id    Attachment ID.
 405       * @param string       $align Part of the class name for aligning the image.
 406       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 407       *                            an array of width and height values in pixels (in that order).
 408       */
 409      $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
 410  
 411      $html = '<img src="' . esc_url( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
 412  
 413      /**
 414       * Filters the HTML content for the image tag.
 415       *
 416       * @since 2.6.0
 417       *
 418       * @param string       $html  HTML content for the image.
 419       * @param int          $id    Attachment ID.
 420       * @param string       $alt   Image description for the alt attribute.
 421       * @param string       $title Image description for the title attribute.
 422       * @param string       $align Part of the class name for aligning the image.
 423       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 424       *                            an array of width and height values in pixels (in that order).
 425       */
 426      return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
 427  }
 428  
 429  /**
 430   * Calculates the new dimensions for a down-sampled image.
 431   *
 432   * If either width or height are empty, no constraint is applied on
 433   * that dimension.
 434   *
 435   * @since 2.5.0
 436   *
 437   * @param int $current_width  Current width of the image.
 438   * @param int $current_height Current height of the image.
 439   * @param int $max_width      Optional. Max width in pixels to constrain to. Default 0.
 440   * @param int $max_height     Optional. Max height in pixels to constrain to. Default 0.
 441   * @return int[] {
 442   *     An array of width and height values.
 443   *
 444   *     @type int $0 The width in pixels.
 445   *     @type int $1 The height in pixels.
 446   * }
 447   */
 448  function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
 449      if ( ! $max_width && ! $max_height ) {
 450          return array( $current_width, $current_height );
 451      }
 452  
 453      $width_ratio  = 1.0;
 454      $height_ratio = 1.0;
 455      $did_width    = false;
 456      $did_height   = false;
 457  
 458      if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
 459          $width_ratio = $max_width / $current_width;
 460          $did_width   = true;
 461      }
 462  
 463      if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
 464          $height_ratio = $max_height / $current_height;
 465          $did_height   = true;
 466      }
 467  
 468      // Calculate the larger/smaller ratios.
 469      $smaller_ratio = min( $width_ratio, $height_ratio );
 470      $larger_ratio  = max( $width_ratio, $height_ratio );
 471  
 472      if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
 473          // The larger ratio is too big. It would result in an overflow.
 474          $ratio = $smaller_ratio;
 475      } else {
 476          // The larger ratio fits, and is likely to be a more "snug" fit.
 477          $ratio = $larger_ratio;
 478      }
 479  
 480      // Very small dimensions may result in 0, 1 should be the minimum.
 481      $w = max( 1, (int) round( $current_width * $ratio ) );
 482      $h = max( 1, (int) round( $current_height * $ratio ) );
 483  
 484      /*
 485       * Sometimes, due to rounding, we'll end up with a result like this:
 486       * 465x700 in a 177x177 box is 117x176... a pixel short.
 487       * We also have issues with recursive calls resulting in an ever-changing result.
 488       * Constraining to the result of a constraint should yield the original result.
 489       * Thus we look for dimensions that are one pixel shy of the max value and bump them up.
 490       */
 491  
 492      // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
 493      if ( $did_width && $w === $max_width - 1 ) {
 494          $w = $max_width; // Round it up.
 495      }
 496  
 497      // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
 498      if ( $did_height && $h === $max_height - 1 ) {
 499          $h = $max_height; // Round it up.
 500      }
 501  
 502      /**
 503       * Filters dimensions to constrain down-sampled images to.
 504       *
 505       * @since 4.1.0
 506       *
 507       * @param int[] $dimensions     {
 508       *     An array of width and height values.
 509       *
 510       *     @type int $0 The width in pixels.
 511       *     @type int $1 The height in pixels.
 512       * }
 513       * @param int   $current_width  The current width of the image.
 514       * @param int   $current_height The current height of the image.
 515       * @param int   $max_width      The maximum width permitted.
 516       * @param int   $max_height     The maximum height permitted.
 517       */
 518      return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
 519  }
 520  
 521  /**
 522   * Retrieves calculated resize dimensions for use in WP_Image_Editor.
 523   *
 524   * Calculates dimensions and coordinates for a resized image that fits
 525   * within a specified width and height.
 526   *
 527   * @since 2.5.0
 528   *
 529   * @param int        $orig_w Original width in pixels.
 530   * @param int        $orig_h Original height in pixels.
 531   * @param int        $dest_w New width in pixels.
 532   * @param int        $dest_h New height in pixels.
 533   * @param bool|array $crop   {
 534   *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 535   *     If true, image will be cropped to the specified dimensions using center positions.
 536   *     If an array, the image will be cropped using the array to specify the crop location:
 537   *
 538   *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 539   *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 540   * }
 541   * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure.
 542   */
 543  function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
 544  
 545      if ( $orig_w <= 0 || $orig_h <= 0 ) {
 546          return false;
 547      }
 548      // At least one of $dest_w or $dest_h must be specific.
 549      if ( $dest_w <= 0 && $dest_h <= 0 ) {
 550          return false;
 551      }
 552  
 553      /**
 554       * Filters whether to preempt calculating the image resize dimensions.
 555       *
 556       * Returning a non-null value from the filter will effectively short-circuit
 557       * image_resize_dimensions(), returning that value instead.
 558       *
 559       * @since 3.4.0
 560       *
 561       * @param null|mixed $null   Whether to preempt output of the resize dimensions.
 562       * @param int        $orig_w Original width in pixels.
 563       * @param int        $orig_h Original height in pixels.
 564       * @param int        $dest_w New width in pixels.
 565       * @param int        $dest_h New height in pixels.
 566       * @param bool|array $crop   Whether to crop image to specified width and height or resize.
 567       *                           An array can specify positioning of the crop area. Default false.
 568       */
 569      $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
 570  
 571      if ( null !== $output ) {
 572          return $output;
 573      }
 574  
 575      // Stop if the destination size is larger than the original image dimensions.
 576      if ( empty( $dest_h ) ) {
 577          if ( $orig_w < $dest_w ) {
 578              return false;
 579          }
 580      } elseif ( empty( $dest_w ) ) {
 581          if ( $orig_h < $dest_h ) {
 582              return false;
 583          }
 584      } else {
 585          if ( $orig_w < $dest_w && $orig_h < $dest_h ) {
 586              return false;
 587          }
 588      }
 589  
 590      if ( $crop ) {
 591          /*
 592           * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h.
 593           * Note that the requested crop dimensions are used as a maximum bounding box for the original image.
 594           * If the original image's width or height is less than the requested width or height
 595           * only the greater one will be cropped.
 596           * For example when the original image is 600x300, and the requested crop dimensions are 400x400,
 597           * the resulting image will be 400x300.
 598           */
 599          $aspect_ratio = $orig_w / $orig_h;
 600          $new_w        = min( $dest_w, $orig_w );
 601          $new_h        = min( $dest_h, $orig_h );
 602  
 603          if ( ! $new_w ) {
 604              $new_w = (int) round( $new_h * $aspect_ratio );
 605          }
 606  
 607          if ( ! $new_h ) {
 608              $new_h = (int) round( $new_w / $aspect_ratio );
 609          }
 610  
 611          $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );
 612  
 613          $crop_w = round( $new_w / $size_ratio );
 614          $crop_h = round( $new_h / $size_ratio );
 615  
 616          if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
 617              $crop = array( 'center', 'center' );
 618          }
 619  
 620          list( $x, $y ) = $crop;
 621  
 622          if ( 'left' === $x ) {
 623              $s_x = 0;
 624          } elseif ( 'right' === $x ) {
 625              $s_x = $orig_w - $crop_w;
 626          } else {
 627              $s_x = floor( ( $orig_w - $crop_w ) / 2 );
 628          }
 629  
 630          if ( 'top' === $y ) {
 631              $s_y = 0;
 632          } elseif ( 'bottom' === $y ) {
 633              $s_y = $orig_h - $crop_h;
 634          } else {
 635              $s_y = floor( ( $orig_h - $crop_h ) / 2 );
 636          }
 637      } else {
 638          // Resize using $dest_w x $dest_h as a maximum bounding box.
 639          $crop_w = $orig_w;
 640          $crop_h = $orig_h;
 641  
 642          $s_x = 0;
 643          $s_y = 0;
 644  
 645          list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
 646      }
 647  
 648      if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) {
 649          // The new size has virtually the same dimensions as the original image.
 650  
 651          /**
 652           * Filters whether to proceed with making an image sub-size with identical dimensions
 653           * with the original/source image. Differences of 1px may be due to rounding and are ignored.
 654           *
 655           * @since 5.3.0
 656           *
 657           * @param bool $proceed The filtered value.
 658           * @param int  $orig_w  Original image width.
 659           * @param int  $orig_h  Original image height.
 660           */
 661          $proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h );
 662  
 663          if ( ! $proceed ) {
 664              return false;
 665          }
 666      }
 667  
 668      /*
 669       * The return array matches the parameters to imagecopyresampled().
 670       * int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
 671       */
 672      return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
 673  }
 674  
 675  /**
 676   * Resizes an image to make a thumbnail or intermediate size.
 677   *
 678   * The returned array has the file size, the image width, and image height. The
 679   * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
 680   * values of the returned array. The only parameter is the resized file path.
 681   *
 682   * @since 2.5.0
 683   *
 684   * @param string     $file   File path.
 685   * @param int        $width  Image width.
 686   * @param int        $height Image height.
 687   * @param bool|array $crop   {
 688   *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 689   *     If true, image will be cropped to the specified dimensions using center positions.
 690   *     If an array, the image will be cropped using the array to specify the crop location:
 691   *
 692   *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 693   *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 694   * }
 695   * @return array|false Metadata array on success. False if no image was created.
 696   */
 697  function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
 698      if ( $width || $height ) {
 699          $editor = wp_get_image_editor( $file );
 700  
 701          if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
 702              return false;
 703          }
 704  
 705          $resized_file = $editor->save();
 706  
 707          if ( ! is_wp_error( $resized_file ) && $resized_file ) {
 708              unset( $resized_file['path'] );
 709              return $resized_file;
 710          }
 711      }
 712      return false;
 713  }
 714  
 715  /**
 716   * Helper function to test if aspect ratios for two images match.
 717   *
 718   * @since 4.6.0
 719   *
 720   * @param int $source_width  Width of the first image in pixels.
 721   * @param int $source_height Height of the first image in pixels.
 722   * @param int $target_width  Width of the second image in pixels.
 723   * @param int $target_height Height of the second image in pixels.
 724   * @return bool True if aspect ratios match within 1px. False if not.
 725   */
 726  function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
 727      /*
 728       * To test for varying crops, we constrain the dimensions of the larger image
 729       * to the dimensions of the smaller image and see if they match.
 730       */
 731      if ( $source_width > $target_width ) {
 732          $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
 733          $expected_size    = array( $target_width, $target_height );
 734      } else {
 735          $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
 736          $expected_size    = array( $source_width, $source_height );
 737      }
 738  
 739      // If the image dimensions are within 1px of the expected size, we consider it a match.
 740      $matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
 741  
 742      return $matched;
 743  }
 744  
 745  /**
 746   * Retrieves the image's intermediate size (resized) path, width, and height.
 747   *
 748   * The $size parameter can be an array with the width and height respectively.
 749   * If the size matches the 'sizes' metadata array for width and height, then it
 750   * will be used. If there is no direct match, then the nearest image size larger
 751   * than the specified size will be used. If nothing is found, then the function
 752   * will break out and return false.
 753   *
 754   * The metadata 'sizes' is used for compatible sizes that can be used for the
 755   * parameter $size value.
 756   *
 757   * The url path will be given, when the $size parameter is a string.
 758   *
 759   * If you are passing an array for the $size, you should consider using
 760   * add_image_size() so that a cropped version is generated. It's much more
 761   * efficient than having to find the closest-sized image and then having the
 762   * browser scale down the image.
 763   *
 764   * @since 2.5.0
 765   *
 766   * @param int          $post_id Attachment ID.
 767   * @param string|int[] $size    Optional. Image size. Accepts any registered image size name, or an array
 768   *                              of width and height values in pixels (in that order). Default 'thumbnail'.
 769   * @return array|false {
 770   *     Array of file relative path, width, and height on success. Additionally includes absolute
 771   *     path and URL if registered size is passed to `$size` parameter. False on failure.
 772   *
 773   *     @type string $file   Filename of image.
 774   *     @type int    $width  Width of image in pixels.
 775   *     @type int    $height Height of image in pixels.
 776   *     @type string $path   Path of image relative to uploads directory.
 777   *     @type string $url    URL of image.
 778   * }
 779   */
 780  function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
 781      $imagedata = wp_get_attachment_metadata( $post_id );
 782  
 783      if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
 784          return false;
 785      }
 786  
 787      $data = array();
 788  
 789      // Find the best match when '$size' is an array.
 790      if ( is_array( $size ) ) {
 791          $candidates = array();
 792  
 793          if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
 794              $imagedata['height'] = $imagedata['sizes']['full']['height'];
 795              $imagedata['width']  = $imagedata['sizes']['full']['width'];
 796          }
 797  
 798          foreach ( $imagedata['sizes'] as $_size => $data ) {
 799              // If there's an exact match to an existing image size, short circuit.
 800              if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) {
 801                  $candidates[ $data['width'] * $data['height'] ] = $data;
 802                  break;
 803              }
 804  
 805              // If it's not an exact match, consider larger sizes with the same aspect ratio.
 806              if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
 807                  // If '0' is passed to either size, we test ratios against the original file.
 808                  if ( 0 === $size[0] || 0 === $size[1] ) {
 809                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
 810                  } else {
 811                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
 812                  }
 813  
 814                  if ( $same_ratio ) {
 815                      $candidates[ $data['width'] * $data['height'] ] = $data;
 816                  }
 817              }
 818          }
 819  
 820          if ( ! empty( $candidates ) ) {
 821              // Sort the array by size if we have more than one candidate.
 822              if ( 1 < count( $candidates ) ) {
 823                  ksort( $candidates );
 824              }
 825  
 826              $data = array_shift( $candidates );
 827              /*
 828              * When the size requested is smaller than the thumbnail dimensions, we
 829              * fall back to the thumbnail size to maintain backward compatibility with
 830              * pre 4.6 versions of WordPress.
 831              */
 832          } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
 833              $data = $imagedata['sizes']['thumbnail'];
 834          } else {
 835              return false;
 836          }
 837  
 838          // Constrain the width and height attributes to the requested values.
 839          list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
 840  
 841      } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
 842          $data = $imagedata['sizes'][ $size ];
 843      }
 844  
 845      // If we still don't have a match at this point, return false.
 846      if ( empty( $data ) ) {
 847          return false;
 848      }
 849  
 850      // Include the full filesystem path of the intermediate file.
 851      if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
 852          $file_url     = wp_get_attachment_url( $post_id );
 853          $data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
 854          $data['url']  = path_join( dirname( $file_url ), $data['file'] );
 855      }
 856  
 857      /**
 858       * Filters the output of image_get_intermediate_size()
 859       *
 860       * @since 4.4.0
 861       *
 862       * @see image_get_intermediate_size()
 863       *
 864       * @param array        $data    Array of file relative path, width, and height on success. May also include
 865       *                              file absolute path and URL.
 866       * @param int          $post_id The ID of the image attachment.
 867       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
 868       *                              an array of width and height values in pixels (in that order).
 869       */
 870      return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
 871  }
 872  
 873  /**
 874   * Gets the available intermediate image size names.
 875   *
 876   * @since 3.0.0
 877   *
 878   * @return string[] An array of image size names.
 879   */
 880  function get_intermediate_image_sizes() {
 881      $default_sizes    = array( 'thumbnail', 'medium', 'medium_large', 'large' );
 882      $additional_sizes = wp_get_additional_image_sizes();
 883  
 884      if ( ! empty( $additional_sizes ) ) {
 885          $default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) );
 886      }
 887  
 888      /**
 889       * Filters the list of intermediate image sizes.
 890       *
 891       * @since 2.5.0
 892       *
 893       * @param string[] $default_sizes An array of intermediate image size names. Defaults
 894       *                                are 'thumbnail', 'medium', 'medium_large', 'large'.
 895       */
 896      return apply_filters( 'intermediate_image_sizes', $default_sizes );
 897  }
 898  
 899  /**
 900   * Returns a normalized list of all currently registered image sub-sizes.
 901   *
 902   * @since 5.3.0
 903   * @uses wp_get_additional_image_sizes()
 904   * @uses get_intermediate_image_sizes()
 905   *
 906   * @return array[] Associative array of arrays of image sub-size information,
 907   *                 keyed by image size name.
 908   */
 909  function wp_get_registered_image_subsizes() {
 910      $additional_sizes = wp_get_additional_image_sizes();
 911      $all_sizes        = array();
 912  
 913      foreach ( get_intermediate_image_sizes() as $size_name ) {
 914          $size_data = array(
 915              'width'  => 0,
 916              'height' => 0,
 917              'crop'   => false,
 918          );
 919  
 920          if ( isset( $additional_sizes[ $size_name ]['width'] ) ) {
 921              // For sizes added by plugins and themes.
 922              $size_data['width'] = (int) $additional_sizes[ $size_name ]['width'];
 923          } else {
 924              // For default sizes set in options.
 925              $size_data['width'] = (int) get_option( "{$size_name}_size_w" );
 926          }
 927  
 928          if ( isset( $additional_sizes[ $size_name ]['height'] ) ) {
 929              $size_data['height'] = (int) $additional_sizes[ $size_name ]['height'];
 930          } else {
 931              $size_data['height'] = (int) get_option( "{$size_name}_size_h" );
 932          }
 933  
 934          if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) {
 935              // This size isn't set.
 936              continue;
 937          }
 938  
 939          if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
 940              $size_data['crop'] = $additional_sizes[ $size_name ]['crop'];
 941          } else {
 942              $size_data['crop'] = get_option( "{$size_name}_crop" );
 943          }
 944  
 945          if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) {
 946              $size_data['crop'] = (bool) $size_data['crop'];
 947          }
 948  
 949          $all_sizes[ $size_name ] = $size_data;
 950      }
 951  
 952      return $all_sizes;
 953  }
 954  
 955  /**
 956   * Retrieves an image to represent an attachment.
 957   *
 958   * @since 2.5.0
 959   *
 960   * @param int          $attachment_id Image attachment ID.
 961   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
 962   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
 963   * @param bool         $icon          Optional. Whether the image should fall back to a mime type icon. Default false.
 964   * @return array|false {
 965   *     Array of image data, or boolean false if no image is available.
 966   *
 967   *     @type string $0 Image source URL.
 968   *     @type int    $1 Image width in pixels.
 969   *     @type int    $2 Image height in pixels.
 970   *     @type bool   $3 Whether the image is a resized image.
 971   * }
 972   */
 973  function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
 974      // Get a thumbnail or intermediate image if there is one.
 975      $image = image_downsize( $attachment_id, $size );
 976      if ( ! $image ) {
 977          $src = false;
 978  
 979          if ( $icon ) {
 980              $src = wp_mime_type_icon( $attachment_id, '.svg' );
 981  
 982              if ( $src ) {
 983                  /** This filter is documented in wp-includes/post.php */
 984                  $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
 985  
 986                  $src_file = $icon_dir . '/' . wp_basename( $src );
 987  
 988                  list( $width, $height ) = wp_getimagesize( $src_file );
 989  
 990                  $ext = strtolower( substr( $src_file, -4 ) );
 991  
 992                  if ( '.svg' === $ext ) {
 993                      // SVG does not have true dimensions, so this assigns width and height directly.
 994                      $width  = 48;
 995                      $height = 64;
 996                  } else {
 997                      list( $width, $height ) = wp_getimagesize( $src_file );
 998                  }
 999              }
1000          }
1001  
1002          if ( $src && $width && $height ) {
1003              $image = array( $src, $width, $height, false );
1004          }
1005      }
1006      /**
1007       * Filters the attachment image source result.
1008       *
1009       * @since 4.3.0
1010       *
1011       * @param array|false  $image         {
1012       *     Array of image data, or boolean false if no image is available.
1013       *
1014       *     @type string $0 Image source URL.
1015       *     @type int    $1 Image width in pixels.
1016       *     @type int    $2 Image height in pixels.
1017       *     @type bool   $3 Whether the image is a resized image.
1018       * }
1019       * @param int          $attachment_id Image attachment ID.
1020       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1021       *                                    an array of width and height values in pixels (in that order).
1022       * @param bool         $icon          Whether the image should be treated as an icon.
1023       */
1024      return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
1025  }
1026  
1027  /**
1028   * Gets an HTML img element representing an image attachment.
1029   *
1030   * While `$size` will accept an array, it is better to register a size with
1031   * add_image_size() so that a cropped version is generated. It's much more
1032   * efficient than having to find the closest-sized image and then having the
1033   * browser scale down the image.
1034   *
1035   * @since 2.5.0
1036   * @since 4.4.0 The `$srcset` and `$sizes` attributes were added.
1037   * @since 5.5.0 The `$loading` attribute was added.
1038   * @since 6.1.0 The `$decoding` attribute was added.
1039   *
1040   * @param int          $attachment_id Image attachment ID.
1041   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array
1042   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
1043   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1044   * @param string|array $attr {
1045   *     Optional. Attributes for the image markup.
1046   *
1047   *     @type string       $src           Image attachment URL.
1048   *     @type string       $class         CSS class name or space-separated list of classes.
1049   *                                       Default `attachment-$size_class size-$size_class`,
1050   *                                       where `$size_class` is the image size being requested.
1051   *     @type string       $alt           Image description for the alt attribute.
1052   *     @type string       $srcset        The 'srcset' attribute value.
1053   *     @type string       $sizes         The 'sizes' attribute value.
1054   *     @type string|false $loading       The 'loading' attribute value. Passing a value of false
1055   *                                       will result in the attribute being omitted for the image.
1056   *                                       Default determined by {@see wp_get_loading_optimization_attributes()}.
1057   *     @type string       $decoding      The 'decoding' attribute value. Possible values are
1058   *                                       'async' (default), 'sync', or 'auto'. Passing false or an empty
1059   *                                       string will result in the attribute being omitted.
1060   *     @type string       $fetchpriority The 'fetchpriority' attribute value, whether `high`, `low`, or `auto`.
1061   *                                       Default determined by {@see wp_get_loading_optimization_attributes()}.
1062   * }
1063   * @return string HTML img element or empty string on failure.
1064   */
1065  function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
1066      $html  = '';
1067      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1068  
1069      if ( $image ) {
1070          list( $src, $width, $height ) = $image;
1071  
1072          $attachment = get_post( $attachment_id );
1073          $hwstring   = image_hwstring( $width, $height );
1074          $size_class = $size;
1075  
1076          if ( is_array( $size_class ) ) {
1077              $size_class = implode( 'x', $size_class );
1078          }
1079  
1080          $default_attr = array(
1081              'src'   => $src,
1082              'class' => "attachment-$size_class size-$size_class",
1083              'alt'   => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
1084          );
1085  
1086          /**
1087           * Filters the context in which wp_get_attachment_image() is used.
1088           *
1089           * @since 6.3.0
1090           *
1091           * @param string $context The context. Default 'wp_get_attachment_image'.
1092           */
1093          $context = apply_filters( 'wp_get_attachment_image_context', 'wp_get_attachment_image' );
1094          $attr    = wp_parse_args( $attr, $default_attr );
1095  
1096          $loading_attr              = $attr;
1097          $loading_attr['width']     = $width;
1098          $loading_attr['height']    = $height;
1099          $loading_optimization_attr = wp_get_loading_optimization_attributes(
1100              'img',
1101              $loading_attr,
1102              $context
1103          );
1104  
1105          // Add loading optimization attributes if not available.
1106          $attr = array_merge( $attr, $loading_optimization_attr );
1107  
1108          // Omit the `decoding` attribute if the value is invalid according to the spec.
1109          if ( empty( $attr['decoding'] ) || ! in_array( $attr['decoding'], array( 'async', 'sync', 'auto' ), true ) ) {
1110              unset( $attr['decoding'] );
1111          }
1112  
1113          /*
1114           * If the default value of `lazy` for the `loading` attribute is overridden
1115           * to omit the attribute for this image, ensure it is not included.
1116           */
1117          if ( isset( $attr['loading'] ) && ! $attr['loading'] ) {
1118              unset( $attr['loading'] );
1119          }
1120  
1121          // If the `fetchpriority` attribute is overridden and set to false or an empty string.
1122          if ( isset( $attr['fetchpriority'] ) && ! $attr['fetchpriority'] ) {
1123              unset( $attr['fetchpriority'] );
1124          }
1125  
1126          // Generate 'srcset' and 'sizes' if not already present.
1127          if ( empty( $attr['srcset'] ) ) {
1128              $image_meta = wp_get_attachment_metadata( $attachment_id );
1129  
1130              if ( is_array( $image_meta ) ) {
1131                  $size_array = array( absint( $width ), absint( $height ) );
1132                  $srcset     = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
1133                  $sizes      = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
1134  
1135                  if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
1136                      $attr['srcset'] = $srcset;
1137  
1138                      if ( empty( $attr['sizes'] ) ) {
1139                          $attr['sizes'] = $sizes;
1140                      }
1141                  }
1142              }
1143          }
1144  
1145          /** This filter is documented in wp-includes/media.php */
1146          $add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true );
1147  
1148          // Adds 'auto' to the sizes attribute if applicable.
1149          if (
1150              $add_auto_sizes &&
1151              isset( $attr['loading'] ) &&
1152              'lazy' === $attr['loading'] &&
1153              isset( $attr['sizes'] ) &&
1154              ! wp_sizes_attribute_includes_valid_auto( $attr['sizes'] )
1155          ) {
1156              $attr['sizes'] = 'auto, ' . $attr['sizes'];
1157          }
1158  
1159          /**
1160           * Filters the list of attachment image attributes.
1161           *
1162           * @since 2.8.0
1163           *
1164           * @param string[]     $attr       Array of attribute values for the image markup, keyed by attribute name.
1165           *                                 See wp_get_attachment_image().
1166           * @param WP_Post      $attachment Image attachment post.
1167           * @param string|int[] $size       Requested image size. Can be any registered image size name, or
1168           *                                 an array of width and height values in pixels (in that order).
1169           */
1170          $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
1171  
1172          $attr = array_map( 'esc_attr', $attr );
1173          $html = rtrim( "<img $hwstring" );
1174  
1175          foreach ( $attr as $name => $value ) {
1176              $html .= " $name=" . '"' . $value . '"';
1177          }
1178  
1179          $html .= ' />';
1180      }
1181  
1182      /**
1183       * Filters the HTML img element representing an image attachment.
1184       *
1185       * @since 5.6.0
1186       *
1187       * @param string       $html          HTML img element or empty string on failure.
1188       * @param int          $attachment_id Image attachment ID.
1189       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1190       *                                    an array of width and height values in pixels (in that order).
1191       * @param bool         $icon          Whether the image should be treated as an icon.
1192       * @param string[]     $attr          Array of attribute values for the image markup, keyed by attribute name.
1193       *                                    See wp_get_attachment_image().
1194       */
1195      return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
1196  }
1197  
1198  /**
1199   * Gets the URL of an image attachment.
1200   *
1201   * @since 4.4.0
1202   *
1203   * @param int          $attachment_id Image attachment ID.
1204   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1205   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
1206   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1207   * @return string|false Attachment URL or false if no image is available. If `$size` does not match
1208   *                      any registered image size, the original image URL will be returned.
1209   */
1210  function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
1211      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1212      return isset( $image[0] ) ? $image[0] : false;
1213  }
1214  
1215  /**
1216   * Gets the attachment path relative to the upload directory.
1217   *
1218   * @since 4.4.1
1219   * @access private
1220   *
1221   * @param string $file Attachment file name.
1222   * @return string Attachment path relative to the upload directory.
1223   */
1224  function _wp_get_attachment_relative_path( $file ) {
1225      $dirname = dirname( $file );
1226  
1227      if ( '.' === $dirname ) {
1228          return '';
1229      }
1230  
1231      if ( str_contains( $dirname, 'wp-content/uploads' ) ) {
1232          // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
1233          $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
1234          $dirname = ltrim( $dirname, '/' );
1235      }
1236  
1237      return $dirname;
1238  }
1239  
1240  /**
1241   * Gets the image size as array from its meta data.
1242   *
1243   * Used for responsive images.
1244   *
1245   * @since 4.4.0
1246   * @access private
1247   *
1248   * @param string $size_name  Image size. Accepts any registered image size name.
1249   * @param array  $image_meta The image meta data.
1250   * @return array|false {
1251   *     Array of width and height or false if the size isn't present in the meta data.
1252   *
1253   *     @type int $0 Image width.
1254   *     @type int $1 Image height.
1255   * }
1256   */
1257  function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
1258      if ( 'full' === $size_name ) {
1259          return array(
1260              absint( $image_meta['width'] ),
1261              absint( $image_meta['height'] ),
1262          );
1263      } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) {
1264          return array(
1265              absint( $image_meta['sizes'][ $size_name ]['width'] ),
1266              absint( $image_meta['sizes'][ $size_name ]['height'] ),
1267          );
1268      }
1269  
1270      return false;
1271  }
1272  
1273  /**
1274   * Retrieves the value for an image attachment's 'srcset' attribute.
1275   *
1276   * @since 4.4.0
1277   *
1278   * @see wp_calculate_image_srcset()
1279   *
1280   * @param int          $attachment_id Image attachment ID.
1281   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1282   *                                    width and height values in pixels (in that order). Default 'medium'.
1283   * @param array|null   $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1284   *                                    Default null.
1285   * @return string|false A 'srcset' value string or false.
1286   */
1287  function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
1288      $image = wp_get_attachment_image_src( $attachment_id, $size );
1289  
1290      if ( ! $image ) {
1291          return false;
1292      }
1293  
1294      if ( ! is_array( $image_meta ) ) {
1295          $image_meta = wp_get_attachment_metadata( $attachment_id );
1296      }
1297  
1298      $image_src  = $image[0];
1299      $size_array = array(
1300          absint( $image[1] ),
1301          absint( $image[2] ),
1302      );
1303  
1304      return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1305  }
1306  
1307  /**
1308   * A helper function to calculate the image sources to include in a 'srcset' attribute.
1309   *
1310   * @since 4.4.0
1311   *
1312   * @param int[]  $size_array    {
1313   *     An array of width and height values.
1314   *
1315   *     @type int $0 The width in pixels.
1316   *     @type int $1 The height in pixels.
1317   * }
1318   * @param string $image_src     The 'src' of the image.
1319   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1320   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1321   * @return string|false The 'srcset' attribute value. False on error or when only one source exists.
1322   */
1323  function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1324      /**
1325       * Pre-filters the image meta to be able to fix inconsistencies in the stored data.
1326       *
1327       * @since 4.5.0
1328       *
1329       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1330       * @param int[]  $size_array    {
1331       *     An array of requested width and height values.
1332       *
1333       *     @type int $0 The width in pixels.
1334       *     @type int $1 The height in pixels.
1335       * }
1336       * @param string $image_src     The 'src' of the image.
1337       * @param int    $attachment_id The image attachment ID or 0 if not supplied.
1338       */
1339      $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1340  
1341      if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
1342          return false;
1343      }
1344  
1345      $image_sizes = $image_meta['sizes'];
1346  
1347      // Get the width and height of the image.
1348      $image_width  = (int) $size_array[0];
1349      $image_height = (int) $size_array[1];
1350  
1351      // Bail early if error/no width.
1352      if ( $image_width < 1 ) {
1353          return false;
1354      }
1355  
1356      $image_basename = wp_basename( $image_meta['file'] );
1357  
1358      /*
1359       * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1360       * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1361       * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1362       */
1363      if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1364          $image_sizes[] = array(
1365              'width'  => $image_meta['width'],
1366              'height' => $image_meta['height'],
1367              'file'   => $image_basename,
1368          );
1369      } elseif ( str_contains( $image_src, $image_meta['file'] ) ) {
1370          return false;
1371      }
1372  
1373      // Retrieve the uploads sub-directory from the full size image.
1374      $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1375  
1376      if ( $dirname ) {
1377          $dirname = trailingslashit( $dirname );
1378      }
1379  
1380      $upload_dir    = wp_get_upload_dir();
1381      $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1382  
1383      /*
1384       * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1385       * (which is to say, when they share the domain name of the current request).
1386       */
1387      if ( is_ssl() && ! str_starts_with( $image_baseurl, 'https' ) ) {
1388          /*
1389           * Since the `Host:` header might contain a port, it should
1390           * be compared against the image URL using the same port.
1391           */
1392          $parsed = parse_url( $image_baseurl );
1393          $domain = isset( $parsed['host'] ) ? $parsed['host'] : '';
1394  
1395          if ( isset( $parsed['port'] ) ) {
1396              $domain .= ':' . $parsed['port'];
1397          }
1398  
1399          if ( $_SERVER['HTTP_HOST'] === $domain ) {
1400              $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1401          }
1402      }
1403  
1404      /*
1405       * Images that have been edited in WordPress after being uploaded will
1406       * contain a unique hash. Look for that hash and use it later to filter
1407       * out images that are leftovers from previous versions.
1408       */
1409      $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1410  
1411      /**
1412       * Filters the maximum image width to be included in a 'srcset' attribute.
1413       *
1414       * @since 4.4.0
1415       *
1416       * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '2048'.
1417       * @param int[] $size_array {
1418       *     An array of requested width and height values.
1419       *
1420       *     @type int $0 The width in pixels.
1421       *     @type int $1 The height in pixels.
1422       * }
1423       */
1424      $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
1425  
1426      // Array to hold URL candidates.
1427      $sources = array();
1428  
1429      /**
1430       * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1431       * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1432       * an incorrect image. See #35045.
1433       */
1434      $src_matched = false;
1435  
1436      /*
1437       * Loop through available images. Only use images that are resized
1438       * versions of the same edit.
1439       */
1440      foreach ( $image_sizes as $image ) {
1441          $is_src = false;
1442  
1443          // Check if image meta isn't corrupted.
1444          if ( ! is_array( $image ) ) {
1445              continue;
1446          }
1447  
1448          // If the file name is part of the `src`, we've confirmed a match.
1449          if ( ! $src_matched && str_contains( $image_src, $dirname . $image['file'] ) ) {
1450              $src_matched = true;
1451              $is_src      = true;
1452          }
1453  
1454          // Filter out images that are from previous edits.
1455          if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1456              continue;
1457          }
1458  
1459          /*
1460           * Filters out images that are wider than '$max_srcset_image_width' unless
1461           * that file is in the 'src' attribute.
1462           */
1463          if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1464              continue;
1465          }
1466  
1467          // If the image dimensions are within 1px of the expected size, use it.
1468          if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
1469              // Add the URL, descriptor, and value to the sources array to be returned.
1470              $source = array(
1471                  'url'        => $image_baseurl . $image['file'],
1472                  'descriptor' => 'w',
1473                  'value'      => $image['width'],
1474              );
1475  
1476              // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1477              if ( $is_src ) {
1478                  $sources = array( $image['width'] => $source ) + $sources;
1479              } else {
1480                  $sources[ $image['width'] ] = $source;
1481              }
1482          }
1483      }
1484  
1485      /**
1486       * Filters an image's 'srcset' sources.
1487       *
1488       * @since 4.4.0
1489       *
1490       * @param array  $sources {
1491       *     One or more arrays of source data to include in the 'srcset'.
1492       *
1493       *     @type array $width {
1494       *         @type string $url        The URL of an image source.
1495       *         @type string $descriptor The descriptor type used in the image candidate string,
1496       *                                  either 'w' or 'x'.
1497       *         @type int    $value      The source width if paired with a 'w' descriptor, or a
1498       *                                  pixel density value if paired with an 'x' descriptor.
1499       *     }
1500       * }
1501       * @param array $size_array     {
1502       *     An array of requested width and height values.
1503       *
1504       *     @type int $0 The width in pixels.
1505       *     @type int $1 The height in pixels.
1506       * }
1507       * @param string $image_src     The 'src' of the image.
1508       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1509       * @param int    $attachment_id Image attachment ID or 0.
1510       */
1511      $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1512  
1513      // Only return a 'srcset' value if there is more than one source.
1514      if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) {
1515          return false;
1516      }
1517  
1518      $srcset = '';
1519  
1520      foreach ( $sources as $source ) {
1521          $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
1522      }
1523  
1524      return rtrim( $srcset, ', ' );
1525  }
1526  
1527  /**
1528   * Retrieves the value for an image attachment's 'sizes' attribute.
1529   *
1530   * @since 4.4.0
1531   *
1532   * @see wp_calculate_image_sizes()
1533   *
1534   * @param int          $attachment_id Image attachment ID.
1535   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1536   *                                    width and height values in pixels (in that order). Default 'medium'.
1537   * @param array|null   $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1538   *                                    Default null.
1539   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1540   */
1541  function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1542      $image = wp_get_attachment_image_src( $attachment_id, $size );
1543  
1544      if ( ! $image ) {
1545          return false;
1546      }
1547  
1548      if ( ! is_array( $image_meta ) ) {
1549          $image_meta = wp_get_attachment_metadata( $attachment_id );
1550      }
1551  
1552      $image_src  = $image[0];
1553      $size_array = array(
1554          absint( $image[1] ),
1555          absint( $image[2] ),
1556      );
1557  
1558      return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1559  }
1560  
1561  /**
1562   * Creates a 'sizes' attribute value for an image.
1563   *
1564   * @since 4.4.0
1565   *
1566   * @param string|int[] $size          Image size. Accepts any registered image size name, or an array of
1567   *                                    width and height values in pixels (in that order).
1568   * @param string|null  $image_src     Optional. The URL to the image file. Default null.
1569   * @param array|null   $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1570   *                                    Default null.
1571   * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1572   *                                    is needed when using the image size name as argument for `$size`. Default 0.
1573   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1574   */
1575  function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1576      $width = 0;
1577  
1578      if ( is_array( $size ) ) {
1579          $width = absint( $size[0] );
1580      } elseif ( is_string( $size ) ) {
1581          if ( ! $image_meta && $attachment_id ) {
1582              $image_meta = wp_get_attachment_metadata( $attachment_id );
1583          }
1584  
1585          if ( is_array( $image_meta ) ) {
1586              $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1587              if ( $size_array ) {
1588                  $width = absint( $size_array[0] );
1589              }
1590          }
1591      }
1592  
1593      if ( ! $width ) {
1594          return false;
1595      }
1596  
1597      // Setup the default 'sizes' attribute.
1598      $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1599  
1600      /**
1601       * Filters the output of 'wp_calculate_image_sizes()'.
1602       *
1603       * @since 4.4.0
1604       *
1605       * @param string       $sizes         A source size value for use in a 'sizes' attribute.
1606       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1607       *                                    an array of width and height values in pixels (in that order).
1608       * @param string|null  $image_src     The URL to the image file or null.
1609       * @param array|null   $image_meta    The image meta data as returned by wp_get_attachment_metadata() or null.
1610       * @param int          $attachment_id Image attachment ID of the original image or 0.
1611       */
1612      return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1613  }
1614  
1615  /**
1616   * Determines if the image meta data is for the image source file.
1617   *
1618   * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change.
1619   * For example when the website is exported and imported at another website. Then the
1620   * attachment post IDs that are in post_content for the exported website may not match
1621   * the same attachments at the new website.
1622   *
1623   * @since 5.5.0
1624   *
1625   * @param string $image_location The full path or URI to the image file.
1626   * @param array  $image_meta     The attachment meta data as returned by 'wp_get_attachment_metadata()'.
1627   * @param int    $attachment_id  Optional. The image attachment ID. Default 0.
1628   * @return bool Whether the image meta is for this image file.
1629   */
1630  function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) {
1631      $match = false;
1632  
1633      // Ensure the $image_meta is valid.
1634      if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) {
1635          // Remove query args in image URI.
1636          list( $image_location ) = explode( '?', $image_location );
1637  
1638          // Check if the relative image path from the image meta is at the end of $image_location.
1639          if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) {
1640              $match = true;
1641          } else {
1642              // Retrieve the uploads sub-directory from the full size image.
1643              $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1644  
1645              if ( $dirname ) {
1646                  $dirname = trailingslashit( $dirname );
1647              }
1648  
1649              if ( ! empty( $image_meta['original_image'] ) ) {
1650                  $relative_path = $dirname . $image_meta['original_image'];
1651  
1652                  if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1653                      $match = true;
1654                  }
1655              }
1656  
1657              if ( ! $match && ! empty( $image_meta['sizes'] ) ) {
1658                  foreach ( $image_meta['sizes'] as $image_size_data ) {
1659                      $relative_path = $dirname . $image_size_data['file'];
1660  
1661                      if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1662                          $match = true;
1663                          break;
1664                      }
1665                  }
1666              }
1667          }
1668      }
1669  
1670      /**
1671       * Filters whether an image path or URI matches image meta.
1672       *
1673       * @since 5.5.0
1674       *
1675       * @param bool   $match          Whether the image relative path from the image meta
1676       *                               matches the end of the URI or path to the image file.
1677       * @param string $image_location Full path or URI to the tested image file.
1678       * @param array  $image_meta     The image meta data as returned by 'wp_get_attachment_metadata()'.
1679       * @param int    $attachment_id  The image attachment ID or 0 if not supplied.
1680       */
1681      return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id );
1682  }
1683  
1684  /**
1685   * Determines an image's width and height dimensions based on the source file.
1686   *
1687   * @since 5.5.0
1688   *
1689   * @param string $image_src     The image source file.
1690   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1691   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1692   * @return array|false Array with first element being the width and second element being the height,
1693   *                     or false if dimensions cannot be determined.
1694   */
1695  function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) {
1696      $dimensions = false;
1697  
1698      // Is it a full size image?
1699      if (
1700          isset( $image_meta['file'] ) &&
1701          str_contains( $image_src, wp_basename( $image_meta['file'] ) )
1702      ) {
1703          $dimensions = array(
1704              (int) $image_meta['width'],
1705              (int) $image_meta['height'],
1706          );
1707      }
1708  
1709      if ( ! $dimensions && ! empty( $image_meta['sizes'] ) ) {
1710          $src_filename = wp_basename( $image_src );
1711  
1712          foreach ( $image_meta['sizes'] as $image_size_data ) {
1713              if ( $src_filename === $image_size_data['file'] ) {
1714                  $dimensions = array(
1715                      (int) $image_size_data['width'],
1716                      (int) $image_size_data['height'],
1717                  );
1718  
1719                  break;
1720              }
1721          }
1722      }
1723  
1724      /**
1725       * Filters the 'wp_image_src_get_dimensions' value.
1726       *
1727       * @since 5.7.0
1728       *
1729       * @param array|false $dimensions    Array with first element being the width
1730       *                                   and second element being the height, or
1731       *                                   false if dimensions could not be determined.
1732       * @param string      $image_src     The image source file.
1733       * @param array       $image_meta    The image meta data as returned by
1734       *                                   'wp_get_attachment_metadata()'.
1735       * @param int         $attachment_id The image attachment ID. Default 0.
1736       */
1737      return apply_filters( 'wp_image_src_get_dimensions', $dimensions, $image_src, $image_meta, $attachment_id );
1738  }
1739  
1740  /**
1741   * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1742   *
1743   * @since 4.4.0
1744   *
1745   * @see wp_calculate_image_srcset()
1746   * @see wp_calculate_image_sizes()
1747   *
1748   * @param string $image         An HTML 'img' element to be filtered.
1749   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1750   * @param int    $attachment_id Image attachment ID.
1751   * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1752   */
1753  function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1754      // Ensure the image meta exists.
1755      if ( empty( $image_meta['sizes'] ) ) {
1756          return $image;
1757      }
1758  
1759      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1760      list( $image_src ) = explode( '?', $image_src );
1761  
1762      // Return early if we couldn't get the image source.
1763      if ( ! $image_src ) {
1764          return $image;
1765      }
1766  
1767      // Bail early if an image has been inserted and later edited.
1768      if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash )
1769          && ! str_contains( wp_basename( $image_src ), $img_edit_hash[0] )
1770      ) {
1771          return $image;
1772      }
1773  
1774      $width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1775      $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1776  
1777      if ( $width && $height ) {
1778          $size_array = array( $width, $height );
1779      } else {
1780          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
1781          if ( ! $size_array ) {
1782              return $image;
1783          }
1784      }
1785  
1786      $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1787  
1788      if ( $srcset ) {
1789          // Check if there is already a 'sizes' attribute.
1790          $sizes = strpos( $image, ' sizes=' );
1791  
1792          if ( ! $sizes ) {
1793              $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1794          }
1795      }
1796  
1797      if ( $srcset && $sizes ) {
1798          // Format the 'srcset' and 'sizes' string and escape attributes.
1799          $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1800  
1801          if ( is_string( $sizes ) ) {
1802              $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1803          }
1804  
1805          // Add the srcset and sizes attributes to the image markup.
1806          return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1807      }
1808  
1809      return $image;
1810  }
1811  
1812  /**
1813   * Determines whether to add the `loading` attribute to the specified tag in the specified context.
1814   *
1815   * @since 5.5.0
1816   * @since 5.7.0 Now returns `true` by default for `iframe` tags.
1817   *
1818   * @param string $tag_name The tag name.
1819   * @param string $context  Additional context, like the current filter name
1820   *                         or the function name from where this was called.
1821   * @return bool Whether to add the attribute.
1822   */
1823  function wp_lazy_loading_enabled( $tag_name, $context ) {
1824      /*
1825       * By default add to all 'img' and 'iframe' tags.
1826       * See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
1827       * See https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-loading
1828       */
1829      $default = ( 'img' === $tag_name || 'iframe' === $tag_name );
1830  
1831      /**
1832       * Filters whether to add the `loading` attribute to the specified tag in the specified context.
1833       *
1834       * @since 5.5.0
1835       *
1836       * @param bool   $default  Default value.
1837       * @param string $tag_name The tag name.
1838       * @param string $context  Additional context, like the current filter name
1839       *                         or the function name from where this was called.
1840       */
1841      return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
1842  }
1843  
1844  /**
1845   * Filters specific tags in post content and modifies their markup.
1846   *
1847   * Modifies HTML tags in post content to include new browser and HTML technologies
1848   * that may not have existed at the time of post creation. These modifications currently
1849   * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags, as well
1850   * as adding `loading` attributes to `iframe` HTML tags.
1851   * Future similar optimizations should be added/expected here.
1852   *
1853   * @since 5.5.0
1854   * @since 5.7.0 Now supports adding `loading` attributes to `iframe` tags.
1855   *
1856   * @see wp_img_tag_add_width_and_height_attr()
1857   * @see wp_img_tag_add_srcset_and_sizes_attr()
1858   * @see wp_img_tag_add_loading_optimization_attrs()
1859   * @see wp_iframe_tag_add_loading_attr()
1860   *
1861   * @param string $content The HTML content to be filtered.
1862   * @param string $context Optional. Additional context to pass to the filters.
1863   *                        Defaults to `current_filter()` when not set.
1864   * @return string Converted content with images modified.
1865   */
1866  function wp_filter_content_tags( $content, $context = null ) {
1867      if ( null === $context ) {
1868          $context = current_filter();
1869      }
1870  
1871      $add_iframe_loading_attr = wp_lazy_loading_enabled( 'iframe', $context );
1872  
1873      if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
1874          return $content;
1875      }
1876  
1877      // List of the unique `img` tags found in $content.
1878      $images = array();
1879  
1880      // List of the unique `iframe` tags found in $content.
1881      $iframes = array();
1882  
1883      foreach ( $matches as $match ) {
1884          list( $tag, $tag_name ) = $match;
1885  
1886          switch ( $tag_name ) {
1887              case 'img':
1888                  if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) {
1889                      $attachment_id = absint( $class_id[1] );
1890  
1891                      if ( $attachment_id ) {
1892                          /*
1893                           * If exactly the same image tag is used more than once, overwrite it.
1894                           * All identical tags will be replaced later with 'str_replace()'.
1895                           */
1896                          $images[ $tag ] = $attachment_id;
1897                          break;
1898                      }
1899                  }
1900                  $images[ $tag ] = 0;
1901                  break;
1902              case 'iframe':
1903                  $iframes[ $tag ] = 0;
1904                  break;
1905          }
1906      }
1907  
1908      // Reduce the array to unique attachment IDs.
1909      $attachment_ids = array_unique( array_filter( array_values( $images ) ) );
1910  
1911      if ( count( $attachment_ids ) > 1 ) {
1912          /*
1913           * Warm the object cache with post and meta information for all found
1914           * images to avoid making individual database calls.
1915           */
1916          _prime_post_caches( $attachment_ids, false, true );
1917      }
1918  
1919      // Iterate through the matches in order of occurrence as it is relevant for whether or not to lazy-load.
1920      foreach ( $matches as $match ) {
1921          // Filter an image match.
1922          if ( isset( $images[ $match[0] ] ) ) {
1923              $filtered_image = $match[0];
1924              $attachment_id  = $images[ $match[0] ];
1925  
1926              // Add 'width' and 'height' attributes if applicable.
1927              if ( $attachment_id > 0 && ! str_contains( $filtered_image, ' width=' ) && ! str_contains( $filtered_image, ' height=' ) ) {
1928                  $filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id );
1929              }
1930  
1931              // Add 'srcset' and 'sizes' attributes if applicable.
1932              if ( $attachment_id > 0 && ! str_contains( $filtered_image, ' srcset=' ) ) {
1933                  $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
1934              }
1935  
1936              // Add loading optimization attributes if applicable.
1937              $filtered_image = wp_img_tag_add_loading_optimization_attrs( $filtered_image, $context );
1938  
1939              // Adds 'auto' to the sizes attribute if applicable.
1940              $filtered_image = wp_img_tag_add_auto_sizes( $filtered_image );
1941  
1942              /**
1943               * Filters an img tag within the content for a given context.
1944               *
1945               * @since 6.0.0
1946               *
1947               * @param string $filtered_image Full img tag with attributes that will replace the source img tag.
1948               * @param string $context        Additional context, like the current filter name or the function name from where this was called.
1949               * @param int    $attachment_id  The image attachment ID. May be 0 in case the image is not an attachment.
1950               */
1951              $filtered_image = apply_filters( 'wp_content_img_tag', $filtered_image, $context, $attachment_id );
1952  
1953              if ( $filtered_image !== $match[0] ) {
1954                  $content = str_replace( $match[0], $filtered_image, $content );
1955              }
1956  
1957              /*
1958               * Unset image lookup to not run the same logic again unnecessarily if the same image tag is used more than
1959               * once in the same blob of content.
1960               */
1961              unset( $images[ $match[0] ] );
1962          }
1963  
1964          // Filter an iframe match.
1965          if ( isset( $iframes[ $match[0] ] ) ) {
1966              $filtered_iframe = $match[0];
1967  
1968              // Add 'loading' attribute if applicable.
1969              if ( $add_iframe_loading_attr && ! str_contains( $filtered_iframe, ' loading=' ) ) {
1970                  $filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, $context );
1971              }
1972  
1973              if ( $filtered_iframe !== $match[0] ) {
1974                  $content = str_replace( $match[0], $filtered_iframe, $content );
1975              }
1976  
1977              /*
1978               * Unset iframe lookup to not run the same logic again unnecessarily if the same iframe tag is used more
1979               * than once in the same blob of content.
1980               */
1981              unset( $iframes[ $match[0] ] );
1982          }
1983      }
1984  
1985      return $content;
1986  }
1987  
1988  /**
1989   * Adds 'auto' to the sizes attribute to the image, if the image is lazy loaded and does not already include it.
1990   *
1991   * @since 6.7.0
1992   *
1993   * @param string $image The image tag markup being filtered.
1994   * @return string The filtered image tag markup.
1995   */
1996  function wp_img_tag_add_auto_sizes( string $image ): string {
1997      /**
1998       * Filters whether auto-sizes for lazy loaded images is enabled.
1999       *
2000       * @since 6.7.1
2001       *
2002       * @param boolean $enabled Whether auto-sizes for lazy loaded images is enabled.
2003       */
2004      if ( ! apply_filters( 'wp_img_tag_add_auto_sizes', true ) ) {
2005          return $image;
2006      }
2007  
2008      $processor = new WP_HTML_Tag_Processor( $image );
2009  
2010      // Bail if there is no IMG tag.
2011      if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
2012          return $image;
2013      }
2014  
2015      // Bail early if the image is not lazy-loaded.
2016      $loading = $processor->get_attribute( 'loading' );
2017      if ( ! is_string( $loading ) || 'lazy' !== strtolower( trim( $loading, " \t\f\r\n" ) ) ) {
2018          return $image;
2019      }
2020  
2021      /*
2022       * Bail early if the image doesn't have a width attribute.
2023       * Per WordPress Core itself, lazy-loaded images should always have a width attribute.
2024       * However, it is possible that lazy-loading could be added by a plugin, where we don't have that guarantee.
2025       * As such, it still makes sense to ensure presence of a width attribute here in order to use `sizes=auto`.
2026       */
2027      $width = $processor->get_attribute( 'width' );
2028      if ( ! is_string( $width ) || '' === $width ) {
2029          return $image;
2030      }
2031  
2032      $sizes = $processor->get_attribute( 'sizes' );
2033  
2034      // Bail early if the image is not responsive.
2035      if ( ! is_string( $sizes ) ) {
2036          return $image;
2037      }
2038  
2039      // Don't add 'auto' to the sizes attribute if it already exists.
2040      if ( wp_sizes_attribute_includes_valid_auto( $sizes ) ) {
2041          return $image;
2042      }
2043  
2044      $processor->set_attribute( 'sizes', "auto, $sizes" );
2045      return $processor->get_updated_html();
2046  }
2047  
2048  /**
2049   * Checks whether the given 'sizes' attribute includes the 'auto' keyword as the first item in the list.
2050   *
2051   * Per the HTML spec, if present it must be the first entry.
2052   *
2053   * @since 6.7.0
2054   *
2055   * @param string $sizes_attr The 'sizes' attribute value.
2056   * @return bool True if the 'auto' keyword is present, false otherwise.
2057   */
2058  function wp_sizes_attribute_includes_valid_auto( string $sizes_attr ): bool {
2059      list( $first_size ) = explode( ',', $sizes_attr, 2 );
2060      return 'auto' === strtolower( trim( $first_size, " \t\f\r\n" ) );
2061  }
2062  
2063  /**
2064   * Prints a CSS rule to fix potential visual issues with images using `sizes=auto`.
2065   *
2066   * This rule overrides the similar rule in the default user agent stylesheet, to avoid images that use e.g.
2067   * `width: auto` or `width: fit-content` to appear smaller.
2068   *
2069   * @since 6.7.1
2070   * @see https://html.spec.whatwg.org/multipage/rendering.html#img-contain-size
2071   * @see https://core.trac.wordpress.org/ticket/62413
2072   */
2073  function wp_print_auto_sizes_contain_css_fix() {
2074      /** This filter is documented in wp-includes/media.php */
2075      $add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true );
2076      if ( ! $add_auto_sizes ) {
2077          return;
2078      }
2079  
2080      ?>
2081      <style>img:is([sizes="auto" i], [sizes^="auto," i]) { contain-intrinsic-size: 3000px 1500px }</style>
2082      <?php
2083  }
2084  
2085  /**
2086   * Adds optimization attributes to an `img` HTML tag.
2087   *
2088   * @since 6.3.0
2089   *
2090   * @param string $image   The HTML `img` tag where the attribute should be added.
2091   * @param string $context Additional context to pass to the filters.
2092   * @return string Converted `img` tag with optimization attributes added.
2093   */
2094  function wp_img_tag_add_loading_optimization_attrs( $image, $context ) {
2095      $src               = preg_match( '/ src=["\']?([^"\']*)/i', $image, $matche_src ) ? $matche_src[1] : null;
2096      $width             = preg_match( '/ width=["\']([0-9]+)["\']/', $image, $match_width ) ? (int) $match_width[1] : null;
2097      $height            = preg_match( '/ height=["\']([0-9]+)["\']/', $image, $match_height ) ? (int) $match_height[1] : null;
2098      $loading_val       = preg_match( '/ loading=["\']([A-Za-z]+)["\']/', $image, $match_loading ) ? $match_loading[1] : null;
2099      $fetchpriority_val = preg_match( '/ fetchpriority=["\']([A-Za-z]+)["\']/', $image, $match_fetchpriority ) ? $match_fetchpriority[1] : null;
2100      $decoding_val      = preg_match( '/ decoding=["\']([A-Za-z]+)["\']/', $image, $match_decoding ) ? $match_decoding[1] : null;
2101  
2102      /*
2103       * Get loading optimization attributes to use.
2104       * This must occur before the conditional check below so that even images
2105       * that are ineligible for being lazy-loaded are considered.
2106       */
2107      $optimization_attrs = wp_get_loading_optimization_attributes(
2108          'img',
2109          array(
2110              'src'           => $src,
2111              'width'         => $width,
2112              'height'        => $height,
2113              'loading'       => $loading_val,
2114              'fetchpriority' => $fetchpriority_val,
2115              'decoding'      => $decoding_val,
2116          ),
2117          $context
2118      );
2119  
2120      // Images should have source for the loading optimization attributes to be added.
2121      if ( ! str_contains( $image, ' src="' ) ) {
2122          return $image;
2123      }
2124  
2125      if ( empty( $decoding_val ) ) {
2126          /**
2127           * Filters the `decoding` attribute value to add to an image. Default `async`.
2128           *
2129           * Returning a falsey value will omit the attribute.
2130           *
2131           * @since 6.1.0
2132           *
2133           * @param string|false|null $value      The `decoding` attribute value. Returning a falsey value
2134           *                                      will result in the attribute being omitted for the image.
2135           *                                      Otherwise, it may be: 'async', 'sync', or 'auto'. Defaults to false.
2136           * @param string            $image      The HTML `img` tag to be filtered.
2137           * @param string            $context    Additional context about how the function was called
2138           *                                      or where the img tag is.
2139           */
2140          $filtered_decoding_attr = apply_filters(
2141              'wp_img_tag_add_decoding_attr',
2142              isset( $optimization_attrs['decoding'] ) ? $optimization_attrs['decoding'] : false,
2143              $image,
2144              $context
2145          );
2146  
2147          // Validate the values after filtering.
2148          if ( isset( $optimization_attrs['decoding'] ) && ! $filtered_decoding_attr ) {
2149              // Unset `decoding` attribute if `$filtered_decoding_attr` is set to `false`.
2150              unset( $optimization_attrs['decoding'] );
2151          } elseif ( in_array( $filtered_decoding_attr, array( 'async', 'sync', 'auto' ), true ) ) {
2152              $optimization_attrs['decoding'] = $filtered_decoding_attr;
2153          }
2154  
2155          if ( ! empty( $optimization_attrs['decoding'] ) ) {
2156              $image = str_replace( '<img', '<img decoding="' . esc_attr( $optimization_attrs['decoding'] ) . '"', $image );
2157          }
2158      }
2159  
2160      // Images should have dimension attributes for the 'loading' and 'fetchpriority' attributes to be added.
2161      if ( ! str_contains( $image, ' width="' ) || ! str_contains( $image, ' height="' ) ) {
2162          return $image;
2163      }
2164  
2165      // Retained for backward compatibility.
2166      $loading_attrs_enabled = wp_lazy_loading_enabled( 'img', $context );
2167  
2168      if ( empty( $loading_val ) && $loading_attrs_enabled ) {
2169          /**
2170           * Filters the `loading` attribute value to add to an image. Default `lazy`.
2171           *
2172           * Returning `false` or an empty string will not add the attribute.
2173           * Returning `true` will add the default value.
2174           *
2175           * @since 5.5.0
2176           *
2177           * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
2178           *                             the attribute being omitted for the image.
2179           * @param string      $image   The HTML `img` tag to be filtered.
2180           * @param string      $context Additional context about how the function was called or where the img tag is.
2181           */
2182          $filtered_loading_attr = apply_filters(
2183              'wp_img_tag_add_loading_attr',
2184              isset( $optimization_attrs['loading'] ) ? $optimization_attrs['loading'] : false,
2185              $image,
2186              $context
2187          );
2188  
2189          // Validate the values after filtering.
2190          if ( isset( $optimization_attrs['loading'] ) && ! $filtered_loading_attr ) {
2191              // Unset `loading` attributes if `$filtered_loading_attr` is set to `false`.
2192              unset( $optimization_attrs['loading'] );
2193          } elseif ( in_array( $filtered_loading_attr, array( 'lazy', 'eager' ), true ) ) {
2194              /*
2195               * If the filter changed the loading attribute to "lazy" when a fetchpriority attribute
2196               * with value "high" is already present, trigger a warning since those two attribute
2197               * values should be mutually exclusive.
2198               *
2199               * The same warning is present in `wp_get_loading_optimization_attributes()`, and here it
2200               * is only intended for the specific scenario where the above filtered caused the problem.
2201               */
2202              if ( isset( $optimization_attrs['fetchpriority'] ) && 'high' === $optimization_attrs['fetchpriority'] &&
2203                  ( isset( $optimization_attrs['loading'] ) ? $optimization_attrs['loading'] : false ) !== $filtered_loading_attr &&
2204                  'lazy' === $filtered_loading_attr
2205              ) {
2206                  _doing_it_wrong(
2207                      __FUNCTION__,
2208                      __( 'An image should not be lazy-loaded and marked as high priority at the same time.' ),
2209                      '6.3.0'
2210                  );
2211              }
2212  
2213              // The filtered value will still be respected.
2214              $optimization_attrs['loading'] = $filtered_loading_attr;
2215          }
2216  
2217          if ( ! empty( $optimization_attrs['loading'] ) ) {
2218              $image = str_replace( '<img', '<img loading="' . esc_attr( $optimization_attrs['loading'] ) . '"', $image );
2219          }
2220      }
2221  
2222      if ( empty( $fetchpriority_val ) && ! empty( $optimization_attrs['fetchpriority'] ) ) {
2223          $image = str_replace( '<img', '<img fetchpriority="' . esc_attr( $optimization_attrs['fetchpriority'] ) . '"', $image );
2224      }
2225  
2226      return $image;
2227  }
2228  
2229  /**
2230   * Adds `width` and `height` attributes to an `img` HTML tag.
2231   *
2232   * @since 5.5.0
2233   *
2234   * @param string $image         The HTML `img` tag where the attribute should be added.
2235   * @param string $context       Additional context to pass to the filters.
2236   * @param int    $attachment_id Image attachment ID.
2237   * @return string Converted 'img' element with 'width' and 'height' attributes added.
2238   */
2239  function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
2240      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
2241      list( $image_src ) = explode( '?', $image_src );
2242  
2243      // Return early if we couldn't get the image source.
2244      if ( ! $image_src ) {
2245          return $image;
2246      }
2247  
2248      /**
2249       * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
2250       *
2251       * Returning anything else than `true` will not add the attributes.
2252       *
2253       * @since 5.5.0
2254       *
2255       * @param bool   $value         The filtered value, defaults to `true`.
2256       * @param string $image         The HTML `img` tag where the attribute should be added.
2257       * @param string $context       Additional context about how the function was called or where the img tag is.
2258       * @param int    $attachment_id The image attachment ID.
2259       */
2260      $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
2261  
2262      if ( true === $add ) {
2263          $image_meta = wp_get_attachment_metadata( $attachment_id );
2264          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
2265  
2266          if ( $size_array && $size_array[0] && $size_array[1] ) {
2267              // If the width is enforced through style (e.g. in an inline image), calculate the dimension attributes.
2268              $style_width = preg_match( '/style="width:\s*(\d+)px;"/', $image, $match_width ) ? (int) $match_width[1] : 0;
2269              if ( $style_width ) {
2270                  $size_array[1] = (int) round( $size_array[1] * $style_width / $size_array[0] );
2271                  $size_array[0] = $style_width;
2272              }
2273  
2274              $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
2275              return str_replace( '<img', "<img {$hw}", $image );
2276          }
2277      }
2278  
2279      return $image;
2280  }
2281  
2282  /**
2283   * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
2284   *
2285   * @since 5.5.0
2286   *
2287   * @param string $image         The HTML `img` tag where the attribute should be added.
2288   * @param string $context       Additional context to pass to the filters.
2289   * @param int    $attachment_id Image attachment ID.
2290   * @return string Converted 'img' element with 'loading' attribute added.
2291   */
2292  function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
2293      /**
2294       * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
2295       *
2296       * Returning anything else than `true` will not add the attributes.
2297       *
2298       * @since 5.5.0
2299       *
2300       * @param bool   $value         The filtered value, defaults to `true`.
2301       * @param string $image         The HTML `img` tag where the attribute should be added.
2302       * @param string $context       Additional context about how the function was called or where the img tag is.
2303       * @param int    $attachment_id The image attachment ID.
2304       */
2305      $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
2306  
2307      if ( true === $add ) {
2308          $image_meta = wp_get_attachment_metadata( $attachment_id );
2309          return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
2310      }
2311  
2312      return $image;
2313  }
2314  
2315  /**
2316   * Adds `loading` attribute to an `iframe` HTML tag.
2317   *
2318   * @since 5.7.0
2319   *
2320   * @param string $iframe  The HTML `iframe` tag where the attribute should be added.
2321   * @param string $context Additional context to pass to the filters.
2322   * @return string Converted `iframe` tag with `loading` attribute added.
2323   */
2324  function wp_iframe_tag_add_loading_attr( $iframe, $context ) {
2325      /*
2326       * Get loading attribute value to use. This must occur before the conditional check below so that even iframes that
2327       * are ineligible for being lazy-loaded are considered.
2328       */
2329      $optimization_attrs = wp_get_loading_optimization_attributes(
2330          'iframe',
2331          array(
2332              /*
2333               * The concrete values for width and height are not important here for now
2334               * since fetchpriority is not yet supported for iframes.
2335               * TODO: Use WP_HTML_Tag_Processor to extract actual values once support is
2336               * added.
2337               */
2338              'width'   => str_contains( $iframe, ' width="' ) ? 100 : null,
2339              'height'  => str_contains( $iframe, ' height="' ) ? 100 : null,
2340              // This function is never called when a 'loading' attribute is already present.
2341              'loading' => null,
2342          ),
2343          $context
2344      );
2345  
2346      // Iframes should have source and dimension attributes for the `loading` attribute to be added.
2347      if ( ! str_contains( $iframe, ' src="' ) || ! str_contains( $iframe, ' width="' ) || ! str_contains( $iframe, ' height="' ) ) {
2348          return $iframe;
2349      }
2350  
2351      $value = isset( $optimization_attrs['loading'] ) ? $optimization_attrs['loading'] : false;
2352  
2353      /**
2354       * Filters the `loading` attribute value to add to an iframe. Default `lazy`.
2355       *
2356       * Returning `false` or an empty string will not add the attribute.
2357       * Returning `true` will add the default value.
2358       *
2359       * @since 5.7.0
2360       *
2361       * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
2362       *                             the attribute being omitted for the iframe.
2363       * @param string      $iframe  The HTML `iframe` tag to be filtered.
2364       * @param string      $context Additional context about how the function was called or where the iframe tag is.
2365       */
2366      $value = apply_filters( 'wp_iframe_tag_add_loading_attr', $value, $iframe, $context );
2367  
2368      if ( $value ) {
2369          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
2370              $value = 'lazy';
2371          }
2372  
2373          return str_replace( '<iframe', '<iframe loading="' . esc_attr( $value ) . '"', $iframe );
2374      }
2375  
2376      return $iframe;
2377  }
2378  
2379  /**
2380   * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
2381   *
2382   * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
2383   * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
2384   *
2385   * @ignore
2386   * @since 2.9.0
2387   *
2388   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2389   * @return string[] Modified array of attributes including the new 'wp-post-image' class.
2390   */
2391  function _wp_post_thumbnail_class_filter( $attr ) {
2392      $attr['class'] .= ' wp-post-image';
2393      return $attr;
2394  }
2395  
2396  /**
2397   * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
2398   * filter hook. Internal use only.
2399   *
2400   * @ignore
2401   * @since 2.9.0
2402   *
2403   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2404   */
2405  function _wp_post_thumbnail_class_filter_add( $attr ) {
2406      add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2407  }
2408  
2409  /**
2410   * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
2411   * filter hook. Internal use only.
2412   *
2413   * @ignore
2414   * @since 2.9.0
2415   *
2416   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2417   */
2418  function _wp_post_thumbnail_class_filter_remove( $attr ) {
2419      remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2420  }
2421  
2422  /**
2423   * Overrides the context used in {@see wp_get_attachment_image()}. Internal use only.
2424   *
2425   * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
2426   * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
2427   *
2428   * @ignore
2429   * @since 6.3.0
2430   * @access private
2431   *
2432   * @param string $context The context for rendering an attachment image.
2433   * @return string Modified context set to 'the_post_thumbnail'.
2434   */
2435  function _wp_post_thumbnail_context_filter( $context ) {
2436      return 'the_post_thumbnail';
2437  }
2438  
2439  /**
2440   * Adds the '_wp_post_thumbnail_context_filter' callback to the 'wp_get_attachment_image_context'
2441   * filter hook. Internal use only.
2442   *
2443   * @ignore
2444   * @since 6.3.0
2445   * @access private
2446   */
2447  function _wp_post_thumbnail_context_filter_add() {
2448      add_filter( 'wp_get_attachment_image_context', '_wp_post_thumbnail_context_filter' );
2449  }
2450  
2451  /**
2452   * Removes the '_wp_post_thumbnail_context_filter' callback from the 'wp_get_attachment_image_context'
2453   * filter hook. Internal use only.
2454   *
2455   * @ignore
2456   * @since 6.3.0
2457   * @access private
2458   */
2459  function _wp_post_thumbnail_context_filter_remove() {
2460      remove_filter( 'wp_get_attachment_image_context', '_wp_post_thumbnail_context_filter' );
2461  }
2462  
2463  add_shortcode( 'wp_caption', 'img_caption_shortcode' );
2464  add_shortcode( 'caption', 'img_caption_shortcode' );
2465  
2466  /**
2467   * Builds the Caption shortcode output.
2468   *
2469   * Allows a plugin to replace the content that would otherwise be returned. The
2470   * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
2471   * parameter and the content parameter values.
2472   *
2473   * The supported attributes for the shortcode are 'id', 'caption_id', 'align',
2474   * 'width', 'caption', and 'class'.
2475   *
2476   * @since 2.6.0
2477   * @since 3.9.0 The `class` attribute was added.
2478   * @since 5.1.0 The `caption_id` attribute was added.
2479   * @since 5.9.0 The `$content` parameter default value changed from `null` to `''`.
2480   *
2481   * @param array  $attr {
2482   *     Attributes of the caption shortcode.
2483   *
2484   *     @type string $id         ID of the image and caption container element, i.e. `<figure>` or `<div>`.
2485   *     @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`.
2486   *     @type string $align      Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
2487   *                              'aligncenter', alignright', 'alignnone'.
2488   *     @type int    $width      The width of the caption, in pixels.
2489   *     @type string $caption    The caption text.
2490   *     @type string $class      Additional class name(s) added to the caption container.
2491   * }
2492   * @param string $content Optional. Shortcode content. Default empty string.
2493   * @return string HTML content to display the caption.
2494   */
2495  function img_caption_shortcode( $attr, $content = '' ) {
2496      // New-style shortcode with the caption inside the shortcode with the link and image tags.
2497      if ( ! isset( $attr['caption'] ) ) {
2498          if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
2499              $content         = $matches[1];
2500              $attr['caption'] = trim( $matches[2] );
2501          }
2502      } elseif ( str_contains( $attr['caption'], '<' ) ) {
2503          $attr['caption'] = wp_kses( $attr['caption'], 'post' );
2504      }
2505  
2506      /**
2507       * Filters the default caption shortcode output.
2508       *
2509       * If the filtered output isn't empty, it will be used instead of generating
2510       * the default caption template.
2511       *
2512       * @since 2.6.0
2513       *
2514       * @see img_caption_shortcode()
2515       *
2516       * @param string $output  The caption output. Default empty.
2517       * @param array  $attr    Attributes of the caption shortcode.
2518       * @param string $content The image element, possibly wrapped in a hyperlink.
2519       */
2520      $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
2521  
2522      if ( ! empty( $output ) ) {
2523          return $output;
2524      }
2525  
2526      $atts = shortcode_atts(
2527          array(
2528              'id'         => '',
2529              'caption_id' => '',
2530              'align'      => 'alignnone',
2531              'width'      => '',
2532              'caption'    => '',
2533              'class'      => '',
2534          ),
2535          $attr,
2536          'caption'
2537      );
2538  
2539      $atts['width'] = (int) $atts['width'];
2540  
2541      if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
2542          return $content;
2543      }
2544  
2545      $id          = '';
2546      $caption_id  = '';
2547      $describedby = '';
2548  
2549      if ( $atts['id'] ) {
2550          $atts['id'] = sanitize_html_class( $atts['id'] );
2551          $id         = 'id="' . esc_attr( $atts['id'] ) . '" ';
2552      }
2553  
2554      if ( $atts['caption_id'] ) {
2555          $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
2556      } elseif ( $atts['id'] ) {
2557          $atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
2558      }
2559  
2560      if ( $atts['caption_id'] ) {
2561          $caption_id  = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
2562          $describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
2563      }
2564  
2565      $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
2566  
2567      $html5 = current_theme_supports( 'html5', 'caption' );
2568      // HTML5 captions never added the extra 10px to the image width.
2569      $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
2570  
2571      /**
2572       * Filters the width of an image's caption.
2573       *
2574       * By default, the caption is 10 pixels greater than the width of the image,
2575       * to prevent post content from running up against a floated image.
2576       *
2577       * @since 3.7.0
2578       *
2579       * @see img_caption_shortcode()
2580       *
2581       * @param int    $width    Width of the caption in pixels. To remove this inline style,
2582       *                         return zero.
2583       * @param array  $atts     Attributes of the caption shortcode.
2584       * @param string $content  The image element, possibly wrapped in a hyperlink.
2585       */
2586      $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
2587  
2588      $style = '';
2589  
2590      if ( $caption_width ) {
2591          $style = 'style="width: ' . (int) $caption_width . 'px" ';
2592      }
2593  
2594      if ( $html5 ) {
2595          $html = sprintf(
2596              '<figure %s%s%sclass="%s">%s%s</figure>',
2597              $id,
2598              $describedby,
2599              $style,
2600              esc_attr( $class ),
2601              do_shortcode( $content ),
2602              sprintf(
2603                  '<figcaption %sclass="wp-caption-text">%s</figcaption>',
2604                  $caption_id,
2605                  $atts['caption']
2606              )
2607          );
2608      } else {
2609          $html = sprintf(
2610              '<div %s%sclass="%s">%s%s</div>',
2611              $id,
2612              $style,
2613              esc_attr( $class ),
2614              str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
2615              sprintf(
2616                  '<p %sclass="wp-caption-text">%s</p>',
2617                  $caption_id,
2618                  $atts['caption']
2619              )
2620          );
2621      }
2622  
2623      return $html;
2624  }
2625  
2626  add_shortcode( 'gallery', 'gallery_shortcode' );
2627  
2628  /**
2629   * Builds the Gallery shortcode output.
2630   *
2631   * This implements the functionality of the Gallery Shortcode for displaying
2632   * WordPress images on a post.
2633   *
2634   * @since 2.5.0
2635   * @since 2.8.0 Added the `$attr` parameter to set the shortcode output. New attributes included
2636   *              such as `size`, `itemtag`, `icontag`, `captiontag`, and columns. Changed markup from
2637   *              `div` tags to `dl`, `dt` and `dd` tags. Support more than one gallery on the
2638   *              same page.
2639   * @since 2.9.0 Added support for `include` and `exclude` to shortcode.
2640   * @since 3.5.0 Use get_post() instead of global `$post`. Handle mapping of `ids` to `include`
2641   *              and `orderby`.
2642   * @since 3.6.0 Added validation for tags used in gallery shortcode. Add orientation information to items.
2643   * @since 3.7.0 Introduced the `link` attribute.
2644   * @since 3.9.0 `html5` gallery support, accepting 'itemtag', 'icontag', and 'captiontag' attributes.
2645   * @since 4.0.0 Removed use of `extract()`.
2646   * @since 4.1.0 Added attribute to `wp_get_attachment_link()` to output `aria-describedby`.
2647   * @since 4.2.0 Passed the shortcode instance ID to `post_gallery` and `post_playlist` filters.
2648   * @since 4.6.0 Standardized filter docs to match documentation standards for PHP.
2649   * @since 5.1.0 Code cleanup for WPCS 1.0.0 coding standards.
2650   * @since 5.3.0 Saved progress of intermediate image creation after upload.
2651   * @since 5.5.0 Ensured that galleries can be output as a list of links in feeds.
2652   * @since 5.6.0 Replaced order-style PHP type conversion functions with typecasts. Fix logic for
2653   *              an array of image dimensions.
2654   *
2655   * @param array $attr {
2656   *     Attributes of the gallery shortcode.
2657   *
2658   *     @type string       $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
2659   *     @type string       $orderby    The field to use when ordering the images. Default 'menu_order ID'.
2660   *                                    Accepts any valid SQL ORDERBY statement.
2661   *     @type int          $id         Post ID.
2662   *     @type string       $itemtag    HTML tag to use for each image in the gallery.
2663   *                                    Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
2664   *     @type string       $icontag    HTML tag to use for each image's icon.
2665   *                                    Default 'dt', or 'div' when the theme registers HTML5 gallery support.
2666   *     @type string       $captiontag HTML tag to use for each image's caption.
2667   *                                    Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
2668   *     @type int          $columns    Number of columns of images to display. Default 3.
2669   *     @type string|int[] $size       Size of the images to display. Accepts any registered image size name, or an array
2670   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
2671   *     @type string       $ids        A comma-separated list of IDs of attachments to display. Default empty.
2672   *     @type string       $include    A comma-separated list of IDs of attachments to include. Default empty.
2673   *     @type string       $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
2674   *     @type string       $link       What to link each image to. Default empty (links to the attachment page).
2675   *                                    Accepts 'file', 'none'.
2676   * }
2677   * @return string HTML content to display gallery.
2678   */
2679  function gallery_shortcode( $attr ) {
2680      $post = get_post();
2681  
2682      static $instance = 0;
2683      ++$instance;
2684  
2685      if ( ! empty( $attr['ids'] ) ) {
2686          // 'ids' is explicitly ordered, unless you specify otherwise.
2687          if ( empty( $attr['orderby'] ) ) {
2688              $attr['orderby'] = 'post__in';
2689          }
2690          $attr['include'] = $attr['ids'];
2691      }
2692  
2693      /**
2694       * Filters the default gallery shortcode output.
2695       *
2696       * If the filtered output isn't empty, it will be used instead of generating
2697       * the default gallery template.
2698       *
2699       * @since 2.5.0
2700       * @since 4.2.0 The `$instance` parameter was added.
2701       *
2702       * @see gallery_shortcode()
2703       *
2704       * @param string $output   The gallery output. Default empty.
2705       * @param array  $attr     Attributes of the gallery shortcode.
2706       * @param int    $instance Unique numeric ID of this gallery shortcode instance.
2707       */
2708      $output = apply_filters( 'post_gallery', '', $attr, $instance );
2709  
2710      if ( ! empty( $output ) ) {
2711          return $output;
2712      }
2713  
2714      $html5 = current_theme_supports( 'html5', 'gallery' );
2715      $atts  = shortcode_atts(
2716          array(
2717              'order'      => 'ASC',
2718              'orderby'    => 'menu_order ID',
2719              'id'         => $post ? $post->ID : 0,
2720              'itemtag'    => $html5 ? 'figure' : 'dl',
2721              'icontag'    => $html5 ? 'div' : 'dt',
2722              'captiontag' => $html5 ? 'figcaption' : 'dd',
2723              'columns'    => 3,
2724              'size'       => 'thumbnail',
2725              'include'    => '',
2726              'exclude'    => '',
2727              'link'       => '',
2728          ),
2729          $attr,
2730          'gallery'
2731      );
2732  
2733      $id = (int) $atts['id'];
2734  
2735      if ( ! empty( $atts['include'] ) ) {
2736          $_attachments = get_posts(
2737              array(
2738                  'include'        => $atts['include'],
2739                  'post_status'    => 'inherit',
2740                  'post_type'      => 'attachment',
2741                  'post_mime_type' => 'image',
2742                  'order'          => $atts['order'],
2743                  'orderby'        => $atts['orderby'],
2744              )
2745          );
2746  
2747          $attachments = array();
2748          foreach ( $_attachments as $key => $val ) {
2749              $attachments[ $val->ID ] = $_attachments[ $key ];
2750          }
2751      } elseif ( ! empty( $atts['exclude'] ) ) {
2752          $post_parent_id = $id;
2753          $attachments    = get_children(
2754              array(
2755                  'post_parent'    => $id,
2756                  'exclude'        => $atts['exclude'],
2757                  'post_status'    => 'inherit',
2758                  'post_type'      => 'attachment',
2759                  'post_mime_type' => 'image',
2760                  'order'          => $atts['order'],
2761                  'orderby'        => $atts['orderby'],
2762              )
2763          );
2764      } else {
2765          $post_parent_id = $id;
2766          $attachments    = get_children(
2767              array(
2768                  'post_parent'    => $id,
2769                  'post_status'    => 'inherit',
2770                  'post_type'      => 'attachment',
2771                  'post_mime_type' => 'image',
2772                  'order'          => $atts['order'],
2773                  'orderby'        => $atts['orderby'],
2774              )
2775          );
2776      }
2777  
2778      if ( ! empty( $post_parent_id ) ) {
2779          $post_parent = get_post( $post_parent_id );
2780  
2781          // Terminate the shortcode execution if the user cannot read the post or it is password-protected.
2782          if ( ! is_post_publicly_viewable( $post_parent->ID ) && ! current_user_can( 'read_post', $post_parent->ID )
2783              || post_password_required( $post_parent )
2784          ) {
2785              return '';
2786          }
2787      }
2788  
2789      if ( empty( $attachments ) ) {
2790          return '';
2791      }
2792  
2793      if ( is_feed() ) {
2794          $output = "\n";
2795          foreach ( $attachments as $att_id => $attachment ) {
2796              if ( ! empty( $atts['link'] ) ) {
2797                  if ( 'none' === $atts['link'] ) {
2798                      $output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr );
2799                  } else {
2800                      $output .= wp_get_attachment_link( $att_id, $atts['size'], false );
2801                  }
2802              } else {
2803                  $output .= wp_get_attachment_link( $att_id, $atts['size'], true );
2804              }
2805              $output .= "\n";
2806          }
2807          return $output;
2808      }
2809  
2810      $itemtag    = tag_escape( $atts['itemtag'] );
2811      $captiontag = tag_escape( $atts['captiontag'] );
2812      $icontag    = tag_escape( $atts['icontag'] );
2813      $valid_tags = wp_kses_allowed_html( 'post' );
2814      if ( ! isset( $valid_tags[ $itemtag ] ) ) {
2815          $itemtag = 'dl';
2816      }
2817      if ( ! isset( $valid_tags[ $captiontag ] ) ) {
2818          $captiontag = 'dd';
2819      }
2820      if ( ! isset( $valid_tags[ $icontag ] ) ) {
2821          $icontag = 'dt';
2822      }
2823  
2824      $columns   = (int) $atts['columns'];
2825      $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
2826      $float     = is_rtl() ? 'right' : 'left';
2827  
2828      $selector = "gallery-{$instance}";
2829  
2830      $gallery_style = '';
2831  
2832      /**
2833       * Filters whether to print default gallery styles.
2834       *
2835       * @since 3.1.0
2836       *
2837       * @param bool $print Whether to print default gallery styles.
2838       *                    Defaults to false if the theme supports HTML5 galleries.
2839       *                    Otherwise, defaults to true.
2840       */
2841      if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
2842          $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
2843  
2844          $gallery_style = "
2845          <style{$type_attr}>
2846              #{$selector} {
2847                  margin: auto;
2848              }
2849              #{$selector} .gallery-item {
2850                  float: {$float};
2851                  margin-top: 10px;
2852                  text-align: center;
2853                  width: {$itemwidth}%;
2854              }
2855              #{$selector} img {
2856                  border: 2px solid #cfcfcf;
2857              }
2858              #{$selector} .gallery-caption {
2859                  margin-left: 0;
2860              }
2861              /* see gallery_shortcode() in wp-includes/media.php */
2862          </style>\n\t\t";
2863      }
2864  
2865      $size_class  = sanitize_html_class( is_array( $atts['size'] ) ? implode( 'x', $atts['size'] ) : $atts['size'] );
2866      $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
2867  
2868      /**
2869       * Filters the default gallery shortcode CSS styles.
2870       *
2871       * @since 2.5.0
2872       *
2873       * @param string $gallery_style Default CSS styles and opening HTML div container
2874       *                              for the gallery shortcode output.
2875       */
2876      $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
2877  
2878      $i = 0;
2879  
2880      foreach ( $attachments as $id => $attachment ) {
2881  
2882          $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
2883  
2884          if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
2885              $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
2886          } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
2887              $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
2888          } else {
2889              $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
2890          }
2891  
2892          $image_meta = wp_get_attachment_metadata( $id );
2893  
2894          $orientation = '';
2895  
2896          if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
2897              $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
2898          }
2899  
2900          $output .= "<{$itemtag} class='gallery-item'>";
2901          $output .= "
2902              <{$icontag} class='gallery-icon {$orientation}'>
2903                  $image_output
2904              </{$icontag}>";
2905  
2906          if ( $captiontag && trim( $attachment->post_excerpt ) ) {
2907              $output .= "
2908                  <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
2909                  " . wptexturize( $attachment->post_excerpt ) . "
2910                  </{$captiontag}>";
2911          }
2912  
2913          $output .= "</{$itemtag}>";
2914  
2915          if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
2916              $output .= '<br style="clear: both" />';
2917          }
2918      }
2919  
2920      if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
2921          $output .= "
2922              <br style='clear: both' />";
2923      }
2924  
2925      $output .= "
2926          </div>\n";
2927  
2928      return $output;
2929  }
2930  
2931  /**
2932   * Outputs the templates used by playlists.
2933   *
2934   * @since 3.9.0
2935   */
2936  function wp_underscore_playlist_templates() {
2937      ?>
2938  <script type="text/html" id="tmpl-wp-playlist-current-item">
2939      <# if ( data.thumb && data.thumb.src ) { #>
2940          <img src="{{ data.thumb.src }}" alt="" />
2941      <# } #>
2942      <div class="wp-playlist-caption">
2943          <span class="wp-playlist-item-meta wp-playlist-item-title">
2944              <# if ( data.meta.album || data.meta.artist ) { #>
2945                  <?php
2946                  /* translators: %s: Playlist item title. */
2947                  printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
2948                  ?>
2949              <# } else { #>
2950                  {{ data.title }}
2951              <# } #>
2952          </span>
2953          <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
2954          <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
2955      </div>
2956  </script>
2957  <script type="text/html" id="tmpl-wp-playlist-item">
2958      <div class="wp-playlist-item">
2959          <a class="wp-playlist-caption" href="{{ data.src }}">
2960              {{ data.index ? ( data.index + '. ' ) : '' }}
2961              <# if ( data.caption ) { #>
2962                  {{ data.caption }}
2963              <# } else { #>
2964                  <# if ( data.artists && data.meta.artist ) { #>
2965                      <span class="wp-playlist-item-title">
2966                          <?php
2967                          /* translators: %s: Playlist item title. */
2968                          printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
2969                          ?>
2970                      </span>
2971                      <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
2972                  <# } else { #>
2973                      <span class="wp-playlist-item-title">{{{ data.title }}}</span>
2974                  <# } #>
2975              <# } #>
2976          </a>
2977          <# if ( data.meta.length_formatted ) { #>
2978          <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
2979          <# } #>
2980      </div>
2981  </script>
2982      <?php
2983  }
2984  
2985  /**
2986   * Outputs and enqueues default scripts and styles for playlists.
2987   *
2988   * @since 3.9.0
2989   *
2990   * @param string $type Type of playlist. Accepts 'audio' or 'video'.
2991   */
2992  function wp_playlist_scripts( $type ) {
2993      wp_enqueue_style( 'wp-mediaelement' );
2994      wp_enqueue_script( 'wp-playlist' );
2995      add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
2996      add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
2997  }
2998  
2999  /**
3000   * Builds the Playlist shortcode output.
3001   *
3002   * This implements the functionality of the playlist shortcode for displaying
3003   * a collection of WordPress audio or video files in a post.
3004   *
3005   * @since 3.9.0
3006   *
3007   * @global int $content_width
3008   *
3009   * @param array $attr {
3010   *     Array of default playlist attributes.
3011   *
3012   *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
3013   *     @type string  $order        Designates ascending or descending order of items in the playlist.
3014   *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
3015   *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
3016   *                                 passed, this defaults to the order of the $ids array ('post__in').
3017   *                                 Otherwise default is 'menu_order ID'.
3018   *     @type int     $id           If an explicit $ids array is not present, this parameter
3019   *                                 will determine which attachments are used for the playlist.
3020   *                                 Default is the current post ID.
3021   *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
3022   *                                 a playlist will be created from all $type attachments of $id.
3023   *                                 Default empty.
3024   *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
3025   *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
3026   *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
3027   *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
3028   *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
3029   *                                 thumbnail). Default true.
3030   *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
3031   * }
3032   *
3033   * @return string Playlist output. Empty string if the passed type is unsupported.
3034   */
3035  function wp_playlist_shortcode( $attr ) {
3036      global $content_width;
3037      $post = get_post();
3038  
3039      static $instance = 0;
3040      ++$instance;
3041  
3042      if ( ! empty( $attr['ids'] ) ) {
3043          // 'ids' is explicitly ordered, unless you specify otherwise.
3044          if ( empty( $attr['orderby'] ) ) {
3045              $attr['orderby'] = 'post__in';
3046          }
3047          $attr['include'] = $attr['ids'];
3048      }
3049  
3050      /**
3051       * Filters the playlist output.
3052       *
3053       * Returning a non-empty value from the filter will short-circuit generation
3054       * of the default playlist output, returning the passed value instead.
3055       *
3056       * @since 3.9.0
3057       * @since 4.2.0 The `$instance` parameter was added.
3058       *
3059       * @param string $output   Playlist output. Default empty.
3060       * @param array  $attr     An array of shortcode attributes.
3061       * @param int    $instance Unique numeric ID of this playlist shortcode instance.
3062       */
3063      $output = apply_filters( 'post_playlist', '', $attr, $instance );
3064  
3065      if ( ! empty( $output ) ) {
3066          return $output;
3067      }
3068  
3069      $atts = shortcode_atts(
3070          array(
3071              'type'         => 'audio',
3072              'order'        => 'ASC',
3073              'orderby'      => 'menu_order ID',
3074              'id'           => $post ? $post->ID : 0,
3075              'include'      => '',
3076              'exclude'      => '',
3077              'style'        => 'light',
3078              'tracklist'    => true,
3079              'tracknumbers' => true,
3080              'images'       => true,
3081              'artists'      => true,
3082          ),
3083          $attr,
3084          'playlist'
3085      );
3086  
3087      $id = (int) $atts['id'];
3088  
3089      if ( 'audio' !== $atts['type'] ) {
3090          $atts['type'] = 'video';
3091      }
3092  
3093      $args = array(
3094          'post_status'    => 'inherit',
3095          'post_type'      => 'attachment',
3096          'post_mime_type' => $atts['type'],
3097          'order'          => $atts['order'],
3098          'orderby'        => $atts['orderby'],
3099      );
3100  
3101      if ( ! empty( $atts['include'] ) ) {
3102          $args['include'] = $atts['include'];
3103          $_attachments    = get_posts( $args );
3104  
3105          $attachments = array();
3106          foreach ( $_attachments as $key => $val ) {
3107              $attachments[ $val->ID ] = $_attachments[ $key ];
3108          }
3109      } elseif ( ! empty( $atts['exclude'] ) ) {
3110          $args['post_parent'] = $id;
3111          $args['exclude']     = $atts['exclude'];
3112          $attachments         = get_children( $args );
3113      } else {
3114          $args['post_parent'] = $id;
3115          $attachments         = get_children( $args );
3116      }
3117  
3118      if ( ! empty( $args['post_parent'] ) ) {
3119          $post_parent = get_post( $id );
3120  
3121          // Terminate the shortcode execution if the user cannot read the post or it is password-protected.
3122          if ( ! current_user_can( 'read_post', $post_parent->ID ) || post_password_required( $post_parent ) ) {
3123              return '';
3124          }
3125      }
3126  
3127      if ( empty( $attachments ) ) {
3128          return '';
3129      }
3130  
3131      if ( is_feed() ) {
3132          $output = "\n";
3133          foreach ( $attachments as $att_id => $attachment ) {
3134              $output .= wp_get_attachment_link( $att_id ) . "\n";
3135          }
3136          return $output;
3137      }
3138  
3139      $outer = 22; // Default padding and border of wrapper.
3140  
3141      $default_width  = 640;
3142      $default_height = 360;
3143  
3144      $theme_width  = empty( $content_width ) ? $default_width : ( $content_width - $outer );
3145      $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
3146  
3147      $data = array(
3148          'type'         => $atts['type'],
3149          // Don't pass strings to JSON, will be truthy in JS.
3150          'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
3151          'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
3152          'images'       => wp_validate_boolean( $atts['images'] ),
3153          'artists'      => wp_validate_boolean( $atts['artists'] ),
3154      );
3155  
3156      $tracks = array();
3157      foreach ( $attachments as $attachment ) {
3158          $url   = wp_get_attachment_url( $attachment->ID );
3159          $ftype = wp_check_filetype( $url, wp_get_mime_types() );
3160          $track = array(
3161              'src'         => $url,
3162              'type'        => $ftype['type'],
3163              'title'       => $attachment->post_title,
3164              'caption'     => $attachment->post_excerpt,
3165              'description' => $attachment->post_content,
3166          );
3167  
3168          $track['meta'] = array();
3169          $meta          = wp_get_attachment_metadata( $attachment->ID );
3170          if ( ! empty( $meta ) ) {
3171  
3172              foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
3173                  if ( ! empty( $meta[ $key ] ) ) {
3174                      $track['meta'][ $key ] = $meta[ $key ];
3175                  }
3176              }
3177  
3178              if ( 'video' === $atts['type'] ) {
3179                  if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
3180                      $width        = $meta['width'];
3181                      $height       = $meta['height'];
3182                      $theme_height = round( ( $height * $theme_width ) / $width );
3183                  } else {
3184                      $width  = $default_width;
3185                      $height = $default_height;
3186                  }
3187  
3188                  $track['dimensions'] = array(
3189                      'original' => compact( 'width', 'height' ),
3190                      'resized'  => array(
3191                          'width'  => $theme_width,
3192                          'height' => $theme_height,
3193                      ),
3194                  );
3195              }
3196          }
3197  
3198          if ( $atts['images'] ) {
3199              $thumb_id = get_post_thumbnail_id( $attachment->ID );
3200              if ( ! empty( $thumb_id ) ) {
3201                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
3202                  $track['image']               = compact( 'src', 'width', 'height' );
3203                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
3204                  $track['thumb']               = compact( 'src', 'width', 'height' );
3205              } else {
3206                  $src            = wp_mime_type_icon( $attachment->ID, '.svg' );
3207                  $width          = 48;
3208                  $height         = 64;
3209                  $track['image'] = compact( 'src', 'width', 'height' );
3210                  $track['thumb'] = compact( 'src', 'width', 'height' );
3211              }
3212          }
3213  
3214          $tracks[] = $track;
3215      }
3216      $data['tracks'] = $tracks;
3217  
3218      $safe_type  = esc_attr( $atts['type'] );
3219      $safe_style = esc_attr( $atts['style'] );
3220  
3221      ob_start();
3222  
3223      if ( 1 === $instance ) {
3224          /**
3225           * Prints and enqueues playlist scripts, styles, and JavaScript templates.
3226           *
3227           * @since 3.9.0
3228           *
3229           * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
3230           * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
3231           */
3232          do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
3233      }
3234      ?>
3235  <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>">
3236      <?php if ( 'audio' === $atts['type'] ) : ?>
3237          <div class="wp-playlist-current-item"></div>
3238      <?php endif; ?>
3239      <<?php echo $safe_type; ?> controls="controls" preload="none" width="<?php echo (int) $theme_width; ?>"
3240          <?php
3241          if ( 'video' === $safe_type ) {
3242              echo ' height="', (int) $theme_height, '"';
3243          }
3244          ?>
3245      ></<?php echo $safe_type; ?>>
3246      <div class="wp-playlist-next"></div>
3247      <div class="wp-playlist-prev"></div>
3248      <noscript>
3249      <ol>
3250          <?php
3251          foreach ( $attachments as $att_id => $attachment ) {
3252              printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
3253          }
3254          ?>
3255      </ol>
3256      </noscript>
3257      <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ); ?></script>
3258  </div>
3259      <?php
3260      return ob_get_clean();
3261  }
3262  add_shortcode( 'playlist', 'wp_playlist_shortcode' );
3263  
3264  /**
3265   * Provides a No-JS Flash fallback as a last resort for audio / video.
3266   *
3267   * @since 3.6.0
3268   *
3269   * @param string $url The media element URL.
3270   * @return string Fallback HTML.
3271   */
3272  function wp_mediaelement_fallback( $url ) {
3273      /**
3274       * Filters the MediaElement fallback output for no-JS.
3275       *
3276       * @since 3.6.0
3277       *
3278       * @param string $output Fallback output for no-JS.
3279       * @param string $url    Media file URL.
3280       */
3281      return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
3282  }
3283  
3284  /**
3285   * Returns a filtered list of supported audio formats.
3286   *
3287   * @since 3.6.0
3288   *
3289   * @return string[] Supported audio formats.
3290   */
3291  function wp_get_audio_extensions() {
3292      /**
3293       * Filters the list of supported audio formats.
3294       *
3295       * @since 3.6.0
3296       *
3297       * @param string[] $extensions An array of supported audio formats. Defaults are
3298       *                            'mp3', 'ogg', 'flac', 'm4a', 'wav'.
3299       */
3300      return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
3301  }
3302  
3303  /**
3304   * Returns useful keys to use to lookup data from an attachment's stored metadata.
3305   *
3306   * @since 3.9.0
3307   *
3308   * @param WP_Post $attachment The current attachment, provided for context.
3309   * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
3310   * @return string[] Key/value pairs of field keys to labels.
3311   */
3312  function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
3313      $fields = array(
3314          'artist' => __( 'Artist' ),
3315          'album'  => __( 'Album' ),
3316      );
3317  
3318      if ( 'display' === $context ) {
3319          $fields['genre']            = __( 'Genre' );
3320          $fields['year']             = __( 'Year' );
3321          $fields['length_formatted'] = _x( 'Length', 'video or audio' );
3322      } elseif ( 'js' === $context ) {
3323          $fields['bitrate']      = __( 'Bitrate' );
3324          $fields['bitrate_mode'] = __( 'Bitrate Mode' );
3325      }
3326  
3327      /**
3328       * Filters the editable list of keys to look up data from an attachment's metadata.
3329       *
3330       * @since 3.9.0
3331       *
3332       * @param array   $fields     Key/value pairs of field keys to labels.
3333       * @param WP_Post $attachment Attachment object.
3334       * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
3335       */
3336      return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
3337  }
3338  /**
3339   * Builds the Audio shortcode output.
3340   *
3341   * This implements the functionality of the Audio Shortcode for displaying
3342   * WordPress mp3s in a post.
3343   *
3344   * @since 3.6.0
3345   * @since 6.8.0 Added the 'muted' attribute.
3346   *
3347   * @param array  $attr {
3348   *     Attributes of the audio shortcode.
3349   *
3350   *     @type string $src      URL to the source of the audio file. Default empty.
3351   *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
3352   *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
3353   *     @type string $muted    The 'muted' attribute for the `<audio>` element. Default 'false'.
3354   *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default 'none'.
3355   *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
3356   *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
3357   * }
3358   * @param string $content Shortcode content.
3359   * @return string|void HTML content to display audio.
3360   */
3361  function wp_audio_shortcode( $attr, $content = '' ) {
3362      $post_id = get_post() ? get_the_ID() : 0;
3363  
3364      static $instance = 0;
3365      ++$instance;
3366  
3367      /**
3368       * Filters the default audio shortcode output.
3369       *
3370       * If the filtered output isn't empty, it will be used instead of generating the default audio template.
3371       *
3372       * @since 3.6.0
3373       *
3374       * @param string $html     Empty variable to be replaced with shortcode markup.
3375       * @param array  $attr     Attributes of the shortcode. See {@see wp_audio_shortcode()}.
3376       * @param string $content  Shortcode content.
3377       * @param int    $instance Unique numeric ID of this audio shortcode instance.
3378       */
3379      $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
3380  
3381      if ( '' !== $override ) {
3382          return $override;
3383      }
3384  
3385      $audio = null;
3386  
3387      $default_types = wp_get_audio_extensions();
3388      $defaults_atts = array(
3389          'src'      => '',
3390          'loop'     => '',
3391          'autoplay' => '',
3392          'muted'    => 'false',
3393          'preload'  => 'none',
3394          'class'    => 'wp-audio-shortcode',
3395          'style'    => 'width: 100%;',
3396      );
3397      foreach ( $default_types as $type ) {
3398          $defaults_atts[ $type ] = '';
3399      }
3400  
3401      $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
3402  
3403      $primary = false;
3404      if ( ! empty( $atts['src'] ) ) {
3405          $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
3406  
3407          if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
3408              return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
3409          }
3410  
3411          $primary = true;
3412          array_unshift( $default_types, 'src' );
3413      } else {
3414          foreach ( $default_types as $ext ) {
3415              if ( ! empty( $atts[ $ext ] ) ) {
3416                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
3417  
3418                  if ( strtolower( $type['ext'] ) === $ext ) {
3419                      $primary = true;
3420                  }
3421              }
3422          }
3423      }
3424  
3425      if ( ! $primary ) {
3426          $audios = get_attached_media( 'audio', $post_id );
3427  
3428          if ( empty( $audios ) ) {
3429              return;
3430          }
3431  
3432          $audio       = reset( $audios );
3433          $atts['src'] = wp_get_attachment_url( $audio->ID );
3434  
3435          if ( empty( $atts['src'] ) ) {
3436              return;
3437          }
3438  
3439          array_unshift( $default_types, 'src' );
3440      }
3441  
3442      /**
3443       * Filters the media library used for the audio shortcode.
3444       *
3445       * @since 3.6.0
3446       *
3447       * @param string $library Media library used for the audio shortcode.
3448       */
3449      $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
3450  
3451      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3452          wp_enqueue_style( 'wp-mediaelement' );
3453          wp_enqueue_script( 'wp-mediaelement' );
3454      }
3455  
3456      /**
3457       * Filters the class attribute for the audio shortcode output container.
3458       *
3459       * @since 3.6.0
3460       * @since 4.9.0 The `$atts` parameter was added.
3461       *
3462       * @param string $class CSS class or list of space-separated classes.
3463       * @param array  $atts  Array of audio shortcode attributes.
3464       */
3465      $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
3466  
3467      $html_atts = array(
3468          'class'    => $atts['class'],
3469          'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
3470          'loop'     => wp_validate_boolean( $atts['loop'] ),
3471          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3472          'muted'    => wp_validate_boolean( $atts['muted'] ),
3473          'preload'  => $atts['preload'],
3474          'style'    => $atts['style'],
3475      );
3476  
3477      // These ones should just be omitted altogether if they are blank.
3478      foreach ( array( 'loop', 'autoplay', 'preload', 'muted' ) as $a ) {
3479          if ( empty( $html_atts[ $a ] ) ) {
3480              unset( $html_atts[ $a ] );
3481          }
3482      }
3483  
3484      $attr_strings = array();
3485  
3486      foreach ( $html_atts as $attribute_name => $attribute_value ) {
3487          if ( in_array( $attribute_name, array( 'loop', 'autoplay', 'muted' ), true ) && true === $attribute_value ) {
3488              // Add boolean attributes without a value.
3489              $attr_strings[] = esc_attr( $attribute_name );
3490          } elseif ( 'preload' === $attribute_name && ! empty( $attribute_value ) ) {
3491              // Handle the preload attribute with specific allowed values.
3492              $allowed_preload_values = array( 'none', 'metadata', 'auto' );
3493              if ( in_array( $attribute_value, $allowed_preload_values, true ) ) {
3494                  $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
3495              }
3496          } else {
3497              // For other attributes, include the value.
3498              $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
3499          }
3500      }
3501  
3502      $html    = sprintf( '<audio %s controls="controls">', implode( ' ', $attr_strings ) );
3503      $fileurl = '';
3504      $source  = '<source type="%s" src="%s" />';
3505  
3506      foreach ( $default_types as $fallback ) {
3507          if ( ! empty( $atts[ $fallback ] ) ) {
3508              if ( empty( $fileurl ) ) {
3509                  $fileurl = $atts[ $fallback ];
3510              }
3511  
3512              $type  = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3513              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3514              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3515          }
3516      }
3517  
3518      if ( 'mediaelement' === $library ) {
3519          $html .= wp_mediaelement_fallback( $fileurl );
3520      }
3521  
3522      $html .= '</audio>';
3523  
3524      /**
3525       * Filters the audio shortcode output.
3526       *
3527       * @since 3.6.0
3528       *
3529       * @param string $html    Audio shortcode HTML output.
3530       * @param array  $atts    Array of audio shortcode attributes.
3531       * @param string $audio   Audio file.
3532       * @param int    $post_id Post ID.
3533       * @param string $library Media library used for the audio shortcode.
3534       */
3535      return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
3536  }
3537  add_shortcode( 'audio', 'wp_audio_shortcode' );
3538  
3539  /**
3540   * Returns a filtered list of supported video formats.
3541   *
3542   * @since 3.6.0
3543   *
3544   * @return string[] List of supported video formats.
3545   */
3546  function wp_get_video_extensions() {
3547      /**
3548       * Filters the list of supported video formats.
3549       *
3550       * @since 3.6.0
3551       *
3552       * @param string[] $extensions An array of supported video formats. Defaults are
3553       *                             'mp4', 'm4v', 'webm', 'ogv', 'flv'.
3554       */
3555      return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
3556  }
3557  
3558  /**
3559   * Builds the Video shortcode output.
3560   *
3561   * This implements the functionality of the Video Shortcode for displaying
3562   * WordPress mp4s in a post.
3563   *
3564   * @since 3.6.0
3565   *
3566   * @global int $content_width
3567   *
3568   * @param array  $attr {
3569   *     Attributes of the shortcode.
3570   *
3571   *     @type string $src      URL to the source of the video file. Default empty.
3572   *     @type int    $height   Height of the video embed in pixels. Default 360.
3573   *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
3574   *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
3575   *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
3576   *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
3577   *     @type string $muted    The 'muted' attribute for the `<video>` element. Default false.
3578   *     @type string $preload  The 'preload' attribute for the `<video>` element.
3579   *                            Default 'metadata'.
3580   *     @type string $class    The 'class' attribute for the `<video>` element.
3581   *                            Default 'wp-video-shortcode'.
3582   * }
3583   * @param string $content Shortcode content.
3584   * @return string|void HTML content to display video.
3585   */
3586  function wp_video_shortcode( $attr, $content = '' ) {
3587      global $content_width;
3588      $post_id = get_post() ? get_the_ID() : 0;
3589  
3590      static $instance = 0;
3591      ++$instance;
3592  
3593      /**
3594       * Filters the default video shortcode output.
3595       *
3596       * If the filtered output isn't empty, it will be used instead of generating
3597       * the default video template.
3598       *
3599       * @since 3.6.0
3600       *
3601       * @see wp_video_shortcode()
3602       *
3603       * @param string $html     Empty variable to be replaced with shortcode markup.
3604       * @param array  $attr     Attributes of the shortcode. See {@see wp_video_shortcode()}.
3605       * @param string $content  Video shortcode content.
3606       * @param int    $instance Unique numeric ID of this video shortcode instance.
3607       */
3608      $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
3609  
3610      if ( '' !== $override ) {
3611          return $override;
3612      }
3613  
3614      $video = null;
3615  
3616      $default_types = wp_get_video_extensions();
3617      $defaults_atts = array(
3618          'src'      => '',
3619          'poster'   => '',
3620          'loop'     => '',
3621          'autoplay' => '',
3622          'muted'    => 'false',
3623          'preload'  => 'metadata',
3624          'width'    => 640,
3625          'height'   => 360,
3626          'class'    => 'wp-video-shortcode',
3627      );
3628  
3629      foreach ( $default_types as $type ) {
3630          $defaults_atts[ $type ] = '';
3631      }
3632  
3633      $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
3634  
3635      if ( is_admin() ) {
3636          // Shrink the video so it isn't huge in the admin.
3637          if ( $atts['width'] > $defaults_atts['width'] ) {
3638              $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
3639              $atts['width']  = $defaults_atts['width'];
3640          }
3641      } else {
3642          // If the video is bigger than the theme.
3643          if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
3644              $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
3645              $atts['width']  = $content_width;
3646          }
3647      }
3648  
3649      $is_vimeo      = false;
3650      $is_youtube    = false;
3651      $yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
3652      $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
3653  
3654      $primary = false;
3655      if ( ! empty( $atts['src'] ) ) {
3656          $is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
3657          $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
3658  
3659          if ( ! $is_youtube && ! $is_vimeo ) {
3660              $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
3661  
3662              if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
3663                  return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
3664              }
3665          }
3666  
3667          if ( $is_vimeo ) {
3668              wp_enqueue_script( 'mediaelement-vimeo' );
3669          }
3670  
3671          $primary = true;
3672          array_unshift( $default_types, 'src' );
3673      } else {
3674          foreach ( $default_types as $ext ) {
3675              if ( ! empty( $atts[ $ext ] ) ) {
3676                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
3677                  if ( strtolower( $type['ext'] ) === $ext ) {
3678                      $primary = true;
3679                  }
3680              }
3681          }
3682      }
3683  
3684      if ( ! $primary ) {
3685          $videos = get_attached_media( 'video', $post_id );
3686          if ( empty( $videos ) ) {
3687              return;
3688          }
3689  
3690          $video       = reset( $videos );
3691          $atts['src'] = wp_get_attachment_url( $video->ID );
3692          if ( empty( $atts['src'] ) ) {
3693              return;
3694          }
3695  
3696          array_unshift( $default_types, 'src' );
3697      }
3698  
3699      /**
3700       * Filters the media library used for the video shortcode.
3701       *
3702       * @since 3.6.0
3703       *
3704       * @param string $library Media library used for the video shortcode.
3705       */
3706      $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
3707      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3708          wp_enqueue_style( 'wp-mediaelement' );
3709          wp_enqueue_script( 'wp-mediaelement' );
3710          wp_enqueue_script( 'mediaelement-vimeo' );
3711      }
3712  
3713      /*
3714       * MediaElement.js has issues with some URL formats for Vimeo and YouTube,
3715       * so update the URL to prevent the ME.js player from breaking.
3716       */
3717      if ( 'mediaelement' === $library ) {
3718          if ( $is_youtube ) {
3719              // Remove `feature` query arg and force SSL - see #40866.
3720              $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
3721              $atts['src'] = set_url_scheme( $atts['src'], 'https' );
3722          } elseif ( $is_vimeo ) {
3723              // Remove all query arguments and force SSL - see #40866.
3724              $parsed_vimeo_url = wp_parse_url( $atts['src'] );
3725              $vimeo_src        = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
3726  
3727              // Add loop param for mejs bug - see #40977, not needed after #39686.
3728              $loop        = $atts['loop'] ? '1' : '0';
3729              $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
3730          }
3731      }
3732  
3733      /**
3734       * Filters the class attribute for the video shortcode output container.
3735       *
3736       * @since 3.6.0
3737       * @since 4.9.0 The `$atts` parameter was added.
3738       *
3739       * @param string $class CSS class or list of space-separated classes.
3740       * @param array  $atts  Array of video shortcode attributes.
3741       */
3742      $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
3743  
3744      $html_atts = array(
3745          'class'    => $atts['class'],
3746          'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
3747          'width'    => absint( $atts['width'] ),
3748          'height'   => absint( $atts['height'] ),
3749          'poster'   => esc_url( $atts['poster'] ),
3750          'loop'     => wp_validate_boolean( $atts['loop'] ),
3751          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3752          'muted'    => wp_validate_boolean( $atts['muted'] ),
3753          'preload'  => $atts['preload'],
3754      );
3755  
3756      // These ones should just be omitted altogether if they are blank.
3757      foreach ( array( 'poster', 'loop', 'autoplay', 'preload', 'muted' ) as $a ) {
3758          if ( empty( $html_atts[ $a ] ) ) {
3759              unset( $html_atts[ $a ] );
3760          }
3761      }
3762  
3763      $attr_strings = array();
3764      foreach ( $html_atts as $attribute_name => $attribute_value ) {
3765          if ( in_array( $attribute_name, array( 'loop', 'autoplay', 'muted' ), true ) && true === $attribute_value ) {
3766              // Add boolean attributes without their value for true.
3767              $attr_strings[] = esc_attr( $attribute_name );
3768          } elseif ( 'preload' === $attribute_name && ! empty( $attribute_value ) ) {
3769              // Handle the preload attribute with specific allowed values.
3770              $allowed_preload_values = array( 'none', 'metadata', 'auto' );
3771              if ( in_array( $attribute_value, $allowed_preload_values, true ) ) {
3772                  $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
3773              }
3774          } elseif ( ! empty( $attribute_value ) ) {
3775              // For non-boolean attributes, add them with their value.
3776              $attr_strings[] = sprintf( '%s="%s"', esc_attr( $attribute_name ), esc_attr( $attribute_value ) );
3777          }
3778      }
3779  
3780      $html    = sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) );
3781      $fileurl = '';
3782      $source  = '<source type="%s" src="%s" />';
3783  
3784      foreach ( $default_types as $fallback ) {
3785          if ( ! empty( $atts[ $fallback ] ) ) {
3786              if ( empty( $fileurl ) ) {
3787                  $fileurl = $atts[ $fallback ];
3788              }
3789              if ( 'src' === $fallback && $is_youtube ) {
3790                  $type = array( 'type' => 'video/youtube' );
3791              } elseif ( 'src' === $fallback && $is_vimeo ) {
3792                  $type = array( 'type' => 'video/vimeo' );
3793              } else {
3794                  $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3795              }
3796              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3797              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3798          }
3799      }
3800  
3801      if ( ! empty( $content ) ) {
3802          if ( str_contains( $content, "\n" ) ) {
3803              $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
3804          }
3805          $html .= trim( $content );
3806      }
3807  
3808      if ( 'mediaelement' === $library ) {
3809          $html .= wp_mediaelement_fallback( $fileurl );
3810      }
3811      $html .= '</video>';
3812  
3813      $width_rule = '';
3814      if ( ! empty( $atts['width'] ) ) {
3815          $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
3816      }
3817      $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
3818  
3819      /**
3820       * Filters the output of the video shortcode.
3821       *
3822       * @since 3.6.0
3823       *
3824       * @param string $output  Video shortcode HTML output.
3825       * @param array  $atts    Array of video shortcode attributes.
3826       * @param string $video   Video file.
3827       * @param int    $post_id Post ID.
3828       * @param string $library Media library used for the video shortcode.
3829       */
3830      return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
3831  }
3832  add_shortcode( 'video', 'wp_video_shortcode' );
3833  
3834  /**
3835   * Gets the previous image link that has the same post parent.
3836   *
3837   * @since 5.8.0
3838   *
3839   * @see get_adjacent_image_link()
3840   *
3841   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3842   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3843   * @param string|false $text Optional. Link text. Default false.
3844   * @return string Markup for previous image link.
3845   */
3846  function get_previous_image_link( $size = 'thumbnail', $text = false ) {
3847      return get_adjacent_image_link( true, $size, $text );
3848  }
3849  
3850  /**
3851   * Displays previous image link that has the same post parent.
3852   *
3853   * @since 2.5.0
3854   *
3855   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3856   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3857   * @param string|false $text Optional. Link text. Default false.
3858   */
3859  function previous_image_link( $size = 'thumbnail', $text = false ) {
3860      echo get_previous_image_link( $size, $text );
3861  }
3862  
3863  /**
3864   * Gets the next image link that has the same post parent.
3865   *
3866   * @since 5.8.0
3867   *
3868   * @see get_adjacent_image_link()
3869   *
3870   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3871   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3872   * @param string|false $text Optional. Link text. Default false.
3873   * @return string Markup for next image link.
3874   */
3875  function get_next_image_link( $size = 'thumbnail', $text = false ) {
3876      return get_adjacent_image_link( false, $size, $text );
3877  }
3878  
3879  /**
3880   * Displays next image link that has the same post parent.
3881   *
3882   * @since 2.5.0
3883   *
3884   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3885   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3886   * @param string|false $text Optional. Link text. Default false.
3887   */
3888  function next_image_link( $size = 'thumbnail', $text = false ) {
3889      echo get_next_image_link( $size, $text );
3890  }
3891  
3892  /**
3893   * Gets the next or previous image link that has the same post parent.
3894   *
3895   * Retrieves the current attachment object from the $post global.
3896   *
3897   * @since 5.8.0
3898   *
3899   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3900   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3901   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3902   * @param bool         $text Optional. Link text. Default false.
3903   * @return string Markup for image link.
3904   */
3905  function get_adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3906      $post        = get_post();
3907      $attachments = array_values(
3908          get_children(
3909              array(
3910                  'post_parent'    => $post->post_parent,
3911                  'post_status'    => 'inherit',
3912                  'post_type'      => 'attachment',
3913                  'post_mime_type' => 'image',
3914                  'order'          => 'ASC',
3915                  'orderby'        => 'menu_order ID',
3916              )
3917          )
3918      );
3919  
3920      foreach ( $attachments as $k => $attachment ) {
3921          if ( (int) $attachment->ID === (int) $post->ID ) {
3922              break;
3923          }
3924      }
3925  
3926      $output        = '';
3927      $attachment_id = 0;
3928  
3929      if ( $attachments ) {
3930          $k = $prev ? $k - 1 : $k + 1;
3931  
3932          if ( isset( $attachments[ $k ] ) ) {
3933              $attachment_id = $attachments[ $k ]->ID;
3934              $attr          = array( 'alt' => get_the_title( $attachment_id ) );
3935              $output        = wp_get_attachment_link( $attachment_id, $size, true, false, $text, $attr );
3936          }
3937      }
3938  
3939      $adjacent = $prev ? 'previous' : 'next';
3940  
3941      /**
3942       * Filters the adjacent image link.
3943       *
3944       * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
3945       * either 'next', or 'previous'.
3946       *
3947       * Possible hook names include:
3948       *
3949       *  - `next_image_link`
3950       *  - `previous_image_link`
3951       *
3952       * @since 3.5.0
3953       *
3954       * @param string $output        Adjacent image HTML markup.
3955       * @param int    $attachment_id Attachment ID
3956       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
3957       *                              an array of width and height values in pixels (in that order).
3958       * @param string $text          Link text.
3959       */
3960      return apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
3961  }
3962  
3963  /**
3964   * Displays next or previous image link that has the same post parent.
3965   *
3966   * Retrieves the current attachment object from the $post global.
3967   *
3968   * @since 2.5.0
3969   *
3970   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3971   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3972   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3973   * @param bool         $text Optional. Link text. Default false.
3974   */
3975  function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3976      echo get_adjacent_image_link( $prev, $size, $text );
3977  }
3978  
3979  /**
3980   * Retrieves taxonomies attached to given the attachment.
3981   *
3982   * @since 2.5.0
3983   * @since 4.7.0 Introduced the `$output` parameter.
3984   *
3985   * @param int|array|object $attachment Attachment ID, data array, or data object.
3986   * @param string           $output     Output type. 'names' to return an array of taxonomy names,
3987   *                                     or 'objects' to return an array of taxonomy objects.
3988   *                                     Default is 'names'.
3989   * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
3990   */
3991  function get_attachment_taxonomies( $attachment, $output = 'names' ) {
3992      if ( is_int( $attachment ) ) {
3993          $attachment = get_post( $attachment );
3994      } elseif ( is_array( $attachment ) ) {
3995          $attachment = (object) $attachment;
3996      }
3997  
3998      if ( ! is_object( $attachment ) ) {
3999          return array();
4000      }
4001  
4002      $file     = get_attached_file( $attachment->ID );
4003      $filename = wp_basename( $file );
4004  
4005      $objects = array( 'attachment' );
4006  
4007      if ( str_contains( $filename, '.' ) ) {
4008          $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
4009      }
4010  
4011      if ( ! empty( $attachment->post_mime_type ) ) {
4012          $objects[] = 'attachment:' . $attachment->post_mime_type;
4013  
4014          if ( str_contains( $attachment->post_mime_type, '/' ) ) {
4015              foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
4016                  if ( ! empty( $token ) ) {
4017                      $objects[] = "attachment:$token";
4018                  }
4019              }
4020          }
4021      }
4022  
4023      $taxonomies = array();
4024  
4025      foreach ( $objects as $object ) {
4026          $taxes = get_object_taxonomies( $object, $output );
4027  
4028          if ( $taxes ) {
4029              $taxonomies = array_merge( $taxonomies, $taxes );
4030          }
4031      }
4032  
4033      if ( 'names' === $output ) {
4034          $taxonomies = array_unique( $taxonomies );
4035      }
4036  
4037      return $taxonomies;
4038  }
4039  
4040  /**
4041   * Retrieves all of the taxonomies that are registered for attachments.
4042   *
4043   * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
4044   *
4045   * @since 3.5.0
4046   *
4047   * @see get_taxonomies()
4048   *
4049   * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
4050   *                       Default 'names'.
4051   * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.
4052   */
4053  function get_taxonomies_for_attachments( $output = 'names' ) {
4054      $taxonomies = array();
4055  
4056      foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
4057          foreach ( $taxonomy->object_type as $object_type ) {
4058              if ( 'attachment' === $object_type || str_starts_with( $object_type, 'attachment:' ) ) {
4059                  if ( 'names' === $output ) {
4060                      $taxonomies[] = $taxonomy->name;
4061                  } else {
4062                      $taxonomies[ $taxonomy->name ] = $taxonomy;
4063                  }
4064                  break;
4065              }
4066          }
4067      }
4068  
4069      return $taxonomies;
4070  }
4071  
4072  /**
4073   * Determines whether the value is an acceptable type for GD image functions.
4074   *
4075   * In PHP 8.0, the GD extension uses GdImage objects for its data structures.
4076   * This function checks if the passed value is either a GdImage object instance
4077   * or a resource of type `gd`. Any other type will return false.
4078   *
4079   * @since 5.6.0
4080   *
4081   * @param resource|GdImage|false $image A value to check the type for.
4082   * @return bool True if `$image` is either a GD image resource or a GdImage instance,
4083   *              false otherwise.
4084   */
4085  function is_gd_image( $image ) {
4086      if ( $image instanceof GdImage
4087          || is_resource( $image ) && 'gd' === get_resource_type( $image )
4088      ) {
4089          return true;
4090      }
4091  
4092      return false;
4093  }
4094  
4095  /**
4096   * Creates a new GD image resource with transparency support.
4097   *
4098   * @todo Deprecate if possible.
4099   *
4100   * @since 2.9.0
4101   *
4102   * @param int $width  Image width in pixels.
4103   * @param int $height Image height in pixels.
4104   * @return resource|GdImage|false The GD image resource or GdImage instance on success.
4105   *                                False on failure.
4106   */
4107  function wp_imagecreatetruecolor( $width, $height ) {
4108      $img = imagecreatetruecolor( $width, $height );
4109  
4110      if ( is_gd_image( $img )
4111          && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' )
4112      ) {
4113          imagealphablending( $img, false );
4114          imagesavealpha( $img, true );
4115      }
4116  
4117      return $img;
4118  }
4119  
4120  /**
4121   * Based on a supplied width/height example, returns the biggest possible dimensions based on the max width/height.
4122   *
4123   * @since 2.9.0
4124   *
4125   * @see wp_constrain_dimensions()
4126   *
4127   * @param int $example_width  The width of an example embed.
4128   * @param int $example_height The height of an example embed.
4129   * @param int $max_width      The maximum allowed width.
4130   * @param int $max_height     The maximum allowed height.
4131   * @return int[] {
4132   *     An array of maximum width and height values.
4133   *
4134   *     @type int $0 The maximum width in pixels.
4135   *     @type int $1 The maximum height in pixels.
4136   * }
4137   */
4138  function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
4139      $example_width  = (int) $example_width;
4140      $example_height = (int) $example_height;
4141      $max_width      = (int) $max_width;
4142      $max_height     = (int) $max_height;
4143  
4144      return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
4145  }
4146  
4147  /**
4148   * Determines the maximum upload size allowed in php.ini.
4149   *
4150   * @since 2.5.0
4151   *
4152   * @return int Allowed upload size.
4153   */
4154  function wp_max_upload_size() {
4155      $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
4156      $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
4157  
4158      /**
4159       * Filters the maximum upload size allowed in php.ini.
4160       *
4161       * @since 2.5.0
4162       *
4163       * @param int $size    Max upload size limit in bytes.
4164       * @param int $u_bytes Maximum upload filesize in bytes.
4165       * @param int $p_bytes Maximum size of POST data in bytes.
4166       */
4167      return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
4168  }
4169  
4170  /**
4171   * Returns a WP_Image_Editor instance and loads file into it.
4172   *
4173   * @since 3.5.0
4174   *
4175   * @param string $path Path to the file to load.
4176   * @param array  $args Optional. Additional arguments for retrieving the image editor.
4177   *                     Default empty array.
4178   * @return WP_Image_Editor|WP_Error The WP_Image_Editor object on success,
4179   *                                  a WP_Error object otherwise.
4180   */
4181  function wp_get_image_editor( $path, $args = array() ) {
4182      $args['path'] = $path;
4183  
4184      // If the mime type is not set in args, try to extract and set it from the file.
4185      if ( ! isset( $args['mime_type'] ) ) {
4186          $file_info = wp_check_filetype( $args['path'] );
4187  
4188          /*
4189           * If $file_info['type'] is false, then we let the editor attempt to
4190           * figure out the file type, rather than forcing a failure based on extension.
4191           */
4192          if ( isset( $file_info ) && $file_info['type'] ) {
4193              $args['mime_type'] = $file_info['type'];
4194          }
4195      }
4196  
4197      // Check and set the output mime type mapped to the input type.
4198      if ( isset( $args['mime_type'] ) ) {
4199          $output_format = wp_get_image_editor_output_format( $path, $args['mime_type'] );
4200          if ( isset( $output_format[ $args['mime_type'] ] ) ) {
4201              $args['output_mime_type'] = $output_format[ $args['mime_type'] ];
4202          }
4203      }
4204  
4205      $implementation = _wp_image_editor_choose( $args );
4206  
4207      if ( $implementation ) {
4208          $editor = new $implementation( $path );
4209          $loaded = $editor->load();
4210  
4211          if ( is_wp_error( $loaded ) ) {
4212              return $loaded;
4213          }
4214  
4215          return $editor;
4216      }
4217  
4218      return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
4219  }
4220  
4221  /**
4222   * Tests whether there is an editor that supports a given mime type or methods.
4223   *
4224   * @since 3.5.0
4225   *
4226   * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
4227   *                           Default empty array.
4228   * @return bool True if an eligible editor is found; false otherwise.
4229   */
4230  function wp_image_editor_supports( $args = array() ) {
4231      return (bool) _wp_image_editor_choose( $args );
4232  }
4233  
4234  /**
4235   * Tests which editors are capable of supporting the request.
4236   *
4237   * @ignore
4238   * @since 3.5.0
4239   *
4240   * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
4241   * @return string|false Class name for the first editor that claims to support the request.
4242   *                      False if no editor claims to support the request.
4243   */
4244  function _wp_image_editor_choose( $args = array() ) {
4245      require_once  ABSPATH . WPINC . '/class-wp-image-editor.php';
4246      require_once  ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
4247      require_once  ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
4248      require_once  ABSPATH . WPINC . '/class-avif-info.php';
4249      /**
4250       * Filters the list of image editing library classes.
4251       *
4252       * @since 3.5.0
4253       *
4254       * @param string[] $image_editors Array of available image editor class names. Defaults are
4255       *                                'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
4256       */
4257      $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
4258  
4259      $editors = wp_cache_get( 'wp_image_editor_choose', 'image_editor' );
4260  
4261      if ( ! is_array( $editors ) ) {
4262          $editors = array();
4263      }
4264  
4265      // Cache the chosen editor implementation based on specific args and available implementations.
4266      $cache_key = md5( serialize( array( $args, $implementations ) ) );
4267  
4268      if ( isset( $editors[ $cache_key ] ) ) {
4269          return $editors[ $cache_key ];
4270      }
4271  
4272      // Assume no support until a capable implementation is identified.
4273      $editor = false;
4274  
4275      foreach ( $implementations as $implementation ) {
4276          if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) {
4277              continue;
4278          }
4279  
4280          // Implementation should support the passed mime type.
4281          if ( isset( $args['mime_type'] ) &&
4282              ! call_user_func(
4283                  array( $implementation, 'supports_mime_type' ),
4284                  $args['mime_type']
4285              ) ) {
4286              continue;
4287          }
4288  
4289          // Implementation should support requested methods.
4290          if ( isset( $args['methods'] ) &&
4291              array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
4292  
4293              continue;
4294          }
4295  
4296          // Implementation should ideally support the output mime type as well if set and different than the passed type.
4297          if (
4298              isset( $args['mime_type'] ) &&
4299              isset( $args['output_mime_type'] ) &&
4300              $args['mime_type'] !== $args['output_mime_type'] &&
4301              ! call_user_func( array( $implementation, 'supports_mime_type' ), $args['output_mime_type'] )
4302          ) {
4303              /*
4304               * This implementation supports the input type but not the output type.
4305               * Keep looking to see if we can find an implementation that supports both.
4306               */
4307              $editor = $implementation;
4308              continue;
4309          }
4310  
4311          // Favor the implementation that supports both input and output mime types.
4312          $editor = $implementation;
4313          break;
4314      }
4315  
4316      $editors[ $cache_key ] = $editor;
4317  
4318      wp_cache_set( 'wp_image_editor_choose', $editors, 'image_editor', DAY_IN_SECONDS );
4319  
4320      return $editor;
4321  }
4322  
4323  /**
4324   * Prints default Plupload arguments.
4325   *
4326   * @since 3.4.0
4327   */
4328  function wp_plupload_default_settings() {
4329      $wp_scripts = wp_scripts();
4330  
4331      $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
4332      if ( $data && str_contains( $data, '_wpPluploadSettings' ) ) {
4333          return;
4334      }
4335  
4336      $max_upload_size    = wp_max_upload_size();
4337      $allowed_extensions = array_keys( get_allowed_mime_types() );
4338      $extensions         = array();
4339      foreach ( $allowed_extensions as $extension ) {
4340          $extensions = array_merge( $extensions, explode( '|', $extension ) );
4341      }
4342  
4343      /*
4344       * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
4345       * and the `flash_swf_url` and `silverlight_xap_url` are not used.
4346       */
4347      $defaults = array(
4348          'file_data_name' => 'async-upload', // Key passed to $_FILE.
4349          'url'            => admin_url( 'async-upload.php', 'relative' ),
4350          'filters'        => array(
4351              'max_file_size' => $max_upload_size . 'b',
4352              'mime_types'    => array( array( 'extensions' => implode( ',', $extensions ) ) ),
4353          ),
4354      );
4355  
4356      /*
4357       * Currently only iOS Safari supports multiple files uploading,
4358       * but iOS 7.x has a bug that prevents uploading of videos when enabled.
4359       * See #29602.
4360       */
4361      if ( wp_is_mobile()
4362          && str_contains( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' )
4363          && str_contains( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' )
4364      ) {
4365          $defaults['multi_selection'] = false;
4366      }
4367  
4368      // Check if WebP images can be edited.
4369      if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ) ) {
4370          $defaults['webp_upload_error'] = true;
4371      }
4372  
4373      // Check if AVIF images can be edited.
4374      if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/avif' ) ) ) {
4375          $defaults['avif_upload_error'] = true;
4376      }
4377  
4378      // Check if HEIC images can be edited.
4379      if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/heic' ) ) ) {
4380          $defaults['heic_upload_error'] = true;
4381      }
4382  
4383      /**
4384       * Filters the Plupload default settings.
4385       *
4386       * @since 3.4.0
4387       *
4388       * @param array $defaults Default Plupload settings array.
4389       */
4390      $defaults = apply_filters( 'plupload_default_settings', $defaults );
4391  
4392      $params = array(
4393          'action' => 'upload-attachment',
4394      );
4395  
4396      /**
4397       * Filters the Plupload default parameters.
4398       *
4399       * @since 3.4.0
4400       *
4401       * @param array $params Default Plupload parameters array.
4402       */
4403      $params = apply_filters( 'plupload_default_params', $params );
4404  
4405      $params['_wpnonce'] = wp_create_nonce( 'media-form' );
4406  
4407      $defaults['multipart_params'] = $params;
4408  
4409      $settings = array(
4410          'defaults'      => $defaults,
4411          'browser'       => array(
4412              'mobile'    => wp_is_mobile(),
4413              'supported' => _device_can_upload(),
4414          ),
4415          'limitExceeded' => is_multisite() && ! is_upload_space_available(),
4416      );
4417  
4418      $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
4419  
4420      if ( $data ) {
4421          $script = "$data\n$script";
4422      }
4423  
4424      $wp_scripts->add_data( 'wp-plupload', 'data', $script );
4425  }
4426  
4427  /**
4428   * Prepares an attachment post object for JS, where it is expected
4429   * to be JSON-encoded and fit into an Attachment model.
4430   *
4431   * @since 3.5.0
4432   *
4433   * @param int|WP_Post $attachment Attachment ID or object.
4434   * @return array|void {
4435   *     Array of attachment details, or void if the parameter does not correspond to an attachment.
4436   *
4437   *     @type string $alt                   Alt text of the attachment.
4438   *     @type string $author                ID of the attachment author, as a string.
4439   *     @type string $authorName            Name of the attachment author.
4440   *     @type string $caption               Caption for the attachment.
4441   *     @type array  $compat                Containing item and meta.
4442   *     @type string $context               Context, whether it's used as the site icon for example.
4443   *     @type int    $date                  Uploaded date, timestamp in milliseconds.
4444   *     @type string $dateFormatted         Formatted date (e.g. June 29, 2018).
4445   *     @type string $description           Description of the attachment.
4446   *     @type string $editLink              URL to the edit page for the attachment.
4447   *     @type string $filename              File name of the attachment.
4448   *     @type string $filesizeHumanReadable Filesize of the attachment in human readable format (e.g. 1 MB).
4449   *     @type int    $filesizeInBytes       Filesize of the attachment in bytes.
4450   *     @type int    $height                If the attachment is an image, represents the height of the image in pixels.
4451   *     @type string $icon                  Icon URL of the attachment (e.g. /wp-includes/images/media/archive.png).
4452   *     @type int    $id                    ID of the attachment.
4453   *     @type string $link                  URL to the attachment.
4454   *     @type int    $menuOrder             Menu order of the attachment post.
4455   *     @type array  $meta                  Meta data for the attachment.
4456   *     @type string $mime                  Mime type of the attachment (e.g. image/jpeg or application/zip).
4457   *     @type int    $modified              Last modified, timestamp in milliseconds.
4458   *     @type string $name                  Name, same as title of the attachment.
4459   *     @type array  $nonces                Nonces for update, delete and edit.
4460   *     @type string $orientation           If the attachment is an image, represents the image orientation
4461   *                                         (landscape or portrait).
4462   *     @type array  $sizes                 If the attachment is an image, contains an array of arrays
4463   *                                         for the images sizes: thumbnail, medium, large, and full.
4464   *     @type string $status                Post status of the attachment (usually 'inherit').
4465   *     @type string $subtype               Mime subtype of the attachment (usually the last part, e.g. jpeg or zip).
4466   *     @type string $title                 Title of the attachment (usually slugified file name without the extension).
4467   *     @type string $type                  Type of the attachment (usually first part of the mime type, e.g. image).
4468   *     @type int    $uploadedTo            Parent post to which the attachment was uploaded.
4469   *     @type string $uploadedToLink        URL to the edit page of the parent post of the attachment.
4470   *     @type string $uploadedToTitle       Post title of the parent of the attachment.
4471   *     @type string $url                   Direct URL to the attachment file (from wp-content).
4472   *     @type int    $width                 If the attachment is an image, represents the width of the image in pixels.
4473   * }
4474   */
4475  function wp_prepare_attachment_for_js( $attachment ) {
4476      $attachment = get_post( $attachment );
4477  
4478      if ( ! $attachment ) {
4479          return;
4480      }
4481  
4482      if ( 'attachment' !== $attachment->post_type ) {
4483          return;
4484      }
4485  
4486      $meta = wp_get_attachment_metadata( $attachment->ID );
4487      if ( str_contains( $attachment->post_mime_type, '/' ) ) {
4488          list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
4489      } else {
4490          list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
4491      }
4492  
4493      $attachment_url = wp_get_attachment_url( $attachment->ID );
4494      $base_url       = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
4495  
4496      $response = array(
4497          'id'            => $attachment->ID,
4498          'title'         => $attachment->post_title,
4499          'filename'      => wp_basename( get_attached_file( $attachment->ID ) ),
4500          'url'           => $attachment_url,
4501          'link'          => get_attachment_link( $attachment->ID ),
4502          'alt'           => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
4503          'author'        => $attachment->post_author,
4504          'description'   => $attachment->post_content,
4505          'caption'       => $attachment->post_excerpt,
4506          'name'          => $attachment->post_name,
4507          'status'        => $attachment->post_status,
4508          'uploadedTo'    => $attachment->post_parent,
4509          'date'          => strtotime( $attachment->post_date_gmt ) * 1000,
4510          'modified'      => strtotime( $attachment->post_modified_gmt ) * 1000,
4511          'menuOrder'     => $attachment->menu_order,
4512          'mime'          => $attachment->post_mime_type,
4513          'type'          => $type,
4514          'subtype'       => $subtype,
4515          'icon'          => wp_mime_type_icon( $attachment->ID, '.svg' ),
4516          'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
4517          'nonces'        => array(
4518              'update' => false,
4519              'delete' => false,
4520              'edit'   => false,
4521          ),
4522          'editLink'      => false,
4523          'meta'          => false,
4524      );
4525  
4526      $author = new WP_User( $attachment->post_author );
4527  
4528      if ( $author->exists() ) {
4529          $author_name            = $author->display_name ? $author->display_name : $author->nickname;
4530          $response['authorName'] = html_entity_decode( $author_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
4531          $response['authorLink'] = get_edit_user_link( $author->ID );
4532      } else {
4533          $response['authorName'] = __( '(no author)' );
4534      }
4535  
4536      if ( $attachment->post_parent ) {
4537          $post_parent = get_post( $attachment->post_parent );
4538          if ( $post_parent ) {
4539              $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
4540              $response['uploadedToLink']  = get_edit_post_link( $attachment->post_parent, 'raw' );
4541          }
4542      }
4543  
4544      $attached_file = get_attached_file( $attachment->ID );
4545  
4546      if ( isset( $meta['filesize'] ) ) {
4547          $bytes = $meta['filesize'];
4548      } elseif ( file_exists( $attached_file ) ) {
4549          $bytes = wp_filesize( $attached_file );
4550      } else {
4551          $bytes = '';
4552      }
4553  
4554      if ( $bytes ) {
4555          $response['filesizeInBytes']       = $bytes;
4556          $response['filesizeHumanReadable'] = size_format( $bytes );
4557      }
4558  
4559      $context             = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
4560      $response['context'] = ( $context ) ? $context : '';
4561  
4562      if ( current_user_can( 'edit_post', $attachment->ID ) ) {
4563          $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
4564          $response['nonces']['edit']   = wp_create_nonce( 'image_editor-' . $attachment->ID );
4565          $response['editLink']         = get_edit_post_link( $attachment->ID, 'raw' );
4566      }
4567  
4568      if ( current_user_can( 'delete_post', $attachment->ID ) ) {
4569          $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
4570      }
4571  
4572      if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
4573          $sizes = array();
4574  
4575          /** This filter is documented in wp-admin/includes/media.php */
4576          $possible_sizes = apply_filters(
4577              'image_size_names_choose',
4578              array(
4579                  'thumbnail' => __( 'Thumbnail' ),
4580                  'medium'    => __( 'Medium' ),
4581                  'large'     => __( 'Large' ),
4582                  'full'      => __( 'Full Size' ),
4583              )
4584          );
4585          unset( $possible_sizes['full'] );
4586  
4587          /*
4588           * Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
4589           * First: run the image_downsize filter. If it returns something, we can use its data.
4590           * If the filter does not return something, then image_downsize() is just an expensive way
4591           * to check the image metadata, which we do second.
4592           */
4593          foreach ( $possible_sizes as $size => $label ) {
4594  
4595              /** This filter is documented in wp-includes/media.php */
4596              $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
4597  
4598              if ( $downsize ) {
4599                  if ( empty( $downsize[3] ) ) {
4600                      continue;
4601                  }
4602  
4603                  $sizes[ $size ] = array(
4604                      'height'      => $downsize[2],
4605                      'width'       => $downsize[1],
4606                      'url'         => $downsize[0],
4607                      'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
4608                  );
4609              } elseif ( isset( $meta['sizes'][ $size ] ) ) {
4610                  // Nothing from the filter, so consult image metadata if we have it.
4611                  $size_meta = $meta['sizes'][ $size ];
4612  
4613                  /*
4614                   * We have the actual image size, but might need to further constrain it if content_width is narrower.
4615                   * Thumbnail, medium, and full sizes are also checked against the site's height/width options.
4616                   */
4617                  list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
4618  
4619                  $sizes[ $size ] = array(
4620                      'height'      => $height,
4621                      'width'       => $width,
4622                      'url'         => $base_url . $size_meta['file'],
4623                      'orientation' => $height > $width ? 'portrait' : 'landscape',
4624                  );
4625              }
4626          }
4627  
4628          if ( 'image' === $type ) {
4629              if ( ! empty( $meta['original_image'] ) ) {
4630                  $response['originalImageURL']  = wp_get_original_image_url( $attachment->ID );
4631                  $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
4632              }
4633  
4634              $sizes['full'] = array( 'url' => $attachment_url );
4635  
4636              if ( isset( $meta['height'], $meta['width'] ) ) {
4637                  $sizes['full']['height']      = $meta['height'];
4638                  $sizes['full']['width']       = $meta['width'];
4639                  $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
4640              }
4641  
4642              $response = array_merge( $response, $sizes['full'] );
4643          } elseif ( $meta['sizes']['full']['file'] ) {
4644              $sizes['full'] = array(
4645                  'url'         => $base_url . $meta['sizes']['full']['file'],
4646                  'height'      => $meta['sizes']['full']['height'],
4647                  'width'       => $meta['sizes']['full']['width'],
4648                  'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape',
4649              );
4650          }
4651  
4652          $response = array_merge( $response, array( 'sizes' => $sizes ) );
4653      }
4654  
4655      if ( $meta && 'video' === $type ) {
4656          if ( isset( $meta['width'] ) ) {
4657              $response['width'] = (int) $meta['width'];
4658          }
4659          if ( isset( $meta['height'] ) ) {
4660              $response['height'] = (int) $meta['height'];
4661          }
4662      }
4663  
4664      if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
4665          if ( isset( $meta['length_formatted'] ) ) {
4666              $response['fileLength']              = $meta['length_formatted'];
4667              $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] );
4668          }
4669  
4670          $response['meta'] = array();
4671          foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
4672              $response['meta'][ $key ] = false;
4673  
4674              if ( ! empty( $meta[ $key ] ) ) {
4675                  $response['meta'][ $key ] = $meta[ $key ];
4676              }
4677          }
4678  
4679          $id = get_post_thumbnail_id( $attachment->ID );
4680          if ( ! empty( $id ) ) {
4681              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
4682              $response['image']            = compact( 'src', 'width', 'height' );
4683              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
4684              $response['thumb']            = compact( 'src', 'width', 'height' );
4685          } else {
4686              $src               = wp_mime_type_icon( $attachment->ID, '.svg' );
4687              $width             = 48;
4688              $height            = 64;
4689              $response['image'] = compact( 'src', 'width', 'height' );
4690              $response['thumb'] = compact( 'src', 'width', 'height' );
4691          }
4692      }
4693  
4694      if ( function_exists( 'get_compat_media_markup' ) ) {
4695          $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
4696      }
4697  
4698      if ( function_exists( 'get_media_states' ) ) {
4699          $media_states = get_media_states( $attachment );
4700          if ( ! empty( $media_states ) ) {
4701              $response['mediaStates'] = implode( ', ', $media_states );
4702          }
4703      }
4704  
4705      /**
4706       * Filters the attachment data prepared for JavaScript.
4707       *
4708       * @since 3.5.0
4709       *
4710       * @param array       $response   Array of prepared attachment data. See {@see wp_prepare_attachment_for_js()}.
4711       * @param WP_Post     $attachment Attachment object.
4712       * @param array|false $meta       Array of attachment meta data, or false if there is none.
4713       */
4714      return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
4715  }
4716  
4717  /**
4718   * Enqueues all scripts, styles, settings, and templates necessary to use
4719   * all media JS APIs.
4720   *
4721   * @since 3.5.0
4722   *
4723   * @global int       $content_width
4724   * @global wpdb      $wpdb          WordPress database abstraction object.
4725   * @global WP_Locale $wp_locale     WordPress date and time locale object.
4726   *
4727   * @param array $args {
4728   *     Arguments for enqueuing media scripts.
4729   *
4730   *     @type int|WP_Post $post Post ID or post object.
4731   * }
4732   */
4733  function wp_enqueue_media( $args = array() ) {
4734      // Enqueue me just once per page, please.
4735      if ( did_action( 'wp_enqueue_media' ) ) {
4736          return;
4737      }
4738  
4739      global $content_width, $wpdb, $wp_locale;
4740  
4741      $defaults = array(
4742          'post' => null,
4743      );
4744      $args     = wp_parse_args( $args, $defaults );
4745  
4746      /*
4747       * We're going to pass the old thickbox media tabs to `media_upload_tabs`
4748       * to ensure plugins will work. We will then unset those tabs.
4749       */
4750      $tabs = array(
4751          // handler action suffix => tab label
4752          'type'     => '',
4753          'type_url' => '',
4754          'gallery'  => '',
4755          'library'  => '',
4756      );
4757  
4758      /** This filter is documented in wp-admin/includes/media.php */
4759      $tabs = apply_filters( 'media_upload_tabs', $tabs );
4760      unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
4761  
4762      $props = array(
4763          'link'  => get_option( 'image_default_link_type' ), // DB default is 'file'.
4764          'align' => get_option( 'image_default_align' ),     // Empty default.
4765          'size'  => get_option( 'image_default_size' ),      // Empty default.
4766      );
4767  
4768      $exts      = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
4769      $mimes     = get_allowed_mime_types();
4770      $ext_mimes = array();
4771      foreach ( $exts as $ext ) {
4772          foreach ( $mimes as $ext_preg => $mime_match ) {
4773              if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
4774                  $ext_mimes[ $ext ] = $mime_match;
4775                  break;
4776              }
4777          }
4778      }
4779  
4780      /**
4781       * Allows showing or hiding the "Create Audio Playlist" button in the media library.
4782       *
4783       * By default, the "Create Audio Playlist" button will always be shown in
4784       * the media library.  If this filter returns `null`, a query will be run
4785       * to determine whether the media library contains any audio items.  This
4786       * was the default behavior prior to version 4.8.0, but this query is
4787       * expensive for large media libraries.
4788       *
4789       * @since 4.7.4
4790       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4791       *
4792       * @link https://core.trac.wordpress.org/ticket/31071
4793       *
4794       * @param bool|null $show Whether to show the button, or `null` to decide based
4795       *                        on whether any audio files exist in the media library.
4796       */
4797      $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
4798      if ( null === $show_audio_playlist ) {
4799          $show_audio_playlist = $wpdb->get_var(
4800              "SELECT ID
4801              FROM $wpdb->posts
4802              WHERE post_type = 'attachment'
4803              AND post_mime_type LIKE 'audio%'
4804              LIMIT 1"
4805          );
4806      }
4807  
4808      /**
4809       * Allows showing or hiding the "Create Video Playlist" button in the media library.
4810       *
4811       * By default, the "Create Video Playlist" button will always be shown in
4812       * the media library.  If this filter returns `null`, a query will be run
4813       * to determine whether the media library contains any video items.  This
4814       * was the default behavior prior to version 4.8.0, but this query is
4815       * expensive for large media libraries.
4816       *
4817       * @since 4.7.4
4818       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4819       *
4820       * @link https://core.trac.wordpress.org/ticket/31071
4821       *
4822       * @param bool|null $show Whether to show the button, or `null` to decide based
4823       *                        on whether any video files exist in the media library.
4824       */
4825      $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
4826      if ( null === $show_video_playlist ) {
4827          $show_video_playlist = $wpdb->get_var(
4828              "SELECT ID
4829              FROM $wpdb->posts
4830              WHERE post_type = 'attachment'
4831              AND post_mime_type LIKE 'video%'
4832              LIMIT 1"
4833          );
4834      }
4835  
4836      /**
4837       * Allows overriding the list of months displayed in the media library.
4838       *
4839       * By default (if this filter does not return an array), a query will be
4840       * run to determine the months that have media items.  This query can be
4841       * expensive for large media libraries, so it may be desirable for sites to
4842       * override this behavior.
4843       *
4844       * @since 4.7.4
4845       *
4846       * @link https://core.trac.wordpress.org/ticket/31071
4847       *
4848       * @param stdClass[]|null $months An array of objects with `month` and `year`
4849       *                                properties, or `null` for default behavior.
4850       */
4851      $months = apply_filters( 'media_library_months_with_files', null );
4852      if ( ! is_array( $months ) ) {
4853          $months = $wpdb->get_results(
4854              $wpdb->prepare(
4855                  "SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
4856                  FROM $wpdb->posts
4857                  WHERE post_type = %s
4858                  ORDER BY post_date DESC",
4859                  'attachment'
4860              )
4861          );
4862      }
4863      foreach ( $months as $month_year ) {
4864          $month_year->text = sprintf(
4865              /* translators: 1: Month, 2: Year. */
4866              __( '%1$s %2$d' ),
4867              $wp_locale->get_month( $month_year->month ),
4868              $month_year->year
4869          );
4870      }
4871  
4872      /**
4873       * Filters whether the Media Library grid has infinite scrolling. Default `false`.
4874       *
4875       * @since 5.8.0
4876       *
4877       * @param bool $infinite Whether the Media Library grid has infinite scrolling.
4878       */
4879      $infinite_scrolling = apply_filters( 'media_library_infinite_scrolling', false );
4880  
4881      $settings = array(
4882          'tabs'              => $tabs,
4883          'tabUrl'            => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ),
4884          'mimeTypes'         => wp_list_pluck( get_post_mime_types(), 0 ),
4885          /** This filter is documented in wp-admin/includes/media.php */
4886          'captions'          => ! apply_filters( 'disable_captions', '' ),
4887          'nonce'             => array(
4888              'sendToEditor'           => wp_create_nonce( 'media-send-to-editor' ),
4889              'setAttachmentThumbnail' => wp_create_nonce( 'set-attachment-thumbnail' ),
4890          ),
4891          'post'              => array(
4892              'id' => 0,
4893          ),
4894          'defaultProps'      => $props,
4895          'attachmentCounts'  => array(
4896              'audio' => ( $show_audio_playlist ) ? 1 : 0,
4897              'video' => ( $show_video_playlist ) ? 1 : 0,
4898          ),
4899          'oEmbedProxyUrl'    => rest_url( 'oembed/1.0/proxy' ),
4900          'embedExts'         => $exts,
4901          'embedMimes'        => $ext_mimes,
4902          'contentWidth'      => $content_width,
4903          'months'            => $months,
4904          'mediaTrash'        => MEDIA_TRASH ? 1 : 0,
4905          'infiniteScrolling' => ( $infinite_scrolling ) ? 1 : 0,
4906      );
4907  
4908      $post = null;
4909      if ( isset( $args['post'] ) ) {
4910          $post             = get_post( $args['post'] );
4911          $settings['post'] = array(
4912              'id'    => $post->ID,
4913              'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
4914          );
4915  
4916          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
4917          if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
4918              if ( wp_attachment_is( 'audio', $post ) ) {
4919                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
4920              } elseif ( wp_attachment_is( 'video', $post ) ) {
4921                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
4922              }
4923          }
4924  
4925          if ( $thumbnail_support ) {
4926              $featured_image_id                   = get_post_meta( $post->ID, '_thumbnail_id', true );
4927              $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
4928          }
4929      }
4930  
4931      if ( $post ) {
4932          $post_type_object = get_post_type_object( $post->post_type );
4933      } else {
4934          $post_type_object = get_post_type_object( 'post' );
4935      }
4936  
4937      $strings = array(
4938          // Generic.
4939          'mediaFrameDefaultTitle'      => __( 'Media' ),
4940          'url'                         => __( 'URL' ),
4941          'addMedia'                    => __( 'Add media' ),
4942          'search'                      => __( 'Search' ),
4943          'select'                      => __( 'Select' ),
4944          'cancel'                      => __( 'Cancel' ),
4945          'update'                      => __( 'Update' ),
4946          'replace'                     => __( 'Replace' ),
4947          'remove'                      => __( 'Remove' ),
4948          'back'                        => __( 'Back' ),
4949          /*
4950           * translators: This is a would-be plural string used in the media manager.
4951           * If there is not a word you can use in your language to avoid issues with the
4952           * lack of plural support here, turn it into "selected: %d" then translate it.
4953           */
4954          'selected'                    => __( '%d selected' ),
4955          'dragInfo'                    => __( 'Drag and drop to reorder media files.' ),
4956  
4957          // Upload.
4958          'uploadFilesTitle'            => __( 'Upload files' ),
4959          'uploadImagesTitle'           => __( 'Upload images' ),
4960  
4961          // Library.
4962          'mediaLibraryTitle'           => __( 'Media Library' ),
4963          'insertMediaTitle'            => __( 'Add media' ),
4964          'createNewGallery'            => __( 'Create a new gallery' ),
4965          'createNewPlaylist'           => __( 'Create a new playlist' ),
4966          'createNewVideoPlaylist'      => __( 'Create a new video playlist' ),
4967          'returnToLibrary'             => __( '&#8592; Go to library' ),
4968          'allMediaItems'               => __( 'All media items' ),
4969          'allDates'                    => __( 'All dates' ),
4970          'noItemsFound'                => __( 'No items found.' ),
4971          'insertIntoPost'              => $post_type_object->labels->insert_into_item,
4972          'unattached'                  => _x( 'Unattached', 'media items' ),
4973          'mine'                        => _x( 'Mine', 'media items' ),
4974          'trash'                       => _x( 'Trash', 'noun' ),
4975          'uploadedToThisPost'          => $post_type_object->labels->uploaded_to_this_item,
4976          'warnDelete'                  => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4977          'warnBulkDelete'              => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4978          'warnBulkTrash'               => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
4979          'bulkSelect'                  => __( 'Bulk select' ),
4980          'trashSelected'               => __( 'Move to Trash' ),
4981          'restoreSelected'             => __( 'Restore from Trash' ),
4982          'deletePermanently'           => __( 'Delete permanently' ),
4983          'errorDeleting'               => __( 'Error in deleting the attachment.' ),
4984          'apply'                       => __( 'Apply' ),
4985          'filterByDate'                => __( 'Filter by date' ),
4986          'filterByType'                => __( 'Filter by type' ),
4987          'searchLabel'                 => __( 'Search media' ),
4988          'searchMediaLabel'            => __( 'Search media' ),          // Backward compatibility pre-5.3.
4989          'searchMediaPlaceholder'      => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
4990          /* translators: %d: Number of attachments found in a search. */
4991          'mediaFound'                  => __( 'Number of media items found: %d' ),
4992          'noMedia'                     => __( 'No media items found.' ),
4993          'noMediaTryNewSearch'         => __( 'No media items found. Try a different search.' ),
4994  
4995          // Library Details.
4996          'attachmentDetails'           => __( 'Attachment details' ),
4997  
4998          // From URL.
4999          'insertFromUrlTitle'          => __( 'Insert from URL' ),
5000  
5001          // Featured Images.
5002          'setFeaturedImageTitle'       => $post_type_object->labels->featured_image,
5003          'setFeaturedImage'            => $post_type_object->labels->set_featured_image,
5004  
5005          // Gallery.
5006          'createGalleryTitle'          => __( 'Create gallery' ),
5007          'editGalleryTitle'            => __( 'Edit gallery' ),
5008          'cancelGalleryTitle'          => __( '&#8592; Cancel gallery' ),
5009          'insertGallery'               => __( 'Insert gallery' ),
5010          'updateGallery'               => __( 'Update gallery' ),
5011          'addToGallery'                => __( 'Add to gallery' ),
5012          'addToGalleryTitle'           => __( 'Add to gallery' ),
5013          'reverseOrder'                => __( 'Reverse order' ),
5014  
5015          // Edit Image.
5016          'imageDetailsTitle'           => __( 'Image details' ),
5017          'imageReplaceTitle'           => __( 'Replace image' ),
5018          'imageDetailsCancel'          => __( 'Cancel edit' ),
5019          'editImage'                   => __( 'Edit image' ),
5020  
5021          // Crop Image.
5022          'chooseImage'                 => __( 'Choose image' ),
5023          'selectAndCrop'               => __( 'Select and crop' ),
5024          'skipCropping'                => __( 'Skip cropping' ),
5025          'cropImage'                   => __( 'Crop image' ),
5026          'cropYourImage'               => __( 'Crop your image' ),
5027          'cropping'                    => __( 'Cropping&hellip;' ),
5028          /* translators: 1: Suggested width number, 2: Suggested height number. */
5029          'suggestedDimensions'         => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
5030          'cropError'                   => __( 'There has been an error cropping your image.' ),
5031  
5032          // Edit Audio.
5033          'audioDetailsTitle'           => __( 'Audio details' ),
5034          'audioReplaceTitle'           => __( 'Replace audio' ),
5035          'audioAddSourceTitle'         => __( 'Add audio source' ),
5036          'audioDetailsCancel'          => __( 'Cancel edit' ),
5037  
5038          // Edit Video.
5039          'videoDetailsTitle'           => __( 'Video details' ),
5040          'videoReplaceTitle'           => __( 'Replace video' ),
5041          'videoAddSourceTitle'         => __( 'Add video source' ),
5042          'videoDetailsCancel'          => __( 'Cancel edit' ),
5043          'videoSelectPosterImageTitle' => __( 'Select poster image' ),
5044          'videoAddTrackTitle'          => __( 'Add subtitles' ),
5045  
5046          // Playlist.
5047          'playlistDragInfo'            => __( 'Drag and drop to reorder tracks.' ),
5048          'createPlaylistTitle'         => __( 'Create audio playlist' ),
5049          'editPlaylistTitle'           => __( 'Edit audio playlist' ),
5050          'cancelPlaylistTitle'         => __( '&#8592; Cancel audio playlist' ),
5051          'insertPlaylist'              => __( 'Insert audio playlist' ),
5052          'updatePlaylist'              => __( 'Update audio playlist' ),
5053          'addToPlaylist'               => __( 'Add to audio playlist' ),
5054          'addToPlaylistTitle'          => __( 'Add to Audio Playlist' ),
5055  
5056          // Video Playlist.
5057          'videoPlaylistDragInfo'       => __( 'Drag and drop to reorder videos.' ),
5058          'createVideoPlaylistTitle'    => __( 'Create video playlist' ),
5059          'editVideoPlaylistTitle'      => __( 'Edit video playlist' ),
5060          'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel video playlist' ),
5061          'insertVideoPlaylist'         => __( 'Insert video playlist' ),
5062          'updateVideoPlaylist'         => __( 'Update video playlist' ),
5063          'addToVideoPlaylist'          => __( 'Add to video playlist' ),
5064          'addToVideoPlaylistTitle'     => __( 'Add to video Playlist' ),
5065  
5066          // Headings.
5067          'filterAttachments'           => __( 'Filter media' ),
5068          'attachmentsList'             => __( 'Media list' ),
5069      );
5070  
5071      /**
5072       * Filters the media view settings.
5073       *
5074       * @since 3.5.0
5075       *
5076       * @param array   $settings List of media view settings.
5077       * @param WP_Post $post     Post object.
5078       */
5079      $settings = apply_filters( 'media_view_settings', $settings, $post );
5080  
5081      /**
5082       * Filters the media view strings.
5083       *
5084       * @since 3.5.0
5085       *
5086       * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
5087       * @param WP_Post  $post    Post object.
5088       */
5089      $strings = apply_filters( 'media_view_strings', $strings, $post );
5090  
5091      $strings['settings'] = $settings;
5092  
5093      /*
5094       * Ensure we enqueue media-editor first, that way media-views
5095       * is registered internally before we try to localize it. See #24724.
5096       */
5097      wp_enqueue_script( 'media-editor' );
5098      wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
5099  
5100      wp_enqueue_script( 'media-audiovideo' );
5101      wp_enqueue_style( 'media-views' );
5102      if ( is_admin() ) {
5103          wp_enqueue_script( 'mce-view' );
5104          wp_enqueue_script( 'image-edit' );
5105      }
5106      wp_enqueue_style( 'imgareaselect' );
5107      wp_plupload_default_settings();
5108  
5109      require_once  ABSPATH . WPINC . '/media-template.php';
5110      add_action( 'admin_footer', 'wp_print_media_templates' );
5111      add_action( 'wp_footer', 'wp_print_media_templates' );
5112      add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
5113  
5114      /**
5115       * Fires at the conclusion of wp_enqueue_media().
5116       *
5117       * @since 3.5.0
5118       */
5119      do_action( 'wp_enqueue_media' );
5120  }
5121  
5122  /**
5123   * Retrieves media attached to the passed post.
5124   *
5125   * @since 3.6.0
5126   *
5127   * @param string      $type Mime type.
5128   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
5129   * @return WP_Post[] Array of media attached to the given post.
5130   */
5131  function get_attached_media( $type, $post = 0 ) {
5132      $post = get_post( $post );
5133  
5134      if ( ! $post ) {
5135          return array();
5136      }
5137  
5138      $args = array(
5139          'post_parent'    => $post->ID,
5140          'post_type'      => 'attachment',
5141          'post_mime_type' => $type,
5142          'posts_per_page' => -1,
5143          'orderby'        => 'menu_order',
5144          'order'          => 'ASC',
5145      );
5146  
5147      /**
5148       * Filters arguments used to retrieve media attached to the given post.
5149       *
5150       * @since 3.6.0
5151       *
5152       * @param array   $args Post query arguments.
5153       * @param string  $type Mime type of the desired media.
5154       * @param WP_Post $post Post object.
5155       */
5156      $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
5157  
5158      $children = get_children( $args );
5159  
5160      /**
5161       * Filters the list of media attached to the given post.
5162       *
5163       * @since 3.6.0
5164       *
5165       * @param WP_Post[] $children Array of media attached to the given post.
5166       * @param string    $type     Mime type of the media desired.
5167       * @param WP_Post   $post     Post object.
5168       */
5169      return (array) apply_filters( 'get_attached_media', $children, $type, $post );
5170  }
5171  
5172  /**
5173   * Checks the HTML content for an audio, video, object, embed, or iframe tags.
5174   *
5175   * @since 3.6.0
5176   *
5177   * @param string   $content A string of HTML which might contain media elements.
5178   * @param string[] $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
5179   * @return string[] Array of found HTML media elements.
5180   */
5181  function get_media_embedded_in_content( $content, $types = null ) {
5182      $html = array();
5183  
5184      /**
5185       * Filters the embedded media types that are allowed to be returned from the content blob.
5186       *
5187       * @since 4.2.0
5188       *
5189       * @param string[] $allowed_media_types An array of allowed media types. Default media types are
5190       *                                      'audio', 'video', 'object', 'embed', and 'iframe'.
5191       */
5192      $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
5193  
5194      if ( ! empty( $types ) ) {
5195          if ( ! is_array( $types ) ) {
5196              $types = array( $types );
5197          }
5198  
5199          $allowed_media_types = array_intersect( $allowed_media_types, $types );
5200      }
5201  
5202      $tags = implode( '|', $allowed_media_types );
5203  
5204      if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
5205          foreach ( $matches[0] as $match ) {
5206              $html[] = $match;
5207          }
5208      }
5209  
5210      return $html;
5211  }
5212  
5213  /**
5214   * Retrieves galleries from the passed post's content.
5215   *
5216   * @since 3.6.0
5217   *
5218   * @param int|WP_Post $post Post ID or object.
5219   * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
5220   * @return array A list of arrays, each containing gallery data and srcs parsed
5221   *               from the expanded shortcode.
5222   */
5223  function get_post_galleries( $post, $html = true ) {
5224      $post = get_post( $post );
5225  
5226      if ( ! $post ) {
5227          return array();
5228      }
5229  
5230      if ( ! has_shortcode( $post->post_content, 'gallery' ) && ! has_block( 'gallery', $post->post_content ) ) {
5231          return array();
5232      }
5233  
5234      $galleries = array();
5235      if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
5236          foreach ( $matches as $shortcode ) {
5237              if ( 'gallery' === $shortcode[2] ) {
5238                  $srcs = array();
5239  
5240                  $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
5241  
5242                  // Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already.
5243                  if ( ! isset( $shortcode_attrs['id'] ) ) {
5244                      $shortcode[3] .= ' id="' . (int) $post->ID . '"';
5245                  }
5246  
5247                  $gallery = do_shortcode_tag( $shortcode );
5248                  if ( $html ) {
5249                      $galleries[] = $gallery;
5250                  } else {
5251                      preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
5252                      if ( ! empty( $src ) ) {
5253                          foreach ( $src as $s ) {
5254                              $srcs[] = $s[2];
5255                          }
5256                      }
5257  
5258                      $galleries[] = array_merge(
5259                          $shortcode_attrs,
5260                          array(
5261                              'src' => array_values( array_unique( $srcs ) ),
5262                          )
5263                      );
5264                  }
5265              }
5266          }
5267      }
5268  
5269      if ( has_block( 'gallery', $post->post_content ) ) {
5270          $post_blocks = parse_blocks( $post->post_content );
5271  
5272          while ( $block = array_shift( $post_blocks ) ) {
5273              $has_inner_blocks = ! empty( $block['innerBlocks'] );
5274  
5275              // Skip blocks with no blockName and no innerHTML.
5276              if ( ! $block['blockName'] ) {
5277                  continue;
5278              }
5279  
5280              // Skip non-Gallery blocks.
5281              if ( 'core/gallery' !== $block['blockName'] ) {
5282                  // Move inner blocks into the root array before skipping.
5283                  if ( $has_inner_blocks ) {
5284                      array_push( $post_blocks, ...$block['innerBlocks'] );
5285                  }
5286                  continue;
5287              }
5288  
5289              // New Gallery block format as HTML.
5290              if ( $has_inner_blocks && $html ) {
5291                  $block_html  = wp_list_pluck( $block['innerBlocks'], 'innerHTML' );
5292                  $galleries[] = '<figure>' . implode( ' ', $block_html ) . '</figure>';
5293                  continue;
5294              }
5295  
5296              $srcs = array();
5297  
5298              // New Gallery block format as an array.
5299              if ( $has_inner_blocks ) {
5300                  $attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' );
5301                  $ids   = wp_list_pluck( $attrs, 'id' );
5302  
5303                  foreach ( $ids as $id ) {
5304                      $url = wp_get_attachment_url( $id );
5305  
5306                      if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
5307                          $srcs[] = $url;
5308                      }
5309                  }
5310  
5311                  $galleries[] = array(
5312                      'ids' => implode( ',', $ids ),
5313                      'src' => $srcs,
5314                  );
5315  
5316                  continue;
5317              }
5318  
5319              // Old Gallery block format as HTML.
5320              if ( $html ) {
5321                  $galleries[] = $block['innerHTML'];
5322                  continue;
5323              }
5324  
5325              // Old Gallery block format as an array.
5326              $ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array();
5327  
5328              // If present, use the image IDs from the JSON blob as canonical.
5329              if ( ! empty( $ids ) ) {
5330                  foreach ( $ids as $id ) {
5331                      $url = wp_get_attachment_url( $id );
5332  
5333                      if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
5334                          $srcs[] = $url;
5335                      }
5336                  }
5337  
5338                  $galleries[] = array(
5339                      'ids' => implode( ',', $ids ),
5340                      'src' => $srcs,
5341                  );
5342  
5343                  continue;
5344              }
5345  
5346              // Otherwise, extract srcs from the innerHTML.
5347              preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $found_srcs, PREG_SET_ORDER );
5348  
5349              if ( ! empty( $found_srcs[0] ) ) {
5350                  foreach ( $found_srcs as $src ) {
5351                      if ( isset( $src[2] ) && ! in_array( $src[2], $srcs, true ) ) {
5352                          $srcs[] = $src[2];
5353                      }
5354                  }
5355              }
5356  
5357              $galleries[] = array( 'src' => $srcs );
5358          }
5359      }
5360  
5361      /**
5362       * Filters the list of all found galleries in the given post.
5363       *
5364       * @since 3.6.0
5365       *
5366       * @param array   $galleries Associative array of all found post galleries.
5367       * @param WP_Post $post      Post object.
5368       */
5369      return apply_filters( 'get_post_galleries', $galleries, $post );
5370  }
5371  
5372  /**
5373   * Checks a specified post's content for gallery and, if present, return the first
5374   *
5375   * @since 3.6.0
5376   *
5377   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
5378   * @param bool        $html Optional. Whether to return HTML or data. Default is true.
5379   * @return string|array Gallery data and srcs parsed from the expanded shortcode.
5380   */
5381  function get_post_gallery( $post = 0, $html = true ) {
5382      $galleries = get_post_galleries( $post, $html );
5383      $gallery   = reset( $galleries );
5384  
5385      /**
5386       * Filters the first-found post gallery.
5387       *
5388       * @since 3.6.0
5389       *
5390       * @param array       $gallery   The first-found post gallery.
5391       * @param int|WP_Post $post      Post ID or object.
5392       * @param array       $galleries Associative array of all found post galleries.
5393       */
5394      return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
5395  }
5396  
5397  /**
5398   * Retrieves the image srcs from galleries from a post's content, if present.
5399   *
5400   * @since 3.6.0
5401   *
5402   * @see get_post_galleries()
5403   *
5404   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
5405   * @return array A list of lists, each containing image srcs parsed.
5406   *               from an expanded shortcode
5407   */
5408  function get_post_galleries_images( $post = 0 ) {
5409      $galleries = get_post_galleries( $post, false );
5410      return wp_list_pluck( $galleries, 'src' );
5411  }
5412  
5413  /**
5414   * Checks a post's content for galleries and return the image srcs for the first found gallery.
5415   *
5416   * @since 3.6.0
5417   *
5418   * @see get_post_gallery()
5419   *
5420   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
5421   * @return string[] A list of a gallery's image srcs in order.
5422   */
5423  function get_post_gallery_images( $post = 0 ) {
5424      $gallery = get_post_gallery( $post, false );
5425      return empty( $gallery['src'] ) ? array() : $gallery['src'];
5426  }
5427  
5428  /**
5429   * Maybe attempts to generate attachment metadata, if missing.
5430   *
5431   * @since 3.9.0
5432   *
5433   * @param WP_Post $attachment Attachment object.
5434   */
5435  function wp_maybe_generate_attachment_metadata( $attachment ) {
5436      if ( empty( $attachment ) || empty( $attachment->ID ) ) {
5437          return;
5438      }
5439  
5440      $attachment_id = (int) $attachment->ID;
5441      $file          = get_attached_file( $attachment_id );
5442      $meta          = wp_get_attachment_metadata( $attachment_id );
5443  
5444      if ( empty( $meta ) && file_exists( $file ) ) {
5445          $_meta = get_post_meta( $attachment_id );
5446          $_lock = 'wp_generating_att_' . $attachment_id;
5447  
5448          if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
5449              set_transient( $_lock, $file );
5450              wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
5451              delete_transient( $_lock );
5452          }
5453      }
5454  }
5455  
5456  /**
5457   * Tries to convert an attachment URL into a post ID.
5458   *
5459   * @since 4.0.0
5460   *
5461   * @global wpdb $wpdb WordPress database abstraction object.
5462   *
5463   * @param string $url The URL to resolve.
5464   * @return int The found post ID, or 0 on failure.
5465   */
5466  function attachment_url_to_postid( $url ) {
5467      global $wpdb;
5468  
5469      /**
5470       * Filters the attachment ID to allow short-circuit the function.
5471       *
5472       * Allows plugins to short-circuit attachment ID lookups. Plugins making
5473       * use of this function should return:
5474       *
5475       * - 0 (integer) to indicate the attachment is not found,
5476       * - attachment ID (integer) to indicate the attachment ID found,
5477       * - null to indicate WordPress should proceed with the lookup.
5478       *
5479       * Warning: The post ID may be null or zero, both of which cast to a
5480       * boolean false. For information about casting to booleans see the
5481       * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}.
5482       * Use the === operator for testing the post ID when developing filters using
5483       * this hook.
5484       *
5485       * @since 6.7.0
5486       *
5487       * @param int|null $post_id The result of the post ID lookup. Null to indicate
5488       *                          no lookup has been attempted. Default null.
5489       * @param string   $url     The URL being looked up.
5490       */
5491      $post_id = apply_filters( 'pre_attachment_url_to_postid', null, $url );
5492      if ( null !== $post_id ) {
5493          return (int) $post_id;
5494      }
5495  
5496      $dir  = wp_get_upload_dir();
5497      $path = $url;
5498  
5499      $site_url   = parse_url( $dir['url'] );
5500      $image_path = parse_url( $path );
5501  
5502      // Force the protocols to match if needed.
5503      if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
5504          $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
5505      }
5506  
5507      if ( str_starts_with( $path, $dir['baseurl'] . '/' ) ) {
5508          $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
5509      }
5510  
5511      $sql = $wpdb->prepare(
5512          "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
5513          $path
5514      );
5515  
5516      $results = $wpdb->get_results( $sql );
5517      $post_id = null;
5518  
5519      if ( $results ) {
5520          // Use the first available result, but prefer a case-sensitive match, if exists.
5521          $post_id = reset( $results )->post_id;
5522  
5523          if ( count( $results ) > 1 ) {
5524              foreach ( $results as $result ) {
5525                  if ( $path === $result->meta_value ) {
5526                      $post_id = $result->post_id;
5527                      break;
5528                  }
5529              }
5530          }
5531      }
5532  
5533      /**
5534       * Filters an attachment ID found by URL.
5535       *
5536       * @since 4.2.0
5537       *
5538       * @param int|null $post_id The post_id (if any) found by the function.
5539       * @param string   $url     The URL being looked up.
5540       */
5541      return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
5542  }
5543  
5544  /**
5545   * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
5546   *
5547   * @since 4.0.0
5548   *
5549   * @return string[] The relevant CSS file URLs.
5550   */
5551  function wpview_media_sandbox_styles() {
5552      $version        = 'ver=' . get_bloginfo( 'version' );
5553      $mediaelement   = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" );
5554      $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
5555  
5556      return array( $mediaelement, $wpmediaelement );
5557  }
5558  
5559  /**
5560   * Registers the personal data exporter for media.
5561   *
5562   * @param array[] $exporters An array of personal data exporters, keyed by their ID.
5563   * @return array[] Updated array of personal data exporters.
5564   */
5565  function wp_register_media_personal_data_exporter( $exporters ) {
5566      $exporters['wordpress-media'] = array(
5567          'exporter_friendly_name' => __( 'WordPress Media' ),
5568          'callback'               => 'wp_media_personal_data_exporter',
5569      );
5570  
5571      return $exporters;
5572  }
5573  
5574  /**
5575   * Finds and exports attachments associated with an email address.
5576   *
5577   * @since 4.9.6
5578   *
5579   * @param string $email_address The attachment owner email address.
5580   * @param int    $page          Attachment page number.
5581   * @return array {
5582   *     An array of personal data.
5583   *
5584   *     @type array[] $data An array of personal data arrays.
5585   *     @type bool    $done Whether the exporter is finished.
5586   * }
5587   */
5588  function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
5589      // Limit us to 50 attachments at a time to avoid timing out.
5590      $number = 50;
5591      $page   = (int) $page;
5592  
5593      $data_to_export = array();
5594  
5595      $user = get_user_by( 'email', $email_address );
5596      if ( false === $user ) {
5597          return array(
5598              'data' => $data_to_export,
5599              'done' => true,
5600          );
5601      }
5602  
5603      $post_query = new WP_Query(
5604          array(
5605              'author'         => $user->ID,
5606              'posts_per_page' => $number,
5607              'paged'          => $page,
5608              'post_type'      => 'attachment',
5609              'post_status'    => 'any',
5610              'orderby'        => 'ID',
5611              'order'          => 'ASC',
5612          )
5613      );
5614  
5615      foreach ( (array) $post_query->posts as $post ) {
5616          $attachment_url = wp_get_attachment_url( $post->ID );
5617  
5618          if ( $attachment_url ) {
5619              $post_data_to_export = array(
5620                  array(
5621                      'name'  => __( 'URL' ),
5622                      'value' => $attachment_url,
5623                  ),
5624              );
5625  
5626              $data_to_export[] = array(
5627                  'group_id'          => 'media',
5628                  'group_label'       => __( 'Media' ),
5629                  'group_description' => __( 'User&#8217;s media data.' ),
5630                  'item_id'           => "post-{$post->ID}",
5631                  'data'              => $post_data_to_export,
5632              );
5633          }
5634      }
5635  
5636      $done = $post_query->max_num_pages <= $page;
5637  
5638      return array(
5639          'data' => $data_to_export,
5640          'done' => $done,
5641      );
5642  }
5643  
5644  /**
5645   * Adds additional default image sub-sizes.
5646   *
5647   * These sizes are meant to enhance the way WordPress displays images on the front-end on larger,
5648   * high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes
5649   * when the users upload large images.
5650   *
5651   * The sizes can be changed or removed by themes and plugins but that is not recommended.
5652   * The size "names" reflect the image dimensions, so changing the sizes would be quite misleading.
5653   *
5654   * @since 5.3.0
5655   * @access private
5656   */
5657  function _wp_add_additional_image_sizes() {
5658      // 2x medium_large size.
5659      add_image_size( '1536x1536', 1536, 1536 );
5660      // 2x large size.
5661      add_image_size( '2048x2048', 2048, 2048 );
5662  }
5663  
5664  /**
5665   * Callback to enable showing of the user error when uploading .heic images.
5666   *
5667   * @since 5.5.0
5668   * @since 6.7.0 The default behavior is to enable heic uploads as long as the server
5669   *              supports the format. The uploads are converted to JPEG's by default.
5670   *
5671   * @param array[] $plupload_settings The settings for Plupload.js.
5672   * @return array[] Modified settings for Plupload.js.
5673   */
5674  function wp_show_heic_upload_error( $plupload_settings ) {
5675      // Check if HEIC images can be edited.
5676      if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/heic' ) ) ) {
5677          $plupload_init['heic_upload_error'] = true;
5678      }
5679      return $plupload_settings;
5680  }
5681  
5682  /**
5683   * Allows PHP's getimagesize() to be debuggable when necessary.
5684   *
5685   * @since 5.7.0
5686   * @since 5.8.0 Added support for WebP images.
5687   * @since 6.5.0 Added support for AVIF images.
5688   *
5689   * @param string $filename   The file path.
5690   * @param array  $image_info Optional. Extended image information (passed by reference).
5691   * @return array|false Array of image information or false on failure.
5692   */
5693  function wp_getimagesize( $filename, ?array &$image_info = null ) {
5694      // Don't silence errors when in debug mode, unless running unit tests.
5695      if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! defined( 'WP_RUN_CORE_TESTS' ) ) {
5696          if ( 2 === func_num_args() ) {
5697              $info = getimagesize( $filename, $image_info );
5698          } else {
5699              $info = getimagesize( $filename );
5700          }
5701      } else {
5702          /*
5703           * Silencing notice and warning is intentional.
5704           *
5705           * getimagesize() has a tendency to generate errors, such as
5706           * "corrupt JPEG data: 7191 extraneous bytes before marker",
5707           * even when it's able to provide image size information.
5708           *
5709           * See https://core.trac.wordpress.org/ticket/42480
5710           */
5711          if ( 2 === func_num_args() ) {
5712              $info = @getimagesize( $filename, $image_info );
5713          } else {
5714              $info = @getimagesize( $filename );
5715          }
5716      }
5717  
5718      if (
5719          ! empty( $info ) &&
5720          // Some PHP versions return 0x0 sizes from `getimagesize` for unrecognized image formats, including AVIFs.
5721          ! ( empty( $info[0] ) && empty( $info[1] ) )
5722      ) {
5723          return $info;
5724      }
5725  
5726      $image_mime_type = wp_get_image_mime( $filename );
5727  
5728      // Not an image?
5729      if ( false === $image_mime_type ) {
5730          return false;
5731      }
5732  
5733      /*
5734       * For PHP versions that don't support WebP images,
5735       * extract the image size info from the file headers.
5736       */
5737      if ( 'image/webp' === $image_mime_type ) {
5738          $webp_info = wp_get_webp_info( $filename );
5739          $width     = $webp_info['width'];
5740          $height    = $webp_info['height'];
5741  
5742          // Mimic the native return format.
5743          if ( $width && $height ) {
5744              return array(
5745                  $width,
5746                  $height,
5747                  IMAGETYPE_WEBP,
5748                  sprintf(
5749                      'width="%d" height="%d"',
5750                      $width,
5751                      $height
5752                  ),
5753                  'mime' => 'image/webp',
5754              );
5755          }
5756      }
5757  
5758      // For PHP versions that don't support AVIF images, extract the image size info from the file headers.
5759      if ( 'image/avif' === $image_mime_type ) {
5760          $avif_info = wp_get_avif_info( $filename );
5761  
5762          $width  = $avif_info['width'];
5763          $height = $avif_info['height'];
5764  
5765          // Mimic the native return format.
5766          if ( $width && $height ) {
5767              return array(
5768                  $width,
5769                  $height,
5770                  IMAGETYPE_AVIF,
5771                  sprintf(
5772                      'width="%d" height="%d"',
5773                      $width,
5774                      $height
5775                  ),
5776                  'mime' => 'image/avif',
5777              );
5778          }
5779      }
5780  
5781      // For PHP versions that don't support HEIC images, extract the size info using Imagick when available.
5782      if ( wp_is_heic_image_mime_type( $image_mime_type ) ) {
5783          $editor = wp_get_image_editor( $filename );
5784  
5785          if ( is_wp_error( $editor ) ) {
5786              return false;
5787          }
5788  
5789          // If the editor for HEICs is Imagick, use it to get the image size.
5790          if ( $editor instanceof WP_Image_Editor_Imagick ) {
5791              $size = $editor->get_size();
5792              return array(
5793                  $size['width'],
5794                  $size['height'],
5795                  IMAGETYPE_HEIC,
5796                  sprintf(
5797                      'width="%d" height="%d"',
5798                      $size['width'],
5799                      $size['height']
5800                  ),
5801                  'mime' => 'image/heic',
5802              );
5803          }
5804      }
5805  
5806      // The image could not be parsed.
5807      return false;
5808  }
5809  
5810  /**
5811   * Extracts meta information about an AVIF file: width, height, bit depth, and number of channels.
5812   *
5813   * @since 6.5.0
5814   *
5815   * @param string $filename Path to an AVIF file.
5816   * @return array {
5817   *     An array of AVIF image information.
5818   *
5819   *     @type int|false $width        Image width on success, false on failure.
5820   *     @type int|false $height       Image height on success, false on failure.
5821   *     @type int|false $bit_depth    Image bit depth on success, false on failure.
5822   *     @type int|false $num_channels Image number of channels on success, false on failure.
5823   * }
5824   */
5825  function wp_get_avif_info( $filename ) {
5826      $results = array(
5827          'width'        => false,
5828          'height'       => false,
5829          'bit_depth'    => false,
5830          'num_channels' => false,
5831      );
5832  
5833      if ( 'image/avif' !== wp_get_image_mime( $filename ) ) {
5834          return $results;
5835      }
5836  
5837      // Parse the file using libavifinfo's PHP implementation.
5838      require_once  ABSPATH . WPINC . '/class-avif-info.php';
5839  
5840      $handle = fopen( $filename, 'rb' );
5841      if ( $handle ) {
5842          $parser  = new Avifinfo\Parser( $handle );
5843          $success = $parser->parse_ftyp() && $parser->parse_file();
5844          fclose( $handle );
5845          if ( $success ) {
5846              $results = $parser->features->primary_item_features;
5847          }
5848      }
5849      return $results;
5850  }
5851  
5852  /**
5853   * Extracts meta information about a WebP file: width, height, and type.
5854   *
5855   * @since 5.8.0
5856   *
5857   * @param string $filename Path to a WebP file.
5858   * @return array {
5859   *     An array of WebP image information.
5860   *
5861   *     @type int|false    $width  Image width on success, false on failure.
5862   *     @type int|false    $height Image height on success, false on failure.
5863   *     @type string|false $type   The WebP type: one of 'lossy', 'lossless' or 'animated-alpha'.
5864   *                                False on failure.
5865   * }
5866   */
5867  function wp_get_webp_info( $filename ) {
5868      $width  = false;
5869      $height = false;
5870      $type   = false;
5871  
5872      if ( 'image/webp' !== wp_get_image_mime( $filename ) ) {
5873          return compact( 'width', 'height', 'type' );
5874      }
5875  
5876      $magic = file_get_contents( $filename, false, null, 0, 40 );
5877  
5878      if ( false === $magic ) {
5879          return compact( 'width', 'height', 'type' );
5880      }
5881  
5882      // Make sure we got enough bytes.
5883      if ( strlen( $magic ) < 40 ) {
5884          return compact( 'width', 'height', 'type' );
5885      }
5886  
5887      /*
5888       * The headers are a little different for each of the three formats.
5889       * Header values based on WebP docs, see https://developers.google.com/speed/webp/docs/riff_container.
5890       */
5891      switch ( substr( $magic, 12, 4 ) ) {
5892          // Lossy WebP.
5893          case 'VP8 ':
5894              $parts  = unpack( 'v2', substr( $magic, 26, 4 ) );
5895              $width  = (int) ( $parts[1] & 0x3FFF );
5896              $height = (int) ( $parts[2] & 0x3FFF );
5897              $type   = 'lossy';
5898              break;
5899          // Lossless WebP.
5900          case 'VP8L':
5901              $parts  = unpack( 'C4', substr( $magic, 21, 4 ) );
5902              $width  = (int) ( $parts[1] | ( ( $parts[2] & 0x3F ) << 8 ) ) + 1;
5903              $height = (int) ( ( ( $parts[2] & 0xC0 ) >> 6 ) | ( $parts[3] << 2 ) | ( ( $parts[4] & 0x03 ) << 10 ) ) + 1;
5904              $type   = 'lossless';
5905              break;
5906          // Animated/alpha WebP.
5907          case 'VP8X':
5908              // Pad 24-bit int.
5909              $width = unpack( 'V', substr( $magic, 24, 3 ) . "\x00" );
5910              $width = (int) ( $width[1] & 0xFFFFFF ) + 1;
5911              // Pad 24-bit int.
5912              $height = unpack( 'V', substr( $magic, 27, 3 ) . "\x00" );
5913              $height = (int) ( $height[1] & 0xFFFFFF ) + 1;
5914              $type   = 'animated-alpha';
5915              break;
5916      }
5917  
5918      return compact( 'width', 'height', 'type' );
5919  }
5920  
5921  /**
5922   * Gets loading optimization attributes.
5923   *
5924   * This function returns an array of attributes that should be merged into the given attributes array to optimize
5925   * loading performance. Potential attributes returned by this function are:
5926   * - `loading` attribute with a value of "lazy"
5927   * - `fetchpriority` attribute with a value of "high"
5928   * - `decoding` attribute with a value of "async"
5929   *
5930   * If any of these attributes are already present in the given attributes, they will not be modified. Note that no
5931   * element should have both `loading="lazy"` and `fetchpriority="high"`, so the function will trigger a warning in case
5932   * both attributes are present with those values.
5933   *
5934   * @since 6.3.0
5935   *
5936   * @global WP_Query $wp_query WordPress Query object.
5937   *
5938   * @param string $tag_name The tag name.
5939   * @param array  $attr     Array of the attributes for the tag.
5940   * @param string $context  Context for the element for which the loading optimization attribute is requested.
5941   * @return array Loading optimization attributes.
5942   */
5943  function wp_get_loading_optimization_attributes( $tag_name, $attr, $context ) {
5944      global $wp_query;
5945  
5946      /**
5947       * Filters whether to short-circuit loading optimization attributes.
5948       *
5949       * Returning an array from the filter will effectively short-circuit the loading of optimization attributes,
5950       * returning that value instead.
5951       *
5952       * @since 6.4.0
5953       *
5954       * @param array|false $loading_attrs False by default, or array of loading optimization attributes to short-circuit.
5955       * @param string      $tag_name      The tag name.
5956       * @param array       $attr          Array of the attributes for the tag.
5957       * @param string      $context       Context for the element for which the loading optimization attribute is requested.
5958       */
5959      $loading_attrs = apply_filters( 'pre_wp_get_loading_optimization_attributes', false, $tag_name, $attr, $context );
5960  
5961      if ( is_array( $loading_attrs ) ) {
5962          return $loading_attrs;
5963      }
5964  
5965      $loading_attrs = array();
5966  
5967      /*
5968       * Skip lazy-loading for the overall block template, as it is handled more granularly.
5969       * The skip is also applicable for `fetchpriority`.
5970       */
5971      if ( 'template' === $context ) {
5972          /** This filter is documented in wp-includes/media.php */
5973          return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
5974      }
5975  
5976      // For now this function only supports images and iframes.
5977      if ( 'img' !== $tag_name && 'iframe' !== $tag_name ) {
5978          /** This filter is documented in wp-includes/media.php */
5979          return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
5980      }
5981  
5982      /*
5983       * Skip programmatically created images within content blobs as they need to be handled together with the other
5984       * images within the post content or widget content.
5985       * Without this clause, they would already be considered within their own context which skews the image count and
5986       * can result in the first post content image being lazy-loaded or an image further down the page being marked as a
5987       * high priority.
5988       */
5989      if (
5990          'the_content' !== $context && doing_filter( 'the_content' ) ||
5991          'widget_text_content' !== $context && doing_filter( 'widget_text_content' ) ||
5992          'widget_block_content' !== $context && doing_filter( 'widget_block_content' )
5993      ) {
5994          /** This filter is documented in wp-includes/media.php */
5995          return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
5996  
5997      }
5998  
5999      /*
6000       * Add `decoding` with a value of "async" for every image unless it has a
6001       * conflicting `decoding` attribute already present.
6002       */
6003      if ( 'img' === $tag_name ) {
6004          if ( isset( $attr['decoding'] ) ) {
6005              $loading_attrs['decoding'] = $attr['decoding'];
6006          } else {
6007              $loading_attrs['decoding'] = 'async';
6008          }
6009      }
6010  
6011      // For any resources, width and height must be provided, to avoid layout shifts.
6012      if ( ! isset( $attr['width'], $attr['height'] ) ) {
6013          /** This filter is documented in wp-includes/media.php */
6014          return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
6015      }
6016  
6017      /*
6018       * The key function logic starts here.
6019       */
6020      $maybe_in_viewport    = null;
6021      $increase_count       = false;
6022      $maybe_increase_count = false;
6023  
6024      // Logic to handle a `loading` attribute that is already provided.
6025      if ( isset( $attr['loading'] ) ) {
6026          /*
6027           * Interpret "lazy" as not in viewport. Any other value can be
6028           * interpreted as in viewport (realistically only "eager" or `false`
6029           * to force-omit the attribute are other potential values).
6030           */
6031          if ( 'lazy' === $attr['loading'] ) {
6032              $maybe_in_viewport = false;
6033          } else {
6034              $maybe_in_viewport = true;
6035          }
6036      }
6037  
6038      // Logic to handle a `fetchpriority` attribute that is already provided.
6039      if ( isset( $attr['fetchpriority'] ) && 'high' === $attr['fetchpriority'] ) {
6040          /*
6041           * If the image was already determined to not be in the viewport (e.g.
6042           * from an already provided `loading` attribute), trigger a warning.
6043           * Otherwise, the value can be interpreted as in viewport, since only
6044           * the most important in-viewport image should have `fetchpriority` set
6045           * to "high".
6046           */
6047          if ( false === $maybe_in_viewport ) {
6048              _doing_it_wrong(
6049                  __FUNCTION__,
6050                  __( 'An image should not be lazy-loaded and marked as high priority at the same time.' ),
6051                  '6.3.0'
6052              );
6053              /*
6054               * Set `fetchpriority` here for backward-compatibility as we should
6055               * not override what a developer decided, even though it seems
6056               * incorrect.
6057               */
6058              $loading_attrs['fetchpriority'] = 'high';
6059          } else {
6060              $maybe_in_viewport = true;
6061          }
6062      }
6063  
6064      if ( null === $maybe_in_viewport ) {
6065          $header_enforced_contexts = array(
6066              'template_part_' . WP_TEMPLATE_PART_AREA_HEADER => true,
6067              'get_header_image_tag' => true,
6068          );
6069  
6070          /**
6071           * Filters the header-specific contexts.
6072           *
6073           * @since 6.4.0
6074           *
6075           * @param array $default_header_enforced_contexts Map of contexts for which elements should be considered
6076           *                                                in the header of the page, as $context => $enabled
6077           *                                                pairs. The $enabled should always be true.
6078           */
6079          $header_enforced_contexts = apply_filters( 'wp_loading_optimization_force_header_contexts', $header_enforced_contexts );
6080  
6081          // Consider elements with these header-specific contexts to be in viewport.
6082          if ( isset( $header_enforced_contexts[ $context ] ) ) {
6083              $maybe_in_viewport    = true;
6084              $maybe_increase_count = true;
6085          } elseif ( ! is_admin() && in_the_loop() && is_main_query() ) {
6086              /*
6087               * Get the content media count, since this is a main query
6088               * content element. This is accomplished by "increasing"
6089               * the count by zero, as the only way to get the count is
6090               * to call this function.
6091               * The actual count increase happens further below, based
6092               * on the `$increase_count` flag set here.
6093               */
6094              $content_media_count = wp_increase_content_media_count( 0 );
6095              $increase_count      = true;
6096  
6097              // If the count so far is below the threshold, `loading` attribute is omitted.
6098              if ( $content_media_count < wp_omit_loading_attr_threshold() ) {
6099                  $maybe_in_viewport = true;
6100              } else {
6101                  $maybe_in_viewport = false;
6102              }
6103          } elseif (
6104              // Only apply for main query but before the loop.
6105              $wp_query->before_loop && $wp_query->is_main_query()
6106              /*
6107               * Any image before the loop, but after the header has started should not be lazy-loaded,
6108               * except when the footer has already started which can happen when the current template
6109               * does not include any loop.
6110               */
6111              && did_action( 'get_header' ) && ! did_action( 'get_footer' )
6112              ) {
6113              $maybe_in_viewport    = true;
6114              $maybe_increase_count = true;
6115          }
6116      }
6117  
6118      /*
6119       * If the element is in the viewport (`true`), potentially add
6120       * `fetchpriority` with a value of "high". Otherwise, i.e. if the element
6121       * is not not in the viewport (`false`) or it is unknown (`null`), add
6122       * `loading` with a value of "lazy".
6123       */
6124      if ( $maybe_in_viewport ) {
6125          $loading_attrs = wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr );
6126      } else {
6127          // Only add `loading="lazy"` if the feature is enabled.
6128          if ( wp_lazy_loading_enabled( $tag_name, $context ) ) {
6129              $loading_attrs['loading'] = 'lazy';
6130          }
6131      }
6132  
6133      /*
6134       * If flag was set based on contextual logic above, increase the content
6135       * media count, either unconditionally, or based on whether the image size
6136       * is larger than the threshold.
6137       */
6138      if ( $increase_count ) {
6139          wp_increase_content_media_count();
6140      } elseif ( $maybe_increase_count ) {
6141          /** This filter is documented in wp-includes/media.php */
6142          $wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 );
6143  
6144          if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) {
6145              wp_increase_content_media_count();
6146          }
6147      }
6148  
6149      /**
6150       * Filters the loading optimization attributes.
6151       *
6152       * @since 6.4.0
6153       *
6154       * @param array  $loading_attrs The loading optimization attributes.
6155       * @param string $tag_name      The tag name.
6156       * @param array  $attr          Array of the attributes for the tag.
6157       * @param string $context       Context for the element for which the loading optimization attribute is requested.
6158       */
6159      return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
6160  }
6161  
6162  /**
6163   * Gets the threshold for how many of the first content media elements to not lazy-load.
6164   *
6165   * This function runs the {@see 'wp_omit_loading_attr_threshold'} filter, which uses a default threshold value of 3.
6166   * The filter is only run once per page load, unless the `$force` parameter is used.
6167   *
6168   * @since 5.9.0
6169   *
6170   * @param bool $force Optional. If set to true, the filter will be (re-)applied even if it already has been before.
6171   *                    Default false.
6172   * @return int The number of content media elements to not lazy-load.
6173   */
6174  function wp_omit_loading_attr_threshold( $force = false ) {
6175      static $omit_threshold;
6176  
6177      // This function may be called multiple times. Run the filter only once per page load.
6178      if ( ! isset( $omit_threshold ) || $force ) {
6179          /**
6180           * Filters the threshold for how many of the first content media elements to not lazy-load.
6181           *
6182           * For these first content media elements, the `loading` attribute will be omitted. By default, this is the case
6183           * for only the very first content media element.
6184           *
6185           * @since 5.9.0
6186           * @since 6.3.0 The default threshold was changed from 1 to 3.
6187           *
6188           * @param int $omit_threshold The number of media elements where the `loading` attribute will not be added. Default 3.
6189           */
6190          $omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 3 );
6191      }
6192  
6193      return $omit_threshold;
6194  }
6195  
6196  /**
6197   * Increases an internal content media count variable.
6198   *
6199   * @since 5.9.0
6200   * @access private
6201   *
6202   * @param int $amount Optional. Amount to increase by. Default 1.
6203   * @return int The latest content media count, after the increase.
6204   */
6205  function wp_increase_content_media_count( $amount = 1 ) {
6206      static $content_media_count = 0;
6207  
6208      $content_media_count += $amount;
6209  
6210      return $content_media_count;
6211  }
6212  
6213  /**
6214   * Determines whether to add `fetchpriority='high'` to loading attributes.
6215   *
6216   * @since 6.3.0
6217   * @access private
6218   *
6219   * @param array  $loading_attrs Array of the loading optimization attributes for the element.
6220   * @param string $tag_name      The tag name.
6221   * @param array  $attr          Array of the attributes for the element.
6222   * @return array Updated loading optimization attributes for the element.
6223   */
6224  function wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr ) {
6225      // For now, adding `fetchpriority="high"` is only supported for images.
6226      if ( 'img' !== $tag_name ) {
6227          return $loading_attrs;
6228      }
6229  
6230      if ( isset( $attr['fetchpriority'] ) ) {
6231          /*
6232           * While any `fetchpriority` value could be set in `$loading_attrs`,
6233           * for consistency we only do it for `fetchpriority="high"` since that
6234           * is the only possible value that WordPress core would apply on its
6235           * own.
6236           */
6237          if ( 'high' === $attr['fetchpriority'] ) {
6238              $loading_attrs['fetchpriority'] = 'high';
6239              wp_high_priority_element_flag( false );
6240          }
6241  
6242          return $loading_attrs;
6243      }
6244  
6245      // Lazy-loading and `fetchpriority="high"` are mutually exclusive.
6246      if ( isset( $loading_attrs['loading'] ) && 'lazy' === $loading_attrs['loading'] ) {
6247          return $loading_attrs;
6248      }
6249  
6250      if ( ! wp_high_priority_element_flag() ) {
6251          return $loading_attrs;
6252      }
6253  
6254      /**
6255       * Filters the minimum square-pixels threshold for an image to be eligible as the high-priority image.
6256       *
6257       * @since 6.3.0
6258       *
6259       * @param int $threshold Minimum square-pixels threshold. Default 50000.
6260       */
6261      $wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 );
6262  
6263      if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) {
6264          $loading_attrs['fetchpriority'] = 'high';
6265          wp_high_priority_element_flag( false );
6266      }
6267  
6268      return $loading_attrs;
6269  }
6270  
6271  /**
6272   * Accesses a flag that indicates if an element is a possible candidate for `fetchpriority='high'`.
6273   *
6274   * @since 6.3.0
6275   * @access private
6276   *
6277   * @param bool $value Optional. Used to change the static variable. Default null.
6278   * @return bool Returns true if high-priority element was marked already, otherwise false.
6279   */
6280  function wp_high_priority_element_flag( $value = null ) {
6281      static $high_priority_element = true;
6282  
6283      if ( is_bool( $value ) ) {
6284          $high_priority_element = $value;
6285      }
6286  
6287      return $high_priority_element;
6288  }
6289  
6290  /**
6291   * Determines the output format for the image editor.
6292   *
6293   * @since 6.7.0
6294   * @access private
6295   *
6296   * @param string $filename  Path to the image.
6297   * @param string $mime_type The source image mime type.
6298   * @return string[] An array of mime type mappings.
6299   */
6300  function wp_get_image_editor_output_format( $filename, $mime_type ) {
6301      $output_format = array(
6302          'image/heic'          => 'image/jpeg',
6303          'image/heif'          => 'image/jpeg',
6304          'image/heic-sequence' => 'image/jpeg',
6305          'image/heif-sequence' => 'image/jpeg',
6306      );
6307  
6308      /**
6309       * Filters the image editor output format mapping.
6310       *
6311       * Enables filtering the mime type used to save images. By default HEIC/HEIF images
6312       * are converted to JPEGs.
6313       *
6314       * @see WP_Image_Editor::get_output_format()
6315       *
6316       * @since 5.8.0
6317       * @since 6.7.0 The default was changed from an empty array to an array
6318       *              containing the HEIC/HEIF images mime types.
6319       *
6320       * @param string[] $output_format {
6321       *     An array of mime type mappings. Maps a source mime type to a new
6322       *     destination mime type. By default maps HEIC/HEIF input to JPEG output.
6323       *
6324       *     @type string ...$0 The new mime type.
6325       * }
6326       * @param string $filename  Path to the image.
6327       * @param string $mime_type The source image mime type.
6328       */
6329      return apply_filters( 'image_editor_output_format', $output_format, $filename, $mime_type );
6330  }


Generated : Sat Jun 14 08:20:01 2025 Cross-referenced by PHPXref