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


Generated: Tue Sep 17 01:00:03 2019 Cross-referenced by PHPXref 0.7.1