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