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


Generated : Tue Mar 19 08:20:01 2024 Cross-referenced by PHPXref