[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Jan 22 01:00:08 2019 Cross-referenced by PHPXref 0.7.1