[ Index ]

PHP Cross Reference of WordPress

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