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


Generated : Fri Jul 10 08:20:14 2026 Cross-referenced by PHPXref