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


Generated : Wed Sep 3 08:20:02 2025 Cross-referenced by PHPXref