[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7