[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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