[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7