[ Index ]

WordPress 5.4.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

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


Generated: Tue May 19 15:51:04 2020 Cross-referenced by PHPXref 0.7.1