[ 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      // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
 221      // Otherwise, a non-image type could be returned.
 222      if ( ! $is_image ) {
 223          if ( ! empty( $meta['sizes']['full'] ) ) {
 224              $img_url          = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
 225              $img_url_basename = $meta['sizes']['full']['file'];
 226              $width            = $meta['sizes']['full']['width'];
 227              $height           = $meta['sizes']['full']['height'];
 228          } else {
 229              return false;
 230          }
 231      }
 232  
 233      // Try for a new style intermediate size.
 234      $intermediate = image_get_intermediate_size( $id, $size );
 235  
 236      if ( $intermediate ) {
 237          $img_url         = str_replace( $img_url_basename, $intermediate['file'], $img_url );
 238          $width           = $intermediate['width'];
 239          $height          = $intermediate['height'];
 240          $is_intermediate = true;
 241      } elseif ( 'thumbnail' === $size && ! empty( $meta['thumb'] ) && is_string( $meta['thumb'] ) ) {
 242          // Fall back to the old thumbnail.
 243          $imagefile = get_attached_file( $id );
 244          $thumbfile = str_replace( wp_basename( $imagefile ), wp_basename( $meta['thumb'] ), $imagefile );
 245  
 246          if ( file_exists( $thumbfile ) ) {
 247              $info = wp_getimagesize( $thumbfile );
 248  
 249              if ( $info ) {
 250                  $img_url         = str_replace( $img_url_basename, wp_basename( $thumbfile ), $img_url );
 251                  $width           = $info[0];
 252                  $height          = $info[1];
 253                  $is_intermediate = true;
 254              }
 255          }
 256      }
 257  
 258      if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) {
 259          // Any other type: use the real image.
 260          $width  = $meta['width'];
 261          $height = $meta['height'];
 262      }
 263  
 264      if ( $img_url ) {
 265          // We have the actual image size, but might need to further constrain it if content_width is narrower.
 266          list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
 267  
 268          return array( $img_url, $width, $height, $is_intermediate );
 269      }
 270  
 271      return false;
 272  }
 273  
 274  /**
 275   * Registers a new image size.
 276   *
 277   * @since 2.9.0
 278   *
 279   * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
 280   *
 281   * @param string     $name   Image size identifier.
 282   * @param int        $width  Optional. Image width in pixels. Default 0.
 283   * @param int        $height Optional. Image height in pixels. Default 0.
 284   * @param bool|array $crop   Optional. Image cropping behavior. If false, the image will be scaled (default),
 285   *                           If true, image will be cropped to the specified dimensions using center positions.
 286   *                           If an array, the image will be cropped using the array to specify the crop location.
 287   *                           Array values must be in the format: array( x_crop_position, y_crop_position ) where:
 288   *                               - x_crop_position accepts: 'left', 'center', or 'right'.
 289   *                               - y_crop_position accepts: 'top', 'center', or 'bottom'.
 290   */
 291  function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
 292      global $_wp_additional_image_sizes;
 293  
 294      $_wp_additional_image_sizes[ $name ] = array(
 295          'width'  => absint( $width ),
 296          'height' => absint( $height ),
 297          'crop'   => $crop,
 298      );
 299  }
 300  
 301  /**
 302   * Checks if an image size exists.
 303   *
 304   * @since 3.9.0
 305   *
 306   * @param string $name The image size to check.
 307   * @return bool True if the image size exists, false if not.
 308   */
 309  function has_image_size( $name ) {
 310      $sizes = wp_get_additional_image_sizes();
 311      return isset( $sizes[ $name ] );
 312  }
 313  
 314  /**
 315   * Removes a new image size.
 316   *
 317   * @since 3.9.0
 318   *
 319   * @global array $_wp_additional_image_sizes
 320   *
 321   * @param string $name The image size to remove.
 322   * @return bool True if the image size was successfully removed, false on failure.
 323   */
 324  function remove_image_size( $name ) {
 325      global $_wp_additional_image_sizes;
 326  
 327      if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
 328          unset( $_wp_additional_image_sizes[ $name ] );
 329          return true;
 330      }
 331  
 332      return false;
 333  }
 334  
 335  /**
 336   * Registers an image size for the post thumbnail.
 337   *
 338   * @since 2.9.0
 339   *
 340   * @see add_image_size() for details on cropping behavior.
 341   *
 342   * @param int        $width  Image width in pixels.
 343   * @param int        $height Image height in pixels.
 344   * @param bool|array $crop   Optional. Whether to crop images to specified width and height or resize.
 345   *                           An array can specify positioning of the crop area. Default false.
 346   */
 347  function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
 348      add_image_size( 'post-thumbnail', $width, $height, $crop );
 349  }
 350  
 351  /**
 352   * Gets an img tag for an image attachment, scaling it down if requested.
 353   *
 354   * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
 355   * image without having to use regular expressions on the HTML content. The
 356   * parameters are: what WordPress will use for the class, the Attachment ID,
 357   * image align value, and the size the image should be.
 358   *
 359   * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
 360   * further manipulated by a plugin to change all attribute values and even HTML
 361   * content.
 362   *
 363   * @since 2.5.0
 364   *
 365   * @param int          $id    Attachment ID.
 366   * @param string       $alt   Image description for the alt attribute.
 367   * @param string       $title Image description for the title attribute.
 368   * @param string       $align Part of the class name for aligning the image.
 369   * @param string|int[] $size  Optional. Image size. Accepts any registered image size name, or an array of
 370   *                            width and height values in pixels (in that order). Default 'medium'.
 371   * @return string HTML IMG element for given image attachment?
 372   */
 373  function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
 374  
 375      list( $img_src, $width, $height ) = image_downsize( $id, $size );
 376      $hwstring                         = image_hwstring( $width, $height );
 377  
 378      $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
 379  
 380      $size_class = is_array( $size ) ? implode( 'x', $size ) : $size;
 381      $class      = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id;
 382  
 383      /**
 384       * Filters the value of the attachment's image tag class attribute.
 385       *
 386       * @since 2.6.0
 387       *
 388       * @param string       $class CSS class name or space-separated list of classes.
 389       * @param int          $id    Attachment ID.
 390       * @param string       $align Part of the class name for aligning the image.
 391       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 392       *                            an array of width and height values in pixels (in that order).
 393       */
 394      $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
 395  
 396      $html = '<img src="' . esc_url( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
 397  
 398      /**
 399       * Filters the HTML content for the image tag.
 400       *
 401       * @since 2.6.0
 402       *
 403       * @param string       $html  HTML content for the image.
 404       * @param int          $id    Attachment ID.
 405       * @param string       $alt   Image description for the alt attribute.
 406       * @param string       $title Image description for the title attribute.
 407       * @param string       $align Part of the class name for aligning the image.
 408       * @param string|int[] $size  Requested image size. Can be any registered image size name, or
 409       *                            an array of width and height values in pixels (in that order).
 410       */
 411      return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
 412  }
 413  
 414  /**
 415   * Calculates the new dimensions for a down-sampled image.
 416   *
 417   * If either width or height are empty, no constraint is applied on
 418   * that dimension.
 419   *
 420   * @since 2.5.0
 421   *
 422   * @param int $current_width  Current width of the image.
 423   * @param int $current_height Current height of the image.
 424   * @param int $max_width      Optional. Max width in pixels to constrain to. Default 0.
 425   * @param int $max_height     Optional. Max height in pixels to constrain to. Default 0.
 426   * @return int[] {
 427   *     An array of width and height values.
 428   *
 429   *     @type int $0 The width in pixels.
 430   *     @type int $1 The height in pixels.
 431   * }
 432   */
 433  function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
 434      if ( ! $max_width && ! $max_height ) {
 435          return array( $current_width, $current_height );
 436      }
 437  
 438      $width_ratio  = 1.0;
 439      $height_ratio = 1.0;
 440      $did_width    = false;
 441      $did_height   = false;
 442  
 443      if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
 444          $width_ratio = $max_width / $current_width;
 445          $did_width   = true;
 446      }
 447  
 448      if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
 449          $height_ratio = $max_height / $current_height;
 450          $did_height   = true;
 451      }
 452  
 453      // Calculate the larger/smaller ratios.
 454      $smaller_ratio = min( $width_ratio, $height_ratio );
 455      $larger_ratio  = max( $width_ratio, $height_ratio );
 456  
 457      if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
 458          // The larger ratio is too big. It would result in an overflow.
 459          $ratio = $smaller_ratio;
 460      } else {
 461          // The larger ratio fits, and is likely to be a more "snug" fit.
 462          $ratio = $larger_ratio;
 463      }
 464  
 465      // Very small dimensions may result in 0, 1 should be the minimum.
 466      $w = max( 1, (int) round( $current_width * $ratio ) );
 467      $h = max( 1, (int) round( $current_height * $ratio ) );
 468  
 469      /*
 470       * Sometimes, due to rounding, we'll end up with a result like this:
 471       * 465x700 in a 177x177 box is 117x176... a pixel short.
 472       * We also have issues with recursive calls resulting in an ever-changing result.
 473       * Constraining to the result of a constraint should yield the original result.
 474       * Thus we look for dimensions that are one pixel shy of the max value and bump them up.
 475       */
 476  
 477      // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
 478      if ( $did_width && $w === $max_width - 1 ) {
 479          $w = $max_width; // Round it up.
 480      }
 481  
 482      // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
 483      if ( $did_height && $h === $max_height - 1 ) {
 484          $h = $max_height; // Round it up.
 485      }
 486  
 487      /**
 488       * Filters dimensions to constrain down-sampled images to.
 489       *
 490       * @since 4.1.0
 491       *
 492       * @param int[] $dimensions     {
 493       *     An array of width and height values.
 494       *
 495       *     @type int $0 The width in pixels.
 496       *     @type int $1 The height in pixels.
 497       * }
 498       * @param int   $current_width  The current width of the image.
 499       * @param int   $current_height The current height of the image.
 500       * @param int   $max_width      The maximum width permitted.
 501       * @param int   $max_height     The maximum height permitted.
 502       */
 503      return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
 504  }
 505  
 506  /**
 507   * Retrieves calculated resize dimensions for use in WP_Image_Editor.
 508   *
 509   * Calculates dimensions and coordinates for a resized image that fits
 510   * within a specified width and height.
 511   *
 512   * Cropping behavior is dependent on the value of $crop:
 513   * 1. If false (default), images will not be cropped.
 514   * 2. If an array in the form of array( x_crop_position, y_crop_position ):
 515   *    - x_crop_position accepts 'left' 'center', or 'right'.
 516   *    - y_crop_position accepts 'top', 'center', or 'bottom'.
 517   *    Images will be cropped to the specified dimensions within the defined crop area.
 518   * 3. If true, images will be cropped to the specified dimensions using center positions.
 519   *
 520   * @since 2.5.0
 521   *
 522   * @param int        $orig_w Original width in pixels.
 523   * @param int        $orig_h Original height in pixels.
 524   * @param int        $dest_w New width in pixels.
 525   * @param int        $dest_h New height in pixels.
 526   * @param bool|array $crop   Optional. Whether to crop image to specified width and height or resize.
 527   *                           An array can specify positioning of the crop area. Default false.
 528   * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure.
 529   */
 530  function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
 531  
 532      if ( $orig_w <= 0 || $orig_h <= 0 ) {
 533          return false;
 534      }
 535      // At least one of $dest_w or $dest_h must be specific.
 536      if ( $dest_w <= 0 && $dest_h <= 0 ) {
 537          return false;
 538      }
 539  
 540      /**
 541       * Filters whether to preempt calculating the image resize dimensions.
 542       *
 543       * Returning a non-null value from the filter will effectively short-circuit
 544       * image_resize_dimensions(), returning that value instead.
 545       *
 546       * @since 3.4.0
 547       *
 548       * @param null|mixed $null   Whether to preempt output of the resize dimensions.
 549       * @param int        $orig_w Original width in pixels.
 550       * @param int        $orig_h Original height in pixels.
 551       * @param int        $dest_w New width in pixels.
 552       * @param int        $dest_h New height in pixels.
 553       * @param bool|array $crop   Whether to crop image to specified width and height or resize.
 554       *                           An array can specify positioning of the crop area. Default false.
 555       */
 556      $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
 557  
 558      if ( null !== $output ) {
 559          return $output;
 560      }
 561  
 562      // Stop if the destination size is larger than the original image dimensions.
 563      if ( empty( $dest_h ) ) {
 564          if ( $orig_w < $dest_w ) {
 565              return false;
 566          }
 567      } elseif ( empty( $dest_w ) ) {
 568          if ( $orig_h < $dest_h ) {
 569              return false;
 570          }
 571      } else {
 572          if ( $orig_w < $dest_w && $orig_h < $dest_h ) {
 573              return false;
 574          }
 575      }
 576  
 577      if ( $crop ) {
 578          /*
 579           * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h.
 580           * Note that the requested crop dimensions are used as a maximum bounding box for the original image.
 581           * If the original image's width or height is less than the requested width or height
 582           * only the greater one will be cropped.
 583           * For example when the original image is 600x300, and the requested crop dimensions are 400x400,
 584           * the resulting image will be 400x300.
 585           */
 586          $aspect_ratio = $orig_w / $orig_h;
 587          $new_w        = min( $dest_w, $orig_w );
 588          $new_h        = min( $dest_h, $orig_h );
 589  
 590          if ( ! $new_w ) {
 591              $new_w = (int) round( $new_h * $aspect_ratio );
 592          }
 593  
 594          if ( ! $new_h ) {
 595              $new_h = (int) round( $new_w / $aspect_ratio );
 596          }
 597  
 598          $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );
 599  
 600          $crop_w = round( $new_w / $size_ratio );
 601          $crop_h = round( $new_h / $size_ratio );
 602  
 603          if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
 604              $crop = array( 'center', 'center' );
 605          }
 606  
 607          list( $x, $y ) = $crop;
 608  
 609          if ( 'left' === $x ) {
 610              $s_x = 0;
 611          } elseif ( 'right' === $x ) {
 612              $s_x = $orig_w - $crop_w;
 613          } else {
 614              $s_x = floor( ( $orig_w - $crop_w ) / 2 );
 615          }
 616  
 617          if ( 'top' === $y ) {
 618              $s_y = 0;
 619          } elseif ( 'bottom' === $y ) {
 620              $s_y = $orig_h - $crop_h;
 621          } else {
 622              $s_y = floor( ( $orig_h - $crop_h ) / 2 );
 623          }
 624      } else {
 625          // Resize using $dest_w x $dest_h as a maximum bounding box.
 626          $crop_w = $orig_w;
 627          $crop_h = $orig_h;
 628  
 629          $s_x = 0;
 630          $s_y = 0;
 631  
 632          list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
 633      }
 634  
 635      if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) {
 636          // The new size has virtually the same dimensions as the original image.
 637  
 638          /**
 639           * Filters whether to proceed with making an image sub-size with identical dimensions
 640           * with the original/source image. Differences of 1px may be due to rounding and are ignored.
 641           *
 642           * @since 5.3.0
 643           *
 644           * @param bool $proceed The filtered value.
 645           * @param int  $orig_w  Original image width.
 646           * @param int  $orig_h  Original image height.
 647           */
 648          $proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h );
 649  
 650          if ( ! $proceed ) {
 651              return false;
 652          }
 653      }
 654  
 655      // The return array matches the parameters to imagecopyresampled().
 656      // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
 657      return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
 658  }
 659  
 660  /**
 661   * Resizes an image to make a thumbnail or intermediate size.
 662   *
 663   * The returned array has the file size, the image width, and image height. The
 664   * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
 665   * values of the returned array. The only parameter is the resized file path.
 666   *
 667   * @since 2.5.0
 668   *
 669   * @param string $file   File path.
 670   * @param int    $width  Image width.
 671   * @param int    $height Image height.
 672   * @param bool   $crop   Optional. Whether to crop image to specified width and height or resize.
 673   *                       Default false.
 674   * @return array|false Metadata array on success. False if no image was created.
 675   */
 676  function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
 677      if ( $width || $height ) {
 678          $editor = wp_get_image_editor( $file );
 679  
 680          if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
 681              return false;
 682          }
 683  
 684          $resized_file = $editor->save();
 685  
 686          if ( ! is_wp_error( $resized_file ) && $resized_file ) {
 687              unset( $resized_file['path'] );
 688              return $resized_file;
 689          }
 690      }
 691      return false;
 692  }
 693  
 694  /**
 695   * Helper function to test if aspect ratios for two images match.
 696   *
 697   * @since 4.6.0
 698   *
 699   * @param int $source_width  Width of the first image in pixels.
 700   * @param int $source_height Height of the first image in pixels.
 701   * @param int $target_width  Width of the second image in pixels.
 702   * @param int $target_height Height of the second image in pixels.
 703   * @return bool True if aspect ratios match within 1px. False if not.
 704   */
 705  function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
 706      /*
 707       * To test for varying crops, we constrain the dimensions of the larger image
 708       * to the dimensions of the smaller image and see if they match.
 709       */
 710      if ( $source_width > $target_width ) {
 711          $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
 712          $expected_size    = array( $target_width, $target_height );
 713      } else {
 714          $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
 715          $expected_size    = array( $source_width, $source_height );
 716      }
 717  
 718      // If the image dimensions are within 1px of the expected size, we consider it a match.
 719      $matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
 720  
 721      return $matched;
 722  }
 723  
 724  /**
 725   * Retrieves the image's intermediate size (resized) path, width, and height.
 726   *
 727   * The $size parameter can be an array with the width and height respectively.
 728   * If the size matches the 'sizes' metadata array for width and height, then it
 729   * will be used. If there is no direct match, then the nearest image size larger
 730   * than the specified size will be used. If nothing is found, then the function
 731   * will break out and return false.
 732   *
 733   * The metadata 'sizes' is used for compatible sizes that can be used for the
 734   * parameter $size value.
 735   *
 736   * The url path will be given, when the $size parameter is a string.
 737   *
 738   * If you are passing an array for the $size, you should consider using
 739   * add_image_size() so that a cropped version is generated. It's much more
 740   * efficient than having to find the closest-sized image and then having the
 741   * browser scale down the image.
 742   *
 743   * @since 2.5.0
 744   *
 745   * @param int          $post_id Attachment ID.
 746   * @param string|int[] $size    Optional. Image size. Accepts any registered image size name, or an array
 747   *                              of width and height values in pixels (in that order). Default 'thumbnail'.
 748   * @return array|false {
 749   *     Array of file relative path, width, and height on success. Additionally includes absolute
 750   *     path and URL if registered size is passed to `$size` parameter. False on failure.
 751   *
 752   *     @type string $file   Path of image relative to uploads directory.
 753   *     @type int    $width  Width of image in pixels.
 754   *     @type int    $height Height of image in pixels.
 755   *     @type string $path   Absolute filesystem path of image.
 756   *     @type string $url    URL of image.
 757   * }
 758   */
 759  function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
 760      $imagedata = wp_get_attachment_metadata( $post_id );
 761  
 762      if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
 763          return false;
 764      }
 765  
 766      $data = array();
 767  
 768      // Find the best match when '$size' is an array.
 769      if ( is_array( $size ) ) {
 770          $candidates = array();
 771  
 772          if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
 773              $imagedata['height'] = $imagedata['sizes']['full']['height'];
 774              $imagedata['width']  = $imagedata['sizes']['full']['width'];
 775          }
 776  
 777          foreach ( $imagedata['sizes'] as $_size => $data ) {
 778              // If there's an exact match to an existing image size, short circuit.
 779              if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) {
 780                  $candidates[ $data['width'] * $data['height'] ] = $data;
 781                  break;
 782              }
 783  
 784              // If it's not an exact match, consider larger sizes with the same aspect ratio.
 785              if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
 786                  // If '0' is passed to either size, we test ratios against the original file.
 787                  if ( 0 === $size[0] || 0 === $size[1] ) {
 788                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
 789                  } else {
 790                      $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
 791                  }
 792  
 793                  if ( $same_ratio ) {
 794                      $candidates[ $data['width'] * $data['height'] ] = $data;
 795                  }
 796              }
 797          }
 798  
 799          if ( ! empty( $candidates ) ) {
 800              // Sort the array by size if we have more than one candidate.
 801              if ( 1 < count( $candidates ) ) {
 802                  ksort( $candidates );
 803              }
 804  
 805              $data = array_shift( $candidates );
 806              /*
 807              * When the size requested is smaller than the thumbnail dimensions, we
 808              * fall back to the thumbnail size to maintain backward compatibility with
 809              * pre 4.6 versions of WordPress.
 810              */
 811          } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
 812              $data = $imagedata['sizes']['thumbnail'];
 813          } else {
 814              return false;
 815          }
 816  
 817          // Constrain the width and height attributes to the requested values.
 818          list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
 819  
 820      } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
 821          $data = $imagedata['sizes'][ $size ];
 822      }
 823  
 824      // If we still don't have a match at this point, return false.
 825      if ( empty( $data ) ) {
 826          return false;
 827      }
 828  
 829      // Include the full filesystem path of the intermediate file.
 830      if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
 831          $file_url     = wp_get_attachment_url( $post_id );
 832          $data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
 833          $data['url']  = path_join( dirname( $file_url ), $data['file'] );
 834      }
 835  
 836      /**
 837       * Filters the output of image_get_intermediate_size()
 838       *
 839       * @since 4.4.0
 840       *
 841       * @see image_get_intermediate_size()
 842       *
 843       * @param array        $data    Array of file relative path, width, and height on success. May also include
 844       *                              file absolute path and URL.
 845       * @param int          $post_id The ID of the image attachment.
 846       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
 847       *                              an array of width and height values in pixels (in that order).
 848       */
 849      return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
 850  }
 851  
 852  /**
 853   * Gets the available intermediate image size names.
 854   *
 855   * @since 3.0.0
 856   *
 857   * @return string[] An array of image size names.
 858   */
 859  function get_intermediate_image_sizes() {
 860      $default_sizes    = array( 'thumbnail', 'medium', 'medium_large', 'large' );
 861      $additional_sizes = wp_get_additional_image_sizes();
 862  
 863      if ( ! empty( $additional_sizes ) ) {
 864          $default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) );
 865      }
 866  
 867      /**
 868       * Filters the list of intermediate image sizes.
 869       *
 870       * @since 2.5.0
 871       *
 872       * @param string[] $default_sizes An array of intermediate image size names. Defaults
 873       *                                are 'thumbnail', 'medium', 'medium_large', 'large'.
 874       */
 875      return apply_filters( 'intermediate_image_sizes', $default_sizes );
 876  }
 877  
 878  /**
 879   * Returns a normalized list of all currently registered image sub-sizes.
 880   *
 881   * @since 5.3.0
 882   * @uses wp_get_additional_image_sizes()
 883   * @uses get_intermediate_image_sizes()
 884   *
 885   * @return array[] Associative array of arrays of image sub-size information,
 886   *                 keyed by image size name.
 887   */
 888  function wp_get_registered_image_subsizes() {
 889      $additional_sizes = wp_get_additional_image_sizes();
 890      $all_sizes        = array();
 891  
 892      foreach ( get_intermediate_image_sizes() as $size_name ) {
 893          $size_data = array(
 894              'width'  => 0,
 895              'height' => 0,
 896              'crop'   => false,
 897          );
 898  
 899          if ( isset( $additional_sizes[ $size_name ]['width'] ) ) {
 900              // For sizes added by plugins and themes.
 901              $size_data['width'] = (int) $additional_sizes[ $size_name ]['width'];
 902          } else {
 903              // For default sizes set in options.
 904              $size_data['width'] = (int) get_option( "{$size_name}_size_w" );
 905          }
 906  
 907          if ( isset( $additional_sizes[ $size_name ]['height'] ) ) {
 908              $size_data['height'] = (int) $additional_sizes[ $size_name ]['height'];
 909          } else {
 910              $size_data['height'] = (int) get_option( "{$size_name}_size_h" );
 911          }
 912  
 913          if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) {
 914              // This size isn't set.
 915              continue;
 916          }
 917  
 918          if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
 919              $size_data['crop'] = $additional_sizes[ $size_name ]['crop'];
 920          } else {
 921              $size_data['crop'] = get_option( "{$size_name}_crop" );
 922          }
 923  
 924          if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) {
 925              $size_data['crop'] = (bool) $size_data['crop'];
 926          }
 927  
 928          $all_sizes[ $size_name ] = $size_data;
 929      }
 930  
 931      return $all_sizes;
 932  }
 933  
 934  /**
 935   * Retrieves an image to represent an attachment.
 936   *
 937   * @since 2.5.0
 938   *
 939   * @param int          $attachment_id Image attachment ID.
 940   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
 941   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
 942   * @param bool         $icon          Optional. Whether the image should fall back to a mime type icon. Default false.
 943   * @return array|false {
 944   *     Array of image data, or boolean false if no image is available.
 945   *
 946   *     @type string $0 Image source URL.
 947   *     @type int    $1 Image width in pixels.
 948   *     @type int    $2 Image height in pixels.
 949   *     @type bool   $3 Whether the image is a resized image.
 950   * }
 951   */
 952  function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
 953      // Get a thumbnail or intermediate image if there is one.
 954      $image = image_downsize( $attachment_id, $size );
 955      if ( ! $image ) {
 956          $src = false;
 957  
 958          if ( $icon ) {
 959              $src = wp_mime_type_icon( $attachment_id );
 960  
 961              if ( $src ) {
 962                  /** This filter is documented in wp-includes/post.php */
 963                  $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
 964  
 965                  $src_file               = $icon_dir . '/' . wp_basename( $src );
 966                  list( $width, $height ) = wp_getimagesize( $src_file );
 967              }
 968          }
 969  
 970          if ( $src && $width && $height ) {
 971              $image = array( $src, $width, $height, false );
 972          }
 973      }
 974      /**
 975       * Filters the attachment image source result.
 976       *
 977       * @since 4.3.0
 978       *
 979       * @param array|false  $image         {
 980       *     Array of image data, or boolean false if no image is available.
 981       *
 982       *     @type string $0 Image source URL.
 983       *     @type int    $1 Image width in pixels.
 984       *     @type int    $2 Image height in pixels.
 985       *     @type bool   $3 Whether the image is a resized image.
 986       * }
 987       * @param int          $attachment_id Image attachment ID.
 988       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
 989       *                                    an array of width and height values in pixels (in that order).
 990       * @param bool         $icon          Whether the image should be treated as an icon.
 991       */
 992      return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
 993  }
 994  
 995  /**
 996   * Gets an HTML img element representing an image attachment.
 997   *
 998   * While `$size` will accept an array, it is better to register a size with
 999   * add_image_size() so that a cropped version is generated. It's much more
1000   * efficient than having to find the closest-sized image and then having the
1001   * browser scale down the image.
1002   *
1003   * @since 2.5.0
1004   * @since 4.4.0 The `$srcset` and `$sizes` attributes were added.
1005   * @since 5.5.0 The `$loading` attribute was added.
1006   * @since 6.1.0 The `$decoding` attribute was added.
1007   *
1008   * @param int          $attachment_id Image attachment ID.
1009   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array
1010   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
1011   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1012   * @param string|array $attr {
1013   *     Optional. Attributes for the image markup.
1014   *
1015   *     @type string       $src      Image attachment URL.
1016   *     @type string       $class    CSS class name or space-separated list of classes.
1017   *                                  Default `attachment-$size_class size-$size_class`,
1018   *                                  where `$size_class` is the image size being requested.
1019   *     @type string       $alt      Image description for the alt attribute.
1020   *     @type string       $srcset   The 'srcset' attribute value.
1021   *     @type string       $sizes    The 'sizes' attribute value.
1022   *     @type string|false $loading  The 'loading' attribute value. Passing a value of false
1023   *                                  will result in the attribute being omitted for the image.
1024   *                                  Defaults to 'lazy', depending on wp_lazy_loading_enabled().
1025   *     @type string       $decoding The 'decoding' attribute value. Possible values are
1026   *                                  'async' (default), 'sync', or 'auto'.
1027   * }
1028   * @return string HTML img element or empty string on failure.
1029   */
1030  function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
1031      $html  = '';
1032      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1033  
1034      if ( $image ) {
1035          list( $src, $width, $height ) = $image;
1036  
1037          $attachment = get_post( $attachment_id );
1038          $hwstring   = image_hwstring( $width, $height );
1039          $size_class = $size;
1040  
1041          if ( is_array( $size_class ) ) {
1042              $size_class = implode( 'x', $size_class );
1043          }
1044  
1045          $default_attr = array(
1046              'src'      => $src,
1047              'class'    => "attachment-$size_class size-$size_class",
1048              'alt'      => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
1049              'decoding' => 'async',
1050          );
1051  
1052          // Add `loading` attribute.
1053          if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
1054              $default_attr['loading'] = wp_get_loading_attr_default( 'wp_get_attachment_image' );
1055          }
1056  
1057          $attr = wp_parse_args( $attr, $default_attr );
1058  
1059          // If the default value of `lazy` for the `loading` attribute is overridden
1060          // to omit the attribute for this image, ensure it is not included.
1061          if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
1062              unset( $attr['loading'] );
1063          }
1064  
1065          // Generate 'srcset' and 'sizes' if not already present.
1066          if ( empty( $attr['srcset'] ) ) {
1067              $image_meta = wp_get_attachment_metadata( $attachment_id );
1068  
1069              if ( is_array( $image_meta ) ) {
1070                  $size_array = array( absint( $width ), absint( $height ) );
1071                  $srcset     = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
1072                  $sizes      = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
1073  
1074                  if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
1075                      $attr['srcset'] = $srcset;
1076  
1077                      if ( empty( $attr['sizes'] ) ) {
1078                          $attr['sizes'] = $sizes;
1079                      }
1080                  }
1081              }
1082          }
1083  
1084          /**
1085           * Filters the list of attachment image attributes.
1086           *
1087           * @since 2.8.0
1088           *
1089           * @param string[]     $attr       Array of attribute values for the image markup, keyed by attribute name.
1090           *                                 See wp_get_attachment_image().
1091           * @param WP_Post      $attachment Image attachment post.
1092           * @param string|int[] $size       Requested image size. Can be any registered image size name, or
1093           *                                 an array of width and height values in pixels (in that order).
1094           */
1095          $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
1096  
1097          $attr = array_map( 'esc_attr', $attr );
1098          $html = rtrim( "<img $hwstring" );
1099  
1100          foreach ( $attr as $name => $value ) {
1101              $html .= " $name=" . '"' . $value . '"';
1102          }
1103  
1104          $html .= ' />';
1105      }
1106  
1107      /**
1108       * Filters the HTML img element representing an image attachment.
1109       *
1110       * @since 5.6.0
1111       *
1112       * @param string       $html          HTML img element or empty string on failure.
1113       * @param int          $attachment_id Image attachment ID.
1114       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1115       *                                    an array of width and height values in pixels (in that order).
1116       * @param bool         $icon          Whether the image should be treated as an icon.
1117       * @param string[]     $attr          Array of attribute values for the image markup, keyed by attribute name.
1118       *                                    See wp_get_attachment_image().
1119       */
1120      return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
1121  }
1122  
1123  /**
1124   * Gets the URL of an image attachment.
1125   *
1126   * @since 4.4.0
1127   *
1128   * @param int          $attachment_id Image attachment ID.
1129   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1130   *                                    width and height values in pixels (in that order). Default 'thumbnail'.
1131   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1132   * @return string|false Attachment URL or false if no image is available. If `$size` does not match
1133   *                      any registered image size, the original image URL will be returned.
1134   */
1135  function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
1136      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1137      return isset( $image[0] ) ? $image[0] : false;
1138  }
1139  
1140  /**
1141   * Gets the attachment path relative to the upload directory.
1142   *
1143   * @since 4.4.1
1144   * @access private
1145   *
1146   * @param string $file Attachment file name.
1147   * @return string Attachment path relative to the upload directory.
1148   */
1149  function _wp_get_attachment_relative_path( $file ) {
1150      $dirname = dirname( $file );
1151  
1152      if ( '.' === $dirname ) {
1153          return '';
1154      }
1155  
1156      if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
1157          // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
1158          $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
1159          $dirname = ltrim( $dirname, '/' );
1160      }
1161  
1162      return $dirname;
1163  }
1164  
1165  /**
1166   * Gets the image size as array from its meta data.
1167   *
1168   * Used for responsive images.
1169   *
1170   * @since 4.4.0
1171   * @access private
1172   *
1173   * @param string $size_name  Image size. Accepts any registered image size name.
1174   * @param array  $image_meta The image meta data.
1175   * @return array|false {
1176   *     Array of width and height or false if the size isn't present in the meta data.
1177   *
1178   *     @type int $0 Image width.
1179   *     @type int $1 Image height.
1180   * }
1181   */
1182  function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
1183      if ( 'full' === $size_name ) {
1184          return array(
1185              absint( $image_meta['width'] ),
1186              absint( $image_meta['height'] ),
1187          );
1188      } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) {
1189          return array(
1190              absint( $image_meta['sizes'][ $size_name ]['width'] ),
1191              absint( $image_meta['sizes'][ $size_name ]['height'] ),
1192          );
1193      }
1194  
1195      return false;
1196  }
1197  
1198  /**
1199   * Retrieves the value for an image attachment's 'srcset' attribute.
1200   *
1201   * @since 4.4.0
1202   *
1203   * @see wp_calculate_image_srcset()
1204   *
1205   * @param int          $attachment_id Image attachment ID.
1206   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1207   *                                    width and height values in pixels (in that order). Default 'medium'.
1208   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1209   *                                    Default null.
1210   * @return string|false A 'srcset' value string or false.
1211   */
1212  function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
1213      $image = wp_get_attachment_image_src( $attachment_id, $size );
1214  
1215      if ( ! $image ) {
1216          return false;
1217      }
1218  
1219      if ( ! is_array( $image_meta ) ) {
1220          $image_meta = wp_get_attachment_metadata( $attachment_id );
1221      }
1222  
1223      $image_src  = $image[0];
1224      $size_array = array(
1225          absint( $image[1] ),
1226          absint( $image[2] ),
1227      );
1228  
1229      return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1230  }
1231  
1232  /**
1233   * A helper function to calculate the image sources to include in a 'srcset' attribute.
1234   *
1235   * @since 4.4.0
1236   *
1237   * @param int[]  $size_array    {
1238   *     An array of width and height values.
1239   *
1240   *     @type int $0 The width in pixels.
1241   *     @type int $1 The height in pixels.
1242   * }
1243   * @param string $image_src     The 'src' of the image.
1244   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1245   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1246   * @return string|false The 'srcset' attribute value. False on error or when only one source exists.
1247   */
1248  function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1249      /**
1250       * Pre-filters the image meta to be able to fix inconsistencies in the stored data.
1251       *
1252       * @since 4.5.0
1253       *
1254       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1255       * @param int[]  $size_array    {
1256       *     An array of requested width and height values.
1257       *
1258       *     @type int $0 The width in pixels.
1259       *     @type int $1 The height in pixels.
1260       * }
1261       * @param string $image_src     The 'src' of the image.
1262       * @param int    $attachment_id The image attachment ID or 0 if not supplied.
1263       */
1264      $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1265  
1266      if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
1267          return false;
1268      }
1269  
1270      $image_sizes = $image_meta['sizes'];
1271  
1272      // Get the width and height of the image.
1273      $image_width  = (int) $size_array[0];
1274      $image_height = (int) $size_array[1];
1275  
1276      // Bail early if error/no width.
1277      if ( $image_width < 1 ) {
1278          return false;
1279      }
1280  
1281      $image_basename = wp_basename( $image_meta['file'] );
1282  
1283      /*
1284       * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1285       * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1286       * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1287       */
1288      if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1289          $image_sizes[] = array(
1290              'width'  => $image_meta['width'],
1291              'height' => $image_meta['height'],
1292              'file'   => $image_basename,
1293          );
1294      } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1295          return false;
1296      }
1297  
1298      // Retrieve the uploads sub-directory from the full size image.
1299      $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1300  
1301      if ( $dirname ) {
1302          $dirname = trailingslashit( $dirname );
1303      }
1304  
1305      $upload_dir    = wp_get_upload_dir();
1306      $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1307  
1308      /*
1309       * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1310       * (which is to say, when they share the domain name of the current request).
1311       */
1312      if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
1313          $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1314      }
1315  
1316      /*
1317       * Images that have been edited in WordPress after being uploaded will
1318       * contain a unique hash. Look for that hash and use it later to filter
1319       * out images that are leftovers from previous versions.
1320       */
1321      $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1322  
1323      /**
1324       * Filters the maximum image width to be included in a 'srcset' attribute.
1325       *
1326       * @since 4.4.0
1327       *
1328       * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '2048'.
1329       * @param int[] $size_array {
1330       *     An array of requested width and height values.
1331       *
1332       *     @type int $0 The width in pixels.
1333       *     @type int $1 The height in pixels.
1334       * }
1335       */
1336      $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
1337  
1338      // Array to hold URL candidates.
1339      $sources = array();
1340  
1341      /**
1342       * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1343       * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1344       * an incorrect image. See #35045.
1345       */
1346      $src_matched = false;
1347  
1348      /*
1349       * Loop through available images. Only use images that are resized
1350       * versions of the same edit.
1351       */
1352      foreach ( $image_sizes as $image ) {
1353          $is_src = false;
1354  
1355          // Check if image meta isn't corrupted.
1356          if ( ! is_array( $image ) ) {
1357              continue;
1358          }
1359  
1360          // If the file name is part of the `src`, we've confirmed a match.
1361          if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1362              $src_matched = true;
1363              $is_src      = true;
1364          }
1365  
1366          // Filter out images that are from previous edits.
1367          if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1368              continue;
1369          }
1370  
1371          /*
1372           * Filters out images that are wider than '$max_srcset_image_width' unless
1373           * that file is in the 'src' attribute.
1374           */
1375          if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1376              continue;
1377          }
1378  
1379          // If the image dimensions are within 1px of the expected size, use it.
1380          if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
1381              // Add the URL, descriptor, and value to the sources array to be returned.
1382              $source = array(
1383                  'url'        => $image_baseurl . $image['file'],
1384                  'descriptor' => 'w',
1385                  'value'      => $image['width'],
1386              );
1387  
1388              // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1389              if ( $is_src ) {
1390                  $sources = array( $image['width'] => $source ) + $sources;
1391              } else {
1392                  $sources[ $image['width'] ] = $source;
1393              }
1394          }
1395      }
1396  
1397      /**
1398       * Filters an image's 'srcset' sources.
1399       *
1400       * @since 4.4.0
1401       *
1402       * @param array  $sources {
1403       *     One or more arrays of source data to include in the 'srcset'.
1404       *
1405       *     @type array $width {
1406       *         @type string $url        The URL of an image source.
1407       *         @type string $descriptor The descriptor type used in the image candidate string,
1408       *                                  either 'w' or 'x'.
1409       *         @type int    $value      The source width if paired with a 'w' descriptor, or a
1410       *                                  pixel density value if paired with an 'x' descriptor.
1411       *     }
1412       * }
1413       * @param array $size_array     {
1414       *     An array of requested width and height values.
1415       *
1416       *     @type int $0 The width in pixels.
1417       *     @type int $1 The height in pixels.
1418       * }
1419       * @param string $image_src     The 'src' of the image.
1420       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1421       * @param int    $attachment_id Image attachment ID or 0.
1422       */
1423      $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1424  
1425      // Only return a 'srcset' value if there is more than one source.
1426      if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) {
1427          return false;
1428      }
1429  
1430      $srcset = '';
1431  
1432      foreach ( $sources as $source ) {
1433          $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
1434      }
1435  
1436      return rtrim( $srcset, ', ' );
1437  }
1438  
1439  /**
1440   * Retrieves the value for an image attachment's 'sizes' attribute.
1441   *
1442   * @since 4.4.0
1443   *
1444   * @see wp_calculate_image_sizes()
1445   *
1446   * @param int          $attachment_id Image attachment ID.
1447   * @param string|int[] $size          Optional. Image size. Accepts any registered image size name, or an array of
1448   *                                    width and height values in pixels (in that order). Default 'medium'.
1449   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1450   *                                    Default null.
1451   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1452   */
1453  function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1454      $image = wp_get_attachment_image_src( $attachment_id, $size );
1455  
1456      if ( ! $image ) {
1457          return false;
1458      }
1459  
1460      if ( ! is_array( $image_meta ) ) {
1461          $image_meta = wp_get_attachment_metadata( $attachment_id );
1462      }
1463  
1464      $image_src  = $image[0];
1465      $size_array = array(
1466          absint( $image[1] ),
1467          absint( $image[2] ),
1468      );
1469  
1470      return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1471  }
1472  
1473  /**
1474   * Creates a 'sizes' attribute value for an image.
1475   *
1476   * @since 4.4.0
1477   *
1478   * @param string|int[] $size          Image size. Accepts any registered image size name, or an array of
1479   *                                    width and height values in pixels (in that order).
1480   * @param string       $image_src     Optional. The URL to the image file. Default null.
1481   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1482   *                                    Default null.
1483   * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1484   *                                    is needed when using the image size name as argument for `$size`. Default 0.
1485   * @return string|false A valid source size value for use in a 'sizes' attribute or false.
1486   */
1487  function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1488      $width = 0;
1489  
1490      if ( is_array( $size ) ) {
1491          $width = absint( $size[0] );
1492      } elseif ( is_string( $size ) ) {
1493          if ( ! $image_meta && $attachment_id ) {
1494              $image_meta = wp_get_attachment_metadata( $attachment_id );
1495          }
1496  
1497          if ( is_array( $image_meta ) ) {
1498              $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1499              if ( $size_array ) {
1500                  $width = absint( $size_array[0] );
1501              }
1502          }
1503      }
1504  
1505      if ( ! $width ) {
1506          return false;
1507      }
1508  
1509      // Setup the default 'sizes' attribute.
1510      $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1511  
1512      /**
1513       * Filters the output of 'wp_calculate_image_sizes()'.
1514       *
1515       * @since 4.4.0
1516       *
1517       * @param string       $sizes         A source size value for use in a 'sizes' attribute.
1518       * @param string|int[] $size          Requested image size. Can be any registered image size name, or
1519       *                                    an array of width and height values in pixels (in that order).
1520       * @param string|null  $image_src     The URL to the image file or null.
1521       * @param array|null   $image_meta    The image meta data as returned by wp_get_attachment_metadata() or null.
1522       * @param int          $attachment_id Image attachment ID of the original image or 0.
1523       */
1524      return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1525  }
1526  
1527  /**
1528   * Determines if the image meta data is for the image source file.
1529   *
1530   * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change.
1531   * For example when the website is exported and imported at another website. Then the
1532   * attachment post IDs that are in post_content for the exported website may not match
1533   * the same attachments at the new website.
1534   *
1535   * @since 5.5.0
1536   *
1537   * @param string $image_location The full path or URI to the image file.
1538   * @param array  $image_meta     The attachment meta data as returned by 'wp_get_attachment_metadata()'.
1539   * @param int    $attachment_id  Optional. The image attachment ID. Default 0.
1540   * @return bool Whether the image meta is for this image file.
1541   */
1542  function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) {
1543      $match = false;
1544  
1545      // Ensure the $image_meta is valid.
1546      if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) {
1547          // Remove quiery args if image URI.
1548          list( $image_location ) = explode( '?', $image_location );
1549  
1550          // Check if the relative image path from the image meta is at the end of $image_location.
1551          if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) {
1552              $match = true;
1553          } else {
1554              // Retrieve the uploads sub-directory from the full size image.
1555              $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1556  
1557              if ( $dirname ) {
1558                  $dirname = trailingslashit( $dirname );
1559              }
1560  
1561              if ( ! empty( $image_meta['original_image'] ) ) {
1562                  $relative_path = $dirname . $image_meta['original_image'];
1563  
1564                  if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1565                      $match = true;
1566                  }
1567              }
1568  
1569              if ( ! $match && ! empty( $image_meta['sizes'] ) ) {
1570                  foreach ( $image_meta['sizes'] as $image_size_data ) {
1571                      $relative_path = $dirname . $image_size_data['file'];
1572  
1573                      if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
1574                          $match = true;
1575                          break;
1576                      }
1577                  }
1578              }
1579          }
1580      }
1581  
1582      /**
1583       * Filters whether an image path or URI matches image meta.
1584       *
1585       * @since 5.5.0
1586       *
1587       * @param bool   $match          Whether the image relative path from the image meta
1588       *                               matches the end of the URI or path to the image file.
1589       * @param string $image_location Full path or URI to the tested image file.
1590       * @param array  $image_meta     The image meta data as returned by 'wp_get_attachment_metadata()'.
1591       * @param int    $attachment_id  The image attachment ID or 0 if not supplied.
1592       */
1593      return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id );
1594  }
1595  
1596  /**
1597   * Determines an image's width and height dimensions based on the source file.
1598   *
1599   * @since 5.5.0
1600   *
1601   * @param string $image_src     The image source file.
1602   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1603   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1604   * @return array|false Array with first element being the width and second element being the height,
1605   *                     or false if dimensions cannot be determined.
1606   */
1607  function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) {
1608      $dimensions = false;
1609  
1610      // Is it a full size image?
1611      if (
1612          isset( $image_meta['file'] ) &&
1613          strpos( $image_src, wp_basename( $image_meta['file'] ) ) !== false
1614      ) {
1615          $dimensions = array(
1616              (int) $image_meta['width'],
1617              (int) $image_meta['height'],
1618          );
1619      }
1620  
1621      if ( ! $dimensions && ! empty( $image_meta['sizes'] ) ) {
1622          $src_filename = wp_basename( $image_src );
1623  
1624          foreach ( $image_meta['sizes'] as $image_size_data ) {
1625              if ( $src_filename === $image_size_data['file'] ) {
1626                  $dimensions = array(
1627                      (int) $image_size_data['width'],
1628                      (int) $image_size_data['height'],
1629                  );
1630  
1631                  break;
1632              }
1633          }
1634      }
1635  
1636      /**
1637       * Filters the 'wp_image_src_get_dimensions' value.
1638       *
1639       * @since 5.7.0
1640       *
1641       * @param array|false $dimensions    Array with first element being the width
1642       *                                   and second element being the height, or
1643       *                                   false if dimensions could not be determined.
1644       * @param string      $image_src     The image source file.
1645       * @param array       $image_meta    The image meta data as returned by
1646       *                                   'wp_get_attachment_metadata()'.
1647       * @param int         $attachment_id The image attachment ID. Default 0.
1648       */
1649      return apply_filters( 'wp_image_src_get_dimensions', $dimensions, $image_src, $image_meta, $attachment_id );
1650  }
1651  
1652  /**
1653   * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1654   *
1655   * @since 4.4.0
1656   *
1657   * @see wp_calculate_image_srcset()
1658   * @see wp_calculate_image_sizes()
1659   *
1660   * @param string $image         An HTML 'img' element to be filtered.
1661   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1662   * @param int    $attachment_id Image attachment ID.
1663   * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1664   */
1665  function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1666      // Ensure the image meta exists.
1667      if ( empty( $image_meta['sizes'] ) ) {
1668          return $image;
1669      }
1670  
1671      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1672      list( $image_src ) = explode( '?', $image_src );
1673  
1674      // Return early if we couldn't get the image source.
1675      if ( ! $image_src ) {
1676          return $image;
1677      }
1678  
1679      // Bail early if an image has been inserted and later edited.
1680      if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1681          strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1682  
1683          return $image;
1684      }
1685  
1686      $width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1687      $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1688  
1689      if ( $width && $height ) {
1690          $size_array = array( $width, $height );
1691      } else {
1692          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
1693          if ( ! $size_array ) {
1694              return $image;
1695          }
1696      }
1697  
1698      $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1699  
1700      if ( $srcset ) {
1701          // Check if there is already a 'sizes' attribute.
1702          $sizes = strpos( $image, ' sizes=' );
1703  
1704          if ( ! $sizes ) {
1705              $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1706          }
1707      }
1708  
1709      if ( $srcset && $sizes ) {
1710          // Format the 'srcset' and 'sizes' string and escape attributes.
1711          $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1712  
1713          if ( is_string( $sizes ) ) {
1714              $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1715          }
1716  
1717          // Add the srcset and sizes attributes to the image markup.
1718          return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1719      }
1720  
1721      return $image;
1722  }
1723  
1724  /**
1725   * Determines whether to add the `loading` attribute to the specified tag in the specified context.
1726   *
1727   * @since 5.5.0
1728   * @since 5.7.0 Now returns `true` by default for `iframe` tags.
1729   *
1730   * @param string $tag_name The tag name.
1731   * @param string $context  Additional context, like the current filter name
1732   *                         or the function name from where this was called.
1733   * @return bool Whether to add the attribute.
1734   */
1735  function wp_lazy_loading_enabled( $tag_name, $context ) {
1736      // By default add to all 'img' and 'iframe' tags.
1737      // See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
1738      // See https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-loading
1739      $default = ( 'img' === $tag_name || 'iframe' === $tag_name );
1740  
1741      /**
1742       * Filters whether to add the `loading` attribute to the specified tag in the specified context.
1743       *
1744       * @since 5.5.0
1745       *
1746       * @param bool   $default  Default value.
1747       * @param string $tag_name The tag name.
1748       * @param string $context  Additional context, like the current filter name
1749       *                         or the function name from where this was called.
1750       */
1751      return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
1752  }
1753  
1754  /**
1755   * Filters specific tags in post content and modifies their markup.
1756   *
1757   * Modifies HTML tags in post content to include new browser and HTML technologies
1758   * that may not have existed at the time of post creation. These modifications currently
1759   * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags, as well
1760   * as adding `loading` attributes to `iframe` HTML tags.
1761   * Future similar optimizations should be added/expected here.
1762   *
1763   * @since 5.5.0
1764   * @since 5.7.0 Now supports adding `loading` attributes to `iframe` tags.
1765   *
1766   * @see wp_img_tag_add_width_and_height_attr()
1767   * @see wp_img_tag_add_srcset_and_sizes_attr()
1768   * @see wp_img_tag_add_loading_attr()
1769   * @see wp_iframe_tag_add_loading_attr()
1770   *
1771   * @param string $content The HTML content to be filtered.
1772   * @param string $context Optional. Additional context to pass to the filters.
1773   *                        Defaults to `current_filter()` when not set.
1774   * @return string Converted content with images modified.
1775   */
1776  function wp_filter_content_tags( $content, $context = null ) {
1777      if ( null === $context ) {
1778          $context = current_filter();
1779      }
1780  
1781      $add_img_loading_attr    = wp_lazy_loading_enabled( 'img', $context );
1782      $add_iframe_loading_attr = wp_lazy_loading_enabled( 'iframe', $context );
1783  
1784      if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
1785          return $content;
1786      }
1787  
1788      // List of the unique `img` tags found in $content.
1789      $images = array();
1790  
1791      // List of the unique `iframe` tags found in $content.
1792      $iframes = array();
1793  
1794      foreach ( $matches as $match ) {
1795          list( $tag, $tag_name ) = $match;
1796  
1797          switch ( $tag_name ) {
1798              case 'img':
1799                  if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) {
1800                      $attachment_id = absint( $class_id[1] );
1801  
1802                      if ( $attachment_id ) {
1803                          // If exactly the same image tag is used more than once, overwrite it.
1804                          // All identical tags will be replaced later with 'str_replace()'.
1805                          $images[ $tag ] = $attachment_id;
1806                          break;
1807                      }
1808                  }
1809                  $images[ $tag ] = 0;
1810                  break;
1811              case 'iframe':
1812                  $iframes[ $tag ] = 0;
1813                  break;
1814          }
1815      }
1816  
1817      // Reduce the array to unique attachment IDs.
1818      $attachment_ids = array_unique( array_filter( array_values( $images ) ) );
1819  
1820      if ( count( $attachment_ids ) > 1 ) {
1821          /*
1822           * Warm the object cache with post and meta information for all found
1823           * images to avoid making individual database calls.
1824           */
1825          _prime_post_caches( $attachment_ids, false, true );
1826      }
1827  
1828      // Iterate through the matches in order of occurrence as it is relevant for whether or not to lazy-load.
1829      foreach ( $matches as $match ) {
1830          // Filter an image match.
1831          if ( isset( $images[ $match[0] ] ) ) {
1832              $filtered_image = $match[0];
1833              $attachment_id  = $images[ $match[0] ];
1834  
1835              // Add 'width' and 'height' attributes if applicable.
1836              if ( $attachment_id > 0 && false === strpos( $filtered_image, ' width=' ) && false === strpos( $filtered_image, ' height=' ) ) {
1837                  $filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id );
1838              }
1839  
1840              // Add 'srcset' and 'sizes' attributes if applicable.
1841              if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
1842                  $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
1843              }
1844  
1845              // Add 'loading' attribute if applicable.
1846              if ( $add_img_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
1847                  $filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
1848              }
1849  
1850              // Add 'decoding=async' attribute unless a 'decoding' attribute is already present.
1851              if ( ! str_contains( $filtered_image, ' decoding=' ) ) {
1852                  $filtered_image = wp_img_tag_add_decoding_attr( $filtered_image, $context );
1853              }
1854  
1855              /**
1856               * Filters an img tag within the content for a given context.
1857               *
1858               * @since 6.0.0
1859               *
1860               * @param string $filtered_image Full img tag with attributes that will replace the source img tag.
1861               * @param string $context        Additional context, like the current filter name or the function name from where this was called.
1862               * @param int    $attachment_id  The image attachment ID. May be 0 in case the image is not an attachment.
1863               */
1864              $filtered_image = apply_filters( 'wp_content_img_tag', $filtered_image, $context, $attachment_id );
1865  
1866              if ( $filtered_image !== $match[0] ) {
1867                  $content = str_replace( $match[0], $filtered_image, $content );
1868              }
1869  
1870              /*
1871               * Unset image lookup to not run the same logic again unnecessarily if the same image tag is used more than
1872               * once in the same blob of content.
1873               */
1874              unset( $images[ $match[0] ] );
1875          }
1876  
1877          // Filter an iframe match.
1878          if ( isset( $iframes[ $match[0] ] ) ) {
1879              $filtered_iframe = $match[0];
1880  
1881              // Add 'loading' attribute if applicable.
1882              if ( $add_iframe_loading_attr && false === strpos( $filtered_iframe, ' loading=' ) ) {
1883                  $filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, $context );
1884              }
1885  
1886              if ( $filtered_iframe !== $match[0] ) {
1887                  $content = str_replace( $match[0], $filtered_iframe, $content );
1888              }
1889  
1890              /*
1891               * Unset iframe lookup to not run the same logic again unnecessarily if the same iframe tag is used more
1892               * than once in the same blob of content.
1893               */
1894              unset( $iframes[ $match[0] ] );
1895          }
1896      }
1897  
1898      return $content;
1899  }
1900  
1901  /**
1902   * Adds `loading` attribute to an `img` HTML tag.
1903   *
1904   * @since 5.5.0
1905   *
1906   * @param string $image   The HTML `img` tag where the attribute should be added.
1907   * @param string $context Additional context to pass to the filters.
1908   * @return string Converted `img` tag with `loading` attribute added.
1909   */
1910  function wp_img_tag_add_loading_attr( $image, $context ) {
1911      // Get loading attribute value to use. This must occur before the conditional check below so that even images that
1912      // are ineligible for being lazy-loaded are considered.
1913      $value = wp_get_loading_attr_default( $context );
1914  
1915      // Images should have source and dimension attributes for the `loading` attribute to be added.
1916      if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) {
1917          return $image;
1918      }
1919  
1920      /**
1921       * Filters the `loading` attribute value to add to an image. Default `lazy`.
1922       *
1923       * Returning `false` or an empty string will not add the attribute.
1924       * Returning `true` will add the default value.
1925       *
1926       * @since 5.5.0
1927       *
1928       * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
1929       *                             the attribute being omitted for the image.
1930       * @param string      $image   The HTML `img` tag to be filtered.
1931       * @param string      $context Additional context about how the function was called or where the img tag is.
1932       */
1933      $value = apply_filters( 'wp_img_tag_add_loading_attr', $value, $image, $context );
1934  
1935      if ( $value ) {
1936          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
1937              $value = 'lazy';
1938          }
1939  
1940          return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image );
1941      }
1942  
1943      return $image;
1944  }
1945  
1946  /**
1947   * Adds `decoding` attribute to an `img` HTML tag.
1948   *
1949   * The `decoding` attribute allows developers to indicate whether the
1950   * browser can decode the image off the main thread (`async`), on the
1951   * main thread (`sync`) or as determined by the browser (`auto`).
1952   *
1953   * By default WordPress adds `decoding="async"` to images but developers
1954   * can use the {@see 'wp_img_tag_add_decoding_attr'} filter to modify this
1955   * to remove the attribute or set it to another accepted value.
1956   *
1957   * @since 6.1.0
1958   *
1959   * @param string $image   The HTML `img` tag where the attribute should be added.
1960   * @param string $context Additional context to pass to the filters.
1961   *
1962   * @return string Converted `img` tag with `decoding` attribute added.
1963   */
1964  function wp_img_tag_add_decoding_attr( $image, $context ) {
1965      /**
1966       * Filters the `decoding` attribute value to add to an image. Default `async`.
1967       *
1968       * Returning a falsey value will omit the attribute.
1969       *
1970       * @since 6.1.0
1971       *
1972       * @param string|false|null $value   The `decoding` attribute value. Returning a falsey value
1973       *                                   will result in the attribute being omitted for the image.
1974       *                                   Otherwise, it may be: 'async' (default), 'sync', or 'auto'.
1975       * @param string            $image   The HTML `img` tag to be filtered.
1976       * @param string            $context Additional context about how the function was called
1977       *                                   or where the img tag is.
1978       */
1979      $value = apply_filters( 'wp_img_tag_add_decoding_attr', 'async', $image, $context );
1980  
1981      if ( in_array( $value, array( 'async', 'sync', 'auto' ), true ) ) {
1982          $image = str_replace( '<img ', '<img decoding="' . esc_attr( $value ) . '" ', $image );
1983      }
1984  
1985      return $image;
1986  }
1987  
1988  /**
1989   * Adds `width` and `height` attributes to an `img` HTML tag.
1990   *
1991   * @since 5.5.0
1992   *
1993   * @param string $image         The HTML `img` tag where the attribute should be added.
1994   * @param string $context       Additional context to pass to the filters.
1995   * @param int    $attachment_id Image attachment ID.
1996   * @return string Converted 'img' element with 'width' and 'height' attributes added.
1997   */
1998  function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
1999      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
2000      list( $image_src ) = explode( '?', $image_src );
2001  
2002      // Return early if we couldn't get the image source.
2003      if ( ! $image_src ) {
2004          return $image;
2005      }
2006  
2007      /**
2008       * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
2009       *
2010       * Returning anything else than `true` will not add the attributes.
2011       *
2012       * @since 5.5.0
2013       *
2014       * @param bool   $value         The filtered value, defaults to `true`.
2015       * @param string $image         The HTML `img` tag where the attribute should be added.
2016       * @param string $context       Additional context about how the function was called or where the img tag is.
2017       * @param int    $attachment_id The image attachment ID.
2018       */
2019      $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
2020  
2021      if ( true === $add ) {
2022          $image_meta = wp_get_attachment_metadata( $attachment_id );
2023          $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
2024  
2025          if ( $size_array ) {
2026              $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
2027              return str_replace( '<img', "<img {$hw}", $image );
2028          }
2029      }
2030  
2031      return $image;
2032  }
2033  
2034  /**
2035   * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
2036   *
2037   * @since 5.5.0
2038   *
2039   * @param string $image         The HTML `img` tag where the attribute should be added.
2040   * @param string $context       Additional context to pass to the filters.
2041   * @param int    $attachment_id Image attachment ID.
2042   * @return string Converted 'img' element with 'loading' attribute added.
2043   */
2044  function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
2045      /**
2046       * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
2047       *
2048       * Returning anything else than `true` will not add the attributes.
2049       *
2050       * @since 5.5.0
2051       *
2052       * @param bool   $value         The filtered value, defaults to `true`.
2053       * @param string $image         The HTML `img` tag where the attribute should be added.
2054       * @param string $context       Additional context about how the function was called or where the img tag is.
2055       * @param int    $attachment_id The image attachment ID.
2056       */
2057      $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
2058  
2059      if ( true === $add ) {
2060          $image_meta = wp_get_attachment_metadata( $attachment_id );
2061          return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
2062      }
2063  
2064      return $image;
2065  }
2066  
2067  /**
2068   * Adds `loading` attribute to an `iframe` HTML tag.
2069   *
2070   * @since 5.7.0
2071   *
2072   * @param string $iframe  The HTML `iframe` tag where the attribute should be added.
2073   * @param string $context Additional context to pass to the filters.
2074   * @return string Converted `iframe` tag with `loading` attribute added.
2075   */
2076  function wp_iframe_tag_add_loading_attr( $iframe, $context ) {
2077      // Iframes with fallback content (see `wp_filter_oembed_result()`) should not be lazy-loaded because they are
2078      // visually hidden initially.
2079      if ( false !== strpos( $iframe, ' data-secret="' ) ) {
2080          return $iframe;
2081      }
2082  
2083      // Get loading attribute value to use. This must occur before the conditional check below so that even iframes that
2084      // are ineligible for being lazy-loaded are considered.
2085      $value = wp_get_loading_attr_default( $context );
2086  
2087      // Iframes should have source and dimension attributes for the `loading` attribute to be added.
2088      if ( false === strpos( $iframe, ' src="' ) || false === strpos( $iframe, ' width="' ) || false === strpos( $iframe, ' height="' ) ) {
2089          return $iframe;
2090      }
2091  
2092      /**
2093       * Filters the `loading` attribute value to add to an iframe. Default `lazy`.
2094       *
2095       * Returning `false` or an empty string will not add the attribute.
2096       * Returning `true` will add the default value.
2097       *
2098       * @since 5.7.0
2099       *
2100       * @param string|bool $value   The `loading` attribute value. Returning a falsey value will result in
2101       *                             the attribute being omitted for the iframe.
2102       * @param string      $iframe  The HTML `iframe` tag to be filtered.
2103       * @param string      $context Additional context about how the function was called or where the iframe tag is.
2104       */
2105      $value = apply_filters( 'wp_iframe_tag_add_loading_attr', $value, $iframe, $context );
2106  
2107      if ( $value ) {
2108          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
2109              $value = 'lazy';
2110          }
2111  
2112          return str_replace( '<iframe', '<iframe loading="' . esc_attr( $value ) . '"', $iframe );
2113      }
2114  
2115      return $iframe;
2116  }
2117  
2118  /**
2119   * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
2120   *
2121   * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
2122   * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
2123   *
2124   * @ignore
2125   * @since 2.9.0
2126   *
2127   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2128   * @return string[] Modified array of attributes including the new 'wp-post-image' class.
2129   */
2130  function _wp_post_thumbnail_class_filter( $attr ) {
2131      $attr['class'] .= ' wp-post-image';
2132      return $attr;
2133  }
2134  
2135  /**
2136   * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
2137   * filter hook. Internal use only.
2138   *
2139   * @ignore
2140   * @since 2.9.0
2141   *
2142   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2143   */
2144  function _wp_post_thumbnail_class_filter_add( $attr ) {
2145      add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2146  }
2147  
2148  /**
2149   * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
2150   * filter hook. Internal use only.
2151   *
2152   * @ignore
2153   * @since 2.9.0
2154   *
2155   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
2156   */
2157  function _wp_post_thumbnail_class_filter_remove( $attr ) {
2158      remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
2159  }
2160  
2161  add_shortcode( 'wp_caption', 'img_caption_shortcode' );
2162  add_shortcode( 'caption', 'img_caption_shortcode' );
2163  
2164  /**
2165   * Builds the Caption shortcode output.
2166   *
2167   * Allows a plugin to replace the content that would otherwise be returned. The
2168   * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
2169   * parameter and the content parameter values.
2170   *
2171   * The supported attributes for the shortcode are 'id', 'caption_id', 'align',
2172   * 'width', 'caption', and 'class'.
2173   *
2174   * @since 2.6.0
2175   * @since 3.9.0 The `class` attribute was added.
2176   * @since 5.1.0 The `caption_id` attribute was added.
2177   * @since 5.9.0 The `$content` parameter default value changed from `null` to `''`.
2178   *
2179   * @param array  $attr {
2180   *     Attributes of the caption shortcode.
2181   *
2182   *     @type string $id         ID of the image and caption container element, i.e. `<figure>` or `<div>`.
2183   *     @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`.
2184   *     @type string $align      Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
2185   *                              'aligncenter', alignright', 'alignnone'.
2186   *     @type int    $width      The width of the caption, in pixels.
2187   *     @type string $caption    The caption text.
2188   *     @type string $class      Additional class name(s) added to the caption container.
2189   * }
2190   * @param string $content Optional. Shortcode content. Default empty string.
2191   * @return string HTML content to display the caption.
2192   */
2193  function img_caption_shortcode( $attr, $content = '' ) {
2194      // New-style shortcode with the caption inside the shortcode with the link and image tags.
2195      if ( ! isset( $attr['caption'] ) ) {
2196          if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
2197              $content         = $matches[1];
2198              $attr['caption'] = trim( $matches[2] );
2199          }
2200      } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
2201          $attr['caption'] = wp_kses( $attr['caption'], 'post' );
2202      }
2203  
2204      /**
2205       * Filters the default caption shortcode output.
2206       *
2207       * If the filtered output isn't empty, it will be used instead of generating
2208       * the default caption template.
2209       *
2210       * @since 2.6.0
2211       *
2212       * @see img_caption_shortcode()
2213       *
2214       * @param string $output  The caption output. Default empty.
2215       * @param array  $attr    Attributes of the caption shortcode.
2216       * @param string $content The image element, possibly wrapped in a hyperlink.
2217       */
2218      $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
2219  
2220      if ( ! empty( $output ) ) {
2221          return $output;
2222      }
2223  
2224      $atts = shortcode_atts(
2225          array(
2226              'id'         => '',
2227              'caption_id' => '',
2228              'align'      => 'alignnone',
2229              'width'      => '',
2230              'caption'    => '',
2231              'class'      => '',
2232          ),
2233          $attr,
2234          'caption'
2235      );
2236  
2237      $atts['width'] = (int) $atts['width'];
2238  
2239      if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
2240          return $content;
2241      }
2242  
2243      $id          = '';
2244      $caption_id  = '';
2245      $describedby = '';
2246  
2247      if ( $atts['id'] ) {
2248          $atts['id'] = sanitize_html_class( $atts['id'] );
2249          $id         = 'id="' . esc_attr( $atts['id'] ) . '" ';
2250      }
2251  
2252      if ( $atts['caption_id'] ) {
2253          $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
2254      } elseif ( $atts['id'] ) {
2255          $atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
2256      }
2257  
2258      if ( $atts['caption_id'] ) {
2259          $caption_id  = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
2260          $describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
2261      }
2262  
2263      $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
2264  
2265      $html5 = current_theme_supports( 'html5', 'caption' );
2266      // HTML5 captions never added the extra 10px to the image width.
2267      $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
2268  
2269      /**
2270       * Filters the width of an image's caption.
2271       *
2272       * By default, the caption is 10 pixels greater than the width of the image,
2273       * to prevent post content from running up against a floated image.
2274       *
2275       * @since 3.7.0
2276       *
2277       * @see img_caption_shortcode()
2278       *
2279       * @param int    $width    Width of the caption in pixels. To remove this inline style,
2280       *                         return zero.
2281       * @param array  $atts     Attributes of the caption shortcode.
2282       * @param string $content  The image element, possibly wrapped in a hyperlink.
2283       */
2284      $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
2285  
2286      $style = '';
2287  
2288      if ( $caption_width ) {
2289          $style = 'style="width: ' . (int) $caption_width . 'px" ';
2290      }
2291  
2292      if ( $html5 ) {
2293          $html = sprintf(
2294              '<figure %s%s%sclass="%s">%s%s</figure>',
2295              $id,
2296              $describedby,
2297              $style,
2298              esc_attr( $class ),
2299              do_shortcode( $content ),
2300              sprintf(
2301                  '<figcaption %sclass="wp-caption-text">%s</figcaption>',
2302                  $caption_id,
2303                  $atts['caption']
2304              )
2305          );
2306      } else {
2307          $html = sprintf(
2308              '<div %s%sclass="%s">%s%s</div>',
2309              $id,
2310              $style,
2311              esc_attr( $class ),
2312              str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
2313              sprintf(
2314                  '<p %sclass="wp-caption-text">%s</p>',
2315                  $caption_id,
2316                  $atts['caption']
2317              )
2318          );
2319      }
2320  
2321      return $html;
2322  }
2323  
2324  add_shortcode( 'gallery', 'gallery_shortcode' );
2325  
2326  /**
2327   * Builds the Gallery shortcode output.
2328   *
2329   * This implements the functionality of the Gallery Shortcode for displaying
2330   * WordPress images on a post.
2331   *
2332   * @since 2.5.0
2333   * @since 2.8.0 Added the `$attr` parameter to set the shortcode output. New attributes included
2334   *              such as `size`, `itemtag`, `icontag`, `captiontag`, and columns. Changed markup from
2335   *              `div` tags to `dl`, `dt` and `dd` tags. Support more than one gallery on the
2336   *              same page.
2337   * @since 2.9.0 Added support for `include` and `exclude` to shortcode.
2338   * @since 3.5.0 Use get_post() instead of global `$post`. Handle mapping of `ids` to `include`
2339   *              and `orderby`.
2340   * @since 3.6.0 Added validation for tags used in gallery shortcode. Add orientation information to items.
2341   * @since 3.7.0 Introduced the `link` attribute.
2342   * @since 3.9.0 `html5` gallery support, accepting 'itemtag', 'icontag', and 'captiontag' attributes.
2343   * @since 4.0.0 Removed use of `extract()`.
2344   * @since 4.1.0 Added attribute to `wp_get_attachment_link()` to output `aria-describedby`.
2345   * @since 4.2.0 Passed the shortcode instance ID to `post_gallery` and `post_playlist` filters.
2346   * @since 4.6.0 Standardized filter docs to match documentation standards for PHP.
2347   * @since 5.1.0 Code cleanup for WPCS 1.0.0 coding standards.
2348   * @since 5.3.0 Saved progress of intermediate image creation after upload.
2349   * @since 5.5.0 Ensured that galleries can be output as a list of links in feeds.
2350   * @since 5.6.0 Replaced order-style PHP type conversion functions with typecasts. Fix logic for
2351   *              an array of image dimensions.
2352   *
2353   * @param array $attr {
2354   *     Attributes of the gallery shortcode.
2355   *
2356   *     @type string       $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
2357   *     @type string       $orderby    The field to use when ordering the images. Default 'menu_order ID'.
2358   *                                    Accepts any valid SQL ORDERBY statement.
2359   *     @type int          $id         Post ID.
2360   *     @type string       $itemtag    HTML tag to use for each image in the gallery.
2361   *                                    Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
2362   *     @type string       $icontag    HTML tag to use for each image's icon.
2363   *                                    Default 'dt', or 'div' when the theme registers HTML5 gallery support.
2364   *     @type string       $captiontag HTML tag to use for each image's caption.
2365   *                                    Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
2366   *     @type int          $columns    Number of columns of images to display. Default 3.
2367   *     @type string|int[] $size       Size of the images to display. Accepts any registered image size name, or an array
2368   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
2369   *     @type string       $ids        A comma-separated list of IDs of attachments to display. Default empty.
2370   *     @type string       $include    A comma-separated list of IDs of attachments to include. Default empty.
2371   *     @type string       $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
2372   *     @type string       $link       What to link each image to. Default empty (links to the attachment page).
2373   *                                    Accepts 'file', 'none'.
2374   * }
2375   * @return string HTML content to display gallery.
2376   */
2377  function gallery_shortcode( $attr ) {
2378      $post = get_post();
2379  
2380      static $instance = 0;
2381      $instance++;
2382  
2383      if ( ! empty( $attr['ids'] ) ) {
2384          // 'ids' is explicitly ordered, unless you specify otherwise.
2385          if ( empty( $attr['orderby'] ) ) {
2386              $attr['orderby'] = 'post__in';
2387          }
2388          $attr['include'] = $attr['ids'];
2389      }
2390  
2391      /**
2392       * Filters the default gallery shortcode output.
2393       *
2394       * If the filtered output isn't empty, it will be used instead of generating
2395       * the default gallery template.
2396       *
2397       * @since 2.5.0
2398       * @since 4.2.0 The `$instance` parameter was added.
2399       *
2400       * @see gallery_shortcode()
2401       *
2402       * @param string $output   The gallery output. Default empty.
2403       * @param array  $attr     Attributes of the gallery shortcode.
2404       * @param int    $instance Unique numeric ID of this gallery shortcode instance.
2405       */
2406      $output = apply_filters( 'post_gallery', '', $attr, $instance );
2407  
2408      if ( ! empty( $output ) ) {
2409          return $output;
2410      }
2411  
2412      $html5 = current_theme_supports( 'html5', 'gallery' );
2413      $atts  = shortcode_atts(
2414          array(
2415              'order'      => 'ASC',
2416              'orderby'    => 'menu_order ID',
2417              'id'         => $post ? $post->ID : 0,
2418              'itemtag'    => $html5 ? 'figure' : 'dl',
2419              'icontag'    => $html5 ? 'div' : 'dt',
2420              'captiontag' => $html5 ? 'figcaption' : 'dd',
2421              'columns'    => 3,
2422              'size'       => 'thumbnail',
2423              'include'    => '',
2424              'exclude'    => '',
2425              'link'       => '',
2426          ),
2427          $attr,
2428          'gallery'
2429      );
2430  
2431      $id = (int) $atts['id'];
2432  
2433      if ( ! empty( $atts['include'] ) ) {
2434          $_attachments = get_posts(
2435              array(
2436                  'include'        => $atts['include'],
2437                  'post_status'    => 'inherit',
2438                  'post_type'      => 'attachment',
2439                  'post_mime_type' => 'image',
2440                  'order'          => $atts['order'],
2441                  'orderby'        => $atts['orderby'],
2442              )
2443          );
2444  
2445          $attachments = array();
2446          foreach ( $_attachments as $key => $val ) {
2447              $attachments[ $val->ID ] = $_attachments[ $key ];
2448          }
2449      } elseif ( ! empty( $atts['exclude'] ) ) {
2450          $attachments = get_children(
2451              array(
2452                  'post_parent'    => $id,
2453                  'exclude'        => $atts['exclude'],
2454                  'post_status'    => 'inherit',
2455                  'post_type'      => 'attachment',
2456                  'post_mime_type' => 'image',
2457                  'order'          => $atts['order'],
2458                  'orderby'        => $atts['orderby'],
2459              )
2460          );
2461      } else {
2462          $attachments = get_children(
2463              array(
2464                  'post_parent'    => $id,
2465                  'post_status'    => 'inherit',
2466                  'post_type'      => 'attachment',
2467                  'post_mime_type' => 'image',
2468                  'order'          => $atts['order'],
2469                  'orderby'        => $atts['orderby'],
2470              )
2471          );
2472      }
2473  
2474      if ( empty( $attachments ) ) {
2475          return '';
2476      }
2477  
2478      if ( is_feed() ) {
2479          $output = "\n";
2480          foreach ( $attachments as $att_id => $attachment ) {
2481              if ( ! empty( $atts['link'] ) ) {
2482                  if ( 'none' === $atts['link'] ) {
2483                      $output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr );
2484                  } else {
2485                      $output .= wp_get_attachment_link( $att_id, $atts['size'], false );
2486                  }
2487              } else {
2488                  $output .= wp_get_attachment_link( $att_id, $atts['size'], true );
2489              }
2490              $output .= "\n";
2491          }
2492          return $output;
2493      }
2494  
2495      $itemtag    = tag_escape( $atts['itemtag'] );
2496      $captiontag = tag_escape( $atts['captiontag'] );
2497      $icontag    = tag_escape( $atts['icontag'] );
2498      $valid_tags = wp_kses_allowed_html( 'post' );
2499      if ( ! isset( $valid_tags[ $itemtag ] ) ) {
2500          $itemtag = 'dl';
2501      }
2502      if ( ! isset( $valid_tags[ $captiontag ] ) ) {
2503          $captiontag = 'dd';
2504      }
2505      if ( ! isset( $valid_tags[ $icontag ] ) ) {
2506          $icontag = 'dt';
2507      }
2508  
2509      $columns   = (int) $atts['columns'];
2510      $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
2511      $float     = is_rtl() ? 'right' : 'left';
2512  
2513      $selector = "gallery-{$instance}";
2514  
2515      $gallery_style = '';
2516  
2517      /**
2518       * Filters whether to print default gallery styles.
2519       *
2520       * @since 3.1.0
2521       *
2522       * @param bool $print Whether to print default gallery styles.
2523       *                    Defaults to false if the theme supports HTML5 galleries.
2524       *                    Otherwise, defaults to true.
2525       */
2526      if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
2527          $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
2528  
2529          $gallery_style = "
2530          <style{$type_attr}>
2531              #{$selector} {
2532                  margin: auto;
2533              }
2534              #{$selector} .gallery-item {
2535                  float: {$float};
2536                  margin-top: 10px;
2537                  text-align: center;
2538                  width: {$itemwidth}%;
2539              }
2540              #{$selector} img {
2541                  border: 2px solid #cfcfcf;
2542              }
2543              #{$selector} .gallery-caption {
2544                  margin-left: 0;
2545              }
2546              /* see gallery_shortcode() in wp-includes/media.php */
2547          </style>\n\t\t";
2548      }
2549  
2550      $size_class  = sanitize_html_class( is_array( $atts['size'] ) ? implode( 'x', $atts['size'] ) : $atts['size'] );
2551      $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
2552  
2553      /**
2554       * Filters the default gallery shortcode CSS styles.
2555       *
2556       * @since 2.5.0
2557       *
2558       * @param string $gallery_style Default CSS styles and opening HTML div container
2559       *                              for the gallery shortcode output.
2560       */
2561      $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
2562  
2563      $i = 0;
2564  
2565      foreach ( $attachments as $id => $attachment ) {
2566  
2567          $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
2568  
2569          if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
2570              $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
2571          } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
2572              $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
2573          } else {
2574              $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
2575          }
2576  
2577          $image_meta = wp_get_attachment_metadata( $id );
2578  
2579          $orientation = '';
2580  
2581          if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
2582              $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
2583          }
2584  
2585          $output .= "<{$itemtag} class='gallery-item'>";
2586          $output .= "
2587              <{$icontag} class='gallery-icon {$orientation}'>
2588                  $image_output
2589              </{$icontag}>";
2590  
2591          if ( $captiontag && trim( $attachment->post_excerpt ) ) {
2592              $output .= "
2593                  <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
2594                  " . wptexturize( $attachment->post_excerpt ) . "
2595                  </{$captiontag}>";
2596          }
2597  
2598          $output .= "</{$itemtag}>";
2599  
2600          if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
2601              $output .= '<br style="clear: both" />';
2602          }
2603      }
2604  
2605      if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
2606          $output .= "
2607              <br style='clear: both' />";
2608      }
2609  
2610      $output .= "
2611          </div>\n";
2612  
2613      return $output;
2614  }
2615  
2616  /**
2617   * Outputs the templates used by playlists.
2618   *
2619   * @since 3.9.0
2620   */
2621  function wp_underscore_playlist_templates() {
2622      ?>
2623  <script type="text/html" id="tmpl-wp-playlist-current-item">
2624      <# if ( data.thumb && data.thumb.src ) { #>
2625          <img src="{{ data.thumb.src }}" alt="" />
2626      <# } #>
2627      <div class="wp-playlist-caption">
2628          <span class="wp-playlist-item-meta wp-playlist-item-title">
2629          <?php
2630              /* translators: %s: Playlist item title. */
2631              printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
2632          ?>
2633          </span>
2634          <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
2635          <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
2636      </div>
2637  </script>
2638  <script type="text/html" id="tmpl-wp-playlist-item">
2639      <div class="wp-playlist-item">
2640          <a class="wp-playlist-caption" href="{{ data.src }}">
2641              {{ data.index ? ( data.index + '. ' ) : '' }}
2642              <# if ( data.caption ) { #>
2643                  {{ data.caption }}
2644              <# } else { #>
2645                  <span class="wp-playlist-item-title">
2646                  <?php
2647                      /* translators: %s: Playlist item title. */
2648                      printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
2649                  ?>
2650                  </span>
2651                  <# if ( data.artists && data.meta.artist ) { #>
2652                  <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
2653                  <# } #>
2654              <# } #>
2655          </a>
2656          <# if ( data.meta.length_formatted ) { #>
2657          <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
2658          <# } #>
2659      </div>
2660  </script>
2661      <?php
2662  }
2663  
2664  /**
2665   * Outputs and enqueues default scripts and styles for playlists.
2666   *
2667   * @since 3.9.0
2668   *
2669   * @param string $type Type of playlist. Accepts 'audio' or 'video'.
2670   */
2671  function wp_playlist_scripts( $type ) {
2672      wp_enqueue_style( 'wp-mediaelement' );
2673      wp_enqueue_script( 'wp-playlist' );
2674      ?>
2675  <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ); ?>');</script><![endif]-->
2676      <?php
2677      add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
2678      add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
2679  }
2680  
2681  /**
2682   * Builds the Playlist shortcode output.
2683   *
2684   * This implements the functionality of the playlist shortcode for displaying
2685   * a collection of WordPress audio or video files in a post.
2686   *
2687   * @since 3.9.0
2688   *
2689   * @global int $content_width
2690   *
2691   * @param array $attr {
2692   *     Array of default playlist attributes.
2693   *
2694   *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
2695   *     @type string  $order        Designates ascending or descending order of items in the playlist.
2696   *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
2697   *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
2698   *                                 passed, this defaults to the order of the $ids array ('post__in').
2699   *                                 Otherwise default is 'menu_order ID'.
2700   *     @type int     $id           If an explicit $ids array is not present, this parameter
2701   *                                 will determine which attachments are used for the playlist.
2702   *                                 Default is the current post ID.
2703   *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
2704   *                                 a playlist will be created from all $type attachments of $id.
2705   *                                 Default empty.
2706   *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
2707   *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
2708   *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
2709   *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
2710   *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
2711   *                                 thumbnail). Default true.
2712   *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
2713   * }
2714   *
2715   * @return string Playlist output. Empty string if the passed type is unsupported.
2716   */
2717  function wp_playlist_shortcode( $attr ) {
2718      global $content_width;
2719      $post = get_post();
2720  
2721      static $instance = 0;
2722      $instance++;
2723  
2724      if ( ! empty( $attr['ids'] ) ) {
2725          // 'ids' is explicitly ordered, unless you specify otherwise.
2726          if ( empty( $attr['orderby'] ) ) {
2727              $attr['orderby'] = 'post__in';
2728          }
2729          $attr['include'] = $attr['ids'];
2730      }
2731  
2732      /**
2733       * Filters the playlist output.
2734       *
2735       * Returning a non-empty value from the filter will short-circuit generation
2736       * of the default playlist output, returning the passed value instead.
2737       *
2738       * @since 3.9.0
2739       * @since 4.2.0 The `$instance` parameter was added.
2740       *
2741       * @param string $output   Playlist output. Default empty.
2742       * @param array  $attr     An array of shortcode attributes.
2743       * @param int    $instance Unique numeric ID of this playlist shortcode instance.
2744       */
2745      $output = apply_filters( 'post_playlist', '', $attr, $instance );
2746  
2747      if ( ! empty( $output ) ) {
2748          return $output;
2749      }
2750  
2751      $atts = shortcode_atts(
2752          array(
2753              'type'         => 'audio',
2754              'order'        => 'ASC',
2755              'orderby'      => 'menu_order ID',
2756              'id'           => $post ? $post->ID : 0,
2757              'include'      => '',
2758              'exclude'      => '',
2759              'style'        => 'light',
2760              'tracklist'    => true,
2761              'tracknumbers' => true,
2762              'images'       => true,
2763              'artists'      => true,
2764          ),
2765          $attr,
2766          'playlist'
2767      );
2768  
2769      $id = (int) $atts['id'];
2770  
2771      if ( 'audio' !== $atts['type'] ) {
2772          $atts['type'] = 'video';
2773      }
2774  
2775      $args = array(
2776          'post_status'    => 'inherit',
2777          'post_type'      => 'attachment',
2778          'post_mime_type' => $atts['type'],
2779          'order'          => $atts['order'],
2780          'orderby'        => $atts['orderby'],
2781      );
2782  
2783      if ( ! empty( $atts['include'] ) ) {
2784          $args['include'] = $atts['include'];
2785          $_attachments    = get_posts( $args );
2786  
2787          $attachments = array();
2788          foreach ( $_attachments as $key => $val ) {
2789              $attachments[ $val->ID ] = $_attachments[ $key ];
2790          }
2791      } elseif ( ! empty( $atts['exclude'] ) ) {
2792          $args['post_parent'] = $id;
2793          $args['exclude']     = $atts['exclude'];
2794          $attachments         = get_children( $args );
2795      } else {
2796          $args['post_parent'] = $id;
2797          $attachments         = get_children( $args );
2798      }
2799  
2800      if ( empty( $attachments ) ) {
2801          return '';
2802      }
2803  
2804      if ( is_feed() ) {
2805          $output = "\n";
2806          foreach ( $attachments as $att_id => $attachment ) {
2807              $output .= wp_get_attachment_link( $att_id ) . "\n";
2808          }
2809          return $output;
2810      }
2811  
2812      $outer = 22; // Default padding and border of wrapper.
2813  
2814      $default_width  = 640;
2815      $default_height = 360;
2816  
2817      $theme_width  = empty( $content_width ) ? $default_width : ( $content_width - $outer );
2818      $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
2819  
2820      $data = array(
2821          'type'         => $atts['type'],
2822          // Don't pass strings to JSON, will be truthy in JS.
2823          'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
2824          'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
2825          'images'       => wp_validate_boolean( $atts['images'] ),
2826          'artists'      => wp_validate_boolean( $atts['artists'] ),
2827      );
2828  
2829      $tracks = array();
2830      foreach ( $attachments as $attachment ) {
2831          $url   = wp_get_attachment_url( $attachment->ID );
2832          $ftype = wp_check_filetype( $url, wp_get_mime_types() );
2833          $track = array(
2834              'src'         => $url,
2835              'type'        => $ftype['type'],
2836              'title'       => $attachment->post_title,
2837              'caption'     => $attachment->post_excerpt,
2838              'description' => $attachment->post_content,
2839          );
2840  
2841          $track['meta'] = array();
2842          $meta          = wp_get_attachment_metadata( $attachment->ID );
2843          if ( ! empty( $meta ) ) {
2844  
2845              foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
2846                  if ( ! empty( $meta[ $key ] ) ) {
2847                      $track['meta'][ $key ] = $meta[ $key ];
2848                  }
2849              }
2850  
2851              if ( 'video' === $atts['type'] ) {
2852                  if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
2853                      $width        = $meta['width'];
2854                      $height       = $meta['height'];
2855                      $theme_height = round( ( $height * $theme_width ) / $width );
2856                  } else {
2857                      $width  = $default_width;
2858                      $height = $default_height;
2859                  }
2860  
2861                  $track['dimensions'] = array(
2862                      'original' => compact( 'width', 'height' ),
2863                      'resized'  => array(
2864                          'width'  => $theme_width,
2865                          'height' => $theme_height,
2866                      ),
2867                  );
2868              }
2869          }
2870  
2871          if ( $atts['images'] ) {
2872              $thumb_id = get_post_thumbnail_id( $attachment->ID );
2873              if ( ! empty( $thumb_id ) ) {
2874                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2875                  $track['image']               = compact( 'src', 'width', 'height' );
2876                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2877                  $track['thumb']               = compact( 'src', 'width', 'height' );
2878              } else {
2879                  $src            = wp_mime_type_icon( $attachment->ID );
2880                  $width          = 48;
2881                  $height         = 64;
2882                  $track['image'] = compact( 'src', 'width', 'height' );
2883                  $track['thumb'] = compact( 'src', 'width', 'height' );
2884              }
2885          }
2886  
2887          $tracks[] = $track;
2888      }
2889      $data['tracks'] = $tracks;
2890  
2891      $safe_type  = esc_attr( $atts['type'] );
2892      $safe_style = esc_attr( $atts['style'] );
2893  
2894      ob_start();
2895  
2896      if ( 1 === $instance ) {
2897          /**
2898           * Prints and enqueues playlist scripts, styles, and JavaScript templates.
2899           *
2900           * @since 3.9.0
2901           *
2902           * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
2903           * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2904           */
2905          do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2906      }
2907      ?>
2908  <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>">
2909      <?php if ( 'audio' === $atts['type'] ) : ?>
2910          <div class="wp-playlist-current-item"></div>
2911      <?php endif; ?>
2912      <<?php echo $safe_type; ?> controls="controls" preload="none" width="<?php echo (int) $theme_width; ?>"
2913          <?php
2914          if ( 'video' === $safe_type ) {
2915              echo ' height="', (int) $theme_height, '"';
2916          }
2917          ?>
2918      ></<?php echo $safe_type; ?>>
2919      <div class="wp-playlist-next"></div>
2920      <div class="wp-playlist-prev"></div>
2921      <noscript>
2922      <ol>
2923          <?php
2924          foreach ( $attachments as $att_id => $attachment ) {
2925              printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2926          }
2927          ?>
2928      </ol>
2929      </noscript>
2930      <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ); ?></script>
2931  </div>
2932      <?php
2933      return ob_get_clean();
2934  }
2935  add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2936  
2937  /**
2938   * Provides a No-JS Flash fallback as a last resort for audio / video.
2939   *
2940   * @since 3.6.0
2941   *
2942   * @param string $url The media element URL.
2943   * @return string Fallback HTML.
2944   */
2945  function wp_mediaelement_fallback( $url ) {
2946      /**
2947       * Filters the Mediaelement fallback output for no-JS.
2948       *
2949       * @since 3.6.0
2950       *
2951       * @param string $output Fallback output for no-JS.
2952       * @param string $url    Media file URL.
2953       */
2954      return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2955  }
2956  
2957  /**
2958   * Returns a filtered list of supported audio formats.
2959   *
2960   * @since 3.6.0
2961   *
2962   * @return string[] Supported audio formats.
2963   */
2964  function wp_get_audio_extensions() {
2965      /**
2966       * Filters the list of supported audio formats.
2967       *
2968       * @since 3.6.0
2969       *
2970       * @param string[] $extensions An array of supported audio formats. Defaults are
2971       *                            'mp3', 'ogg', 'flac', 'm4a', 'wav'.
2972       */
2973      return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
2974  }
2975  
2976  /**
2977   * Returns useful keys to use to lookup data from an attachment's stored metadata.
2978   *
2979   * @since 3.9.0
2980   *
2981   * @param WP_Post $attachment The current attachment, provided for context.
2982   * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2983   * @return string[] Key/value pairs of field keys to labels.
2984   */
2985  function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2986      $fields = array(
2987          'artist' => __( 'Artist' ),
2988          'album'  => __( 'Album' ),
2989      );
2990  
2991      if ( 'display' === $context ) {
2992          $fields['genre']            = __( 'Genre' );
2993          $fields['year']             = __( 'Year' );
2994          $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2995      } elseif ( 'js' === $context ) {
2996          $fields['bitrate']      = __( 'Bitrate' );
2997          $fields['bitrate_mode'] = __( 'Bitrate Mode' );
2998      }
2999  
3000      /**
3001       * Filters the editable list of keys to look up data from an attachment's metadata.
3002       *
3003       * @since 3.9.0
3004       *
3005       * @param array   $fields     Key/value pairs of field keys to labels.
3006       * @param WP_Post $attachment Attachment object.
3007       * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
3008       */
3009      return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
3010  }
3011  /**
3012   * Builds the Audio shortcode output.
3013   *
3014   * This implements the functionality of the Audio Shortcode for displaying
3015   * WordPress mp3s in a post.
3016   *
3017   * @since 3.6.0
3018   *
3019   * @param array  $attr {
3020   *     Attributes of the audio shortcode.
3021   *
3022   *     @type string $src      URL to the source of the audio file. Default empty.
3023   *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
3024   *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
3025   *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default 'none'.
3026   *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
3027   *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
3028   * }
3029   * @param string $content Shortcode content.
3030   * @return string|void HTML content to display audio.
3031   */
3032  function wp_audio_shortcode( $attr, $content = '' ) {
3033      $post_id = get_post() ? get_the_ID() : 0;
3034  
3035      static $instance = 0;
3036      $instance++;
3037  
3038      /**
3039       * Filters the default audio shortcode output.
3040       *
3041       * If the filtered output isn't empty, it will be used instead of generating the default audio template.
3042       *
3043       * @since 3.6.0
3044       *
3045       * @param string $html     Empty variable to be replaced with shortcode markup.
3046       * @param array  $attr     Attributes of the shortcode. @see wp_audio_shortcode()
3047       * @param string $content  Shortcode content.
3048       * @param int    $instance Unique numeric ID of this audio shortcode instance.
3049       */
3050      $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
3051  
3052      if ( '' !== $override ) {
3053          return $override;
3054      }
3055  
3056      $audio = null;
3057  
3058      $default_types = wp_get_audio_extensions();
3059      $defaults_atts = array(
3060          'src'      => '',
3061          'loop'     => '',
3062          'autoplay' => '',
3063          'preload'  => 'none',
3064          'class'    => 'wp-audio-shortcode',
3065          'style'    => 'width: 100%;',
3066      );
3067      foreach ( $default_types as $type ) {
3068          $defaults_atts[ $type ] = '';
3069      }
3070  
3071      $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
3072  
3073      $primary = false;
3074      if ( ! empty( $atts['src'] ) ) {
3075          $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
3076  
3077          if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
3078              return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
3079          }
3080  
3081          $primary = true;
3082          array_unshift( $default_types, 'src' );
3083      } else {
3084          foreach ( $default_types as $ext ) {
3085              if ( ! empty( $atts[ $ext ] ) ) {
3086                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
3087  
3088                  if ( strtolower( $type['ext'] ) === $ext ) {
3089                      $primary = true;
3090                  }
3091              }
3092          }
3093      }
3094  
3095      if ( ! $primary ) {
3096          $audios = get_attached_media( 'audio', $post_id );
3097  
3098          if ( empty( $audios ) ) {
3099              return;
3100          }
3101  
3102          $audio       = reset( $audios );
3103          $atts['src'] = wp_get_attachment_url( $audio->ID );
3104  
3105          if ( empty( $atts['src'] ) ) {
3106              return;
3107          }
3108  
3109          array_unshift( $default_types, 'src' );
3110      }
3111  
3112      /**
3113       * Filters the media library used for the audio shortcode.
3114       *
3115       * @since 3.6.0
3116       *
3117       * @param string $library Media library used for the audio shortcode.
3118       */
3119      $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
3120  
3121      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3122          wp_enqueue_style( 'wp-mediaelement' );
3123          wp_enqueue_script( 'wp-mediaelement' );
3124      }
3125  
3126      /**
3127       * Filters the class attribute for the audio shortcode output container.
3128       *
3129       * @since 3.6.0
3130       * @since 4.9.0 The `$atts` parameter was added.
3131       *
3132       * @param string $class CSS class or list of space-separated classes.
3133       * @param array  $atts  Array of audio shortcode attributes.
3134       */
3135      $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
3136  
3137      $html_atts = array(
3138          'class'    => $atts['class'],
3139          'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
3140          'loop'     => wp_validate_boolean( $atts['loop'] ),
3141          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3142          'preload'  => $atts['preload'],
3143          'style'    => $atts['style'],
3144      );
3145  
3146      // These ones should just be omitted altogether if they are blank.
3147      foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
3148          if ( empty( $html_atts[ $a ] ) ) {
3149              unset( $html_atts[ $a ] );
3150          }
3151      }
3152  
3153      $attr_strings = array();
3154  
3155      foreach ( $html_atts as $k => $v ) {
3156          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
3157      }
3158  
3159      $html = '';
3160  
3161      if ( 'mediaelement' === $library && 1 === $instance ) {
3162          $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
3163      }
3164  
3165      $html .= sprintf( '<audio %s controls="controls">', implode( ' ', $attr_strings ) );
3166  
3167      $fileurl = '';
3168      $source  = '<source type="%s" src="%s" />';
3169  
3170      foreach ( $default_types as $fallback ) {
3171          if ( ! empty( $atts[ $fallback ] ) ) {
3172              if ( empty( $fileurl ) ) {
3173                  $fileurl = $atts[ $fallback ];
3174              }
3175  
3176              $type  = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3177              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3178              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3179          }
3180      }
3181  
3182      if ( 'mediaelement' === $library ) {
3183          $html .= wp_mediaelement_fallback( $fileurl );
3184      }
3185  
3186      $html .= '</audio>';
3187  
3188      /**
3189       * Filters the audio shortcode output.
3190       *
3191       * @since 3.6.0
3192       *
3193       * @param string $html    Audio shortcode HTML output.
3194       * @param array  $atts    Array of audio shortcode attributes.
3195       * @param string $audio   Audio file.
3196       * @param int    $post_id Post ID.
3197       * @param string $library Media library used for the audio shortcode.
3198       */
3199      return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
3200  }
3201  add_shortcode( 'audio', 'wp_audio_shortcode' );
3202  
3203  /**
3204   * Returns a filtered list of supported video formats.
3205   *
3206   * @since 3.6.0
3207   *
3208   * @return string[] List of supported video formats.
3209   */
3210  function wp_get_video_extensions() {
3211      /**
3212       * Filters the list of supported video formats.
3213       *
3214       * @since 3.6.0
3215       *
3216       * @param string[] $extensions An array of supported video formats. Defaults are
3217       *                             'mp4', 'm4v', 'webm', 'ogv', 'flv'.
3218       */
3219      return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
3220  }
3221  
3222  /**
3223   * Builds the Video shortcode output.
3224   *
3225   * This implements the functionality of the Video Shortcode for displaying
3226   * WordPress mp4s in a post.
3227   *
3228   * @since 3.6.0
3229   *
3230   * @global int $content_width
3231   *
3232   * @param array  $attr {
3233   *     Attributes of the shortcode.
3234   *
3235   *     @type string $src      URL to the source of the video file. Default empty.
3236   *     @type int    $height   Height of the video embed in pixels. Default 360.
3237   *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
3238   *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
3239   *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
3240   *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
3241   *     @type string $muted    The 'muted' attribute for the `<video>` element. Default false.
3242   *     @type string $preload  The 'preload' attribute for the `<video>` element.
3243   *                            Default 'metadata'.
3244   *     @type string $class    The 'class' attribute for the `<video>` element.
3245   *                            Default 'wp-video-shortcode'.
3246   * }
3247   * @param string $content Shortcode content.
3248   * @return string|void HTML content to display video.
3249   */
3250  function wp_video_shortcode( $attr, $content = '' ) {
3251      global $content_width;
3252      $post_id = get_post() ? get_the_ID() : 0;
3253  
3254      static $instance = 0;
3255      $instance++;
3256  
3257      /**
3258       * Filters the default video shortcode output.
3259       *
3260       * If the filtered output isn't empty, it will be used instead of generating
3261       * the default video template.
3262       *
3263       * @since 3.6.0
3264       *
3265       * @see wp_video_shortcode()
3266       *
3267       * @param string $html     Empty variable to be replaced with shortcode markup.
3268       * @param array  $attr     Attributes of the shortcode. @see wp_video_shortcode()
3269       * @param string $content  Video shortcode content.
3270       * @param int    $instance Unique numeric ID of this video shortcode instance.
3271       */
3272      $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
3273  
3274      if ( '' !== $override ) {
3275          return $override;
3276      }
3277  
3278      $video = null;
3279  
3280      $default_types = wp_get_video_extensions();
3281      $defaults_atts = array(
3282          'src'      => '',
3283          'poster'   => '',
3284          'loop'     => '',
3285          'autoplay' => '',
3286          'muted'    => 'false',
3287          'preload'  => 'metadata',
3288          'width'    => 640,
3289          'height'   => 360,
3290          'class'    => 'wp-video-shortcode',
3291      );
3292  
3293      foreach ( $default_types as $type ) {
3294          $defaults_atts[ $type ] = '';
3295      }
3296  
3297      $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
3298  
3299      if ( is_admin() ) {
3300          // Shrink the video so it isn't huge in the admin.
3301          if ( $atts['width'] > $defaults_atts['width'] ) {
3302              $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
3303              $atts['width']  = $defaults_atts['width'];
3304          }
3305      } else {
3306          // If the video is bigger than the theme.
3307          if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
3308              $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
3309              $atts['width']  = $content_width;
3310          }
3311      }
3312  
3313      $is_vimeo      = false;
3314      $is_youtube    = false;
3315      $yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
3316      $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
3317  
3318      $primary = false;
3319      if ( ! empty( $atts['src'] ) ) {
3320          $is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
3321          $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
3322  
3323          if ( ! $is_youtube && ! $is_vimeo ) {
3324              $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
3325  
3326              if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
3327                  return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
3328              }
3329          }
3330  
3331          if ( $is_vimeo ) {
3332              wp_enqueue_script( 'mediaelement-vimeo' );
3333          }
3334  
3335          $primary = true;
3336          array_unshift( $default_types, 'src' );
3337      } else {
3338          foreach ( $default_types as $ext ) {
3339              if ( ! empty( $atts[ $ext ] ) ) {
3340                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
3341                  if ( strtolower( $type['ext'] ) === $ext ) {
3342                      $primary = true;
3343                  }
3344              }
3345          }
3346      }
3347  
3348      if ( ! $primary ) {
3349          $videos = get_attached_media( 'video', $post_id );
3350          if ( empty( $videos ) ) {
3351              return;
3352          }
3353  
3354          $video       = reset( $videos );
3355          $atts['src'] = wp_get_attachment_url( $video->ID );
3356          if ( empty( $atts['src'] ) ) {
3357              return;
3358          }
3359  
3360          array_unshift( $default_types, 'src' );
3361      }
3362  
3363      /**
3364       * Filters the media library used for the video shortcode.
3365       *
3366       * @since 3.6.0
3367       *
3368       * @param string $library Media library used for the video shortcode.
3369       */
3370      $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
3371      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3372          wp_enqueue_style( 'wp-mediaelement' );
3373          wp_enqueue_script( 'wp-mediaelement' );
3374          wp_enqueue_script( 'mediaelement-vimeo' );
3375      }
3376  
3377      // MediaElement.js has issues with some URL formats for Vimeo and YouTube,
3378      // so update the URL to prevent the ME.js player from breaking.
3379      if ( 'mediaelement' === $library ) {
3380          if ( $is_youtube ) {
3381              // Remove `feature` query arg and force SSL - see #40866.
3382              $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
3383              $atts['src'] = set_url_scheme( $atts['src'], 'https' );
3384          } elseif ( $is_vimeo ) {
3385              // Remove all query arguments and force SSL - see #40866.
3386              $parsed_vimeo_url = wp_parse_url( $atts['src'] );
3387              $vimeo_src        = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
3388  
3389              // Add loop param for mejs bug - see #40977, not needed after #39686.
3390              $loop        = $atts['loop'] ? '1' : '0';
3391              $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
3392          }
3393      }
3394  
3395      /**
3396       * Filters the class attribute for the video shortcode output container.
3397       *
3398       * @since 3.6.0
3399       * @since 4.9.0 The `$atts` parameter was added.
3400       *
3401       * @param string $class CSS class or list of space-separated classes.
3402       * @param array  $atts  Array of video shortcode attributes.
3403       */
3404      $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
3405  
3406      $html_atts = array(
3407          'class'    => $atts['class'],
3408          'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
3409          'width'    => absint( $atts['width'] ),
3410          'height'   => absint( $atts['height'] ),
3411          'poster'   => esc_url( $atts['poster'] ),
3412          'loop'     => wp_validate_boolean( $atts['loop'] ),
3413          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3414          'muted'    => wp_validate_boolean( $atts['muted'] ),
3415          'preload'  => $atts['preload'],
3416      );
3417  
3418      // These ones should just be omitted altogether if they are blank.
3419      foreach ( array( 'poster', 'loop', 'autoplay', 'preload', 'muted' ) as $a ) {
3420          if ( empty( $html_atts[ $a ] ) ) {
3421              unset( $html_atts[ $a ] );
3422          }
3423      }
3424  
3425      $attr_strings = array();
3426      foreach ( $html_atts as $k => $v ) {
3427          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
3428      }
3429  
3430      $html = '';
3431  
3432      if ( 'mediaelement' === $library && 1 === $instance ) {
3433          $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
3434      }
3435  
3436      $html .= sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) );
3437  
3438      $fileurl = '';
3439      $source  = '<source type="%s" src="%s" />';
3440  
3441      foreach ( $default_types as $fallback ) {
3442          if ( ! empty( $atts[ $fallback ] ) ) {
3443              if ( empty( $fileurl ) ) {
3444                  $fileurl = $atts[ $fallback ];
3445              }
3446              if ( 'src' === $fallback && $is_youtube ) {
3447                  $type = array( 'type' => 'video/youtube' );
3448              } elseif ( 'src' === $fallback && $is_vimeo ) {
3449                  $type = array( 'type' => 'video/vimeo' );
3450              } else {
3451                  $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3452              }
3453              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3454              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3455          }
3456      }
3457  
3458      if ( ! empty( $content ) ) {
3459          if ( false !== strpos( $content, "\n" ) ) {
3460              $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
3461          }
3462          $html .= trim( $content );
3463      }
3464  
3465      if ( 'mediaelement' === $library ) {
3466          $html .= wp_mediaelement_fallback( $fileurl );
3467      }
3468      $html .= '</video>';
3469  
3470      $width_rule = '';
3471      if ( ! empty( $atts['width'] ) ) {
3472          $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
3473      }
3474      $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
3475  
3476      /**
3477       * Filters the output of the video shortcode.
3478       *
3479       * @since 3.6.0
3480       *
3481       * @param string $output  Video shortcode HTML output.
3482       * @param array  $atts    Array of video shortcode attributes.
3483       * @param string $video   Video file.
3484       * @param int    $post_id Post ID.
3485       * @param string $library Media library used for the video shortcode.
3486       */
3487      return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
3488  }
3489  add_shortcode( 'video', 'wp_video_shortcode' );
3490  
3491  /**
3492   * Gets the previous image link that has the same post parent.
3493   *
3494   * @since 5.8.0
3495   *
3496   * @see get_adjacent_image_link()
3497   *
3498   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3499   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3500   * @param string|false $text Optional. Link text. Default false.
3501   * @return string Markup for previous image link.
3502   */
3503  function get_previous_image_link( $size = 'thumbnail', $text = false ) {
3504      return get_adjacent_image_link( true, $size, $text );
3505  }
3506  
3507  /**
3508   * Displays previous image link that has the same post parent.
3509   *
3510   * @since 2.5.0
3511   *
3512   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3513   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3514   * @param string|false $text Optional. Link text. Default false.
3515   */
3516  function previous_image_link( $size = 'thumbnail', $text = false ) {
3517      echo get_previous_image_link( $size, $text );
3518  }
3519  
3520  /**
3521   * Gets the next image link that has the same post parent.
3522   *
3523   * @since 5.8.0
3524   *
3525   * @see get_adjacent_image_link()
3526   *
3527   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3528   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3529   * @param string|false $text Optional. Link text. Default false.
3530   * @return string Markup for next image link.
3531   */
3532  function get_next_image_link( $size = 'thumbnail', $text = false ) {
3533      return get_adjacent_image_link( false, $size, $text );
3534  }
3535  
3536  /**
3537   * Displays next image link that has the same post parent.
3538   *
3539   * @since 2.5.0
3540   *
3541   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3542   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3543   * @param string|false $text Optional. Link text. Default false.
3544   */
3545  function next_image_link( $size = 'thumbnail', $text = false ) {
3546      echo get_next_image_link( $size, $text );
3547  }
3548  
3549  /**
3550   * Gets the next or previous image link that has the same post parent.
3551   *
3552   * Retrieves the current attachment object from the $post global.
3553   *
3554   * @since 5.8.0
3555   *
3556   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3557   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3558   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3559   * @param bool         $text Optional. Link text. Default false.
3560   * @return string Markup for image link.
3561   */
3562  function get_adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3563      $post        = get_post();
3564      $attachments = array_values(
3565          get_children(
3566              array(
3567                  'post_parent'    => $post->post_parent,
3568                  'post_status'    => 'inherit',
3569                  'post_type'      => 'attachment',
3570                  'post_mime_type' => 'image',
3571                  'order'          => 'ASC',
3572                  'orderby'        => 'menu_order ID',
3573              )
3574          )
3575      );
3576  
3577      foreach ( $attachments as $k => $attachment ) {
3578          if ( (int) $attachment->ID === (int) $post->ID ) {
3579              break;
3580          }
3581      }
3582  
3583      $output        = '';
3584      $attachment_id = 0;
3585  
3586      if ( $attachments ) {
3587          $k = $prev ? $k - 1 : $k + 1;
3588  
3589          if ( isset( $attachments[ $k ] ) ) {
3590              $attachment_id = $attachments[ $k ]->ID;
3591              $attr          = array( 'alt' => get_the_title( $attachment_id ) );
3592              $output        = wp_get_attachment_link( $attachment_id, $size, true, false, $text, $attr );
3593          }
3594      }
3595  
3596      $adjacent = $prev ? 'previous' : 'next';
3597  
3598      /**
3599       * Filters the adjacent image link.
3600       *
3601       * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
3602       * either 'next', or 'previous'.
3603       *
3604       * Possible hook names include:
3605       *
3606       *  - `next_image_link`
3607       *  - `previous_image_link`
3608       *
3609       * @since 3.5.0
3610       *
3611       * @param string $output        Adjacent image HTML markup.
3612       * @param int    $attachment_id Attachment ID
3613       * @param string|int[] $size    Requested image size. Can be any registered image size name, or
3614       *                              an array of width and height values in pixels (in that order).
3615       * @param string $text          Link text.
3616       */
3617      return apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
3618  }
3619  
3620  /**
3621   * Displays next or previous image link that has the same post parent.
3622   *
3623   * Retrieves the current attachment object from the $post global.
3624   *
3625   * @since 2.5.0
3626   *
3627   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3628   * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
3629   *                           of width and height values in pixels (in that order). Default 'thumbnail'.
3630   * @param bool         $text Optional. Link text. Default false.
3631   */
3632  function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3633      echo get_adjacent_image_link( $prev, $size, $text );
3634  }
3635  
3636  /**
3637   * Retrieves taxonomies attached to given the attachment.
3638   *
3639   * @since 2.5.0
3640   * @since 4.7.0 Introduced the `$output` parameter.
3641   *
3642   * @param int|array|object $attachment Attachment ID, data array, or data object.
3643   * @param string           $output     Output type. 'names' to return an array of taxonomy names,
3644   *                                     or 'objects' to return an array of taxonomy objects.
3645   *                                     Default is 'names'.
3646   * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
3647   */
3648  function get_attachment_taxonomies( $attachment, $output = 'names' ) {
3649      if ( is_int( $attachment ) ) {
3650          $attachment = get_post( $attachment );
3651      } elseif ( is_array( $attachment ) ) {
3652          $attachment = (object) $attachment;
3653      }
3654  
3655      if ( ! is_object( $attachment ) ) {
3656          return array();
3657      }
3658  
3659      $file     = get_attached_file( $attachment->ID );
3660      $filename = wp_basename( $file );
3661  
3662      $objects = array( 'attachment' );
3663  
3664      if ( false !== strpos( $filename, '.' ) ) {
3665          $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
3666      }
3667  
3668      if ( ! empty( $attachment->post_mime_type ) ) {
3669          $objects[] = 'attachment:' . $attachment->post_mime_type;
3670  
3671          if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
3672              foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
3673                  if ( ! empty( $token ) ) {
3674                      $objects[] = "attachment:$token";
3675                  }
3676              }
3677          }
3678      }
3679  
3680      $taxonomies = array();
3681  
3682      foreach ( $objects as $object ) {
3683          $taxes = get_object_taxonomies( $object, $output );
3684  
3685          if ( $taxes ) {
3686              $taxonomies = array_merge( $taxonomies, $taxes );
3687          }
3688      }
3689  
3690      if ( 'names' === $output ) {
3691          $taxonomies = array_unique( $taxonomies );
3692      }
3693  
3694      return $taxonomies;
3695  }
3696  
3697  /**
3698   * Retrieves all of the taxonomies that are registered for attachments.
3699   *
3700   * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
3701   *
3702   * @since 3.5.0
3703   *
3704   * @see get_taxonomies()
3705   *
3706   * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
3707   *                       Default 'names'.
3708   * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.
3709   */
3710  function get_taxonomies_for_attachments( $output = 'names' ) {
3711      $taxonomies = array();
3712  
3713      foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
3714          foreach ( $taxonomy->object_type as $object_type ) {
3715              if ( 'attachment' === $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
3716                  if ( 'names' === $output ) {
3717                      $taxonomies[] = $taxonomy->name;
3718                  } else {
3719                      $taxonomies[ $taxonomy->name ] = $taxonomy;
3720                  }
3721                  break;
3722              }
3723          }
3724      }
3725  
3726      return $taxonomies;
3727  }
3728  
3729  /**
3730   * Determines whether the value is an acceptable type for GD image functions.
3731   *
3732   * In PHP 8.0, the GD extension uses GdImage objects for its data structures.
3733   * This function checks if the passed value is either a resource of type `gd`
3734   * or a GdImage object instance. Any other type will return false.
3735   *
3736   * @since 5.6.0
3737   *
3738   * @param resource|GdImage|false $image A value to check the type for.
3739   * @return bool True if $image is either a GD image resource or GdImage instance,
3740   *              false otherwise.
3741   */
3742  function is_gd_image( $image ) {
3743      if ( is_resource( $image ) && 'gd' === get_resource_type( $image )
3744          || is_object( $image ) && $image instanceof GdImage
3745      ) {
3746          return true;
3747      }
3748  
3749      return false;
3750  }
3751  
3752  /**
3753   * Creates new GD image resource with transparency support.
3754   *
3755   * @todo Deprecate if possible.
3756   *
3757   * @since 2.9.0
3758   *
3759   * @param int $width  Image width in pixels.
3760   * @param int $height Image height in pixels.
3761   * @return resource|GdImage|false The GD image resource or GdImage instance on success.
3762   *                                False on failure.
3763   */
3764  function wp_imagecreatetruecolor( $width, $height ) {
3765      $img = imagecreatetruecolor( $width, $height );
3766  
3767      if ( is_gd_image( $img )
3768          && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' )
3769      ) {
3770          imagealphablending( $img, false );
3771          imagesavealpha( $img, true );
3772      }
3773  
3774      return $img;
3775  }
3776  
3777  /**
3778   * Based on a supplied width/height example, returns the biggest possible dimensions based on the max width/height.
3779   *
3780   * @since 2.9.0
3781   *
3782   * @see wp_constrain_dimensions()
3783   *
3784   * @param int $example_width  The width of an example embed.
3785   * @param int $example_height The height of an example embed.
3786   * @param int $max_width      The maximum allowed width.
3787   * @param int $max_height     The maximum allowed height.
3788   * @return int[] {
3789   *     An array of maximum width and height values.
3790   *
3791   *     @type int $0 The maximum width in pixels.
3792   *     @type int $1 The maximum height in pixels.
3793   * }
3794   */
3795  function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
3796      $example_width  = (int) $example_width;
3797      $example_height = (int) $example_height;
3798      $max_width      = (int) $max_width;
3799      $max_height     = (int) $max_height;
3800  
3801      return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
3802  }
3803  
3804  /**
3805   * Determines the maximum upload size allowed in php.ini.
3806   *
3807   * @since 2.5.0
3808   *
3809   * @return int Allowed upload size.
3810   */
3811  function wp_max_upload_size() {
3812      $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
3813      $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
3814  
3815      /**
3816       * Filters the maximum upload size allowed in php.ini.
3817       *
3818       * @since 2.5.0
3819       *
3820       * @param int $size    Max upload size limit in bytes.
3821       * @param int $u_bytes Maximum upload filesize in bytes.
3822       * @param int $p_bytes Maximum size of POST data in bytes.
3823       */
3824      return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
3825  }
3826  
3827  /**
3828   * Returns a WP_Image_Editor instance and loads file into it.
3829   *
3830   * @since 3.5.0
3831   *
3832   * @param string $path Path to the file to load.
3833   * @param array  $args Optional. Additional arguments for retrieving the image editor.
3834   *                     Default empty array.
3835   * @return WP_Image_Editor|WP_Error The WP_Image_Editor object on success,
3836   *                                  a WP_Error object otherwise.
3837   */
3838  function wp_get_image_editor( $path, $args = array() ) {
3839      $args['path'] = $path;
3840  
3841      if ( ! isset( $args['mime_type'] ) ) {
3842          $file_info = wp_check_filetype( $args['path'] );
3843  
3844          // If $file_info['type'] is false, then we let the editor attempt to
3845          // figure out the file type, rather than forcing a failure based on extension.
3846          if ( isset( $file_info ) && $file_info['type'] ) {
3847              $args['mime_type'] = $file_info['type'];
3848          }
3849      }
3850  
3851      $implementation = _wp_image_editor_choose( $args );
3852  
3853      if ( $implementation ) {
3854          $editor = new $implementation( $path );
3855          $loaded = $editor->load();
3856  
3857          if ( is_wp_error( $loaded ) ) {
3858              return $loaded;
3859          }
3860  
3861          return $editor;
3862      }
3863  
3864      return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
3865  }
3866  
3867  /**
3868   * Tests whether there is an editor that supports a given mime type or methods.
3869   *
3870   * @since 3.5.0
3871   *
3872   * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
3873   *                           Default empty array.
3874   * @return bool True if an eligible editor is found; false otherwise.
3875   */
3876  function wp_image_editor_supports( $args = array() ) {
3877      return (bool) _wp_image_editor_choose( $args );
3878  }
3879  
3880  /**
3881   * Tests which editors are capable of supporting the request.
3882   *
3883   * @ignore
3884   * @since 3.5.0
3885   *
3886   * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
3887   * @return string|false Class name for the first editor that claims to support the request.
3888   *                      False if no editor claims to support the request.
3889   */
3890  function _wp_image_editor_choose( $args = array() ) {
3891      require_once  ABSPATH . WPINC . '/class-wp-image-editor.php';
3892      require_once  ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
3893      require_once  ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
3894      /**
3895       * Filters the list of image editing library classes.
3896       *
3897       * @since 3.5.0
3898       *
3899       * @param string[] $image_editors Array of available image editor class names. Defaults are
3900       *                                'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
3901       */
3902      $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
3903  
3904      foreach ( $implementations as $implementation ) {
3905          if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) {
3906              continue;
3907          }
3908  
3909          if ( isset( $args['mime_type'] ) &&
3910              ! call_user_func(
3911                  array( $implementation, 'supports_mime_type' ),
3912                  $args['mime_type']
3913              ) ) {
3914              continue;
3915          }
3916  
3917          if ( isset( $args['methods'] ) &&
3918              array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
3919  
3920              continue;
3921          }
3922  
3923          return $implementation;
3924      }
3925  
3926      return false;
3927  }
3928  
3929  /**
3930   * Prints default Plupload arguments.
3931   *
3932   * @since 3.4.0
3933   */
3934  function wp_plupload_default_settings() {
3935      $wp_scripts = wp_scripts();
3936  
3937      $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
3938      if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) ) {
3939          return;
3940      }
3941  
3942      $max_upload_size    = wp_max_upload_size();
3943      $allowed_extensions = array_keys( get_allowed_mime_types() );
3944      $extensions         = array();
3945      foreach ( $allowed_extensions as $extension ) {
3946          $extensions = array_merge( $extensions, explode( '|', $extension ) );
3947      }
3948  
3949      /*
3950       * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
3951       * and the `flash_swf_url` and `silverlight_xap_url` are not used.
3952       */
3953      $defaults = array(
3954          'file_data_name' => 'async-upload', // Key passed to $_FILE.
3955          'url'            => admin_url( 'async-upload.php', 'relative' ),
3956          'filters'        => array(
3957              'max_file_size' => $max_upload_size . 'b',
3958              'mime_types'    => array( array( 'extensions' => implode( ',', $extensions ) ) ),
3959          ),
3960      );
3961  
3962      /*
3963       * Currently only iOS Safari supports multiple files uploading,
3964       * but iOS 7.x has a bug that prevents uploading of videos when enabled.
3965       * See #29602.
3966       */
3967      if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
3968          strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
3969  
3970          $defaults['multi_selection'] = false;
3971      }
3972  
3973      // Check if WebP images can be edited.
3974      if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ) ) {
3975          $defaults['webp_upload_error'] = true;
3976      }
3977  
3978      /**
3979       * Filters the Plupload default settings.
3980       *
3981       * @since 3.4.0
3982       *
3983       * @param array $defaults Default Plupload settings array.
3984       */
3985      $defaults = apply_filters( 'plupload_default_settings', $defaults );
3986  
3987      $params = array(
3988          'action' => 'upload-attachment',
3989      );
3990  
3991      /**
3992       * Filters the Plupload default parameters.
3993       *
3994       * @since 3.4.0
3995       *
3996       * @param array $params Default Plupload parameters array.
3997       */
3998      $params = apply_filters( 'plupload_default_params', $params );
3999  
4000      $params['_wpnonce'] = wp_create_nonce( 'media-form' );
4001  
4002      $defaults['multipart_params'] = $params;
4003  
4004      $settings = array(
4005          'defaults'      => $defaults,
4006          'browser'       => array(
4007              'mobile'    => wp_is_mobile(),
4008              'supported' => _device_can_upload(),
4009          ),
4010          'limitExceeded' => is_multisite() && ! is_upload_space_available(),
4011      );
4012  
4013      $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
4014  
4015      if ( $data ) {
4016          $script = "$data\n$script";
4017      }
4018  
4019      $wp_scripts->add_data( 'wp-plupload', 'data', $script );
4020  }
4021  
4022  /**
4023   * Prepares an attachment post object for JS, where it is expected
4024   * to be JSON-encoded and fit into an Attachment model.
4025   *
4026   * @since 3.5.0
4027   *
4028   * @param int|WP_Post $attachment Attachment ID or object.
4029   * @return array|void {
4030   *     Array of attachment details, or void if the parameter does not correspond to an attachment.
4031   *
4032   *     @type string $alt                   Alt text of the attachment.
4033   *     @type string $author                ID of the attachment author, as a string.
4034   *     @type string $authorName            Name of the attachment author.
4035   *     @type string $caption               Caption for the attachment.
4036   *     @type array  $compat                Containing item and meta.
4037   *     @type string $context               Context, whether it's used as the site icon for example.
4038   *     @type int    $date                  Uploaded date, timestamp in milliseconds.
4039   *     @type string $dateFormatted         Formatted date (e.g. June 29, 2018).
4040   *     @type string $description           Description of the attachment.
4041   *     @type string $editLink              URL to the edit page for the attachment.
4042   *     @type string $filename              File name of the attachment.
4043   *     @type string $filesizeHumanReadable Filesize of the attachment in human readable format (e.g. 1 MB).
4044   *     @type int    $filesizeInBytes       Filesize of the attachment in bytes.
4045   *     @type int    $height                If the attachment is an image, represents the height of the image in pixels.
4046   *     @type string $icon                  Icon URL of the attachment (e.g. /wp-includes/images/media/archive.png).
4047   *     @type int    $id                    ID of the attachment.
4048   *     @type string $link                  URL to the attachment.
4049   *     @type int    $menuOrder             Menu order of the attachment post.
4050   *     @type array  $meta                  Meta data for the attachment.
4051   *     @type string $mime                  Mime type of the attachment (e.g. image/jpeg or application/zip).
4052   *     @type int    $modified              Last modified, timestamp in milliseconds.
4053   *     @type string $name                  Name, same as title of the attachment.
4054   *     @type array  $nonces                Nonces for update, delete and edit.
4055   *     @type string $orientation           If the attachment is an image, represents the image orientation
4056   *                                         (landscape or portrait).
4057   *     @type array  $sizes                 If the attachment is an image, contains an array of arrays
4058   *                                         for the images sizes: thumbnail, medium, large, and full.
4059   *     @type string $status                Post status of the attachment (usually 'inherit').
4060   *     @type string $subtype               Mime subtype of the attachment (usually the last part, e.g. jpeg or zip).
4061   *     @type string $title                 Title of the attachment (usually slugified file name without the extension).
4062   *     @type string $type                  Type of the attachment (usually first part of the mime type, e.g. image).
4063   *     @type int    $uploadedTo            Parent post to which the attachment was uploaded.
4064   *     @type string $uploadedToLink        URL to the edit page of the parent post of the attachment.
4065   *     @type string $uploadedToTitle       Post title of the parent of the attachment.
4066   *     @type string $url                   Direct URL to the attachment file (from wp-content).
4067   *     @type int    $width                 If the attachment is an image, represents the width of the image in pixels.
4068   * }
4069   *
4070   */
4071  function wp_prepare_attachment_for_js( $attachment ) {
4072      $attachment = get_post( $attachment );
4073  
4074      if ( ! $attachment ) {
4075          return;
4076      }
4077  
4078      if ( 'attachment' !== $attachment->post_type ) {
4079          return;
4080      }
4081  
4082      $meta = wp_get_attachment_metadata( $attachment->ID );
4083      if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
4084          list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
4085      } else {
4086          list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
4087      }
4088  
4089      $attachment_url = wp_get_attachment_url( $attachment->ID );
4090      $base_url       = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
4091  
4092      $response = array(
4093          'id'            => $attachment->ID,
4094          'title'         => $attachment->post_title,
4095          'filename'      => wp_basename( get_attached_file( $attachment->ID ) ),
4096          'url'           => $attachment_url,
4097          'link'          => get_attachment_link( $attachment->ID ),
4098          'alt'           => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
4099          'author'        => $attachment->post_author,
4100          'description'   => $attachment->post_content,
4101          'caption'       => $attachment->post_excerpt,
4102          'name'          => $attachment->post_name,
4103          'status'        => $attachment->post_status,
4104          'uploadedTo'    => $attachment->post_parent,
4105          'date'          => strtotime( $attachment->post_date_gmt ) * 1000,
4106          'modified'      => strtotime( $attachment->post_modified_gmt ) * 1000,
4107          'menuOrder'     => $attachment->menu_order,
4108          'mime'          => $attachment->post_mime_type,
4109          'type'          => $type,
4110          'subtype'       => $subtype,
4111          'icon'          => wp_mime_type_icon( $attachment->ID ),
4112          'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
4113          'nonces'        => array(
4114              'update' => false,
4115              'delete' => false,
4116              'edit'   => false,
4117          ),
4118          'editLink'      => false,
4119          'meta'          => false,
4120      );
4121  
4122      $author = new WP_User( $attachment->post_author );
4123  
4124      if ( $author->exists() ) {
4125          $author_name            = $author->display_name ? $author->display_name : $author->nickname;
4126          $response['authorName'] = html_entity_decode( $author_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
4127          $response['authorLink'] = get_edit_user_link( $author->ID );
4128      } else {
4129          $response['authorName'] = __( '(no author)' );
4130      }
4131  
4132      if ( $attachment->post_parent ) {
4133          $post_parent = get_post( $attachment->post_parent );
4134          if ( $post_parent ) {
4135              $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
4136              $response['uploadedToLink']  = get_edit_post_link( $attachment->post_parent, 'raw' );
4137          }
4138      }
4139  
4140      $attached_file = get_attached_file( $attachment->ID );
4141  
4142      if ( isset( $meta['filesize'] ) ) {
4143          $bytes = $meta['filesize'];
4144      } elseif ( file_exists( $attached_file ) ) {
4145          $bytes = wp_filesize( $attached_file );
4146      } else {
4147          $bytes = '';
4148      }
4149  
4150      if ( $bytes ) {
4151          $response['filesizeInBytes']       = $bytes;
4152          $response['filesizeHumanReadable'] = size_format( $bytes );
4153      }
4154  
4155      $context             = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
4156      $response['context'] = ( $context ) ? $context : '';
4157  
4158      if ( current_user_can( 'edit_post', $attachment->ID ) ) {
4159          $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
4160          $response['nonces']['edit']   = wp_create_nonce( 'image_editor-' . $attachment->ID );
4161          $response['editLink']         = get_edit_post_link( $attachment->ID, 'raw' );
4162      }
4163  
4164      if ( current_user_can( 'delete_post', $attachment->ID ) ) {
4165          $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
4166      }
4167  
4168      if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
4169          $sizes = array();
4170  
4171          /** This filter is documented in wp-admin/includes/media.php */
4172          $possible_sizes = apply_filters(
4173              'image_size_names_choose',
4174              array(
4175                  'thumbnail' => __( 'Thumbnail' ),
4176                  'medium'    => __( 'Medium' ),
4177                  'large'     => __( 'Large' ),
4178                  'full'      => __( 'Full Size' ),
4179              )
4180          );
4181          unset( $possible_sizes['full'] );
4182  
4183          /*
4184           * Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
4185           * First: run the image_downsize filter. If it returns something, we can use its data.
4186           * If the filter does not return something, then image_downsize() is just an expensive way
4187           * to check the image metadata, which we do second.
4188           */
4189          foreach ( $possible_sizes as $size => $label ) {
4190  
4191              /** This filter is documented in wp-includes/media.php */
4192              $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
4193  
4194              if ( $downsize ) {
4195                  if ( empty( $downsize[3] ) ) {
4196                      continue;
4197                  }
4198  
4199                  $sizes[ $size ] = array(
4200                      'height'      => $downsize[2],
4201                      'width'       => $downsize[1],
4202                      'url'         => $downsize[0],
4203                      'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
4204                  );
4205              } elseif ( isset( $meta['sizes'][ $size ] ) ) {
4206                  // Nothing from the filter, so consult image metadata if we have it.
4207                  $size_meta = $meta['sizes'][ $size ];
4208  
4209                  // We have the actual image size, but might need to further constrain it if content_width is narrower.
4210                  // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
4211                  list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
4212  
4213                  $sizes[ $size ] = array(
4214                      'height'      => $height,
4215                      'width'       => $width,
4216                      'url'         => $base_url . $size_meta['file'],
4217                      'orientation' => $height > $width ? 'portrait' : 'landscape',
4218                  );
4219              }
4220          }
4221  
4222          if ( 'image' === $type ) {
4223              if ( ! empty( $meta['original_image'] ) ) {
4224                  $response['originalImageURL']  = wp_get_original_image_url( $attachment->ID );
4225                  $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
4226              }
4227  
4228              $sizes['full'] = array( 'url' => $attachment_url );
4229  
4230              if ( isset( $meta['height'], $meta['width'] ) ) {
4231                  $sizes['full']['height']      = $meta['height'];
4232                  $sizes['full']['width']       = $meta['width'];
4233                  $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
4234              }
4235  
4236              $response = array_merge( $response, $sizes['full'] );
4237          } elseif ( $meta['sizes']['full']['file'] ) {
4238              $sizes['full'] = array(
4239                  'url'         => $base_url . $meta['sizes']['full']['file'],
4240                  'height'      => $meta['sizes']['full']['height'],
4241                  'width'       => $meta['sizes']['full']['width'],
4242                  'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape',
4243              );
4244          }
4245  
4246          $response = array_merge( $response, array( 'sizes' => $sizes ) );
4247      }
4248  
4249      if ( $meta && 'video' === $type ) {
4250          if ( isset( $meta['width'] ) ) {
4251              $response['width'] = (int) $meta['width'];
4252          }
4253          if ( isset( $meta['height'] ) ) {
4254              $response['height'] = (int) $meta['height'];
4255          }
4256      }
4257  
4258      if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
4259          if ( isset( $meta['length_formatted'] ) ) {
4260              $response['fileLength']              = $meta['length_formatted'];
4261              $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] );
4262          }
4263  
4264          $response['meta'] = array();
4265          foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
4266              $response['meta'][ $key ] = false;
4267  
4268              if ( ! empty( $meta[ $key ] ) ) {
4269                  $response['meta'][ $key ] = $meta[ $key ];
4270              }
4271          }
4272  
4273          $id = get_post_thumbnail_id( $attachment->ID );
4274          if ( ! empty( $id ) ) {
4275              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
4276              $response['image']            = compact( 'src', 'width', 'height' );
4277              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
4278              $response['thumb']            = compact( 'src', 'width', 'height' );
4279          } else {
4280              $src               = wp_mime_type_icon( $attachment->ID );
4281              $width             = 48;
4282              $height            = 64;
4283              $response['image'] = compact( 'src', 'width', 'height' );
4284              $response['thumb'] = compact( 'src', 'width', 'height' );
4285          }
4286      }
4287  
4288      if ( function_exists( 'get_compat_media_markup' ) ) {
4289          $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
4290      }
4291  
4292      if ( function_exists( 'get_media_states' ) ) {
4293          $media_states = get_media_states( $attachment );
4294          if ( ! empty( $media_states ) ) {
4295              $response['mediaStates'] = implode( ', ', $media_states );
4296          }
4297      }
4298  
4299      /**
4300       * Filters the attachment data prepared for JavaScript.
4301       *
4302       * @since 3.5.0
4303       *
4304       * @param array       $response   Array of prepared attachment data. @see wp_prepare_attachment_for_js().
4305       * @param WP_Post     $attachment Attachment object.
4306       * @param array|false $meta       Array of attachment meta data, or false if there is none.
4307       */
4308      return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
4309  }
4310  
4311  /**
4312   * Enqueues all scripts, styles, settings, and templates necessary to use
4313   * all media JS APIs.
4314   *
4315   * @since 3.5.0
4316   *
4317   * @global int       $content_width
4318   * @global wpdb      $wpdb          WordPress database abstraction object.
4319   * @global WP_Locale $wp_locale     WordPress date and time locale object.
4320   *
4321   * @param array $args {
4322   *     Arguments for enqueuing media scripts.
4323   *
4324   *     @type int|WP_Post $post Post ID or post object.
4325   * }
4326   */
4327  function wp_enqueue_media( $args = array() ) {
4328      // Enqueue me just once per page, please.
4329      if ( did_action( 'wp_enqueue_media' ) ) {
4330          return;
4331      }
4332  
4333      global $content_width, $wpdb, $wp_locale;
4334  
4335      $defaults = array(
4336          'post' => null,
4337      );
4338      $args     = wp_parse_args( $args, $defaults );
4339  
4340      // We're going to pass the old thickbox media tabs to `media_upload_tabs`
4341      // to ensure plugins will work. We will then unset those tabs.
4342      $tabs = array(
4343          // handler action suffix => tab label
4344          'type'     => '',
4345          'type_url' => '',
4346          'gallery'  => '',
4347          'library'  => '',
4348      );
4349  
4350      /** This filter is documented in wp-admin/includes/media.php */
4351      $tabs = apply_filters( 'media_upload_tabs', $tabs );
4352      unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
4353  
4354      $props = array(
4355          'link'  => get_option( 'image_default_link_type' ), // DB default is 'file'.
4356          'align' => get_option( 'image_default_align' ),     // Empty default.
4357          'size'  => get_option( 'image_default_size' ),      // Empty default.
4358      );
4359  
4360      $exts      = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
4361      $mimes     = get_allowed_mime_types();
4362      $ext_mimes = array();
4363      foreach ( $exts as $ext ) {
4364          foreach ( $mimes as $ext_preg => $mime_match ) {
4365              if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
4366                  $ext_mimes[ $ext ] = $mime_match;
4367                  break;
4368              }
4369          }
4370      }
4371  
4372      /**
4373       * Allows showing or hiding the "Create Audio Playlist" button in the media library.
4374       *
4375       * By default, the "Create Audio Playlist" button will always be shown in
4376       * the media library.  If this filter returns `null`, a query will be run
4377       * to determine whether the media library contains any audio items.  This
4378       * was the default behavior prior to version 4.8.0, but this query is
4379       * expensive for large media libraries.
4380       *
4381       * @since 4.7.4
4382       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4383       *
4384       * @link https://core.trac.wordpress.org/ticket/31071
4385       *
4386       * @param bool|null $show Whether to show the button, or `null` to decide based
4387       *                        on whether any audio files exist in the media library.
4388       */
4389      $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
4390      if ( null === $show_audio_playlist ) {
4391          $show_audio_playlist = $wpdb->get_var(
4392              "
4393              SELECT ID
4394              FROM $wpdb->posts
4395              WHERE post_type = 'attachment'
4396              AND post_mime_type LIKE 'audio%'
4397              LIMIT 1
4398          "
4399          );
4400      }
4401  
4402      /**
4403       * Allows showing or hiding the "Create Video Playlist" button in the media library.
4404       *
4405       * By default, the "Create Video Playlist" button will always be shown in
4406       * the media library.  If this filter returns `null`, a query will be run
4407       * to determine whether the media library contains any video items.  This
4408       * was the default behavior prior to version 4.8.0, but this query is
4409       * expensive for large media libraries.
4410       *
4411       * @since 4.7.4
4412       * @since 4.8.0 The filter's default value is `true` rather than `null`.
4413       *
4414       * @link https://core.trac.wordpress.org/ticket/31071
4415       *
4416       * @param bool|null $show Whether to show the button, or `null` to decide based
4417       *                        on whether any video files exist in the media library.
4418       */
4419      $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
4420      if ( null === $show_video_playlist ) {
4421          $show_video_playlist = $wpdb->get_var(
4422              "
4423              SELECT ID
4424              FROM $wpdb->posts
4425              WHERE post_type = 'attachment'
4426              AND post_mime_type LIKE 'video%'
4427              LIMIT 1
4428          "
4429          );
4430      }
4431  
4432      /**
4433       * Allows overriding the list of months displayed in the media library.
4434       *
4435       * By default (if this filter does not return an array), a query will be
4436       * run to determine the months that have media items.  This query can be
4437       * expensive for large media libraries, so it may be desirable for sites to
4438       * override this behavior.
4439       *
4440       * @since 4.7.4
4441       *
4442       * @link https://core.trac.wordpress.org/ticket/31071
4443       *
4444       * @param stdClass[]|null $months An array of objects with `month` and `year`
4445       *                                properties, or `null` for default behavior.
4446       */
4447      $months = apply_filters( 'media_library_months_with_files', null );
4448      if ( ! is_array( $months ) ) {
4449          $months = $wpdb->get_results(
4450              $wpdb->prepare(
4451                  "
4452              SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
4453              FROM $wpdb->posts
4454              WHERE post_type = %s
4455              ORDER BY post_date DESC
4456          ",
4457                  'attachment'
4458              )
4459          );
4460      }
4461      foreach ( $months as $month_year ) {
4462          $month_year->text = sprintf(
4463              /* translators: 1: Month, 2: Year. */
4464              __( '%1$s %2$d' ),
4465              $wp_locale->get_month( $month_year->month ),
4466              $month_year->year
4467          );
4468      }
4469  
4470      /**
4471       * Filters whether the Media Library grid has infinite scrolling. Default `false`.
4472       *
4473       * @since 5.8.0
4474       *
4475       * @param bool $infinite Whether the Media Library grid has infinite scrolling.
4476       */
4477      $infinite_scrolling = apply_filters( 'media_library_infinite_scrolling', false );
4478  
4479      $settings = array(
4480          'tabs'              => $tabs,
4481          'tabUrl'            => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ),
4482          'mimeTypes'         => wp_list_pluck( get_post_mime_types(), 0 ),
4483          /** This filter is documented in wp-admin/includes/media.php */
4484          'captions'          => ! apply_filters( 'disable_captions', '' ),
4485          'nonce'             => array(
4486              'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
4487          ),
4488          'post'              => array(
4489              'id' => 0,
4490          ),
4491          'defaultProps'      => $props,
4492          'attachmentCounts'  => array(
4493              'audio' => ( $show_audio_playlist ) ? 1 : 0,
4494              'video' => ( $show_video_playlist ) ? 1 : 0,
4495          ),
4496          'oEmbedProxyUrl'    => rest_url( 'oembed/1.0/proxy' ),
4497          'embedExts'         => $exts,
4498          'embedMimes'        => $ext_mimes,
4499          'contentWidth'      => $content_width,
4500          'months'            => $months,
4501          'mediaTrash'        => MEDIA_TRASH ? 1 : 0,
4502          'infiniteScrolling' => ( $infinite_scrolling ) ? 1 : 0,
4503      );
4504  
4505      $post = null;
4506      if ( isset( $args['post'] ) ) {
4507          $post             = get_post( $args['post'] );
4508          $settings['post'] = array(
4509              'id'    => $post->ID,
4510              'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
4511          );
4512  
4513          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
4514          if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
4515              if ( wp_attachment_is( 'audio', $post ) ) {
4516                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
4517              } elseif ( wp_attachment_is( 'video', $post ) ) {
4518                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
4519              }
4520          }
4521  
4522          if ( $thumbnail_support ) {
4523              $featured_image_id                   = get_post_meta( $post->ID, '_thumbnail_id', true );
4524              $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
4525          }
4526      }
4527  
4528      if ( $post ) {
4529          $post_type_object = get_post_type_object( $post->post_type );
4530      } else {
4531          $post_type_object = get_post_type_object( 'post' );
4532      }
4533  
4534      $strings = array(
4535          // Generic.
4536          'mediaFrameDefaultTitle'      => __( 'Media' ),
4537          'url'                         => __( 'URL' ),
4538          'addMedia'                    => __( 'Add media' ),
4539          'search'                      => __( 'Search' ),
4540          'select'                      => __( 'Select' ),
4541          'cancel'                      => __( 'Cancel' ),
4542          'update'                      => __( 'Update' ),
4543          'replace'                     => __( 'Replace' ),
4544          'remove'                      => __( 'Remove' ),
4545          'back'                        => __( 'Back' ),
4546          /*
4547           * translators: This is a would-be plural string used in the media manager.
4548           * If there is not a word you can use in your language to avoid issues with the
4549           * lack of plural support here, turn it into "selected: %d" then translate it.
4550           */
4551          'selected'                    => __( '%d selected' ),
4552          'dragInfo'                    => __( 'Drag and drop to reorder media files.' ),
4553  
4554          // Upload.
4555          'uploadFilesTitle'            => __( 'Upload files' ),
4556          'uploadImagesTitle'           => __( 'Upload images' ),
4557  
4558          // Library.
4559          'mediaLibraryTitle'           => __( 'Media Library' ),
4560          'insertMediaTitle'            => __( 'Add media' ),
4561          'createNewGallery'            => __( 'Create a new gallery' ),
4562          'createNewPlaylist'           => __( 'Create a new playlist' ),
4563          'createNewVideoPlaylist'      => __( 'Create a new video playlist' ),
4564          'returnToLibrary'             => __( '&#8592; Go to library' ),
4565          'allMediaItems'               => __( 'All media items' ),
4566          'allDates'                    => __( 'All dates' ),
4567          'noItemsFound'                => __( 'No items found.' ),
4568          'insertIntoPost'              => $post_type_object->labels->insert_into_item,
4569          'unattached'                  => _x( 'Unattached', 'media items' ),
4570          'mine'                        => _x( 'Mine', 'media items' ),
4571          'trash'                       => _x( 'Trash', 'noun' ),
4572          'uploadedToThisPost'          => $post_type_object->labels->uploaded_to_this_item,
4573          'warnDelete'                  => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4574          'warnBulkDelete'              => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4575          'warnBulkTrash'               => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
4576          'bulkSelect'                  => __( 'Bulk select' ),
4577          'trashSelected'               => __( 'Move to Trash' ),
4578          'restoreSelected'             => __( 'Restore from Trash' ),
4579          'deletePermanently'           => __( 'Delete permanently' ),
4580          'errorDeleting'               => __( 'Error in deleting the attachment.' ),
4581          'apply'                       => __( 'Apply' ),
4582          'filterByDate'                => __( 'Filter by date' ),
4583          'filterByType'                => __( 'Filter by type' ),
4584          'searchLabel'                 => __( 'Search' ),
4585          'searchMediaLabel'            => __( 'Search media' ),          // Backward compatibility pre-5.3.
4586          'searchMediaPlaceholder'      => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
4587          /* translators: %d: Number of attachments found in a search. */
4588          'mediaFound'                  => __( 'Number of media items found: %d' ),
4589          'noMedia'                     => __( 'No media items found.' ),
4590          'noMediaTryNewSearch'         => __( 'No media items found. Try a different search.' ),
4591  
4592          // Library Details.
4593          'attachmentDetails'           => __( 'Attachment details' ),
4594  
4595          // From URL.
4596          'insertFromUrlTitle'          => __( 'Insert from URL' ),
4597  
4598          // Featured Images.
4599          'setFeaturedImageTitle'       => $post_type_object->labels->featured_image,
4600          'setFeaturedImage'            => $post_type_object->labels->set_featured_image,
4601  
4602          // Gallery.
4603          'createGalleryTitle'          => __( 'Create gallery' ),
4604          'editGalleryTitle'            => __( 'Edit gallery' ),
4605          'cancelGalleryTitle'          => __( '&#8592; Cancel gallery' ),
4606          'insertGallery'               => __( 'Insert gallery' ),
4607          'updateGallery'               => __( 'Update gallery' ),
4608          'addToGallery'                => __( 'Add to gallery' ),
4609          'addToGalleryTitle'           => __( 'Add to gallery' ),
4610          'reverseOrder'                => __( 'Reverse order' ),
4611  
4612          // Edit Image.
4613          'imageDetailsTitle'           => __( 'Image details' ),
4614          'imageReplaceTitle'           => __( 'Replace image' ),
4615          'imageDetailsCancel'          => __( 'Cancel edit' ),
4616          'editImage'                   => __( 'Edit image' ),
4617  
4618          // Crop Image.
4619          'chooseImage'                 => __( 'Choose image' ),
4620          'selectAndCrop'               => __( 'Select and crop' ),
4621          'skipCropping'                => __( 'Skip cropping' ),
4622          'cropImage'                   => __( 'Crop image' ),
4623          'cropYourImage'               => __( 'Crop your image' ),
4624          'cropping'                    => __( 'Cropping&hellip;' ),
4625          /* translators: 1: Suggested width number, 2: Suggested height number. */
4626          'suggestedDimensions'         => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
4627          'cropError'                   => __( 'There has been an error cropping your image.' ),
4628  
4629          // Edit Audio.
4630          'audioDetailsTitle'           => __( 'Audio details' ),
4631          'audioReplaceTitle'           => __( 'Replace audio' ),
4632          'audioAddSourceTitle'         => __( 'Add audio source' ),
4633          'audioDetailsCancel'          => __( 'Cancel edit' ),
4634  
4635          // Edit Video.
4636          'videoDetailsTitle'           => __( 'Video details' ),
4637          'videoReplaceTitle'           => __( 'Replace video' ),
4638          'videoAddSourceTitle'         => __( 'Add video source' ),
4639          'videoDetailsCancel'          => __( 'Cancel edit' ),
4640          'videoSelectPosterImageTitle' => __( 'Select poster image' ),
4641          'videoAddTrackTitle'          => __( 'Add subtitles' ),
4642  
4643          // Playlist.
4644          'playlistDragInfo'            => __( 'Drag and drop to reorder tracks.' ),
4645          'createPlaylistTitle'         => __( 'Create audio playlist' ),
4646          'editPlaylistTitle'           => __( 'Edit audio playlist' ),
4647          'cancelPlaylistTitle'         => __( '&#8592; Cancel audio playlist' ),
4648          'insertPlaylist'              => __( 'Insert audio playlist' ),
4649          'updatePlaylist'              => __( 'Update audio playlist' ),
4650          'addToPlaylist'               => __( 'Add to audio playlist' ),
4651          'addToPlaylistTitle'          => __( 'Add to Audio Playlist' ),
4652  
4653          // Video Playlist.
4654          'videoPlaylistDragInfo'       => __( 'Drag and drop to reorder videos.' ),
4655          'createVideoPlaylistTitle'    => __( 'Create video playlist' ),
4656          'editVideoPlaylistTitle'      => __( 'Edit video playlist' ),
4657          'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel video playlist' ),
4658          'insertVideoPlaylist'         => __( 'Insert video playlist' ),
4659          'updateVideoPlaylist'         => __( 'Update video playlist' ),
4660          'addToVideoPlaylist'          => __( 'Add to video playlist' ),
4661          'addToVideoPlaylistTitle'     => __( 'Add to video Playlist' ),
4662  
4663          // Headings.
4664          'filterAttachments'           => __( 'Filter media' ),
4665          'attachmentsList'             => __( 'Media list' ),
4666      );
4667  
4668      /**
4669       * Filters the media view settings.
4670       *
4671       * @since 3.5.0
4672       *
4673       * @param array   $settings List of media view settings.
4674       * @param WP_Post $post     Post object.
4675       */
4676      $settings = apply_filters( 'media_view_settings', $settings, $post );
4677  
4678      /**
4679       * Filters the media view strings.
4680       *
4681       * @since 3.5.0
4682       *
4683       * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
4684       * @param WP_Post  $post    Post object.
4685       */
4686      $strings = apply_filters( 'media_view_strings', $strings, $post );
4687  
4688      $strings['settings'] = $settings;
4689  
4690      // Ensure we enqueue media-editor first, that way media-views
4691      // is registered internally before we try to localize it. See #24724.
4692      wp_enqueue_script( 'media-editor' );
4693      wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
4694  
4695      wp_enqueue_script( 'media-audiovideo' );
4696      wp_enqueue_style( 'media-views' );
4697      if ( is_admin() ) {
4698          wp_enqueue_script( 'mce-view' );
4699          wp_enqueue_script( 'image-edit' );
4700      }
4701      wp_enqueue_style( 'imgareaselect' );
4702      wp_plupload_default_settings();
4703  
4704      require_once  ABSPATH . WPINC . '/media-template.php';
4705      add_action( 'admin_footer', 'wp_print_media_templates' );
4706      add_action( 'wp_footer', 'wp_print_media_templates' );
4707      add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
4708  
4709      /**
4710       * Fires at the conclusion of wp_enqueue_media().
4711       *
4712       * @since 3.5.0
4713       */
4714      do_action( 'wp_enqueue_media' );
4715  }
4716  
4717  /**
4718   * Retrieves media attached to the passed post.
4719   *
4720   * @since 3.6.0
4721   *
4722   * @param string      $type Mime type.
4723   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4724   * @return WP_Post[] Array of media attached to the given post.
4725   */
4726  function get_attached_media( $type, $post = 0 ) {
4727      $post = get_post( $post );
4728  
4729      if ( ! $post ) {
4730          return array();
4731      }
4732  
4733      $args = array(
4734          'post_parent'    => $post->ID,
4735          'post_type'      => 'attachment',
4736          'post_mime_type' => $type,
4737          'posts_per_page' => -1,
4738          'orderby'        => 'menu_order',
4739          'order'          => 'ASC',
4740      );
4741  
4742      /**
4743       * Filters arguments used to retrieve media attached to the given post.
4744       *
4745       * @since 3.6.0
4746       *
4747       * @param array   $args Post query arguments.
4748       * @param string  $type Mime type of the desired media.
4749       * @param WP_Post $post Post object.
4750       */
4751      $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
4752  
4753      $children = get_children( $args );
4754  
4755      /**
4756       * Filters the list of media attached to the given post.
4757       *
4758       * @since 3.6.0
4759       *
4760       * @param WP_Post[] $children Array of media attached to the given post.
4761       * @param string    $type     Mime type of the media desired.
4762       * @param WP_Post   $post     Post object.
4763       */
4764      return (array) apply_filters( 'get_attached_media', $children, $type, $post );
4765  }
4766  
4767  /**
4768   * Checks the HTML content for a audio, video, object, embed, or iframe tags.
4769   *
4770   * @since 3.6.0
4771   *
4772   * @param string   $content A string of HTML which might contain media elements.
4773   * @param string[] $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
4774   * @return string[] Array of found HTML media elements.
4775   */
4776  function get_media_embedded_in_content( $content, $types = null ) {
4777      $html = array();
4778  
4779      /**
4780       * Filters the embedded media types that are allowed to be returned from the content blob.
4781       *
4782       * @since 4.2.0
4783       *
4784       * @param string[] $allowed_media_types An array of allowed media types. Default media types are
4785       *                                      'audio', 'video', 'object', 'embed', and 'iframe'.
4786       */
4787      $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
4788  
4789      if ( ! empty( $types ) ) {
4790          if ( ! is_array( $types ) ) {
4791              $types = array( $types );
4792          }
4793  
4794          $allowed_media_types = array_intersect( $allowed_media_types, $types );
4795      }
4796  
4797      $tags = implode( '|', $allowed_media_types );
4798  
4799      if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
4800          foreach ( $matches[0] as $match ) {
4801              $html[] = $match;
4802          }
4803      }
4804  
4805      return $html;
4806  }
4807  
4808  /**
4809   * Retrieves galleries from the passed post's content.
4810   *
4811   * @since 3.6.0
4812   *
4813   * @param int|WP_Post $post Post ID or object.
4814   * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
4815   * @return array A list of arrays, each containing gallery data and srcs parsed
4816   *               from the expanded shortcode.
4817   */
4818  function get_post_galleries( $post, $html = true ) {
4819      $post = get_post( $post );
4820  
4821      if ( ! $post ) {
4822          return array();
4823      }
4824  
4825      if ( ! has_shortcode( $post->post_content, 'gallery' ) && ! has_block( 'gallery', $post->post_content ) ) {
4826          return array();
4827      }
4828  
4829      $galleries = array();
4830      if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
4831          foreach ( $matches as $shortcode ) {
4832              if ( 'gallery' === $shortcode[2] ) {
4833                  $srcs = array();
4834  
4835                  $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
4836                  if ( ! is_array( $shortcode_attrs ) ) {
4837                      $shortcode_attrs = array();
4838                  }
4839  
4840                  // Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already.
4841                  if ( ! isset( $shortcode_attrs['id'] ) ) {
4842                      $shortcode[3] .= ' id="' . (int) $post->ID . '"';
4843                  }
4844  
4845                  $gallery = do_shortcode_tag( $shortcode );
4846                  if ( $html ) {
4847                      $galleries[] = $gallery;
4848                  } else {
4849                      preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
4850                      if ( ! empty( $src ) ) {
4851                          foreach ( $src as $s ) {
4852                              $srcs[] = $s[2];
4853                          }
4854                      }
4855  
4856                      $galleries[] = array_merge(
4857                          $shortcode_attrs,
4858                          array(
4859                              'src' => array_values( array_unique( $srcs ) ),
4860                          )
4861                      );
4862                  }
4863              }
4864          }
4865      }
4866  
4867      if ( has_block( 'gallery', $post->post_content ) ) {
4868          $post_blocks = parse_blocks( $post->post_content );
4869  
4870          while ( $block = array_shift( $post_blocks ) ) {
4871              $has_inner_blocks = ! empty( $block['innerBlocks'] );
4872  
4873              // Skip blocks with no blockName and no innerHTML.
4874              if ( ! $block['blockName'] ) {
4875                  continue;
4876              }
4877  
4878              // Skip non-Gallery blocks.
4879              if ( 'core/gallery' !== $block['blockName'] ) {
4880                  // Move inner blocks into the root array before skipping.
4881                  if ( $has_inner_blocks ) {
4882                      array_push( $post_blocks, ...$block['innerBlocks'] );
4883                  }
4884                  continue;
4885              }
4886  
4887              // New Gallery block format as HTML.
4888              if ( $has_inner_blocks && $html ) {
4889                  $block_html  = wp_list_pluck( $block['innerBlocks'], 'innerHTML' );
4890                  $galleries[] = '<figure>' . implode( ' ', $block_html ) . '</figure>';
4891                  continue;
4892              }
4893  
4894              $srcs = array();
4895  
4896              // New Gallery block format as an array.
4897              if ( $has_inner_blocks ) {
4898                  $attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' );
4899                  $ids   = wp_list_pluck( $attrs, 'id' );
4900  
4901                  foreach ( $ids as $id ) {
4902                      $url = wp_get_attachment_url( $id );
4903  
4904                      if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
4905                          $srcs[] = $url;
4906                      }
4907                  }
4908  
4909                  $galleries[] = array(
4910                      'ids' => implode( ',', $ids ),
4911                      'src' => $srcs,
4912                  );
4913  
4914                  continue;
4915              }
4916  
4917              // Old Gallery block format as HTML.
4918              if ( $html ) {
4919                  $galleries[] = $block['innerHTML'];
4920                  continue;
4921              }
4922  
4923              // Old Gallery block format as an array.
4924              $ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array();
4925  
4926              // If present, use the image IDs from the JSON blob as canonical.
4927              if ( ! empty( $ids ) ) {
4928                  foreach ( $ids as $id ) {
4929                      $url = wp_get_attachment_url( $id );
4930  
4931                      if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
4932                          $srcs[] = $url;
4933                      }
4934                  }
4935  
4936                  $galleries[] = array(
4937                      'ids' => implode( ',', $ids ),
4938                      'src' => $srcs,
4939                  );
4940  
4941                  continue;
4942              }
4943  
4944              // Otherwise, extract srcs from the innerHTML.
4945              preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $found_srcs, PREG_SET_ORDER );
4946  
4947              if ( ! empty( $found_srcs[0] ) ) {
4948                  foreach ( $found_srcs as $src ) {
4949                      if ( isset( $src[2] ) && ! in_array( $src[2], $srcs, true ) ) {
4950                          $srcs[] = $src[2];
4951                      }
4952                  }
4953              }
4954  
4955              $galleries[] = array( 'src' => $srcs );
4956          }
4957      }
4958  
4959      /**
4960       * Filters the list of all found galleries in the given post.
4961       *
4962       * @since 3.6.0
4963       *
4964       * @param array   $galleries Associative array of all found post galleries.
4965       * @param WP_Post $post      Post object.
4966       */
4967      return apply_filters( 'get_post_galleries', $galleries, $post );
4968  }
4969  
4970  /**
4971   * Checks a specified post's content for gallery and, if present, return the first
4972   *
4973   * @since 3.6.0
4974   *
4975   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4976   * @param bool        $html Optional. Whether to return HTML or data. Default is true.
4977   * @return string|array Gallery data and srcs parsed from the expanded shortcode.
4978   */
4979  function get_post_gallery( $post = 0, $html = true ) {
4980      $galleries = get_post_galleries( $post, $html );
4981      $gallery   = reset( $galleries );
4982  
4983      /**
4984       * Filters the first-found post gallery.
4985       *
4986       * @since 3.6.0
4987       *
4988       * @param array       $gallery   The first-found post gallery.
4989       * @param int|WP_Post $post      Post ID or object.
4990       * @param array       $galleries Associative array of all found post galleries.
4991       */
4992      return apply_filters( 'get_post_gallery', $gallery,