[ 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       * Passing a non-null value to 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 $data {
 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          // Generate 'srcset' and 'sizes' if not already present.
1052          if ( empty( $attr['srcset'] ) ) {
1053              $image_meta = wp_get_attachment_metadata( $attachment_id );
1054  
1055              if ( is_array( $image_meta ) ) {
1056                  $size_array = array( absint( $width ), absint( $height ) );
1057                  $srcset     = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
1058                  $sizes      = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
1059  
1060                  if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
1061                      $attr['srcset'] = $srcset;
1062  
1063                      if ( empty( $attr['sizes'] ) ) {
1064                          $attr['sizes'] = $sizes;
1065                      }
1066                  }
1067              }
1068          }
1069  
1070          /**
1071           * Filters the list of attachment image attributes.
1072           *
1073           * @since 2.8.0
1074           *
1075           * @param array        $attr       Array of attribute values for the image markup, keyed by attribute name.
1076           *                                 See wp_get_attachment_image().
1077           * @param WP_Post      $attachment Image attachment post.
1078           * @param string|array $size       Requested size. Image size or array of width and height values
1079           *                                 (in that order). Default 'thumbnail'.
1080           */
1081          $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
1082  
1083          $attr = array_map( 'esc_attr', $attr );
1084          $html = rtrim( "<img $hwstring" );
1085  
1086          foreach ( $attr as $name => $value ) {
1087              $html .= " $name=" . '"' . $value . '"';
1088          }
1089  
1090          $html .= ' />';
1091      }
1092  
1093      return $html;
1094  }
1095  
1096  /**
1097   * Get the URL of an image attachment.
1098   *
1099   * @since 4.4.0
1100   *
1101   * @param int          $attachment_id Image attachment ID.
1102   * @param string|array $size          Optional. Image size to retrieve. Accepts any valid image size, or an array
1103   *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
1104   * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
1105   * @return string|false Attachment URL or false if no image is available.
1106   */
1107  function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
1108      $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
1109      return isset( $image['0'] ) ? $image['0'] : false;
1110  }
1111  
1112  /**
1113   * Get the attachment path relative to the upload directory.
1114   *
1115   * @since 4.4.1
1116   * @access private
1117   *
1118   * @param string $file Attachment file name.
1119   * @return string Attachment path relative to the upload directory.
1120   */
1121  function _wp_get_attachment_relative_path( $file ) {
1122      $dirname = dirname( $file );
1123  
1124      if ( '.' === $dirname ) {
1125          return '';
1126      }
1127  
1128      if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
1129          // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
1130          $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
1131          $dirname = ltrim( $dirname, '/' );
1132      }
1133  
1134      return $dirname;
1135  }
1136  
1137  /**
1138   * Get the image size as array from its meta data.
1139   *
1140   * Used for responsive images.
1141   *
1142   * @since 4.4.0
1143   * @access private
1144   *
1145   * @param string $size_name  Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
1146   * @param array  $image_meta The image meta data.
1147   * @return array|bool The image meta data as returned by `wp_get_attachment_metadata()`.
1148   */
1149  function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
1150      if ( 'full' === $size_name ) {
1151          return array(
1152              absint( $image_meta['width'] ),
1153              absint( $image_meta['height'] ),
1154          );
1155      } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) {
1156          return array(
1157              absint( $image_meta['sizes'][ $size_name ]['width'] ),
1158              absint( $image_meta['sizes'][ $size_name ]['height'] ),
1159          );
1160      }
1161  
1162      return false;
1163  }
1164  
1165  /**
1166   * Retrieves the value for an image attachment's 'srcset' attribute.
1167   *
1168   * @since 4.4.0
1169   *
1170   * @see wp_calculate_image_srcset()
1171   *
1172   * @param int          $attachment_id Image attachment ID.
1173   * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of
1174   *                                    width and height values in pixels (in that order). Default 'medium'.
1175   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1176   *                                    Default null.
1177   * @return string|bool A 'srcset' value string or false.
1178   */
1179  function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
1180      $image = wp_get_attachment_image_src( $attachment_id, $size );
1181  
1182      if ( ! $image ) {
1183          return false;
1184      }
1185  
1186      if ( ! is_array( $image_meta ) ) {
1187          $image_meta = wp_get_attachment_metadata( $attachment_id );
1188      }
1189  
1190      $image_src  = $image[0];
1191      $size_array = array(
1192          absint( $image[1] ),
1193          absint( $image[2] ),
1194      );
1195  
1196      return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1197  }
1198  
1199  /**
1200   * A helper function to calculate the image sources to include in a 'srcset' attribute.
1201   *
1202   * @since 4.4.0
1203   *
1204   * @param int[]  $size_array    {
1205   *     An array of width and height values.
1206   *
1207   *     @type int $0 The width in pixels.
1208   *     @type int $1 The height in pixels.
1209   * }
1210   * @param string $image_src     The 'src' of the image.
1211   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1212   * @param int    $attachment_id Optional. The image attachment ID. Default 0.
1213   * @return string|bool          The 'srcset' attribute value. False on error or when only one source exists.
1214   */
1215  function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
1216      /**
1217       * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
1218       *
1219       * @since 4.5.0
1220       *
1221       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1222       * @param int[]  $size_array    {
1223       *     An array of requested width and height values.
1224       *
1225       *     @type int $0 The width in pixels.
1226       *     @type int $1 The height in pixels.
1227       * }
1228       * @param string $image_src     The 'src' of the image.
1229       * @param int    $attachment_id The image attachment ID or 0 if not supplied.
1230       */
1231      $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
1232  
1233      if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
1234          return false;
1235      }
1236  
1237      $image_sizes = $image_meta['sizes'];
1238  
1239      // Get the width and height of the image.
1240      $image_width  = (int) $size_array[0];
1241      $image_height = (int) $size_array[1];
1242  
1243      // Bail early if error/no width.
1244      if ( $image_width < 1 ) {
1245          return false;
1246      }
1247  
1248      $image_basename = wp_basename( $image_meta['file'] );
1249  
1250      /*
1251       * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1252       * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1253       * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1254       */
1255      if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1256          $image_sizes[] = array(
1257              'width'  => $image_meta['width'],
1258              'height' => $image_meta['height'],
1259              'file'   => $image_basename,
1260          );
1261      } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1262          return false;
1263      }
1264  
1265      // Retrieve the uploads sub-directory from the full size image.
1266      $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1267  
1268      if ( $dirname ) {
1269          $dirname = trailingslashit( $dirname );
1270      }
1271  
1272      $upload_dir    = wp_get_upload_dir();
1273      $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1274  
1275      /*
1276       * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1277       * (which is to say, when they share the domain name of the current request).
1278       */
1279      if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
1280          $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1281      }
1282  
1283      /*
1284       * Images that have been edited in WordPress after being uploaded will
1285       * contain a unique hash. Look for that hash and use it later to filter
1286       * out images that are leftovers from previous versions.
1287       */
1288      $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1289  
1290      /**
1291       * Filters the maximum image width to be included in a 'srcset' attribute.
1292       *
1293       * @since 4.4.0
1294       *
1295       * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '2048'.
1296       * @param int[] $size_array {
1297       *     An array of requested width and height values.
1298       *
1299       *     @type int $0 The width in pixels.
1300       *     @type int $1 The height in pixels.
1301       * }
1302       */
1303      $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
1304  
1305      // Array to hold URL candidates.
1306      $sources = array();
1307  
1308      /**
1309       * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1310       * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1311       * an incorrect image. See #35045.
1312       */
1313      $src_matched = false;
1314  
1315      /*
1316       * Loop through available images. Only use images that are resized
1317       * versions of the same edit.
1318       */
1319      foreach ( $image_sizes as $image ) {
1320          $is_src = false;
1321  
1322          // Check if image meta isn't corrupted.
1323          if ( ! is_array( $image ) ) {
1324              continue;
1325          }
1326  
1327          // If the file name is part of the `src`, we've confirmed a match.
1328          if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1329              $src_matched = true;
1330              $is_src      = true;
1331          }
1332  
1333          // Filter out images that are from previous edits.
1334          if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1335              continue;
1336          }
1337  
1338          /*
1339           * Filters out images that are wider than '$max_srcset_image_width' unless
1340           * that file is in the 'src' attribute.
1341           */
1342          if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1343              continue;
1344          }
1345  
1346          // If the image dimensions are within 1px of the expected size, use it.
1347          if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
1348              // Add the URL, descriptor, and value to the sources array to be returned.
1349              $source = array(
1350                  'url'        => $image_baseurl . $image['file'],
1351                  'descriptor' => 'w',
1352                  'value'      => $image['width'],
1353              );
1354  
1355              // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1356              if ( $is_src ) {
1357                  $sources = array( $image['width'] => $source ) + $sources;
1358              } else {
1359                  $sources[ $image['width'] ] = $source;
1360              }
1361          }
1362      }
1363  
1364      /**
1365       * Filters an image's 'srcset' sources.
1366       *
1367       * @since 4.4.0
1368       *
1369       * @param array  $sources {
1370       *     One or more arrays of source data to include in the 'srcset'.
1371       *
1372       *     @type array $width {
1373       *         @type string $url        The URL of an image source.
1374       *         @type string $descriptor The descriptor type used in the image candidate string,
1375       *                                  either 'w' or 'x'.
1376       *         @type int    $value      The source width if paired with a 'w' descriptor, or a
1377       *                                  pixel density value if paired with an 'x' descriptor.
1378       *     }
1379       * }
1380       * @param array $size_array     {
1381       *     An array of requested width and height values.
1382       *
1383       *     @type int $0 The width in pixels.
1384       *     @type int $1 The height in pixels.
1385       * }
1386       * @param string $image_src     The 'src' of the image.
1387       * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1388       * @param int    $attachment_id Image attachment ID or 0.
1389       */
1390      $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1391  
1392      // Only return a 'srcset' value if there is more than one source.
1393      if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) {
1394          return false;
1395      }
1396  
1397      $srcset = '';
1398  
1399      foreach ( $sources as $source ) {
1400          $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
1401      }
1402  
1403      return rtrim( $srcset, ', ' );
1404  }
1405  
1406  /**
1407   * Retrieves the value for an image attachment's 'sizes' attribute.
1408   *
1409   * @since 4.4.0
1410   *
1411   * @see wp_calculate_image_sizes()
1412   *
1413   * @param int          $attachment_id Image attachment ID.
1414   * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of width
1415   *                                    and height values in pixels (in that order). Default 'medium'.
1416   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1417   *                                    Default null.
1418   * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1419   */
1420  function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1421      $image = wp_get_attachment_image_src( $attachment_id, $size );
1422  
1423      if ( ! $image ) {
1424          return false;
1425      }
1426  
1427      if ( ! is_array( $image_meta ) ) {
1428          $image_meta = wp_get_attachment_metadata( $attachment_id );
1429      }
1430  
1431      $image_src  = $image[0];
1432      $size_array = array(
1433          absint( $image[1] ),
1434          absint( $image[2] ),
1435      );
1436  
1437      return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1438  }
1439  
1440  /**
1441   * Creates a 'sizes' attribute value for an image.
1442   *
1443   * @since 4.4.0
1444   *
1445   * @param array|string $size          Image size to retrieve. Accepts any valid image size, or an array
1446   *                                    of width and height values in pixels (in that order). Default 'medium'.
1447   * @param string       $image_src     Optional. The URL to the image file. Default null.
1448   * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1449   *                                    Default null.
1450   * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1451   *                                    is needed when using the image size name as argument for `$size`. Default 0.
1452   * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1453   */
1454  function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1455      $width = 0;
1456  
1457      if ( is_array( $size ) ) {
1458          $width = absint( $size[0] );
1459      } elseif ( is_string( $size ) ) {
1460          if ( ! $image_meta && $attachment_id ) {
1461              $image_meta = wp_get_attachment_metadata( $attachment_id );
1462          }
1463  
1464          if ( is_array( $image_meta ) ) {
1465              $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1466              if ( $size_array ) {
1467                  $width = absint( $size_array[0] );
1468              }
1469          }
1470      }
1471  
1472      if ( ! $width ) {
1473          return false;
1474      }
1475  
1476      // Setup the default 'sizes' attribute.
1477      $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1478  
1479      /**
1480       * Filters the output of 'wp_calculate_image_sizes()'.
1481       *
1482       * @since 4.4.0
1483       *
1484       * @param string       $sizes         A source size value for use in a 'sizes' attribute.
1485       * @param array|string $size          Requested size. Image size or array of width and height values
1486       *                                    in pixels (in that order).
1487       * @param string|null  $image_src     The URL to the image file or null.
1488       * @param array|null   $image_meta    The image meta data as returned by wp_get_attachment_metadata() or null.
1489       * @param int          $attachment_id Image attachment ID of the original image or 0.
1490       */
1491      return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1492  }
1493  
1494  /**
1495   * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1496   *
1497   * @since 4.4.0
1498   *
1499   * @see wp_calculate_image_srcset()
1500   * @see wp_calculate_image_sizes()
1501   *
1502   * @param string $image         An HTML 'img' element to be filtered.
1503   * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1504   * @param int    $attachment_id Image attachment ID.
1505   * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1506   */
1507  function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1508      // Ensure the image meta exists.
1509      if ( empty( $image_meta['sizes'] ) ) {
1510          return $image;
1511      }
1512  
1513      $image_src         = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1514      list( $image_src ) = explode( '?', $image_src );
1515  
1516      // Return early if we couldn't get the image source.
1517      if ( ! $image_src ) {
1518          return $image;
1519      }
1520  
1521      // Bail early if an image has been inserted and later edited.
1522      if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1523          strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1524  
1525          return $image;
1526      }
1527  
1528      $width  = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
1529      $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1530  
1531      if ( ! $width || ! $height ) {
1532          /*
1533           * If attempts to parse the size value failed, attempt to use the image meta data to match
1534           * the image file name from 'src' against the available sizes for an attachment.
1535           */
1536          $image_filename = wp_basename( $image_src );
1537  
1538          if ( wp_basename( $image_meta['file'] ) === $image_filename ) {
1539              $width  = (int) $image_meta['width'];
1540              $height = (int) $image_meta['height'];
1541          } else {
1542              foreach ( $image_meta['sizes'] as $image_size_data ) {
1543                  if ( $image_filename === $image_size_data['file'] ) {
1544                      $width  = (int) $image_size_data['width'];
1545                      $height = (int) $image_size_data['height'];
1546                      break;
1547                  }
1548              }
1549          }
1550      }
1551  
1552      if ( ! $width || ! $height ) {
1553          return $image;
1554      }
1555  
1556      $size_array = array( $width, $height );
1557      $srcset     = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1558  
1559      if ( $srcset ) {
1560          // Check if there is already a 'sizes' attribute.
1561          $sizes = strpos( $image, ' sizes=' );
1562  
1563          if ( ! $sizes ) {
1564              $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1565          }
1566      }
1567  
1568      if ( $srcset && $sizes ) {
1569          // Format the 'srcset' and 'sizes' string and escape attributes.
1570          $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1571  
1572          if ( is_string( $sizes ) ) {
1573              $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1574          }
1575  
1576          // Add 'srcset' and 'sizes' attributes to the image markup.
1577          $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1578      }
1579  
1580      return $image;
1581  }
1582  
1583  /**
1584   * Determine whether to add the `loading` attribute to the specified tag in the specified context.
1585   *
1586   * @since 5.5.0
1587   *
1588   * @param string $tag_name The tag name.
1589   * @param string $context Additional context, like the current filter name or the function name from where this was called.
1590   * @return bool Whether to add the attribute.
1591   */
1592  function wp_lazy_loading_enabled( $tag_name, $context ) {
1593      // By default add to all 'img' tags.
1594      // See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
1595      $default = ( 'img' === $tag_name );
1596  
1597      /**
1598       * Filters whether to add the `loading` attribute to the specified tag in the specified context.
1599       *
1600       * @since 5.5.0
1601       *
1602       * @param bool   $default Default value.
1603       * @param string $tag_name The tag name.
1604       * @param string $context Additional context, like the current filter name or the function name from where this was called.
1605       */
1606      return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
1607  }
1608  
1609  /**
1610   * Filters specific tags in post content and modifies their markup.
1611   *
1612   * This function adds `srcset`, `sizes`, and `loading` attributes to `img` HTML tags.
1613   *
1614   * @since 5.5.0
1615   *
1616   * @see wp_img_tag_add_loading_attr()
1617   * @see wp_img_tag_add_srcset_and_sizes_attr()
1618   *
1619   * @param string $content The HTML content to be filtered.
1620   * @param string $context Optional. Additional context to pass to the filters. Defaults to `current_filter()` when not set.
1621   * @return string Converted content with images modified.
1622   */
1623  function wp_filter_content_tags( $content, $context = null ) {
1624      if ( null === $context ) {
1625          $context = current_filter();
1626      }
1627  
1628      $add_loading_attr = wp_lazy_loading_enabled( 'img', $context );
1629  
1630      if ( false === strpos( $content, '<img' ) ) {
1631          return $content;
1632      }
1633  
1634      if ( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches ) ) {
1635          return $content;
1636      }
1637  
1638      // List of the unique `img` tags found in $content.
1639      $images = array();
1640  
1641      foreach ( $matches[0] as $image ) {
1642          if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) ) {
1643              $attachment_id = absint( $class_id[1] );
1644  
1645              if ( $attachment_id ) {
1646                  // If exactly the same image tag is used more than once, overwrite it.
1647                  // All identical tags will be replaced later with 'str_replace()'.
1648                  $images[ $image ] = $attachment_id;
1649                  continue;
1650              }
1651          }
1652  
1653          $images[ $image ] = 0;
1654      }
1655  
1656      // Reduce the array to unique attachment IDs.
1657      $attachment_ids = array_unique( array_filter( array_values( $images ) ) );
1658  
1659      if ( count( $attachment_ids ) > 1 ) {
1660          /*
1661           * Warm the object cache with post and meta information for all found
1662           * images to avoid making individual database calls.
1663           */
1664          _prime_post_caches( $attachment_ids, false, true );
1665      }
1666  
1667      foreach ( $images as $image => $attachment_id ) {
1668          $filtered_image = $image;
1669  
1670          // Add 'srcset' and 'sizes' attributes if applicable.
1671          if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
1672              $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
1673          }
1674  
1675          // Add 'loading' attribute if applicable.
1676          if ( $add_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
1677              $filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
1678          }
1679  
1680          if ( $filtered_image !== $image ) {
1681              $content = str_replace( $image, $filtered_image, $content );
1682          }
1683      }
1684  
1685      return $content;
1686  }
1687  
1688  /**
1689   * Adds `loading` attribute to an `img` HTML tag.
1690   *
1691   * @since 5.5.0
1692   *
1693   * @param string $image   The HTML `img` tag where the attribute should be added.
1694   * @param string $context Additional context to pass to the filters.
1695   * @return string Converted `img` tag with `loading` attribute added.
1696   */
1697  function wp_img_tag_add_loading_attr( $image, $context ) {
1698      /**
1699       * Filters the `loading` attribute value. Default `lazy`.
1700       *
1701       * Returning `false` or an empty string will not add the attribute.
1702       * Returning `true` will add the default value.
1703       *
1704       * @since 5.5.0
1705       *
1706       * @param string $value   The `loading` attribute value, defaults to `lazy`.
1707       * @param string $image   The HTML `img` tag to be filtered.
1708       * @param string $context Additional context about how the function was called or where the img tag is.
1709       */
1710      $value = apply_filters( 'wp_img_tag_add_loading_attr', 'lazy', $image, $context );
1711  
1712      if ( $value ) {
1713          if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
1714              $value = 'lazy';
1715          }
1716  
1717          $quote = null;
1718  
1719          // Check if the img tag is valid (has `src` attribute) and get the quote character.
1720          // In almost all cases it will have src and a double quote.
1721          if ( false !== strpos( $image, ' src="' ) ) {
1722              $quote = '"';
1723          } elseif ( preg_match( '/\ssrc\s*=(["\'])/', $image, $matches ) ) {
1724              $quote = $matches[1];
1725          }
1726  
1727          if ( $quote ) {
1728              $loading = "loading={$quote}{$value}{$quote}";
1729  
1730              return str_replace( '<img', "<img {$loading}", $image );
1731          }
1732      }
1733  
1734      return $image;
1735  }
1736  
1737  /**
1738   * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
1739   *
1740   * @since 5.5.0
1741   *
1742   * @param string $image         The HTML `img` tag where the attribute should be added.
1743   * @param string $context       Additional context to pass to the filters.
1744   * @param int    $attachment_id Image attachment ID.
1745   * @return string Converted 'img' element with 'loading' attribute added.
1746   */
1747  function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
1748      /**
1749       * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
1750       *
1751       * Returning anything else than `true` will not add the attributes.
1752       *
1753       * @since 5.5.0
1754       *
1755       * @param bool   $value         The filtered value, defaults to `true`.
1756       * @param string $image         The HTML `img` tag where the attribute should be added.
1757       * @param string $context       Additional context about how the function was called or where the img tag is.
1758       * @param int    $attachment_id The image attachment ID.
1759       */
1760      $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
1761  
1762      if ( true === $add ) {
1763          $image_meta = wp_get_attachment_metadata( $attachment_id );
1764          return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
1765      }
1766  
1767      return $image;
1768  }
1769  
1770  /**
1771   * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
1772   *
1773   * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
1774   * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
1775   *
1776   * @ignore
1777   * @since 2.9.0
1778   *
1779   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
1780   * @return string[] Modified array of attributes including the new 'wp-post-image' class.
1781   */
1782  function _wp_post_thumbnail_class_filter( $attr ) {
1783      $attr['class'] .= ' wp-post-image';
1784      return $attr;
1785  }
1786  
1787  /**
1788   * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
1789   * filter hook. Internal use only.
1790   *
1791   * @ignore
1792   * @since 2.9.0
1793   *
1794   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
1795   */
1796  function _wp_post_thumbnail_class_filter_add( $attr ) {
1797      add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1798  }
1799  
1800  /**
1801   * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
1802   * filter hook. Internal use only.
1803   *
1804   * @ignore
1805   * @since 2.9.0
1806   *
1807   * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
1808   */
1809  function _wp_post_thumbnail_class_filter_remove( $attr ) {
1810      remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1811  }
1812  
1813  add_shortcode( 'wp_caption', 'img_caption_shortcode' );
1814  add_shortcode( 'caption', 'img_caption_shortcode' );
1815  
1816  /**
1817   * Builds the Caption shortcode output.
1818   *
1819   * Allows a plugin to replace the content that would otherwise be returned. The
1820   * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
1821   * parameter and the content parameter values.
1822   *
1823   * The supported attributes for the shortcode are 'id', 'caption_id', 'align',
1824   * 'width', 'caption', and 'class'.
1825   *
1826   * @since 2.6.0
1827   * @since 3.9.0 The `class` attribute was added.
1828   * @since 5.1.0 The `caption_id` attribute was added.
1829   *
1830   * @param array  $attr {
1831   *     Attributes of the caption shortcode.
1832   *
1833   *     @type string $id         ID of the image and caption container element, i.e. `<figure>` or `<div>`.
1834   *     @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`.
1835   *     @type string $align      Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
1836   *                              'aligncenter', alignright', 'alignnone'.
1837   *     @type int    $width      The width of the caption, in pixels.
1838   *     @type string $caption    The caption text.
1839   *     @type string $class      Additional class name(s) added to the caption container.
1840   * }
1841   * @param string $content Shortcode content.
1842   * @return string HTML content to display the caption.
1843   */
1844  function img_caption_shortcode( $attr, $content = null ) {
1845      // New-style shortcode with the caption inside the shortcode with the link and image tags.
1846      if ( ! isset( $attr['caption'] ) ) {
1847          if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
1848              $content         = $matches[1];
1849              $attr['caption'] = trim( $matches[2] );
1850          }
1851      } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
1852          $attr['caption'] = wp_kses( $attr['caption'], 'post' );
1853      }
1854  
1855      /**
1856       * Filters the default caption shortcode output.
1857       *
1858       * If the filtered output isn't empty, it will be used instead of generating
1859       * the default caption template.
1860       *
1861       * @since 2.6.0
1862       *
1863       * @see img_caption_shortcode()
1864       *
1865       * @param string $output  The caption output. Default empty.
1866       * @param array  $attr    Attributes of the caption shortcode.
1867       * @param string $content The image element, possibly wrapped in a hyperlink.
1868       */
1869      $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
1870  
1871      if ( ! empty( $output ) ) {
1872          return $output;
1873      }
1874  
1875      $atts = shortcode_atts(
1876          array(
1877              'id'         => '',
1878              'caption_id' => '',
1879              'align'      => 'alignnone',
1880              'width'      => '',
1881              'caption'    => '',
1882              'class'      => '',
1883          ),
1884          $attr,
1885          'caption'
1886      );
1887  
1888      $atts['width'] = (int) $atts['width'];
1889  
1890      if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
1891          return $content;
1892      }
1893  
1894      $id          = '';
1895      $caption_id  = '';
1896      $describedby = '';
1897  
1898      if ( $atts['id'] ) {
1899          $atts['id'] = sanitize_html_class( $atts['id'] );
1900          $id         = 'id="' . esc_attr( $atts['id'] ) . '" ';
1901      }
1902  
1903      if ( $atts['caption_id'] ) {
1904          $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
1905      } elseif ( $atts['id'] ) {
1906          $atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
1907      }
1908  
1909      if ( $atts['caption_id'] ) {
1910          $caption_id  = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
1911          $describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
1912      }
1913  
1914      $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
1915  
1916      $html5 = current_theme_supports( 'html5', 'caption' );
1917      // HTML5 captions never added the extra 10px to the image width.
1918      $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
1919  
1920      /**
1921       * Filters the width of an image's caption.
1922       *
1923       * By default, the caption is 10 pixels greater than the width of the image,
1924       * to prevent post content from running up against a floated image.
1925       *
1926       * @since 3.7.0
1927       *
1928       * @see img_caption_shortcode()
1929       *
1930       * @param int    $width    Width of the caption in pixels. To remove this inline style,
1931       *                         return zero.
1932       * @param array  $atts     Attributes of the caption shortcode.
1933       * @param string $content  The image element, possibly wrapped in a hyperlink.
1934       */
1935      $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
1936  
1937      $style = '';
1938  
1939      if ( $caption_width ) {
1940          $style = 'style="width: ' . (int) $caption_width . 'px" ';
1941      }
1942  
1943      if ( $html5 ) {
1944          $html = sprintf(
1945              '<figure %s%s%sclass="%s">%s%s</figure>',
1946              $id,
1947              $describedby,
1948              $style,
1949              esc_attr( $class ),
1950              do_shortcode( $content ),
1951              sprintf(
1952                  '<figcaption %sclass="wp-caption-text">%s</figcaption>',
1953                  $caption_id,
1954                  $atts['caption']
1955              )
1956          );
1957      } else {
1958          $html = sprintf(
1959              '<div %s%sclass="%s">%s%s</div>',
1960              $id,
1961              $style,
1962              esc_attr( $class ),
1963              str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
1964              sprintf(
1965                  '<p %sclass="wp-caption-text">%s</p>',
1966                  $caption_id,
1967                  $atts['caption']
1968              )
1969          );
1970      }
1971  
1972      return $html;
1973  }
1974  
1975  add_shortcode( 'gallery', 'gallery_shortcode' );
1976  
1977  /**
1978   * Builds the Gallery shortcode output.
1979   *
1980   * This implements the functionality of the Gallery Shortcode for displaying
1981   * WordPress images on a post.
1982   *
1983   * @since 2.5.0
1984   *
1985   * @staticvar int $instance
1986   *
1987   * @param array $attr {
1988   *     Attributes of the gallery shortcode.
1989   *
1990   *     @type string       $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
1991   *     @type string       $orderby    The field to use when ordering the images. Default 'menu_order ID'.
1992   *                                    Accepts any valid SQL ORDERBY statement.
1993   *     @type int          $id         Post ID.
1994   *     @type string       $itemtag    HTML tag to use for each image in the gallery.
1995   *                                    Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
1996   *     @type string       $icontag    HTML tag to use for each image's icon.
1997   *                                    Default 'dt', or 'div' when the theme registers HTML5 gallery support.
1998   *     @type string       $captiontag HTML tag to use for each image's caption.
1999   *                                    Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
2000   *     @type int          $columns    Number of columns of images to display. Default 3.
2001   *     @type string|array $size       Size of the images to display. Accepts any valid image size, or an array of width
2002   *                                    and height values in pixels (in that order). Default 'thumbnail'.
2003   *     @type string       $ids        A comma-separated list of IDs of attachments to display. Default empty.
2004   *     @type string       $include    A comma-separated list of IDs of attachments to include. Default empty.
2005   *     @type string       $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
2006   *     @type string       $link       What to link each image to. Default empty (links to the attachment page).
2007   *                                    Accepts 'file', 'none'.
2008   * }
2009   * @return string HTML content to display gallery.
2010   */
2011  function gallery_shortcode( $attr ) {
2012      $post = get_post();
2013  
2014      static $instance = 0;
2015      $instance++;
2016  
2017      if ( ! empty( $attr['ids'] ) ) {
2018          // 'ids' is explicitly ordered, unless you specify otherwise.
2019          if ( empty( $attr['orderby'] ) ) {
2020              $attr['orderby'] = 'post__in';
2021          }
2022          $attr['include'] = $attr['ids'];
2023      }
2024  
2025      /**
2026       * Filters the default gallery shortcode output.
2027       *
2028       * If the filtered output isn't empty, it will be used instead of generating
2029       * the default gallery template.
2030       *
2031       * @since 2.5.0
2032       * @since 4.2.0 The `$instance` parameter was added.
2033       *
2034       * @see gallery_shortcode()
2035       *
2036       * @param string $output   The gallery output. Default empty.
2037       * @param array  $attr     Attributes of the gallery shortcode.
2038       * @param int    $instance Unique numeric ID of this gallery shortcode instance.
2039       */
2040      $output = apply_filters( 'post_gallery', '', $attr, $instance );
2041  
2042      if ( ! empty( $output ) ) {
2043          return $output;
2044      }
2045  
2046      $html5 = current_theme_supports( 'html5', 'gallery' );
2047      $atts  = shortcode_atts(
2048          array(
2049              'order'      => 'ASC',
2050              'orderby'    => 'menu_order ID',
2051              'id'         => $post ? $post->ID : 0,
2052              'itemtag'    => $html5 ? 'figure' : 'dl',
2053              'icontag'    => $html5 ? 'div' : 'dt',
2054              'captiontag' => $html5 ? 'figcaption' : 'dd',
2055              'columns'    => 3,
2056              'size'       => 'thumbnail',
2057              'include'    => '',
2058              'exclude'    => '',
2059              'link'       => '',
2060          ),
2061          $attr,
2062          'gallery'
2063      );
2064  
2065      $id = intval( $atts['id'] );
2066  
2067      if ( ! empty( $atts['include'] ) ) {
2068          $_attachments = get_posts(
2069              array(
2070                  'include'        => $atts['include'],
2071                  'post_status'    => 'inherit',
2072                  'post_type'      => 'attachment',
2073                  'post_mime_type' => 'image',
2074                  'order'          => $atts['order'],
2075                  'orderby'        => $atts['orderby'],
2076              )
2077          );
2078  
2079          $attachments = array();
2080          foreach ( $_attachments as $key => $val ) {
2081              $attachments[ $val->ID ] = $_attachments[ $key ];
2082          }
2083      } elseif ( ! empty( $atts['exclude'] ) ) {
2084          $attachments = get_children(
2085              array(
2086                  'post_parent'    => $id,
2087                  'exclude'        => $atts['exclude'],
2088                  'post_status'    => 'inherit',
2089                  'post_type'      => 'attachment',
2090                  'post_mime_type' => 'image',
2091                  'order'          => $atts['order'],
2092                  'orderby'        => $atts['orderby'],
2093              )
2094          );
2095      } else {
2096          $attachments = get_children(
2097              array(
2098                  'post_parent'    => $id,
2099                  'post_status'    => 'inherit',
2100                  'post_type'      => 'attachment',
2101                  'post_mime_type' => 'image',
2102                  'order'          => $atts['order'],
2103                  'orderby'        => $atts['orderby'],
2104              )
2105          );
2106      }
2107  
2108      if ( empty( $attachments ) ) {
2109          return '';
2110      }
2111  
2112      if ( is_feed() ) {
2113          $output = "\n";
2114          foreach ( $attachments as $att_id => $attachment ) {
2115              $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
2116          }
2117          return $output;
2118      }
2119  
2120      $itemtag    = tag_escape( $atts['itemtag'] );
2121      $captiontag = tag_escape( $atts['captiontag'] );
2122      $icontag    = tag_escape( $atts['icontag'] );
2123      $valid_tags = wp_kses_allowed_html( 'post' );
2124      if ( ! isset( $valid_tags[ $itemtag ] ) ) {
2125          $itemtag = 'dl';
2126      }
2127      if ( ! isset( $valid_tags[ $captiontag ] ) ) {
2128          $captiontag = 'dd';
2129      }
2130      if ( ! isset( $valid_tags[ $icontag ] ) ) {
2131          $icontag = 'dt';
2132      }
2133  
2134      $columns   = intval( $atts['columns'] );
2135      $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
2136      $float     = is_rtl() ? 'right' : 'left';
2137  
2138      $selector = "gallery-{$instance}";
2139  
2140      $gallery_style = '';
2141  
2142      /**
2143       * Filters whether to print default gallery styles.
2144       *
2145       * @since 3.1.0
2146       *
2147       * @param bool $print Whether to print default gallery styles.
2148       *                    Defaults to false if the theme supports HTML5 galleries.
2149       *                    Otherwise, defaults to true.
2150       */
2151      if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
2152          $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
2153  
2154          $gallery_style = "
2155          <style{$type_attr}>
2156              #{$selector} {
2157                  margin: auto;
2158              }
2159              #{$selector} .gallery-item {
2160                  float: {$float};
2161                  margin-top: 10px;
2162                  text-align: center;
2163                  width: {$itemwidth}%;
2164              }
2165              #{$selector} img {
2166                  border: 2px solid #cfcfcf;
2167              }
2168              #{$selector} .gallery-caption {
2169                  margin-left: 0;
2170              }
2171              /* see gallery_shortcode() in wp-includes/media.php */
2172          </style>\n\t\t";
2173      }
2174  
2175      $size_class  = sanitize_html_class( $atts['size'] );
2176      $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
2177  
2178      /**
2179       * Filters the default gallery shortcode CSS styles.
2180       *
2181       * @since 2.5.0
2182       *
2183       * @param string $gallery_style Default CSS styles and opening HTML div container
2184       *                              for the gallery shortcode output.
2185       */
2186      $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
2187  
2188      $i = 0;
2189  
2190      foreach ( $attachments as $id => $attachment ) {
2191  
2192          $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
2193  
2194          if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
2195              $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
2196          } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
2197              $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
2198          } else {
2199              $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
2200          }
2201  
2202          $image_meta = wp_get_attachment_metadata( $id );
2203  
2204          $orientation = '';
2205  
2206          if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
2207              $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
2208          }
2209  
2210          $output .= "<{$itemtag} class='gallery-item'>";
2211          $output .= "
2212              <{$icontag} class='gallery-icon {$orientation}'>
2213                  $image_output
2214              </{$icontag}>";
2215  
2216          if ( $captiontag && trim( $attachment->post_excerpt ) ) {
2217              $output .= "
2218                  <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
2219                  " . wptexturize( $attachment->post_excerpt ) . "
2220                  </{$captiontag}>";
2221          }
2222  
2223          $output .= "</{$itemtag}>";
2224  
2225          if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
2226              $output .= '<br style="clear: both" />';
2227          }
2228      }
2229  
2230      if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
2231          $output .= "
2232              <br style='clear: both' />";
2233      }
2234  
2235      $output .= "
2236          </div>\n";
2237  
2238      return $output;
2239  }
2240  
2241  /**
2242   * Outputs the templates used by playlists.
2243   *
2244   * @since 3.9.0
2245   */
2246  function wp_underscore_playlist_templates() {
2247      ?>
2248  <script type="text/html" id="tmpl-wp-playlist-current-item">
2249      <# if ( data.image ) { #>
2250      <img src="{{ data.thumb.src }}" alt="" />
2251      <# } #>
2252      <div class="wp-playlist-caption">
2253          <span class="wp-playlist-item-meta wp-playlist-item-title">
2254          <?php
2255              /* translators: %s: Playlist item title. */
2256              printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
2257          ?>
2258          </span>
2259          <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
2260          <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
2261      </div>
2262  </script>
2263  <script type="text/html" id="tmpl-wp-playlist-item">
2264      <div class="wp-playlist-item">
2265          <a class="wp-playlist-caption" href="{{ data.src }}">
2266              {{ data.index ? ( data.index + '. ' ) : '' }}
2267              <# if ( data.caption ) { #>
2268                  {{ data.caption }}
2269              <# } else { #>
2270                  <span class="wp-playlist-item-title">
2271                  <?php
2272                      /* translators: %s: Playlist item title. */
2273                      printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
2274                  ?>
2275                  </span>
2276                  <# if ( data.artists && data.meta.artist ) { #>
2277                  <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
2278                  <# } #>
2279              <# } #>
2280          </a>
2281          <# if ( data.meta.length_formatted ) { #>
2282          <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
2283          <# } #>
2284      </div>
2285  </script>
2286      <?php
2287  }
2288  
2289  /**
2290   * Outputs and enqueue default scripts and styles for playlists.
2291   *
2292   * @since 3.9.0
2293   *
2294   * @param string $type Type of playlist. Accepts 'audio' or 'video'.
2295   */
2296  function wp_playlist_scripts( $type ) {
2297      wp_enqueue_style( 'wp-mediaelement' );
2298      wp_enqueue_script( 'wp-playlist' );
2299      ?>
2300  <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ); ?>');</script><![endif]-->
2301      <?php
2302      add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
2303      add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
2304  }
2305  
2306  /**
2307   * Builds the Playlist shortcode output.
2308   *
2309   * This implements the functionality of the playlist shortcode for displaying
2310   * a collection of WordPress audio or video files in a post.
2311   *
2312   * @since 3.9.0
2313   *
2314   * @global int $content_width
2315   * @staticvar int $instance
2316   *
2317   * @param array $attr {
2318   *     Array of default playlist attributes.
2319   *
2320   *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
2321   *     @type string  $order        Designates ascending or descending order of items in the playlist.
2322   *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
2323   *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
2324   *                                 passed, this defaults to the order of the $ids array ('post__in').
2325   *                                 Otherwise default is 'menu_order ID'.
2326   *     @type int     $id           If an explicit $ids array is not present, this parameter
2327   *                                 will determine which attachments are used for the playlist.
2328   *                                 Default is the current post ID.
2329   *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
2330   *                                 a playlist will be created from all $type attachments of $id.
2331   *                                 Default empty.
2332   *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
2333   *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
2334   *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
2335   *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
2336   *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
2337   *                                 thumbnail). Default true.
2338   *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
2339   * }
2340   *
2341   * @return string Playlist output. Empty string if the passed type is unsupported.
2342   */
2343  function wp_playlist_shortcode( $attr ) {
2344      global $content_width;
2345      $post = get_post();
2346  
2347      static $instance = 0;
2348      $instance++;
2349  
2350      if ( ! empty( $attr['ids'] ) ) {
2351          // 'ids' is explicitly ordered, unless you specify otherwise.
2352          if ( empty( $attr['orderby'] ) ) {
2353              $attr['orderby'] = 'post__in';
2354          }
2355          $attr['include'] = $attr['ids'];
2356      }
2357  
2358      /**
2359       * Filters the playlist output.
2360       *
2361       * Passing a non-empty value to the filter will short-circuit generation
2362       * of the default playlist output, returning the passed value instead.
2363       *
2364       * @since 3.9.0
2365       * @since 4.2.0 The `$instance` parameter was added.
2366       *
2367       * @param string $output   Playlist output. Default empty.
2368       * @param array  $attr     An array of shortcode attributes.
2369       * @param int    $instance Unique numeric ID of this playlist shortcode instance.
2370       */
2371      $output = apply_filters( 'post_playlist', '', $attr, $instance );
2372  
2373      if ( ! empty( $output ) ) {
2374          return $output;
2375      }
2376  
2377      $atts = shortcode_atts(
2378          array(
2379              'type'         => 'audio',
2380              'order'        => 'ASC',
2381              'orderby'      => 'menu_order ID',
2382              'id'           => $post ? $post->ID : 0,
2383              'include'      => '',
2384              'exclude'      => '',
2385              'style'        => 'light',
2386              'tracklist'    => true,
2387              'tracknumbers' => true,
2388              'images'       => true,
2389              'artists'      => true,
2390          ),
2391          $attr,
2392          'playlist'
2393      );
2394  
2395      $id = intval( $atts['id'] );
2396  
2397      if ( 'audio' !== $atts['type'] ) {
2398          $atts['type'] = 'video';
2399      }
2400  
2401      $args = array(
2402          'post_status'    => 'inherit',
2403          'post_type'      => 'attachment',
2404          'post_mime_type' => $atts['type'],
2405          'order'          => $atts['order'],
2406          'orderby'        => $atts['orderby'],
2407      );
2408  
2409      if ( ! empty( $atts['include'] ) ) {
2410          $args['include'] = $atts['include'];
2411          $_attachments    = get_posts( $args );
2412  
2413          $attachments = array();
2414          foreach ( $_attachments as $key => $val ) {
2415              $attachments[ $val->ID ] = $_attachments[ $key ];
2416          }
2417      } elseif ( ! empty( $atts['exclude'] ) ) {
2418          $args['post_parent'] = $id;
2419          $args['exclude']     = $atts['exclude'];
2420          $attachments         = get_children( $args );
2421      } else {
2422          $args['post_parent'] = $id;
2423          $attachments         = get_children( $args );
2424      }
2425  
2426      if ( empty( $attachments ) ) {
2427          return '';
2428      }
2429  
2430      if ( is_feed() ) {
2431          $output = "\n";
2432          foreach ( $attachments as $att_id => $attachment ) {
2433              $output .= wp_get_attachment_link( $att_id ) . "\n";
2434          }
2435          return $output;
2436      }
2437  
2438      $outer = 22; // Default padding and border of wrapper.
2439  
2440      $default_width  = 640;
2441      $default_height = 360;
2442  
2443      $theme_width  = empty( $content_width ) ? $default_width : ( $content_width - $outer );
2444      $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
2445  
2446      $data = array(
2447          'type'         => $atts['type'],
2448          // Don't pass strings to JSON, will be truthy in JS.
2449          'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
2450          'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
2451          'images'       => wp_validate_boolean( $atts['images'] ),
2452          'artists'      => wp_validate_boolean( $atts['artists'] ),
2453      );
2454  
2455      $tracks = array();
2456      foreach ( $attachments as $attachment ) {
2457          $url   = wp_get_attachment_url( $attachment->ID );
2458          $ftype = wp_check_filetype( $url, wp_get_mime_types() );
2459          $track = array(
2460              'src'         => $url,
2461              'type'        => $ftype['type'],
2462              'title'       => $attachment->post_title,
2463              'caption'     => $attachment->post_excerpt,
2464              'description' => $attachment->post_content,
2465          );
2466  
2467          $track['meta'] = array();
2468          $meta          = wp_get_attachment_metadata( $attachment->ID );
2469          if ( ! empty( $meta ) ) {
2470  
2471              foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
2472                  if ( ! empty( $meta[ $key ] ) ) {
2473                      $track['meta'][ $key ] = $meta[ $key ];
2474                  }
2475              }
2476  
2477              if ( 'video' === $atts['type'] ) {
2478                  if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
2479                      $width        = $meta['width'];
2480                      $height       = $meta['height'];
2481                      $theme_height = round( ( $height * $theme_width ) / $width );
2482                  } else {
2483                      $width  = $default_width;
2484                      $height = $default_height;
2485                  }
2486  
2487                  $track['dimensions'] = array(
2488                      'original' => compact( 'width', 'height' ),
2489                      'resized'  => array(
2490                          'width'  => $theme_width,
2491                          'height' => $theme_height,
2492                      ),
2493                  );
2494              }
2495          }
2496  
2497          if ( $atts['images'] ) {
2498              $thumb_id = get_post_thumbnail_id( $attachment->ID );
2499              if ( ! empty( $thumb_id ) ) {
2500                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2501                  $track['image']               = compact( 'src', 'width', 'height' );
2502                  list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2503                  $track['thumb']               = compact( 'src', 'width', 'height' );
2504              } else {
2505                  $src            = wp_mime_type_icon( $attachment->ID );
2506                  $width          = 48;
2507                  $height         = 64;
2508                  $track['image'] = compact( 'src', 'width', 'height' );
2509                  $track['thumb'] = compact( 'src', 'width', 'height' );
2510              }
2511          }
2512  
2513          $tracks[] = $track;
2514      }
2515      $data['tracks'] = $tracks;
2516  
2517      $safe_type  = esc_attr( $atts['type'] );
2518      $safe_style = esc_attr( $atts['style'] );
2519  
2520      ob_start();
2521  
2522      if ( 1 === $instance ) {
2523          /**
2524           * Prints and enqueues playlist scripts, styles, and JavaScript templates.
2525           *
2526           * @since 3.9.0
2527           *
2528           * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
2529           * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2530           */
2531          do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2532      }
2533      ?>
2534  <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>">
2535      <?php if ( 'audio' === $atts['type'] ) : ?>
2536      <div class="wp-playlist-current-item"></div>
2537      <?php endif ?>
2538      <<?php echo $safe_type; ?> controls="controls" preload="none" width="
2539                  <?php
2540                  echo (int) $theme_width;
2541                  ?>
2542      "
2543      <?php
2544      if ( 'video' === $safe_type ) :
2545          echo ' height="', (int) $theme_height, '"';
2546      endif;
2547      ?>
2548      ></<?php echo $safe_type; ?>>
2549      <div class="wp-playlist-next"></div>
2550      <div class="wp-playlist-prev"></div>
2551      <noscript>
2552      <ol>
2553      <?php
2554      foreach ( $attachments as $att_id => $attachment ) {
2555          printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2556      }
2557      ?>
2558      </ol>
2559      </noscript>
2560      <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ); ?></script>
2561  </div>
2562      <?php
2563      return ob_get_clean();
2564  }
2565  add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2566  
2567  /**
2568   * Provides a No-JS Flash fallback as a last resort for audio / video.
2569   *
2570   * @since 3.6.0
2571   *
2572   * @param string $url The media element URL.
2573   * @return string Fallback HTML.
2574   */
2575  function wp_mediaelement_fallback( $url ) {
2576      /**
2577       * Filters the Mediaelement fallback output for no-JS.
2578       *
2579       * @since 3.6.0
2580       *
2581       * @param string $output Fallback output for no-JS.
2582       * @param string $url    Media file URL.
2583       */
2584      return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2585  }
2586  
2587  /**
2588   * Returns a filtered list of supported audio formats.
2589   *
2590   * @since 3.6.0
2591   *
2592   * @return string[] Supported audio formats.
2593   */
2594  function wp_get_audio_extensions() {
2595      /**
2596       * Filters the list of supported audio formats.
2597       *
2598       * @since 3.6.0
2599       *
2600       * @param string[] $extensions An array of supported audio formats. Defaults are
2601       *                            'mp3', 'ogg', 'flac', 'm4a', 'wav'.
2602       */
2603      return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
2604  }
2605  
2606  /**
2607   * Returns useful keys to use to lookup data from an attachment's stored metadata.
2608   *
2609   * @since 3.9.0
2610   *
2611   * @param WP_Post $attachment The current attachment, provided for context.
2612   * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2613   * @return string[] Key/value pairs of field keys to labels.
2614   */
2615  function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2616      $fields = array(
2617          'artist' => __( 'Artist' ),
2618          'album'  => __( 'Album' ),
2619      );
2620  
2621      if ( 'display' === $context ) {
2622          $fields['genre']            = __( 'Genre' );
2623          $fields['year']             = __( 'Year' );
2624          $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2625      } elseif ( 'js' === $context ) {
2626          $fields['bitrate']      = __( 'Bitrate' );
2627          $fields['bitrate_mode'] = __( 'Bitrate Mode' );
2628      }
2629  
2630      /**
2631       * Filters the editable list of keys to look up data from an attachment's metadata.
2632       *
2633       * @since 3.9.0
2634       *
2635       * @param array   $fields     Key/value pairs of field keys to labels.
2636       * @param WP_Post $attachment Attachment object.
2637       * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
2638       */
2639      return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
2640  }
2641  /**
2642   * Builds the Audio shortcode output.
2643   *
2644   * This implements the functionality of the Audio Shortcode for displaying
2645   * WordPress mp3s in a post.
2646   *
2647   * @since 3.6.0
2648   *
2649   * @staticvar int $instance
2650   *
2651   * @param array  $attr {
2652   *     Attributes of the audio shortcode.
2653   *
2654   *     @type string $src      URL to the source of the audio file. Default empty.
2655   *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
2656   *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
2657   *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default 'none'.
2658   *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
2659   *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
2660   * }
2661   * @param string $content Shortcode content.
2662   * @return string|void HTML content to display audio.
2663   */
2664  function wp_audio_shortcode( $attr, $content = '' ) {
2665      $post_id = get_post() ? get_the_ID() : 0;
2666  
2667      static $instance = 0;
2668      $instance++;
2669  
2670      /**
2671       * Filters the default audio shortcode output.
2672       *
2673       * If the filtered output isn't empty, it will be used instead of generating the default audio template.
2674       *
2675       * @since 3.6.0
2676       *
2677       * @param string $html     Empty variable to be replaced with shortcode markup.
2678       * @param array  $attr     Attributes of the shortcode. @see wp_audio_shortcode()
2679       * @param string $content  Shortcode content.
2680       * @param int    $instance Unique numeric ID of this audio shortcode instance.
2681       */
2682      $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
2683  
2684      if ( '' !== $override ) {
2685          return $override;
2686      }
2687  
2688      $audio = null;
2689  
2690      $default_types = wp_get_audio_extensions();
2691      $defaults_atts = array(
2692          'src'      => '',
2693          'loop'     => '',
2694          'autoplay' => '',
2695          'preload'  => 'none',
2696          'class'    => 'wp-audio-shortcode',
2697          'style'    => 'width: 100%;',
2698      );
2699      foreach ( $default_types as $type ) {
2700          $defaults_atts[ $type ] = '';
2701      }
2702  
2703      $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
2704  
2705      $primary = false;
2706      if ( ! empty( $atts['src'] ) ) {
2707          $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2708  
2709          if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
2710              return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2711          }
2712  
2713          $primary = true;
2714          array_unshift( $default_types, 'src' );
2715      } else {
2716          foreach ( $default_types as $ext ) {
2717              if ( ! empty( $atts[ $ext ] ) ) {
2718                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2719  
2720                  if ( strtolower( $type['ext'] ) === $ext ) {
2721                      $primary = true;
2722                  }
2723              }
2724          }
2725      }
2726  
2727      if ( ! $primary ) {
2728          $audios = get_attached_media( 'audio', $post_id );
2729  
2730          if ( empty( $audios ) ) {
2731              return;
2732          }
2733  
2734          $audio       = reset( $audios );
2735          $atts['src'] = wp_get_attachment_url( $audio->ID );
2736  
2737          if ( empty( $atts['src'] ) ) {
2738              return;
2739          }
2740  
2741          array_unshift( $default_types, 'src' );
2742      }
2743  
2744      /**
2745       * Filters the media library used for the audio shortcode.
2746       *
2747       * @since 3.6.0
2748       *
2749       * @param string $library Media library used for the audio shortcode.
2750       */
2751      $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
2752  
2753      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2754          wp_enqueue_style( 'wp-mediaelement' );
2755          wp_enqueue_script( 'wp-mediaelement' );
2756      }
2757  
2758      /**
2759       * Filters the class attribute for the audio shortcode output container.
2760       *
2761       * @since 3.6.0
2762       * @since 4.9.0 The `$atts` parameter was added.
2763       *
2764       * @param string $class CSS class or list of space-separated classes.
2765       * @param array  $atts  Array of audio shortcode attributes.
2766       */
2767      $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
2768  
2769      $html_atts = array(
2770          'class'    => $atts['class'],
2771          'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
2772          'loop'     => wp_validate_boolean( $atts['loop'] ),
2773          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2774          'preload'  => $atts['preload'],
2775          'style'    => $atts['style'],
2776      );
2777  
2778      // These ones should just be omitted altogether if they are blank.
2779      foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
2780          if ( empty( $html_atts[ $a ] ) ) {
2781              unset( $html_atts[ $a ] );
2782          }
2783      }
2784  
2785      $attr_strings = array();
2786  
2787      foreach ( $html_atts as $k => $v ) {
2788          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2789      }
2790  
2791      $html = '';
2792  
2793      if ( 'mediaelement' === $library && 1 === $instance ) {
2794          $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
2795      }
2796  
2797      $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
2798  
2799      $fileurl = '';
2800      $source  = '<source type="%s" src="%s" />';
2801  
2802      foreach ( $default_types as $fallback ) {
2803          if ( ! empty( $atts[ $fallback ] ) ) {
2804              if ( empty( $fileurl ) ) {
2805                  $fileurl = $atts[ $fallback ];
2806              }
2807  
2808              $type  = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2809              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
2810              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2811          }
2812      }
2813  
2814      if ( 'mediaelement' === $library ) {
2815          $html .= wp_mediaelement_fallback( $fileurl );
2816      }
2817  
2818      $html .= '</audio>';
2819  
2820      /**
2821       * Filters the audio shortcode output.
2822       *
2823       * @since 3.6.0
2824       *
2825       * @param string $html    Audio shortcode HTML output.
2826       * @param array  $atts    Array of audio shortcode attributes.
2827       * @param string $audio   Audio file.
2828       * @param int    $post_id Post ID.
2829       * @param string $library Media library used for the audio shortcode.
2830       */
2831      return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
2832  }
2833  add_shortcode( 'audio', 'wp_audio_shortcode' );
2834  
2835  /**
2836   * Returns a filtered list of supported video formats.
2837   *
2838   * @since 3.6.0
2839   *
2840   * @return string[] List of supported video formats.
2841   */
2842  function wp_get_video_extensions() {
2843      /**
2844       * Filters the list of supported video formats.
2845       *
2846       * @since 3.6.0
2847       *
2848       * @param string[] $extensions An array of supported video formats. Defaults are
2849       *                             'mp4', 'm4v', 'webm', 'ogv', 'flv'.
2850       */
2851      return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
2852  }
2853  
2854  /**
2855   * Builds the Video shortcode output.
2856   *
2857   * This implements the functionality of the Video Shortcode for displaying
2858   * WordPress mp4s in a post.
2859   *
2860   * @since 3.6.0
2861   *
2862   * @global int $content_width
2863   * @staticvar int $instance
2864   *
2865   * @param array  $attr {
2866   *     Attributes of the shortcode.
2867   *
2868   *     @type string $src      URL to the source of the video file. Default empty.
2869   *     @type int    $height   Height of the video embed in pixels. Default 360.
2870   *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
2871   *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
2872   *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
2873   *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
2874   *     @type string $preload  The 'preload' attribute for the `<video>` element.
2875   *                            Default 'metadata'.
2876   *     @type string $class    The 'class' attribute for the `<video>` element.
2877   *                            Default 'wp-video-shortcode'.
2878   * }
2879   * @param string $content Shortcode content.
2880   * @return string|void HTML content to display video.
2881   */
2882  function wp_video_shortcode( $attr, $content = '' ) {
2883      global $content_width;
2884      $post_id = get_post() ? get_the_ID() : 0;
2885  
2886      static $instance = 0;
2887      $instance++;
2888  
2889      /**
2890       * Filters the default video shortcode output.
2891       *
2892       * If the filtered output isn't empty, it will be used instead of generating
2893       * the default video template.
2894       *
2895       * @since 3.6.0
2896       *
2897       * @see wp_video_shortcode()
2898       *
2899       * @param string $html     Empty variable to be replaced with shortcode markup.
2900       * @param array  $attr     Attributes of the shortcode. @see wp_video_shortcode()
2901       * @param string $content  Video shortcode content.
2902       * @param int    $instance Unique numeric ID of this video shortcode instance.
2903       */
2904      $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
2905  
2906      if ( '' !== $override ) {
2907          return $override;
2908      }
2909  
2910      $video = null;
2911  
2912      $default_types = wp_get_video_extensions();
2913      $defaults_atts = array(
2914          'src'      => '',
2915          'poster'   => '',
2916          'loop'     => '',
2917          'autoplay' => '',
2918          'preload'  => 'metadata',
2919          'width'    => 640,
2920          'height'   => 360,
2921          'class'    => 'wp-video-shortcode',
2922      );
2923  
2924      foreach ( $default_types as $type ) {
2925          $defaults_atts[ $type ] = '';
2926      }
2927  
2928      $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
2929  
2930      if ( is_admin() ) {
2931          // Shrink the video so it isn't huge in the admin.
2932          if ( $atts['width'] > $defaults_atts['width'] ) {
2933              $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
2934              $atts['width']  = $defaults_atts['width'];
2935          }
2936      } else {
2937          // If the video is bigger than the theme.
2938          if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
2939              $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
2940              $atts['width']  = $content_width;
2941          }
2942      }
2943  
2944      $is_vimeo      = false;
2945      $is_youtube    = false;
2946      $yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
2947      $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
2948  
2949      $primary = false;
2950      if ( ! empty( $atts['src'] ) ) {
2951          $is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
2952          $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
2953  
2954          if ( ! $is_youtube && ! $is_vimeo ) {
2955              $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2956  
2957              if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
2958                  return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2959              }
2960          }
2961  
2962          if ( $is_vimeo ) {
2963              wp_enqueue_script( 'mediaelement-vimeo' );
2964          }
2965  
2966          $primary = true;
2967          array_unshift( $default_types, 'src' );
2968      } else {
2969          foreach ( $default_types as $ext ) {
2970              if ( ! empty( $atts[ $ext ] ) ) {
2971                  $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2972                  if ( strtolower( $type['ext'] ) === $ext ) {
2973                      $primary = true;
2974                  }
2975              }
2976          }
2977      }
2978  
2979      if ( ! $primary ) {
2980          $videos = get_attached_media( 'video', $post_id );
2981          if ( empty( $videos ) ) {
2982              return;
2983          }
2984  
2985          $video       = reset( $videos );
2986          $atts['src'] = wp_get_attachment_url( $video->ID );
2987          if ( empty( $atts['src'] ) ) {
2988              return;
2989          }
2990  
2991          array_unshift( $default_types, 'src' );
2992      }
2993  
2994      /**
2995       * Filters the media library used for the video shortcode.
2996       *
2997       * @since 3.6.0
2998       *
2999       * @param string $library Media library used for the video shortcode.
3000       */
3001      $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
3002      if ( 'mediaelement' === $library && did_action( 'init' ) ) {
3003          wp_enqueue_style( 'wp-mediaelement' );
3004          wp_enqueue_script( 'wp-mediaelement' );
3005          wp_enqueue_script( 'mediaelement-vimeo' );
3006      }
3007  
3008      // MediaElement.js has issues with some URL formats for Vimeo and YouTube,
3009      // so update the URL to prevent the ME.js player from breaking.
3010      if ( 'mediaelement' === $library ) {
3011          if ( $is_youtube ) {
3012              // Remove `feature` query arg and force SSL - see #40866.
3013              $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
3014              $atts['src'] = set_url_scheme( $atts['src'], 'https' );
3015          } elseif ( $is_vimeo ) {
3016              // Remove all query arguments and force SSL - see #40866.
3017              $parsed_vimeo_url = wp_parse_url( $atts['src'] );
3018              $vimeo_src        = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
3019  
3020              // Add loop param for mejs bug - see #40977, not needed after #39686.
3021              $loop        = $atts['loop'] ? '1' : '0';
3022              $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
3023          }
3024      }
3025  
3026      /**
3027       * Filters the class attribute for the video shortcode output container.
3028       *
3029       * @since 3.6.0
3030       * @since 4.9.0 The `$atts` parameter was added.
3031       *
3032       * @param string $class CSS class or list of space-separated classes.
3033       * @param array  $atts  Array of video shortcode attributes.
3034       */
3035      $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
3036  
3037      $html_atts = array(
3038          'class'    => $atts['class'],
3039          'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
3040          'width'    => absint( $atts['width'] ),
3041          'height'   => absint( $atts['height'] ),
3042          'poster'   => esc_url( $atts['poster'] ),
3043          'loop'     => wp_validate_boolean( $atts['loop'] ),
3044          'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
3045          'preload'  => $atts['preload'],
3046      );
3047  
3048      // These ones should just be omitted altogether if they are blank.
3049      foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
3050          if ( empty( $html_atts[ $a ] ) ) {
3051              unset( $html_atts[ $a ] );
3052          }
3053      }
3054  
3055      $attr_strings = array();
3056      foreach ( $html_atts as $k => $v ) {
3057          $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
3058      }
3059  
3060      $html = '';
3061      if ( 'mediaelement' === $library && 1 === $instance ) {
3062          $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
3063      }
3064      $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
3065  
3066      $fileurl = '';
3067      $source  = '<source type="%s" src="%s" />';
3068      foreach ( $default_types as $fallback ) {
3069          if ( ! empty( $atts[ $fallback ] ) ) {
3070              if ( empty( $fileurl ) ) {
3071                  $fileurl = $atts[ $fallback ];
3072              }
3073              if ( 'src' === $fallback && $is_youtube ) {
3074                  $type = array( 'type' => 'video/youtube' );
3075              } elseif ( 'src' === $fallback && $is_vimeo ) {
3076                  $type = array( 'type' => 'video/vimeo' );
3077              } else {
3078                  $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
3079              }
3080              $url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
3081              $html .= sprintf( $source, $type['type'], esc_url( $url ) );
3082          }
3083      }
3084  
3085      if ( ! empty( $content ) ) {
3086          if ( false !== strpos( $content, "\n" ) ) {
3087              $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
3088          }
3089          $html .= trim( $content );
3090      }
3091  
3092      if ( 'mediaelement' === $library ) {
3093          $html .= wp_mediaelement_fallback( $fileurl );
3094      }
3095      $html .= '</video>';
3096  
3097      $width_rule = '';
3098      if ( ! empty( $atts['width'] ) ) {
3099          $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
3100      }
3101      $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
3102  
3103      /**
3104       * Filters the output of the video shortcode.
3105       *
3106       * @since 3.6.0
3107       *
3108       * @param string $output  Video shortcode HTML output.
3109       * @param array  $atts    Array of video shortcode attributes.
3110       * @param string $video   Video file.
3111       * @param int    $post_id Post ID.
3112       * @param string $library Media library used for the video shortcode.
3113       */
3114      return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
3115  }
3116  add_shortcode( 'video', 'wp_video_shortcode' );
3117  
3118  /**
3119   * Displays previous image link that has the same post parent.
3120   *
3121   * @since 2.5.0
3122   *
3123   * @see adjacent_image_link()
3124   *
3125   * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
3126   *                           height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
3127   *                           default to 'post_title' or `$text`. Default 'thumbnail'.
3128   * @param string       $text Optional. Link text. Default false.
3129   */
3130  function previous_image_link( $size = 'thumbnail', $text = false ) {
3131      adjacent_image_link( true, $size, $text );
3132  }
3133  
3134  /**
3135   * Displays next image link that has the same post parent.
3136   *
3137   * @since 2.5.0
3138   *
3139   * @see adjacent_image_link()
3140   *
3141   * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
3142   *                           height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
3143   *                           default to 'post_title' or `$text`. Default 'thumbnail'.
3144   * @param string       $text Optional. Link text. Default false.
3145   */
3146  function next_image_link( $size = 'thumbnail', $text = false ) {
3147      adjacent_image_link( false, $size, $text );
3148  }
3149  
3150  /**
3151   * Displays next or previous image link that has the same post parent.
3152   *
3153   * Retrieves the current attachment object from the $post global.
3154   *
3155   * @since 2.5.0
3156   *
3157   * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
3158   * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
3159   *                           values in pixels (in that order). Default 'thumbnail'.
3160   * @param bool         $text Optional. Link text. Default false.
3161   */
3162  function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
3163      $post        = get_post();
3164      $attachments = array_values(
3165          get_children(
3166              array(
3167                  'post_parent'    => $post->post_parent,
3168                  'post_status'    => 'inherit',
3169                  'post_type'      => 'attachment',
3170                  'post_mime_type' => 'image',
3171                  'order'          => 'ASC',
3172                  'orderby'        => 'menu_order ID',
3173              )
3174          )
3175      );
3176  
3177      foreach ( $attachments as $k => $attachment ) {
3178          if ( intval( $attachment->ID ) === intval( $post->ID ) ) {
3179              break;
3180          }
3181      }
3182  
3183      $output        = '';
3184      $attachment_id = 0;
3185  
3186      if ( $attachments ) {
3187          $k = $prev ? $k - 1 : $k + 1;
3188  
3189          if ( isset( $attachments[ $k ] ) ) {
3190              $attachment_id = $attachments[ $k ]->ID;
3191              $output        = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
3192          }
3193      }
3194  
3195      $adjacent = $prev ? 'previous' : 'next';
3196  
3197      /**
3198       * Filters the adjacent image link.
3199       *
3200       * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
3201       * either 'next', or 'previous'.
3202       *
3203       * @since 3.5.0
3204       *
3205       * @param string $output        Adjacent image HTML markup.
3206       * @param int    $attachment_id Attachment ID
3207       * @param string $size          Image size.
3208       * @param string $text          Link text.
3209       */
3210      echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
3211  }
3212  
3213  /**
3214   * Retrieves taxonomies attached to given the attachment.
3215   *
3216   * @since 2.5.0
3217   * @since 4.7.0 Introduced the `$output` parameter.
3218   *
3219   * @param int|array|object $attachment Attachment ID, data array, or data object.
3220   * @param string           $output     Output type. 'names' to return an array of taxonomy names,
3221   *                                     or 'objects' to return an array of taxonomy objects.
3222   *                                     Default is 'names'.
3223   * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
3224   */
3225  function get_attachment_taxonomies( $attachment, $output = 'names' ) {
3226      if ( is_int( $attachment ) ) {
3227          $attachment = get_post( $attachment );
3228      } elseif ( is_array( $attachment ) ) {
3229          $attachment = (object) $attachment;
3230      }
3231  
3232      if ( ! is_object( $attachment ) ) {
3233          return array();
3234      }
3235  
3236      $file     = get_attached_file( $attachment->ID );
3237      $filename = wp_basename( $file );
3238  
3239      $objects = array( 'attachment' );
3240  
3241      if ( false !== strpos( $filename, '.' ) ) {
3242          $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
3243      }
3244  
3245      if ( ! empty( $attachment->post_mime_type ) ) {
3246          $objects[] = 'attachment:' . $attachment->post_mime_type;
3247  
3248          if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
3249              foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
3250                  if ( ! empty( $token ) ) {
3251                      $objects[] = "attachment:$token";
3252                  }
3253              }
3254          }
3255      }
3256  
3257      $taxonomies = array();
3258  
3259      foreach ( $objects as $object ) {
3260          $taxes = get_object_taxonomies( $object, $output );
3261  
3262          if ( $taxes ) {
3263              $taxonomies = array_merge( $taxonomies, $taxes );
3264          }
3265      }
3266  
3267      if ( 'names' === $output ) {
3268          $taxonomies = array_unique( $taxonomies );
3269      }
3270  
3271      return $taxonomies;
3272  }
3273  
3274  /**
3275   * Retrieves all of the taxonomies that are registered for attachments.
3276   *
3277   * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
3278   *
3279   * @since 3.5.0
3280   * @see get_taxonomies()
3281   *
3282   * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
3283   *                       Default 'names'.
3284   * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.
3285   */
3286  function get_taxonomies_for_attachments( $output = 'names' ) {
3287      $taxonomies = array();
3288  
3289      foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
3290          foreach ( $taxonomy->object_type as $object_type ) {
3291              if ( 'attachment' === $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
3292                  if ( 'names' === $output ) {
3293                      $taxonomies[] = $taxonomy->name;
3294                  } else {
3295                      $taxonomies[ $taxonomy->name ] = $taxonomy;
3296                  }
3297                  break;
3298              }
3299          }
3300      }
3301  
3302      return $taxonomies;
3303  }
3304  
3305  /**
3306   * Create new GD image resource with transparency support
3307   *
3308   * @todo Deprecate if possible.
3309   *
3310   * @since 2.9.0
3311   *
3312   * @param int $width  Image width in pixels.
3313   * @param int $height Image height in pixels..
3314   * @return resource The GD image resource.
3315   */
3316  function wp_imagecreatetruecolor( $width, $height ) {
3317      $img = imagecreatetruecolor( $width, $height );
3318      if ( is_resource( $img ) && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
3319          imagealphablending( $img, false );
3320          imagesavealpha( $img, true );
3321      }
3322      return $img;
3323  }
3324  
3325  /**
3326   * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
3327   *
3328   * @since 2.9.0
3329   *
3330   * @see wp_constrain_dimensions()
3331   *
3332   * @param int $example_width  The width of an example embed.
3333   * @param int $example_height The height of an example embed.
3334   * @param int $max_width      The maximum allowed width.
3335   * @param int $max_height     The maximum allowed height.
3336   * @return int[] {
3337   *     An array of maximum width and height values.
3338   *
3339   *     @type int $0 The maximum width in pixels.
3340   *     @type int $1 The maximum height in pixels.
3341   * }
3342   */
3343  function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
3344      $example_width  = (int) $example_width;
3345      $example_height = (int) $example_height;
3346      $max_width      = (int) $max_width;
3347      $max_height     = (int) $max_height;
3348  
3349      return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
3350  }
3351  
3352  /**
3353   * Determines the maximum upload size allowed in php.ini.
3354   *
3355   * @since 2.5.0
3356   *
3357   * @return int Allowed upload size.
3358   */
3359  function wp_max_upload_size() {
3360      $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
3361      $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
3362  
3363      /**
3364       * Filters the maximum upload size allowed in php.ini.
3365       *
3366       * @since 2.5.0
3367       *
3368       * @param int $size    Max upload size limit in bytes.
3369       * @param int $u_bytes Maximum upload filesize in bytes.
3370       * @param int $p_bytes Maximum size of POST data in bytes.
3371       */
3372      return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
3373  }
3374  
3375  /**
3376   * Returns a WP_Image_Editor instance and loads file into it.
3377   *
3378   * @since 3.5.0
3379   *
3380   * @param string $path Path to the file to load.
3381   * @param array  $args Optional. Additional arguments for retrieving the image editor.
3382   *                     Default empty array.
3383   * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
3384   *                                  object otherwise.
3385   */
3386  function wp_get_image_editor( $path, $args = array() ) {
3387      $args['path'] = $path;
3388  
3389      if ( ! isset( $args['mime_type'] ) ) {
3390          $file_info = wp_check_filetype( $args['path'] );
3391  
3392          // If $file_info['type'] is false, then we let the editor attempt to
3393          // figure out the file type, rather than forcing a failure based on extension.
3394          if ( isset( $file_info ) && $file_info['type'] ) {
3395              $args['mime_type'] = $file_info['type'];
3396          }
3397      }
3398  
3399      $implementation = _wp_image_editor_choose( $args );
3400  
3401      if ( $implementation ) {
3402          $editor = new $implementation( $path );
3403          $loaded = $editor->load();
3404  
3405          if ( is_wp_error( $loaded ) ) {
3406              return $loaded;
3407          }
3408  
3409          return $editor;
3410      }
3411  
3412      return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
3413  }
3414  
3415  /**
3416   * Tests whether there is an editor that supports a given mime type or methods.
3417   *
3418   * @since 3.5.0
3419   *
3420   * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
3421   *                           Default empty array.
3422   * @return bool True if an eligible editor is found; false otherwise.
3423   */
3424  function wp_image_editor_supports( $args = array() ) {
3425      return (bool) _wp_image_editor_choose( $args );
3426  }
3427  
3428  /**
3429   * Tests which editors are capable of supporting the request.
3430   *
3431   * @ignore
3432   * @since 3.5.0
3433   *
3434   * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
3435   * @return string|false Class name for the first editor that claims to support the request. False if no
3436   *                     editor claims to support the request.
3437   */
3438  function _wp_image_editor_choose( $args = array() ) {
3439      require_once  ABSPATH . WPINC . '/class-wp-image-editor.php';
3440      require_once  ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
3441      require_once  ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
3442      /**
3443       * Filters the list of image editing library classes.
3444       *
3445       * @since 3.5.0
3446       *
3447       * @param string[] $image_editors Array of available image editor class names. Defaults are
3448       *                                'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
3449       */
3450      $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
3451  
3452      foreach ( $implementations as $implementation ) {
3453          if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) {
3454              continue;
3455          }
3456  
3457          if ( isset( $args['mime_type'] ) &&
3458              ! call_user_func(
3459                  array( $implementation, 'supports_mime_type' ),
3460                  $args['mime_type']
3461              ) ) {
3462              continue;
3463          }
3464  
3465          if ( isset( $args['methods'] ) &&
3466              array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
3467  
3468              continue;
3469          }
3470  
3471          return $implementation;
3472      }
3473  
3474      return false;
3475  }
3476  
3477  /**
3478   * Prints default Plupload arguments.
3479   *
3480   * @since 3.4.0
3481   */
3482  function wp_plupload_default_settings() {
3483      $wp_scripts = wp_scripts();
3484  
3485      $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
3486      if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) ) {
3487          return;
3488      }
3489  
3490      $max_upload_size    = wp_max_upload_size();
3491      $allowed_extensions = array_keys( get_allowed_mime_types() );
3492      $extensions         = array();
3493      foreach ( $allowed_extensions as $extension ) {
3494          $extensions = array_merge( $extensions, explode( '|', $extension ) );
3495      }
3496  
3497      /*
3498       * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
3499       * and the `flash_swf_url` and `silverlight_xap_url` are not used.
3500       */
3501      $defaults = array(
3502          'file_data_name' => 'async-upload', // Key passed to $_FILE.
3503          'url'            => admin_url( 'async-upload.php', 'relative' ),
3504          'filters'        => array(
3505              'max_file_size' => $max_upload_size . 'b',
3506              'mime_types'    => array( array( 'extensions' => implode( ',', $extensions ) ) ),
3507          ),
3508      );
3509  
3510      /*
3511       * Currently only iOS Safari supports multiple files uploading,
3512       * but iOS 7.x has a bug that prevents uploading of videos when enabled.
3513       * See #29602.
3514       */
3515      if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
3516          strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
3517  
3518          $defaults['multi_selection'] = false;
3519      }
3520  
3521      /**
3522       * Filters the Plupload default settings.
3523       *
3524       * @since 3.4.0
3525       *
3526       * @param array $defaults Default Plupload settings array.
3527       */
3528      $defaults = apply_filters( 'plupload_default_settings', $defaults );
3529  
3530      $params = array(
3531          'action' => 'upload-attachment',
3532      );
3533  
3534      /**
3535       * Filters the Plupload default parameters.
3536       *
3537       * @since 3.4.0
3538       *
3539       * @param array $params Default Plupload parameters array.
3540       */
3541      $params                       = apply_filters( 'plupload_default_params', $params );
3542      $params['_wpnonce']           = wp_create_nonce( 'media-form' );
3543      $defaults['multipart_params'] = $params;
3544  
3545      $settings = array(
3546          'defaults'      => $defaults,
3547          'browser'       => array(
3548              'mobile'    => wp_is_mobile(),
3549              'supported' => _device_can_upload(),
3550          ),
3551          'limitExceeded' => is_multisite() && ! is_upload_space_available(),
3552      );
3553  
3554      $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
3555  
3556      if ( $data ) {
3557          $script = "$data\n$script";
3558      }
3559  
3560      $wp_scripts->add_data( 'wp-plupload', 'data', $script );
3561  }
3562  
3563  /**
3564   * Prepares an attachment post object for JS, where it is expected
3565   * to be JSON-encoded and fit into an Attachment model.
3566   *
3567   * @since 3.5.0
3568   *
3569   * @param int|WP_Post $attachment Attachment ID or object.
3570   * @return array|void Array of attachment details.
3571   */
3572  function wp_prepare_attachment_for_js( $attachment ) {
3573      $attachment = get_post( $attachment );
3574  
3575      if ( ! $attachment ) {
3576          return;
3577      }
3578  
3579      if ( 'attachment' !== $attachment->post_type ) {
3580          return;
3581      }
3582  
3583      $meta = wp_get_attachment_metadata( $attachment->ID );
3584      if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
3585          list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
3586      } else {
3587          list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
3588      }
3589  
3590      $attachment_url = wp_get_attachment_url( $attachment->ID );
3591      $base_url       = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
3592  
3593      $response = array(
3594          'id'            => $attachment->ID,
3595          'title'         => $attachment->post_title,
3596          'filename'      => wp_basename( get_attached_file( $attachment->ID ) ),
3597          'url'           => $attachment_url,
3598          'link'          => get_attachment_link( $attachment->ID ),
3599          'alt'           => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
3600          'author'        => $attachment->post_author,
3601          'description'   => $attachment->post_content,
3602          'caption'       => $attachment->post_excerpt,
3603          'name'          => $attachment->post_name,
3604          'status'        => $attachment->post_status,
3605          'uploadedTo'    => $attachment->post_parent,
3606          'date'          => strtotime( $attachment->post_date_gmt ) * 1000,
3607          'modified'      => strtotime( $attachment->post_modified_gmt ) * 1000,
3608          'menuOrder'     => $attachment->menu_order,
3609          'mime'          => $attachment->post_mime_type,
3610          'type'          => $type,
3611          'subtype'       => $subtype,
3612          'icon'          => wp_mime_type_icon( $attachment->ID ),
3613          'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
3614          'nonces'        => array(
3615              'update' => false,
3616              'delete' => false,
3617              'edit'   => false,
3618          ),
3619          'editLink'      => false,
3620          'meta'          => false,
3621      );
3622  
3623      $author = new WP_User( $attachment->post_author );
3624      if ( $author->exists() ) {
3625          $response['authorName'] = html_entity_decode( $author->display_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
3626      } else {
3627          $response['authorName'] = __( '(no author)' );
3628      }
3629  
3630      if ( $attachment->post_parent ) {
3631          $post_parent = get_post( $attachment->post_parent );
3632      } else {
3633          $post_parent = false;
3634      }
3635  
3636      if ( $post_parent ) {
3637          $parent_type = get_post_type_object( $post_parent->post_type );
3638  
3639          if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
3640              $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
3641          }
3642  
3643          if ( $parent_type && current_user_can( 'read_post', $attachment->post_parent ) ) {
3644              $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
3645          }
3646      }
3647  
3648      $attached_file = get_attached_file( $attachment->ID );
3649  
3650      if ( isset( $meta['filesize'] ) ) {
3651          $bytes = $meta['filesize'];
3652      } elseif ( file_exists( $attached_file ) ) {
3653          $bytes = filesize( $attached_file );
3654      } else {
3655          $bytes = '';
3656      }
3657  
3658      if ( $bytes ) {
3659          $response['filesizeInBytes']       = $bytes;
3660          $response['filesizeHumanReadable'] = size_format( $bytes );
3661      }
3662  
3663      $context             = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
3664      $response['context'] = ( $context ) ? $context : '';
3665  
3666      if ( current_user_can( 'edit_post', $attachment->ID ) ) {
3667          $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
3668          $response['nonces']['edit']   = wp_create_nonce( 'image_editor-' . $attachment->ID );
3669          $response['editLink']         = get_edit_post_link( $attachment->ID, 'raw' );
3670      }
3671  
3672      if ( current_user_can( 'delete_post', $attachment->ID ) ) {
3673          $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
3674      }
3675  
3676      if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
3677          $sizes = array();
3678  
3679          /** This filter is documented in wp-admin/includes/media.php */
3680          $possible_sizes = apply_filters(
3681              'image_size_names_choose',
3682              array(
3683                  'thumbnail' => __( 'Thumbnail' ),
3684                  'medium'    => __( 'Medium' ),
3685                  'large'     => __( 'Large' ),
3686                  'full'      => __( 'Full Size' ),
3687              )
3688          );
3689          unset( $possible_sizes['full'] );
3690  
3691          /*
3692           * Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
3693           * First: run the image_downsize filter. If it returns something, we can use its data.
3694           * If the filter does not return something, then image_downsize() is just an expensive way
3695           * to check the image metadata, which we do second.
3696           */
3697          foreach ( $possible_sizes as $size => $label ) {
3698  
3699              /** This filter is documented in wp-includes/media.php */
3700              $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
3701  
3702              if ( $downsize ) {
3703                  if ( empty( $downsize[3] ) ) {
3704                      continue;
3705                  }
3706  
3707                  $sizes[ $size ] = array(
3708                      'height'      => $downsize[2],
3709                      'width'       => $downsize[1],
3710                      'url'         => $downsize[0],
3711                      'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
3712                  );
3713              } elseif ( isset( $meta['sizes'][ $size ] ) ) {
3714                  // Nothing from the filter, so consult image metadata if we have it.
3715                  $size_meta = $meta['sizes'][ $size ];
3716  
3717                  // We have the actual image size, but might need to further constrain it if content_width is narrower.
3718                  // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
3719                  list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
3720  
3721                  $sizes[ $size ] = array(
3722                      'height'      => $height,
3723                      'width'       => $width,
3724                      'url'         => $base_url . $size_meta['file'],
3725                      'orientation' => $height > $width ? 'portrait' : 'landscape',
3726                  );
3727              }
3728          }
3729  
3730          if ( 'image' === $type ) {
3731              if ( ! empty( $meta['original_image'] ) ) {
3732                  $response['originalImageURL']  = wp_get_original_image_url( $attachment->ID );
3733                  $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
3734              }
3735  
3736              $sizes['full'] = array( 'url' => $attachment_url );
3737  
3738              if ( isset( $meta['height'], $meta['width'] ) ) {
3739                  $sizes['full']['height']      = $meta['height'];
3740                  $sizes['full']['width']       = $meta['width'];
3741                  $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
3742              }
3743  
3744              $response = array_merge( $response, $sizes['full'] );
3745          } elseif ( $meta['sizes']['full']['file'] ) {
3746              $sizes['full'] = array(
3747                  'url'         => $base_url . $meta['sizes']['full']['file'],
3748                  'height'      => $meta['sizes']['full']['height'],
3749                  'width'       => $meta['sizes']['full']['width'],
3750                  'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape',
3751              );
3752          }
3753  
3754          $response = array_merge( $response, array( 'sizes' => $sizes ) );
3755      }
3756  
3757      if ( $meta && 'video' === $type ) {
3758          if ( isset( $meta['width'] ) ) {
3759              $response['width'] = (int) $meta['width'];
3760          }
3761          if ( isset( $meta['height'] ) ) {
3762              $response['height'] = (int) $meta['height'];
3763          }
3764      }
3765  
3766      if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
3767          if ( isset( $meta['length_formatted'] ) ) {
3768              $response['fileLength']              = $meta['length_formatted'];
3769              $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] );
3770          }
3771  
3772          $response['meta'] = array();
3773          foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
3774              $response['meta'][ $key ] = false;
3775  
3776              if ( ! empty( $meta[ $key ] ) ) {
3777                  $response['meta'][ $key ] = $meta[ $key ];
3778              }
3779          }
3780  
3781          $id = get_post_thumbnail_id( $attachment->ID );
3782          if ( ! empty( $id ) ) {
3783              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
3784              $response['image']            = compact( 'src', 'width', 'height' );
3785              list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
3786              $response['thumb']            = compact( 'src', 'width', 'height' );
3787          } else {
3788              $src               = wp_mime_type_icon( $attachment->ID );
3789              $width             = 48;
3790              $height            = 64;
3791              $response['image'] = compact( 'src', 'width', 'height' );
3792              $response['thumb'] = compact( 'src', 'width', 'height' );
3793          }
3794      }
3795  
3796      if ( function_exists( 'get_compat_media_markup' ) ) {
3797          $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
3798      }
3799  
3800      /**
3801       * Filters the attachment data prepared for JavaScript.
3802       *
3803       * @since 3.5.0
3804       *
3805       * @param array       $response   Array of prepared attachment data.
3806       * @param WP_Post     $attachment Attachment object.
3807       * @param array|false $meta       Array of attachment meta data, or false if there is none.
3808       */
3809      return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
3810  }
3811  
3812  /**
3813   * Enqueues all scripts, styles, settings, and templates necessary to use
3814   * all media JS APIs.
3815   *
3816   * @since 3.5.0
3817   *
3818   * @global int       $content_width
3819   * @global wpdb      $wpdb          WordPress database abstraction object.
3820   * @global WP_Locale $wp_locale     WordPress date and time locale object.
3821   *
3822   * @param array $args {
3823   *     Arguments for enqueuing media scripts.
3824   *
3825   *     @type int|WP_Post A post object or ID.
3826   * }
3827   */
3828  function wp_enqueue_media( $args = array() ) {
3829      // Enqueue me just once per page, please.
3830      if ( did_action( 'wp_enqueue_media' ) ) {
3831          return;
3832      }
3833  
3834      global $content_width, $wpdb, $wp_locale;
3835  
3836      $defaults = array(
3837          'post' => null,
3838      );
3839      $args     = wp_parse_args( $args, $defaults );
3840  
3841      // We're going to pass the old thickbox media tabs to `media_upload_tabs`
3842      // to ensure plugins will work. We will then unset those tabs.
3843      $tabs = array(
3844          // handler action suffix => tab label
3845          'type'     => '',
3846          'type_url' => '',
3847          'gallery'  => '',
3848          'library'  => '',
3849      );
3850  
3851      /** This filter is documented in wp-admin/includes/media.php */
3852      $tabs = apply_filters( 'media_upload_tabs', $tabs );
3853      unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
3854  
3855      $props = array(
3856          'link'  => get_option( 'image_default_link_type' ), // DB default is 'file'.
3857          'align' => get_option( 'image_default_align' ),     // Empty default.
3858          'size'  => get_option( 'image_default_size' ),      // Empty default.
3859      );
3860  
3861      $exts      = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
3862      $mimes     = get_allowed_mime_types();
3863      $ext_mimes = array();
3864      foreach ( $exts as $ext ) {
3865          foreach ( $mimes as $ext_preg => $mime_match ) {
3866              if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
3867                  $ext_mimes[ $ext ] = $mime_match;
3868                  break;
3869              }
3870          }
3871      }
3872  
3873      /**
3874       * Allows showing or hiding the "Create Audio Playlist" button in the media library.
3875       *
3876       * By default, the "Create Audio Playlist" button will always be shown in
3877       * the media library.  If this filter returns `null`, a query will be run
3878       * to determine whether the media library contains any audio items.  This
3879       * was the default behavior prior to version 4.8.0, but this query is
3880       * expensive for large media libraries.
3881       *
3882       * @since 4.7.4
3883       * @since 4.8.0 The filter's default value is `true` rather than `null`.
3884       *
3885       * @link https://core.trac.wordpress.org/ticket/31071
3886       *
3887       * @param bool|null $show Whether to show the button, or `null` to decide based
3888       *                        on whether any audio files exist in the media library.
3889       */
3890      $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
3891      if ( null === $show_audio_playlist ) {
3892          $show_audio_playlist = $wpdb->get_var(
3893              "
3894              SELECT ID
3895              FROM $wpdb->posts
3896              WHERE post_type = 'attachment'
3897              AND post_mime_type LIKE 'audio%'
3898              LIMIT 1
3899          "
3900          );
3901      }
3902  
3903      /**
3904       * Allows showing or hiding the "Create Video Playlist" button in the media library.
3905       *
3906       * By default, the "Create Video Playlist" button will always be shown in
3907       * the media library.  If this filter returns `null`, a query will be run
3908       * to determine whether the media library contains any video items.  This
3909       * was the default behavior prior to version 4.8.0, but this query is
3910       * expensive for large media libraries.
3911       *
3912       * @since 4.7.4
3913       * @since 4.8.0 The filter's default value is `true` rather than `null`.
3914       *
3915       * @link https://core.trac.wordpress.org/ticket/31071
3916       *
3917       * @param bool|null $show Whether to show the button, or `null` to decide based
3918       *                        on whether any video files exist in the media library.
3919       */
3920      $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
3921      if ( null === $show_video_playlist ) {
3922          $show_video_playlist = $wpdb->get_var(
3923              "
3924              SELECT ID
3925              FROM $wpdb->posts
3926              WHERE post_type = 'attachment'
3927              AND post_mime_type LIKE 'video%'
3928              LIMIT 1
3929          "
3930          );
3931      }
3932  
3933      /**
3934       * Allows overriding the list of months displayed in the media library.
3935       *
3936       * By default (if this filter does not return an array), a query will be
3937       * run to determine the months that have media items.  This query can be
3938       * expensive for large media libraries, so it may be desirable for sites to
3939       * override this behavior.
3940       *
3941       * @since 4.7.4
3942       *
3943       * @link https://core.trac.wordpress.org/ticket/31071
3944       *
3945       * @param array|null $months An array of objects with `month` and `year`
3946       *                           properties, or `null` (or any other non-array value)
3947       *                           for default behavior.
3948       */
3949      $months = apply_filters( 'media_library_months_with_files', null );
3950      if ( ! is_array( $months ) ) {
3951          $months = $wpdb->get_results(
3952              $wpdb->prepare(
3953                  "
3954              SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
3955              FROM $wpdb->posts
3956              WHERE post_type = %s
3957              ORDER BY post_date DESC
3958          ",
3959                  'attachment'
3960              )
3961          );
3962      }
3963      foreach ( $months as $month_year ) {
3964          $month_year->text = sprintf(
3965              /* translators: 1: Month, 2: Year. */
3966              __( '%1$s %2$d' ),
3967              $wp_locale->get_month( $month_year->month ),
3968              $month_year->year
3969          );
3970      }
3971  
3972      $settings = array(
3973          'tabs'             => $tabs,
3974          'tabUrl'           => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ),
3975          'mimeTypes'        => wp_list_pluck( get_post_mime_types(), 0 ),
3976          /** This filter is documented in wp-admin/includes/media.php */
3977          'captions'         => ! apply_filters( 'disable_captions', '' ),
3978          'nonce'            => array(
3979              'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
3980          ),
3981          'post'             => array(
3982              'id' => 0,
3983          ),
3984          'defaultProps'     => $props,
3985          'attachmentCounts' => array(
3986              'audio' => ( $show_audio_playlist ) ? 1 : 0,
3987              'video' => ( $show_video_playlist ) ? 1 : 0,
3988          ),
3989          'oEmbedProxyUrl'   => rest_url( 'oembed/1.0/proxy' ),
3990          'embedExts'        => $exts,
3991          'embedMimes'       => $ext_mimes,
3992          'contentWidth'     => $content_width,
3993          'months'           => $months,
3994          'mediaTrash'       => MEDIA_TRASH ? 1 : 0,
3995      );
3996  
3997      $post = null;
3998      if ( isset( $args['post'] ) ) {
3999          $post             = get_post( $args['post'] );
4000          $settings['post'] = array(
4001              'id'    => $post->ID,
4002              'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
4003          );
4004  
4005          $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
4006          if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
4007              if ( wp_attachment_is( 'audio', $post ) ) {
4008                  $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
4009              } elseif ( wp_attachment_is( 'video', $post ) ) {
4010                  $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
4011              }
4012          }
4013  
4014          if ( $thumbnail_support ) {
4015              $featured_image_id                   = get_post_meta( $post->ID, '_thumbnail_id', true );
4016              $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
4017          }
4018      }
4019  
4020      if ( $post ) {
4021          $post_type_object = get_post_type_object( $post->post_type );
4022      } else {
4023          $post_type_object = get_post_type_object( 'post' );
4024      }
4025  
4026      $strings = array(
4027          // Generic.
4028          'mediaFrameDefaultTitle'      => __( 'Media' ),
4029          'url'                         => __( 'URL' ),
4030          'addMedia'                    => __( 'Add Media' ),
4031          'search'                      => __( 'Search' ),
4032          'select'                      => __( 'Select' ),
4033          'cancel'                      => __( 'Cancel' ),
4034          'update'                      => __( 'Update' ),
4035          'replace'                     => __( 'Replace' ),
4036          'remove'                      => __( 'Remove' ),
4037          'back'                        => __( 'Back' ),
4038          /*
4039           * translators: This is a would-be plural string used in the media manager.
4040           * If there is not a word you can use in your language to avoid issues with the
4041           * lack of plural support here, turn it into "selected: %d" then translate it.
4042           */
4043          'selected'                    => __( '%d selected' ),
4044          'dragInfo'                    => __( 'Drag and drop to reorder media files.' ),
4045  
4046          // Upload.
4047          'uploadFilesTitle'            => __( 'Upload Files' ),
4048          'uploadImagesTitle'           => __( 'Upload Images' ),
4049  
4050          // Library.
4051          'mediaLibraryTitle'           => __( 'Media Library' ),
4052          'insertMediaTitle'            => __( 'Add Media' ),
4053          'createNewGallery'            => __( 'Create a new gallery' ),
4054          'createNewPlaylist'           => __( 'Create a new playlist' ),
4055          'createNewVideoPlaylist'      => __( 'Create a new video playlist' ),
4056          'returnToLibrary'             => __( '&#8592; Return to library' ),
4057          'allMediaItems'               => __( 'All media items' ),
4058          'allDates'                    => __( 'All dates' ),
4059          'noItemsFound'                => __( 'No items found.' ),
4060          'insertIntoPost'              => $post_type_object->labels->insert_into_item,
4061          'unattached'                  => __( 'Unattached' ),
4062          'mine'                        => _x( 'Mine', 'media items' ),
4063          'trash'                       => _x( 'Trash', 'noun' ),
4064          'uploadedToThisPost'          => $post_type_object->labels->uploaded_to_this_item,
4065          'warnDelete'                  => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4066          'warnBulkDelete'              => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
4067          'warnBulkTrash'               => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
4068          'bulkSelect'                  => __( 'Bulk Select' ),
4069          'trashSelected'               => __( 'Move to Trash' ),
4070          'restoreSelected'             => __( 'Restore from Trash' ),
4071          'deletePermanently'           => __( 'Delete Permanently' ),
4072          'apply'                       => __( 'Apply' ),
4073          'filterByDate'                => __( 'Filter by date' ),
4074          'filterByType'                => __( 'Filter by type' ),
4075          'searchLabel'                 => __( 'Search' ),
4076          'searchMediaLabel'            => __( 'Search Media' ),          // Backward compatibility pre-5.3.
4077          'searchMediaPlaceholder'      => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
4078          'mediaFound'                  => __( 'Number of media items found: %d' ),
4079          'mediaFoundHasMoreResults'    => __( 'Number of media items displayed: %d. Scroll the page for more results.' ),
4080          'noMedia'                     => __( 'No media items found.' ),
4081          'noMediaTryNewSearch'         => __( 'No media items found. Try a different search.' ),
4082  
4083          // Library Details.
4084          'attachmentDetails'           => __( 'Attachment Details' ),
4085  
4086          // From URL.
4087          'insertFromUrlTitle'          => __( 'Insert from URL' ),
4088  
4089          // Featured Images.
4090          'setFeaturedImageTitle'       => $post_type_object->labels->featured_image,
4091          'setFeaturedImage'            => $post_type_object->labels->set_featured_image,
4092  
4093          // Gallery.
4094          'createGalleryTitle'          => __( 'Create Gallery' ),
4095          'editGalleryTitle'            => __( 'Edit Gallery' ),
4096          'cancelGalleryTitle'          => __( '&#8592; Cancel Gallery' ),
4097          'insertGallery'               => __( 'Insert gallery' ),
4098          'updateGallery'               => __( 'Update gallery' ),
4099          'addToGallery'                => __( 'Add to gallery' ),
4100          'addToGalleryTitle'           => __( 'Add to Gallery' ),
4101          'reverseOrder'                => __( 'Reverse order' ),
4102  
4103          // Edit Image.
4104          'imageDetailsTitle'           => __( 'Image Details' ),
4105          'imageReplaceTitle'           => __( 'Replace Image' ),
4106          'imageDetailsCancel'          => __( 'Cancel Edit' ),
4107          'editImage'                   => __( 'Edit Image' ),
4108  
4109          // Crop Image.
4110          'chooseImage'                 => __( 'Choose Image' ),
4111          'selectAndCrop'               => __( 'Select and Crop' ),
4112          'skipCropping'                => __( 'Skip Cropping' ),
4113          'cropImage'                   => __( 'Crop Image' ),
4114          'cropYourImage'               => __( 'Crop your image' ),
4115          'cropping'                    => __( 'Cropping&hellip;' ),
4116          /* translators: 1: Suggested width number, 2: Suggested height number. */
4117          'suggestedDimensions'         => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
4118          'cropError'                   => __( 'There has been an error cropping your image.' ),
4119  
4120          // Edit Audio.
4121          'audioDetailsTitle'           => __( 'Audio Details' ),
4122          'audioReplaceTitle'           => __( 'Replace Audio' ),
4123          'audioAddSourceTitle'         => __( 'Add Audio Source' ),
4124          'audioDetailsCancel'          => __( 'Cancel Edit' ),
4125  
4126          // Edit Video.
4127          'videoDetailsTitle'           => __( 'Video Details' ),
4128          'videoReplaceTitle'           => __( 'Replace Video' ),
4129          'videoAddSourceTitle'         => __( 'Add Video Source' ),
4130          'videoDetailsCancel'          => __( 'Cancel Edit' ),
4131          'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
4132          'videoAddTrackTitle'          => __( 'Add Subtitles' ),
4133  
4134          // Playlist.
4135          'playlistDragInfo'            => __( 'Drag and drop to reorder tracks.' ),
4136          'createPlaylistTitle'         => __( 'Create Audio Playlist' ),
4137          'editPlaylistTitle'           => __( 'Edit Audio Playlist' ),
4138          'cancelPlaylistTitle'         => __( '&#8592; Cancel Audio Playlist' ),
4139          'insertPlaylist'              => __( 'Insert audio playlist' ),
4140          'updatePlaylist'              => __( 'Update audio playlist' ),
4141          'addToPlaylist'               => __( 'Add to audio playlist' ),
4142          'addToPlaylistTitle'          => __( 'Add to Audio Playlist' ),
4143  
4144          // Video Playlist.
4145          'videoPlaylistDragInfo'       => __( 'Drag and drop to reorder videos.' ),
4146          'createVideoPlaylistTitle'    => __( 'Create Video Playlist' ),
4147          'editVideoPlaylistTitle'      => __( 'Edit Video Playlist' ),
4148          'cancelVideoPlaylistTitle'    => __( '&#8592; Cancel Video Playlist' ),
4149          'insertVideoPlaylist'         => __( 'Insert video playlist' ),
4150          'updateVideoPlaylist'         => __( 'Update video playlist' ),
4151          'addToVideoPlaylist'          => __( 'Add to video playlist' ),
4152          'addToVideoPlaylistTitle'     => __( 'Add to Video Playlist' ),
4153  
4154          // Headings.
4155          'filterAttachments'           => __( 'Filter Media' ),
4156          'attachmentsList'             => __( 'Media list' ),
4157      );
4158  
4159      /**
4160       * Filters the media view settings.
4161       *
4162       * @since 3.5.0
4163       *
4164       * @param array   $settings List of media view settings.
4165       * @param WP_Post $post     Post object.
4166       */
4167      $settings = apply_filters( 'media_view_settings', $settings, $post );
4168  
4169      /**
4170       * Filters the media view strings.
4171       *
4172       * @since 3.5.0
4173       *
4174       * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
4175       * @param WP_Post  $post    Post object.
4176       */
4177      $strings = apply_filters( 'media_view_strings', $strings, $post );
4178  
4179      $strings['settings'] = $settings;
4180  
4181      // Ensure we enqueue media-editor first, that way media-views
4182      // is registered internally before we try to localize it. See #24724.
4183      wp_enqueue_script( 'media-editor' );
4184      wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
4185  
4186      wp_enqueue_script( 'media-audiovideo' );
4187      wp_enqueue_style( 'media-views' );
4188      if ( is_admin() ) {
4189          wp_enqueue_script( 'mce-view' );
4190          wp_enqueue_script( 'image-edit' );
4191      }
4192      wp_enqueue_style( 'imgareaselect' );
4193      wp_plupload_default_settings();
4194  
4195      require_once  ABSPATH . WPINC . '/media-template.php';
4196      add_action( 'admin_footer', 'wp_print_media_templates' );
4197      add_action( 'wp_footer', 'wp_print_media_templates' );
4198      add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
4199  
4200      /**
4201       * Fires at the conclusion of wp_enqueue_media().
4202       *
4203       * @since 3.5.0
4204       */
4205      do_action( 'wp_enqueue_media' );
4206  }
4207  
4208  /**
4209   * Retrieves media attached to the passed post.
4210   *
4211   * @since 3.6.0
4212   *
4213   * @param string      $type Mime type.
4214   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4215   * @return WP_Post[] Array of media attached to the given post.
4216   */
4217  function get_attached_media( $type, $post = 0 ) {
4218      $post = get_post( $post );
4219  
4220      if ( ! $post ) {
4221          return array();
4222      }
4223  
4224      $args = array(
4225          'post_parent'    => $post->ID,
4226          'post_type'      => 'attachment',
4227          'post_mime_type' => $type,
4228          'posts_per_page' => -1,
4229          'orderby'        => 'menu_order',
4230          'order'          => 'ASC',
4231      );
4232  
4233      /**
4234       * Filters arguments used to retrieve media attached to the given post.
4235       *
4236       * @since 3.6.0
4237       *
4238       * @param array   $args Post query arguments.
4239       * @param string  $type Mime type of the desired media.
4240       * @param WP_Post $post Post object.
4241       */
4242      $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
4243  
4244      $children = get_children( $args );
4245  
4246      /**
4247       * Filters the list of media attached to the given post.
4248       *
4249       * @since 3.6.0
4250       *
4251       * @param WP_Post[] $children Array of media attached to the given post.
4252       * @param string    $type     Mime type of the media desired.
4253       * @param WP_Post   $post     Post object.
4254       */
4255      return (array) apply_filters( 'get_attached_media', $children, $type, $post );
4256  }
4257  
4258  /**
4259   * Check the content HTML for a audio, video, object, embed, or iframe tags.
4260   *
4261   * @since 3.6.0
4262   *
4263   * @param string   $content A string of HTML which might contain media elements.
4264   * @param string[] $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
4265   * @return string[] Array of found HTML media elements.
4266   */
4267  function get_media_embedded_in_content( $content, $types = null ) {
4268      $html = array();
4269  
4270      /**
4271       * Filters the embedded media types that are allowed to be returned from the content blob.
4272       *
4273       * @since 4.2.0
4274       *
4275       * @param string[] $allowed_media_types An array of allowed media types. Default media types are
4276       *                                      'audio', 'video', 'object', 'embed', and 'iframe'.
4277       */
4278      $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
4279  
4280      if ( ! empty( $types ) ) {
4281          if ( ! is_array( $types ) ) {
4282              $types = array( $types );
4283          }
4284  
4285          $allowed_media_types = array_intersect( $allowed_media_types, $types );
4286      }
4287  
4288      $tags = implode( '|', $allowed_media_types );
4289  
4290      if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
4291          foreach ( $matches[0] as $match ) {
4292              $html[] = $match;
4293          }
4294      }
4295  
4296      return $html;
4297  }
4298  
4299  /**
4300   * Retrieves galleries from the passed post's content.
4301   *
4302   * @since 3.6.0
4303   *
4304   * @param int|WP_Post $post Post ID or object.
4305   * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
4306   * @return array A list of arrays, each containing gallery data and srcs parsed
4307   *               from the expanded shortcode.
4308   */
4309  function get_post_galleries( $post, $html = true ) {
4310      $post = get_post( $post );
4311  
4312      if ( ! $post ) {
4313          return array();
4314      }
4315  
4316      if ( ! has_shortcode( $post->post_content, 'gallery' ) ) {
4317          return array();
4318      }
4319  
4320      $galleries = array();
4321      if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
4322          foreach ( $matches as $shortcode ) {
4323              if ( 'gallery' === $shortcode[2] ) {
4324                  $srcs = array();
4325  
4326                  $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
4327                  if ( ! is_array( $shortcode_attrs ) ) {
4328                      $shortcode_attrs = array();
4329                  }
4330  
4331                  // Specify the post id of the gallery we're viewing if the shortcode doesn't reference another post already.
4332                  if ( ! isset( $shortcode_attrs['id'] ) ) {
4333                      $shortcode[3] .= ' id="' . intval( $post->ID ) . '"';
4334                  }
4335  
4336                  $gallery = do_shortcode_tag( $shortcode );
4337                  if ( $html ) {
4338                      $galleries[] = $gallery;
4339                  } else {
4340                      preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
4341                      if ( ! empty( $src ) ) {
4342                          foreach ( $src as $s ) {
4343                              $srcs[] = $s[2];
4344                          }
4345                      }
4346  
4347                      $galleries[] = array_merge(
4348                          $shortcode_attrs,
4349                          array(
4350                              'src' => array_values( array_unique( $srcs ) ),
4351                          )
4352                      );
4353                  }
4354              }
4355          }
4356      }
4357  
4358      /**
4359       * Filters the list of all found galleries in the given post.
4360       *
4361       * @since 3.6.0
4362       *
4363       * @param array   $galleries Associative array of all found post galleries.
4364       * @param WP_Post $post      Post object.
4365       */
4366      return apply_filters( 'get_post_galleries', $galleries, $post );
4367  }
4368  
4369  /**
4370   * Check a specified post's content for gallery and, if present, return the first
4371   *
4372   * @since 3.6.0
4373   *
4374   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4375   * @param bool        $html Optional. Whether to return HTML or data. Default is true.
4376   * @return string|array Gallery data and srcs parsed from the expanded shortcode.
4377   */
4378  function get_post_gallery( $post = 0, $html = true ) {
4379      $galleries = get_post_galleries( $post, $html );
4380      $gallery   = reset( $galleries );
4381  
4382      /**
4383       * Filters the first-found post gallery.
4384       *
4385       * @since 3.6.0
4386       *
4387       * @param array       $gallery   The first-found post gallery.
4388       * @param int|WP_Post $post      Post ID or object.
4389       * @param array       $galleries Associative array of all found post galleries.
4390       */
4391      return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
4392  }
4393  
4394  /**
4395   * Retrieve the image srcs from galleries from a post's content, if present
4396   *
4397   * @since 3.6.0
4398   *
4399   * @see get_post_galleries()
4400   *
4401   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
4402   * @return array A list of lists, each containing image srcs parsed.
4403   *               from an expanded shortcode
4404   */
4405  function get_post_galleries_images( $post = 0 ) {
4406      $galleries = get_post_galleries( $post, false );
4407      return wp_list_pluck( $galleries, 'src' );
4408  }
4409  
4410  /**
4411   * Checks a post's content for galleries and return the image srcs for the first found gallery
4412   *
4413   * @since 3.6.0
4414   *
4415   * @see get_post_gallery()
4416   *
4417   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
4418   * @return string[] A list of a gallery's image srcs in order.
4419   */
4420  function get_post_gallery_images( $post = 0 ) {
4421      $gallery = get_post_gallery( $post, false );
4422      return empty( $gallery['src'] ) ? array() : $gallery['src'];
4423  }
4424  
4425  /**
4426   * Maybe attempts to generate attachment metadata, if missing.
4427   *
4428   * @since 3.9.0
4429   *
4430   * @param WP_Post $attachment Attachment object.
4431   */
4432  function wp_maybe_generate_attachment_metadata( $attachment ) {
4433      if ( empty( $attachment ) || empty( $attachment->ID ) ) {
4434          return;
4435      }
4436  
4437      $attachment_id = (int) $attachment->ID;
4438      $file          = get_attached_file( $attachment_id );
4439      $meta          = wp_get_attachment_metadata( $attachment_id );
4440  
4441      if ( empty( $meta ) && file_exists( $file ) ) {
4442          $_meta = get_post_meta( $attachment_id );
4443          $_lock = 'wp_generating_att_' . $attachment_id;
4444  
4445          if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
4446              set_transient( $_lock, $file );
4447              wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
4448              delete_transient( $_lock );
4449          }
4450      }
4451  }
4452  
4453  /**
4454   * Tries to convert an attachment URL into a post ID.
4455   *
4456   * @since 4.0.0
4457   *
4458   * @global wpdb $wpdb WordPress database abstraction object.
4459   *
4460   * @param string $url The URL to resolve.
4461   * @return int The found post ID, or 0 on failure.
4462   */
4463  function attachment_url_to_postid( $url ) {
4464      global $wpdb;
4465  
4466      $dir  = wp_get_upload_dir();
4467      $path = $url;
4468  
4469      $site_url   = parse_url( $dir['url'] );
4470      $image_path = parse_url( $path );
4471  
4472      // Force the protocols to match if needed.
4473      if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
4474          $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
4475      }
4476  
4477      if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
4478          $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
4479      }
4480  
4481      $sql = $wpdb->prepare(
4482          "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
4483          $path
4484      );
4485  
4486      $results = $wpdb->get_results( $sql );
4487      $post_id = null;
4488  
4489      if ( $results ) {
4490          // Use the first available result, but prefer a case-sensitive match, if exists.
4491          $post_id = reset( $results )->post_id;
4492  
4493          if ( count( $results ) > 1 ) {
4494              foreach ( $results as $result ) {
4495                  if ( $path === $result->meta_value ) {
4496                      $post_id = $result->post_id;
4497                      break;
4498                  }
4499              }
4500          }
4501      }
4502  
4503      /**
4504       * Filters an attachment id found by URL.
4505       *
4506       * @since 4.2.0
4507       *
4508       * @param int|null $post_id The post_id (if any) found by the function.
4509       * @param string   $url     The URL being looked up.
4510       */
4511      return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
4512  }
4513  
4514  /**
4515   * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
4516   *
4517   * @since 4.0.0
4518   *
4519   * @return string[] The relevant CSS file URLs.
4520   */
4521  function wpview_media_sandbox_styles() {
4522      $version        = 'ver=' . get_bloginfo( 'version' );
4523      $mediaelement   = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" );
4524      $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
4525  
4526      return array( $mediaelement, $wpmediaelement );
4527  }
4528  
4529  /**
4530   * Registers the personal data exporter for media.
4531   *
4532   * @param array[] $exporters An array of personal data exporters, keyed by their ID.
4533   * @return array[] Updated array of personal data exporters.
4534   */
4535  function wp_register_media_personal_data_exporter( $exporters ) {
4536      $exporters['wordpress-media'] = array(
4537          'exporter_friendly_name' => __( 'WordPress Media' ),
4538          'callback'               => 'wp_media_personal_data_exporter',
4539      );
4540  
4541      return $exporters;
4542  }
4543  
4544  /**
4545   * Finds and exports attachments associated with an email address.
4546   *
4547   * @since 4.9.6
4548   *
4549   * @param  string $email_address The attachment owner email address.
4550   * @param  int    $page          Attachment page.
4551   * @return array  $return        An array of personal data.
4552   */
4553  function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
4554      // Limit us to 50 attachments at a time to avoid timing out.
4555      $number = 50;
4556      $page   = (int) $page;
4557  
4558      $data_to_export = array();
4559  
4560      $user = get_user_by( 'email', $email_address );
4561      if ( false === $user ) {
4562          return array(
4563              'data' => $data_to_export,
4564              'done' => true,
4565          );
4566      }
4567  
4568      $post_query = new WP_Query(
4569          array(
4570              'author'         => $user->ID,
4571              'posts_per_page' => $number,
4572              'paged'          => $page,
4573              'post_type'      => 'attachment',
4574              'post_status'    => 'any',
4575              'orderby'        => 'ID',
4576              'order'          => 'ASC',
4577          )
4578      );
4579  
4580      foreach ( (array) $post_query->posts as $post ) {
4581          $attachment_url = wp_get_attachment_url( $post->ID );
4582  
4583          if ( $attachment_url ) {
4584              $post_data_to_export = array(
4585                  array(
4586                      'name'  => __( 'URL' ),
4587                      'value' => $attachment_url,
4588                  ),
4589              );
4590  
4591              $data_to_export[] = array(
4592                  'group_id'          => 'media',
4593                  'group_label'       => __( 'Media' ),
4594                  'group_description' => __( 'User&#8217;s media data.' ),
4595                  'item_id'           => "post-{$post->ID}",
4596                  'data'              => $post_data_to_export,
4597              );
4598          }
4599      }
4600  
4601      $done = $post_query->max_num_pages <= $page;
4602  
4603      return array(
4604          'data' => $data_to_export,
4605          'done' => $done,
4606      );
4607  }
4608  
4609  /**
4610   * Add additional default image sub-sizes.
4611   *
4612   * These sizes are meant to enhance the way WordPress displays images on the front-end on larger,
4613   * high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes
4614   * when the users upload large images.
4615   *
4616   * The sizes can be changed or removed by themes and plugins but that is not recommended.
4617   * The size "names" reflect the image dimensions, so changing the sizes would be quite misleading.
4618   *
4619   * @since 5.3.0
4620   * @access private
4621   */
4622  function _wp_add_additional_image_sizes() {
4623      // 2x medium_large size.
4624      add_image_size( '1536x1536', 1536, 1536 );
4625      // 2x large size.
4626      add_image_size( '2048x2048', 2048, 2048 );
4627  }


Generated: Sat May 30 01:00:03 2020 Cross-referenced by PHPXref 0.7.1