[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Wed Nov 13 01:00:03 2019 Cross-referenced by PHPXref 0.7.1