[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Fri Jul 11 08:20:01 2025 Cross-referenced by PHPXref