[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sat Jan 20 01:00:02 2018 Cross-referenced by PHPXref 0.7.1