]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/media.php
WordPress 4.5.1
[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  * Get the attachment path relative to the upload directory.
882  *
883  * @since 4.4.1
884  * @access private
885  *
886  * @param string $file Attachment file name.
887  * @return string Attachment path relative to the upload directory.
888  */
889 function _wp_get_attachment_relative_path( $file ) {
890         $dirname = dirname( $file );
891
892         if ( '.' === $dirname ) {
893                 return '';
894         }
895
896         if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
897                 // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
898                 $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
899                 $dirname = ltrim( $dirname, '/' );
900         }
901
902         return $dirname;
903 }
904
905 /**
906  * Get the image size as array from its meta data.
907  *
908  * Used for responsive images.
909  *
910  * @since 4.4.0
911  * @access private
912  *
913  * @param string $size_name  Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
914  * @param array  $image_meta The image meta data.
915  * @return array|bool Array of width and height values in pixels (in that order)
916  *                    or false if the size doesn't exist.
917  */
918 function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
919         if ( $size_name === 'full' ) {
920                 return array(
921                         absint( $image_meta['width'] ),
922                         absint( $image_meta['height'] ),
923                 );
924         } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
925                 return array(
926                         absint( $image_meta['sizes'][$size_name]['width'] ),
927                         absint( $image_meta['sizes'][$size_name]['height'] ),
928                 );
929         }
930
931         return false;
932 }
933
934 /**
935  * Retrieves the value for an image attachment's 'srcset' attribute.
936  *
937  * @since 4.4.0
938  *
939  * @see wp_calculate_image_srcset()
940  *
941  * @param int          $attachment_id Image attachment ID.
942  * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of
943  *                                    width and height values in pixels (in that order). Default 'medium'.
944  * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
945  *                                    Default null.
946  * @return string|bool A 'srcset' value string or false.
947  */
948 function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
949         if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
950                 return false;
951         }
952
953         if ( ! is_array( $image_meta ) ) {
954                 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
955         }
956
957         $image_src = $image[0];
958         $size_array = array(
959                 absint( $image[1] ),
960                 absint( $image[2] )
961         );
962
963         return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
964 }
965
966 /**
967  * A helper function to calculate the image sources to include in a 'srcset' attribute.
968  *
969  * @since 4.4.0
970  *
971  * @param array  $size_array    Array of width and height values in pixels (in that order).
972  * @param string $image_src     The 'src' of the image.
973  * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
974  * @param int    $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
975  * @return string|bool          The 'srcset' attribute value. False on error or when only one source exists.
976  */
977 function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
978         /**
979          * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
980          *
981          * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
982          * @param array  $size_array    Array of width and height values in pixels (in that order).
983          * @param string $image_src     The 'src' of the image.
984          * @param int    $attachment_id The image attachment ID or 0 if not supplied.
985          */
986         $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
987
988         if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
989                 return false;
990         }
991
992         $image_sizes = $image_meta['sizes'];
993
994         // Get the width and height of the image.
995         $image_width = (int) $size_array[0];
996         $image_height = (int) $size_array[1];
997
998         // Bail early if error/no width.
999         if ( $image_width < 1 ) {
1000                 return false;
1001         }
1002
1003         $image_basename = wp_basename( $image_meta['file'] );
1004
1005         /*
1006          * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
1007          * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
1008          * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
1009          */
1010         if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
1011                 $image_sizes['full'] = array(
1012                         'width'  => $image_meta['width'],
1013                         'height' => $image_meta['height'],
1014                         'file'   => $image_basename,
1015                 );
1016         } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
1017                 return false;
1018         }
1019
1020         // Retrieve the uploads sub-directory from the full size image.
1021         $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
1022
1023         if ( $dirname ) {
1024                 $dirname = trailingslashit( $dirname );
1025         }
1026
1027         $upload_dir = wp_get_upload_dir();
1028         $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
1029
1030         /*
1031          * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
1032          * (which is to say, when they share the domain name of the current request).
1033          */
1034         if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
1035                 $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
1036         }
1037
1038         /*
1039          * Images that have been edited in WordPress after being uploaded will
1040          * contain a unique hash. Look for that hash and use it later to filter
1041          * out images that are leftovers from previous versions.
1042          */
1043         $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
1044
1045         /**
1046          * Filter the maximum image width to be included in a 'srcset' attribute.
1047          *
1048          * @since 4.4.0
1049          *
1050          * @param int   $max_width  The maximum image width to be included in the 'srcset'. Default '1600'.
1051          * @param array $size_array Array of width and height values in pixels (in that order).
1052          */
1053         $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
1054
1055         // Array to hold URL candidates.
1056         $sources = array();
1057
1058         /**
1059          * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
1060          * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
1061          * an incorrect image. See #35045.
1062          */
1063         $src_matched = false;
1064
1065         /*
1066          * Loop through available images. Only use images that are resized
1067          * versions of the same edit.
1068          */
1069         foreach ( $image_sizes as $image ) {
1070                 $is_src = false;
1071
1072                 // Check if image meta isn't corrupted.
1073                 if ( ! is_array( $image ) ) {
1074                         continue;
1075                 }
1076
1077                 // If the file name is part of the `src`, we've confirmed a match.
1078                 if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
1079                         $src_matched = $is_src = true;
1080                 }
1081
1082                 // Filter out images that are from previous edits.
1083                 if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
1084                         continue;
1085                 }
1086
1087                 /*
1088                  * Filter out images that are wider than '$max_srcset_image_width' unless
1089                  * that file is in the 'src' attribute.
1090                  */
1091                 if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
1092                         continue;
1093                 }
1094
1095                 /**
1096                  * To check for varying crops, we calculate the expected size of the smaller
1097                  * image if the larger were constrained by the width of the smaller and then
1098                  * see if it matches what we're expecting.
1099                  */
1100                 if ( $image_width > $image['width'] ) {
1101                         $constrained_size = wp_constrain_dimensions( $image_width, $image_height, $image['width'] );
1102                         $expected_size = array( $image['width'], $image['height'] );
1103                 } else {
1104                         $constrained_size = wp_constrain_dimensions( $image['width'], $image['height'], $image_width );
1105                         $expected_size = array( $image_width, $image_height );
1106                 }
1107
1108                 // If the image dimensions are within 1px of the expected size, use it.
1109                 if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) {
1110                         // Add the URL, descriptor, and value to the sources array to be returned.
1111                         $source = array(
1112                                 'url'        => $image_baseurl . $image['file'],
1113                                 'descriptor' => 'w',
1114                                 'value'      => $image['width'],
1115                         );
1116
1117                         // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
1118                         if ( $is_src ) {
1119                                 $sources = array( $image['width'] => $source ) + $sources;
1120                         } else {
1121                                 $sources[ $image['width'] ] = $source;
1122                         }
1123                 }
1124         }
1125
1126         /**
1127          * Filter an image's 'srcset' sources.
1128          *
1129          * @since 4.4.0
1130          *
1131          * @param array  $sources {
1132          *     One or more arrays of source data to include in the 'srcset'.
1133          *
1134          *     @type array $width {
1135          *         @type string $url        The URL of an image source.
1136          *         @type string $descriptor The descriptor type used in the image candidate string,
1137          *                                  either 'w' or 'x'.
1138          *         @type int    $value      The source width if paired with a 'w' descriptor, or a
1139          *                                  pixel density value if paired with an 'x' descriptor.
1140          *     }
1141          * }
1142          * @param array  $size_array    Array of width and height values in pixels (in that order).
1143          * @param string $image_src     The 'src' of the image.
1144          * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1145          * @param int    $attachment_id Image attachment ID or 0.
1146          */
1147         $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
1148
1149         // Only return a 'srcset' value if there is more than one source.
1150         if ( ! $src_matched || count( $sources ) < 2 ) {
1151                 return false;
1152         }
1153
1154         $srcset = '';
1155
1156         foreach ( $sources as $source ) {
1157                 $srcset .= $source['url'] . ' ' . $source['value'] . $source['descriptor'] . ', ';
1158         }
1159
1160         return rtrim( $srcset, ', ' );
1161 }
1162
1163 /**
1164  * Retrieves the value for an image attachment's 'sizes' attribute.
1165  *
1166  * @since 4.4.0
1167  *
1168  * @see wp_calculate_image_sizes()
1169  *
1170  * @param int          $attachment_id Image attachment ID.
1171  * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of width
1172  *                                    and height values in pixels (in that order). Default 'medium'.
1173  * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1174  *                                    Default null.
1175  * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1176  */
1177 function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
1178         if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
1179                 return false;
1180         }
1181
1182         if ( ! is_array( $image_meta ) ) {
1183                 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1184         }
1185
1186         $image_src = $image[0];
1187         $size_array = array(
1188                 absint( $image[1] ),
1189                 absint( $image[2] )
1190         );
1191
1192         return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1193 }
1194
1195 /**
1196  * Creates a 'sizes' attribute value for an image.
1197  *
1198  * @since 4.4.0
1199  *
1200  * @param array|string $size          Image size to retrieve. Accepts any valid image size, or an array
1201  *                                    of width and height values in pixels (in that order). Default 'medium'.
1202  * @param string       $image_src     Optional. The URL to the image file. Default null.
1203  * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
1204  *                                    Default null.
1205  * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
1206  *                                    is needed when using the image size name as argument for `$size`. Default 0.
1207  * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
1208  */
1209 function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
1210         $width = 0;
1211
1212         if ( is_array( $size ) ) {
1213                 $width = absint( $size[0] );
1214         } elseif ( is_string( $size ) ) {
1215                 if ( ! $image_meta && $attachment_id ) {
1216                         $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1217                 }
1218
1219                 if ( is_array( $image_meta ) ) {
1220                         $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
1221                         if ( $size_array ) {
1222                                 $width = absint( $size_array[0] );
1223                         }
1224                 }
1225         }
1226
1227         if ( ! $width ) {
1228                 return false;
1229         }
1230
1231         // Setup the default 'sizes' attribute.
1232         $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
1233
1234         /**
1235          * Filter the output of 'wp_calculate_image_sizes()'.
1236          *
1237          * @since 4.4.0
1238          *
1239          * @param string       $sizes         A source size value for use in a 'sizes' attribute.
1240          * @param array|string $size          Requested size. Image size or array of width and height values
1241          *                                    in pixels (in that order).
1242          * @param string|null  $image_src     The URL to the image file or null.
1243          * @param array|null   $image_meta    The image meta data as returned by wp_get_attachment_metadata() or null.
1244          * @param int          $attachment_id Image attachment ID of the original image or 0.
1245          */
1246         return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
1247 }
1248
1249 /**
1250  * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
1251  *
1252  * @since 4.4.0
1253  *
1254  * @see wp_image_add_srcset_and_sizes()
1255  *
1256  * @param string $content The raw post content to be filtered.
1257  * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
1258  */
1259 function wp_make_content_images_responsive( $content ) {
1260         if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
1261                 return $content;
1262         }
1263
1264         $selected_images = $attachment_ids = array();
1265
1266         foreach( $matches[0] as $image ) {
1267                 if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
1268                         ( $attachment_id = absint( $class_id[1] ) ) ) {
1269
1270                         /*
1271                          * If exactly the same image tag is used more than once, overwrite it.
1272                          * All identical tags will be replaced later with 'str_replace()'.
1273                          */
1274                         $selected_images[ $image ] = $attachment_id;
1275                         // Overwrite the ID when the same image is included more than once.
1276                         $attachment_ids[ $attachment_id ] = true;
1277                 }
1278         }
1279
1280         if ( count( $attachment_ids ) > 1 ) {
1281                 /*
1282                  * Warm object cache for use with 'get_post_meta()'.
1283                  *
1284                  * To avoid making a database call for each image, a single query
1285                  * warms the object cache with the meta information for all images.
1286                  */
1287                 update_meta_cache( 'post', array_keys( $attachment_ids ) );
1288         }
1289
1290         foreach ( $selected_images as $image => $attachment_id ) {
1291                 $image_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
1292                 $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
1293         }
1294
1295         return $content;
1296 }
1297
1298 /**
1299  * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
1300  *
1301  * @since 4.4.0
1302  *
1303  * @see wp_calculate_image_srcset()
1304  * @see wp_calculate_image_sizes()
1305  *
1306  * @param string $image         An HTML 'img' element to be filtered.
1307  * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
1308  * @param int    $attachment_id Image attachment ID.
1309  * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
1310  */
1311 function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
1312         // Ensure the image meta exists.
1313         if ( empty( $image_meta['sizes'] ) ) {
1314                 return $image;
1315         }
1316
1317         $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
1318         list( $image_src ) = explode( '?', $image_src );
1319
1320         // Return early if we couldn't get the image source.
1321         if ( ! $image_src ) {
1322                 return $image;
1323         }
1324
1325         // Bail early if an image has been inserted and later edited.
1326         if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
1327                 strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
1328
1329                 return $image;
1330         }
1331
1332         $width  = preg_match( '/ width="([0-9]+)"/',  $image, $match_width  ) ? (int) $match_width[1]  : 0;
1333         $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
1334
1335         if ( ! $width || ! $height ) {
1336                 /*
1337                  * If attempts to parse the size value failed, attempt to use the image meta data to match
1338                  * the image file name from 'src' against the available sizes for an attachment.
1339                  */
1340                 $image_filename = wp_basename( $image_src );
1341
1342                 if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
1343                         $width = (int) $image_meta['width'];
1344                         $height = (int) $image_meta['height'];
1345                 } else {
1346                         foreach( $image_meta['sizes'] as $image_size_data ) {
1347                                 if ( $image_filename === $image_size_data['file'] ) {
1348                                         $width = (int) $image_size_data['width'];
1349                                         $height = (int) $image_size_data['height'];
1350                                         break;
1351                                 }
1352                         }
1353                 }
1354         }
1355
1356         if ( ! $width || ! $height ) {
1357                 return $image;
1358         }
1359
1360         $size_array = array( $width, $height );
1361         $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
1362
1363         if ( $srcset ) {
1364                 // Check if there is already a 'sizes' attribute.
1365                 $sizes = strpos( $image, ' sizes=' );
1366
1367                 if ( ! $sizes ) {
1368                         $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
1369                 }
1370         }
1371
1372         if ( $srcset && $sizes ) {
1373                 // Format the 'srcset' and 'sizes' string and escape attributes.
1374                 $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
1375
1376                 if ( is_string( $sizes ) ) {
1377                         $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
1378                 }
1379
1380                 // Add 'srcset' and 'sizes' attributes to the image markup.
1381                 $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
1382         }
1383
1384         return $image;
1385 }
1386
1387 /**
1388  * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
1389  *
1390  * Uses the 'begin_fetch_post_thumbnail_html' and 'end_fetch_post_thumbnail_html' action hooks to
1391  * dynamically add/remove itself so as to only filter post thumbnails.
1392  *
1393  * @ignore
1394  * @since 2.9.0
1395  *
1396  * @param array $attr Thumbnail attributes including src, class, alt, title.
1397  * @return array Modified array of attributes including the new 'wp-post-image' class.
1398  */
1399 function _wp_post_thumbnail_class_filter( $attr ) {
1400         $attr['class'] .= ' wp-post-image';
1401         return $attr;
1402 }
1403
1404 /**
1405  * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
1406  * filter hook. Internal use only.
1407  *
1408  * @ignore
1409  * @since 2.9.0
1410  *
1411  * @param array $attr Thumbnail attributes including src, class, alt, title.
1412  */
1413 function _wp_post_thumbnail_class_filter_add( $attr ) {
1414         add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1415 }
1416
1417 /**
1418  * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
1419  * filter hook. Internal use only.
1420  *
1421  * @ignore
1422  * @since 2.9.0
1423  *
1424  * @param array $attr Thumbnail attributes including src, class, alt, title.
1425  */
1426 function _wp_post_thumbnail_class_filter_remove( $attr ) {
1427         remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
1428 }
1429
1430 add_shortcode('wp_caption', 'img_caption_shortcode');
1431 add_shortcode('caption', 'img_caption_shortcode');
1432
1433 /**
1434  * Builds the Caption shortcode output.
1435  *
1436  * Allows a plugin to replace the content that would otherwise be returned. The
1437  * filter is 'img_caption_shortcode' and passes an empty string, the attr
1438  * parameter and the content parameter values.
1439  *
1440  * The supported attributes for the shortcode are 'id', 'align', 'width', and
1441  * 'caption'.
1442  *
1443  * @since 2.6.0
1444  *
1445  * @param array  $attr {
1446  *     Attributes of the caption shortcode.
1447  *
1448  *     @type string $id      ID of the div element for the caption.
1449  *     @type string $align   Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
1450  *                           'aligncenter', alignright', 'alignnone'.
1451  *     @type int    $width   The width of the caption, in pixels.
1452  *     @type string $caption The caption text.
1453  *     @type string $class   Additional class name(s) added to the caption container.
1454  * }
1455  * @param string $content Shortcode content.
1456  * @return string HTML content to display the caption.
1457  */
1458 function img_caption_shortcode( $attr, $content = null ) {
1459         // New-style shortcode with the caption inside the shortcode with the link and image tags.
1460         if ( ! isset( $attr['caption'] ) ) {
1461                 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
1462                         $content = $matches[1];
1463                         $attr['caption'] = trim( $matches[2] );
1464                 }
1465         } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
1466                 $attr['caption'] = wp_kses( $attr['caption'], 'post' );
1467         }
1468
1469         /**
1470          * Filter the default caption shortcode output.
1471          *
1472          * If the filtered output isn't empty, it will be used instead of generating
1473          * the default caption template.
1474          *
1475          * @since 2.6.0
1476          *
1477          * @see img_caption_shortcode()
1478          *
1479          * @param string $output  The caption output. Default empty.
1480          * @param array  $attr    Attributes of the caption shortcode.
1481          * @param string $content The image element, possibly wrapped in a hyperlink.
1482          */
1483         $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
1484         if ( $output != '' )
1485                 return $output;
1486
1487         $atts = shortcode_atts( array(
1488                 'id'      => '',
1489                 'align'   => 'alignnone',
1490                 'width'   => '',
1491                 'caption' => '',
1492                 'class'   => '',
1493         ), $attr, 'caption' );
1494
1495         $atts['width'] = (int) $atts['width'];
1496         if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
1497                 return $content;
1498
1499         if ( ! empty( $atts['id'] ) )
1500                 $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
1501
1502         $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
1503
1504         $html5 = current_theme_supports( 'html5', 'caption' );
1505         // HTML5 captions never added the extra 10px to the image width
1506         $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
1507
1508         /**
1509          * Filter the width of an image's caption.
1510          *
1511          * By default, the caption is 10 pixels greater than the width of the image,
1512          * to prevent post content from running up against a floated image.
1513          *
1514          * @since 3.7.0
1515          *
1516          * @see img_caption_shortcode()
1517          *
1518          * @param int    $width    Width of the caption in pixels. To remove this inline style,
1519          *                         return zero.
1520          * @param array  $atts     Attributes of the caption shortcode.
1521          * @param string $content  The image element, possibly wrapped in a hyperlink.
1522          */
1523         $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
1524
1525         $style = '';
1526         if ( $caption_width )
1527                 $style = 'style="width: ' . (int) $caption_width . 'px" ';
1528
1529         $html = '';
1530         if ( $html5 ) {
1531                 $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1532                 . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
1533         } else {
1534                 $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
1535                 . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
1536         }
1537
1538         return $html;
1539 }
1540
1541 add_shortcode('gallery', 'gallery_shortcode');
1542
1543 /**
1544  * Builds the Gallery shortcode output.
1545  *
1546  * This implements the functionality of the Gallery Shortcode for displaying
1547  * WordPress images on a post.
1548  *
1549  * @since 2.5.0
1550  *
1551  * @staticvar int $instance
1552  *
1553  * @param array $attr {
1554  *     Attributes of the gallery shortcode.
1555  *
1556  *     @type string       $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
1557  *     @type string       $orderby    The field to use when ordering the images. Default 'menu_order ID'.
1558  *                                    Accepts any valid SQL ORDERBY statement.
1559  *     @type int          $id         Post ID.
1560  *     @type string       $itemtag    HTML tag to use for each image in the gallery.
1561  *                                    Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
1562  *     @type string       $icontag    HTML tag to use for each image's icon.
1563  *                                    Default 'dt', or 'div' when the theme registers HTML5 gallery support.
1564  *     @type string       $captiontag HTML tag to use for each image's caption.
1565  *                                    Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
1566  *     @type int          $columns    Number of columns of images to display. Default 3.
1567  *     @type string|array $size       Size of the images to display. Accepts any valid image size, or an array of width
1568  *                                    and height values in pixels (in that order). Default 'thumbnail'.
1569  *     @type string       $ids        A comma-separated list of IDs of attachments to display. Default empty.
1570  *     @type string       $include    A comma-separated list of IDs of attachments to include. Default empty.
1571  *     @type string       $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
1572  *     @type string       $link       What to link each image to. Default empty (links to the attachment page).
1573  *                                    Accepts 'file', 'none'.
1574  * }
1575  * @return string HTML content to display gallery.
1576  */
1577 function gallery_shortcode( $attr ) {
1578         $post = get_post();
1579
1580         static $instance = 0;
1581         $instance++;
1582
1583         if ( ! empty( $attr['ids'] ) ) {
1584                 // 'ids' is explicitly ordered, unless you specify otherwise.
1585                 if ( empty( $attr['orderby'] ) ) {
1586                         $attr['orderby'] = 'post__in';
1587                 }
1588                 $attr['include'] = $attr['ids'];
1589         }
1590
1591         /**
1592          * Filter the default gallery shortcode output.
1593          *
1594          * If the filtered output isn't empty, it will be used instead of generating
1595          * the default gallery template.
1596          *
1597          * @since 2.5.0
1598          * @since 4.2.0 The `$instance` parameter was added.
1599          *
1600          * @see gallery_shortcode()
1601          *
1602          * @param string $output   The gallery output. Default empty.
1603          * @param array  $attr     Attributes of the gallery shortcode.
1604          * @param int    $instance Unique numeric ID of this gallery shortcode instance.
1605          */
1606         $output = apply_filters( 'post_gallery', '', $attr, $instance );
1607         if ( $output != '' ) {
1608                 return $output;
1609         }
1610
1611         $html5 = current_theme_supports( 'html5', 'gallery' );
1612         $atts = shortcode_atts( array(
1613                 'order'      => 'ASC',
1614                 'orderby'    => 'menu_order ID',
1615                 'id'         => $post ? $post->ID : 0,
1616                 'itemtag'    => $html5 ? 'figure'     : 'dl',
1617                 'icontag'    => $html5 ? 'div'        : 'dt',
1618                 'captiontag' => $html5 ? 'figcaption' : 'dd',
1619                 'columns'    => 3,
1620                 'size'       => 'thumbnail',
1621                 'include'    => '',
1622                 'exclude'    => '',
1623                 'link'       => ''
1624         ), $attr, 'gallery' );
1625
1626         $id = intval( $atts['id'] );
1627
1628         if ( ! empty( $atts['include'] ) ) {
1629                 $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1630
1631                 $attachments = array();
1632                 foreach ( $_attachments as $key => $val ) {
1633                         $attachments[$val->ID] = $_attachments[$key];
1634                 }
1635         } elseif ( ! empty( $atts['exclude'] ) ) {
1636                 $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'] ) );
1637         } else {
1638                 $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
1639         }
1640
1641         if ( empty( $attachments ) ) {
1642                 return '';
1643         }
1644
1645         if ( is_feed() ) {
1646                 $output = "\n";
1647                 foreach ( $attachments as $att_id => $attachment ) {
1648                         $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
1649                 }
1650                 return $output;
1651         }
1652
1653         $itemtag = tag_escape( $atts['itemtag'] );
1654         $captiontag = tag_escape( $atts['captiontag'] );
1655         $icontag = tag_escape( $atts['icontag'] );
1656         $valid_tags = wp_kses_allowed_html( 'post' );
1657         if ( ! isset( $valid_tags[ $itemtag ] ) ) {
1658                 $itemtag = 'dl';
1659         }
1660         if ( ! isset( $valid_tags[ $captiontag ] ) ) {
1661                 $captiontag = 'dd';
1662         }
1663         if ( ! isset( $valid_tags[ $icontag ] ) ) {
1664                 $icontag = 'dt';
1665         }
1666
1667         $columns = intval( $atts['columns'] );
1668         $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
1669         $float = is_rtl() ? 'right' : 'left';
1670
1671         $selector = "gallery-{$instance}";
1672
1673         $gallery_style = '';
1674
1675         /**
1676          * Filter whether to print default gallery styles.
1677          *
1678          * @since 3.1.0
1679          *
1680          * @param bool $print Whether to print default gallery styles.
1681          *                    Defaults to false if the theme supports HTML5 galleries.
1682          *                    Otherwise, defaults to true.
1683          */
1684         if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1685                 $gallery_style = "
1686                 <style type='text/css'>
1687                         #{$selector} {
1688                                 margin: auto;
1689                         }
1690                         #{$selector} .gallery-item {
1691                                 float: {$float};
1692                                 margin-top: 10px;
1693                                 text-align: center;
1694                                 width: {$itemwidth}%;
1695                         }
1696                         #{$selector} img {
1697                                 border: 2px solid #cfcfcf;
1698                         }
1699                         #{$selector} .gallery-caption {
1700                                 margin-left: 0;
1701                         }
1702                         /* see gallery_shortcode() in wp-includes/media.php */
1703                 </style>\n\t\t";
1704         }
1705
1706         $size_class = sanitize_html_class( $atts['size'] );
1707         $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1708
1709         /**
1710          * Filter the default gallery shortcode CSS styles.
1711          *
1712          * @since 2.5.0
1713          *
1714          * @param string $gallery_style Default CSS styles and opening HTML div container
1715          *                              for the gallery shortcode output.
1716          */
1717         $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1718
1719         $i = 0;
1720         foreach ( $attachments as $id => $attachment ) {
1721
1722                 $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
1723                 if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
1724                         $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
1725                 } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
1726                         $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
1727                 } else {
1728                         $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
1729                 }
1730                 $image_meta  = wp_get_attachment_metadata( $id );
1731
1732                 $orientation = '';
1733                 if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
1734                         $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1735                 }
1736                 $output .= "<{$itemtag} class='gallery-item'>";
1737                 $output .= "
1738                         <{$icontag} class='gallery-icon {$orientation}'>
1739                                 $image_output
1740                         </{$icontag}>";
1741                 if ( $captiontag && trim($attachment->post_excerpt) ) {
1742                         $output .= "
1743                                 <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
1744                                 " . wptexturize($attachment->post_excerpt) . "
1745                                 </{$captiontag}>";
1746                 }
1747                 $output .= "</{$itemtag}>";
1748                 if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1749                         $output .= '<br style="clear: both" />';
1750                 }
1751         }
1752
1753         if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1754                 $output .= "
1755                         <br style='clear: both' />";
1756         }
1757
1758         $output .= "
1759                 </div>\n";
1760
1761         return $output;
1762 }
1763
1764 /**
1765  * Outputs the templates used by playlists.
1766  *
1767  * @since 3.9.0
1768  */
1769 function wp_underscore_playlist_templates() {
1770 ?>
1771 <script type="text/html" id="tmpl-wp-playlist-current-item">
1772         <# if ( data.image ) { #>
1773         <img src="{{ data.thumb.src }}" alt="" />
1774         <# } #>
1775         <div class="wp-playlist-caption">
1776                 <span class="wp-playlist-item-meta wp-playlist-item-title"><?php
1777                         /* translators: playlist item title */
1778                         printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
1779                 ?></span>
1780                 <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1781                 <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1782         </div>
1783 </script>
1784 <script type="text/html" id="tmpl-wp-playlist-item">
1785         <div class="wp-playlist-item">
1786                 <a class="wp-playlist-caption" href="{{ data.src }}">
1787                         {{ data.index ? ( data.index + '. ' ) : '' }}
1788                         <# if ( data.caption ) { #>
1789                                 {{ data.caption }}
1790                         <# } else { #>
1791                                 <span class="wp-playlist-item-title"><?php
1792                                         /* translators: playlist item title */
1793                                         printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
1794                                 ?></span>
1795                                 <# if ( data.artists && data.meta.artist ) { #>
1796                                 <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
1797                                 <# } #>
1798                         <# } #>
1799                 </a>
1800                 <# if ( data.meta.length_formatted ) { #>
1801                 <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1802                 <# } #>
1803         </div>
1804 </script>
1805 <?php
1806 }
1807
1808 /**
1809  * Outputs and enqueue default scripts and styles for playlists.
1810  *
1811  * @since 3.9.0
1812  *
1813  * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1814  */
1815 function wp_playlist_scripts( $type ) {
1816         wp_enqueue_style( 'wp-mediaelement' );
1817         wp_enqueue_script( 'wp-playlist' );
1818 ?>
1819 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1820 <?php
1821         add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1822         add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1823 }
1824
1825 /**
1826  * Builds the Playlist shortcode output.
1827  *
1828  * This implements the functionality of the playlist shortcode for displaying
1829  * a collection of WordPress audio or video files in a post.
1830  *
1831  * @since 3.9.0
1832  *
1833  * @global int $content_width
1834  * @staticvar int $instance
1835  *
1836  * @param array $attr {
1837  *     Array of default playlist attributes.
1838  *
1839  *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
1840  *     @type string  $order        Designates ascending or descending order of items in the playlist.
1841  *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
1842  *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
1843  *                                 passed, this defaults to the order of the $ids array ('post__in').
1844  *                                 Otherwise default is 'menu_order ID'.
1845  *     @type int     $id           If an explicit $ids array is not present, this parameter
1846  *                                 will determine which attachments are used for the playlist.
1847  *                                 Default is the current post ID.
1848  *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
1849  *                                 a playlist will be created from all $type attachments of $id.
1850  *                                 Default empty.
1851  *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
1852  *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
1853  *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
1854  *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
1855  *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
1856  *                                 thumbnail). Default true.
1857  *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
1858  * }
1859  *
1860  * @return string Playlist output. Empty string if the passed type is unsupported.
1861  */
1862 function wp_playlist_shortcode( $attr ) {
1863         global $content_width;
1864         $post = get_post();
1865
1866         static $instance = 0;
1867         $instance++;
1868
1869         if ( ! empty( $attr['ids'] ) ) {
1870                 // 'ids' is explicitly ordered, unless you specify otherwise.
1871                 if ( empty( $attr['orderby'] ) ) {
1872                         $attr['orderby'] = 'post__in';
1873                 }
1874                 $attr['include'] = $attr['ids'];
1875         }
1876
1877         /**
1878          * Filter the playlist output.
1879          *
1880          * Passing a non-empty value to the filter will short-circuit generation
1881          * of the default playlist output, returning the passed value instead.
1882          *
1883          * @since 3.9.0
1884          * @since 4.2.0 The `$instance` parameter was added.
1885          *
1886          * @param string $output   Playlist output. Default empty.
1887          * @param array  $attr     An array of shortcode attributes.
1888          * @param int    $instance Unique numeric ID of this playlist shortcode instance.
1889          */
1890         $output = apply_filters( 'post_playlist', '', $attr, $instance );
1891         if ( $output != '' ) {
1892                 return $output;
1893         }
1894
1895         $atts = shortcode_atts( array(
1896                 'type'          => 'audio',
1897                 'order'         => 'ASC',
1898                 'orderby'       => 'menu_order ID',
1899                 'id'            => $post ? $post->ID : 0,
1900                 'include'       => '',
1901                 'exclude'   => '',
1902                 'style'         => 'light',
1903                 'tracklist' => true,
1904                 'tracknumbers' => true,
1905                 'images'        => true,
1906                 'artists'       => true
1907         ), $attr, 'playlist' );
1908
1909         $id = intval( $atts['id'] );
1910
1911         if ( $atts['type'] !== 'audio' ) {
1912                 $atts['type'] = 'video';
1913         }
1914
1915         $args = array(
1916                 'post_status' => 'inherit',
1917                 'post_type' => 'attachment',
1918                 'post_mime_type' => $atts['type'],
1919                 'order' => $atts['order'],
1920                 'orderby' => $atts['orderby']
1921         );
1922
1923         if ( ! empty( $atts['include'] ) ) {
1924                 $args['include'] = $atts['include'];
1925                 $_attachments = get_posts( $args );
1926
1927                 $attachments = array();
1928                 foreach ( $_attachments as $key => $val ) {
1929                         $attachments[$val->ID] = $_attachments[$key];
1930                 }
1931         } elseif ( ! empty( $atts['exclude'] ) ) {
1932                 $args['post_parent'] = $id;
1933                 $args['exclude'] = $atts['exclude'];
1934                 $attachments = get_children( $args );
1935         } else {
1936                 $args['post_parent'] = $id;
1937                 $attachments = get_children( $args );
1938         }
1939
1940         if ( empty( $attachments ) ) {
1941                 return '';
1942         }
1943
1944         if ( is_feed() ) {
1945                 $output = "\n";
1946                 foreach ( $attachments as $att_id => $attachment ) {
1947                         $output .= wp_get_attachment_link( $att_id ) . "\n";
1948                 }
1949                 return $output;
1950         }
1951
1952         $outer = 22; // default padding and border of wrapper
1953
1954         $default_width = 640;
1955         $default_height = 360;
1956
1957         $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1958         $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1959
1960         $data = array(
1961                 'type' => $atts['type'],
1962                 // don't pass strings to JSON, will be truthy in JS
1963                 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
1964                 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
1965                 'images' => wp_validate_boolean( $atts['images'] ),
1966                 'artists' => wp_validate_boolean( $atts['artists'] ),
1967         );
1968
1969         $tracks = array();
1970         foreach ( $attachments as $attachment ) {
1971                 $url = wp_get_attachment_url( $attachment->ID );
1972                 $ftype = wp_check_filetype( $url, wp_get_mime_types() );
1973                 $track = array(
1974                         'src' => $url,
1975                         'type' => $ftype['type'],
1976                         'title' => $attachment->post_title,
1977                         'caption' => $attachment->post_excerpt,
1978                         'description' => $attachment->post_content
1979                 );
1980
1981                 $track['meta'] = array();
1982                 $meta = wp_get_attachment_metadata( $attachment->ID );
1983                 if ( ! empty( $meta ) ) {
1984
1985                         foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1986                                 if ( ! empty( $meta[ $key ] ) ) {
1987                                         $track['meta'][ $key ] = $meta[ $key ];
1988                                 }
1989                         }
1990
1991                         if ( 'video' === $atts['type'] ) {
1992                                 if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1993                                         $width = $meta['width'];
1994                                         $height = $meta['height'];
1995                                         $theme_height = round( ( $height * $theme_width ) / $width );
1996                                 } else {
1997                                         $width = $default_width;
1998                                         $height = $default_height;
1999                                 }
2000
2001                                 $track['dimensions'] = array(
2002                                         'original' => compact( 'width', 'height' ),
2003                                         'resized' => array(
2004                                                 'width' => $theme_width,
2005                                                 'height' => $theme_height
2006                                         )
2007                                 );
2008                         }
2009                 }
2010
2011                 if ( $atts['images'] ) {
2012                         $thumb_id = get_post_thumbnail_id( $attachment->ID );
2013                         if ( ! empty( $thumb_id ) ) {
2014                                 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
2015                                 $track['image'] = compact( 'src', 'width', 'height' );
2016                                 list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
2017                                 $track['thumb'] = compact( 'src', 'width', 'height' );
2018                         } else {
2019                                 $src = wp_mime_type_icon( $attachment->ID );
2020                                 $width = 48;
2021                                 $height = 64;
2022                                 $track['image'] = compact( 'src', 'width', 'height' );
2023                                 $track['thumb'] = compact( 'src', 'width', 'height' );
2024                         }
2025                 }
2026
2027                 $tracks[] = $track;
2028         }
2029         $data['tracks'] = $tracks;
2030
2031         $safe_type = esc_attr( $atts['type'] );
2032         $safe_style = esc_attr( $atts['style'] );
2033
2034         ob_start();
2035
2036         if ( 1 === $instance ) {
2037                 /**
2038                  * Print and enqueue playlist scripts, styles, and JavaScript templates.
2039                  *
2040                  * @since 3.9.0
2041                  *
2042                  * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
2043                  * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
2044                  */
2045                 do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
2046         } ?>
2047 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
2048         <?php if ( 'audio' === $atts['type'] ): ?>
2049         <div class="wp-playlist-current-item"></div>
2050         <?php endif ?>
2051         <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
2052                 echo (int) $theme_width;
2053         ?>"<?php if ( 'video' === $safe_type ):
2054                 echo ' height="', (int) $theme_height, '"';
2055         else:
2056                 echo ' style="visibility: hidden"';
2057         endif; ?>></<?php echo $safe_type ?>>
2058         <div class="wp-playlist-next"></div>
2059         <div class="wp-playlist-prev"></div>
2060         <noscript>
2061         <ol><?php
2062         foreach ( $attachments as $att_id => $attachment ) {
2063                 printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
2064         }
2065         ?></ol>
2066         </noscript>
2067         <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
2068 </div>
2069         <?php
2070         return ob_get_clean();
2071 }
2072 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
2073
2074 /**
2075  * Provides a No-JS Flash fallback as a last resort for audio / video.
2076  *
2077  * @since 3.6.0
2078  *
2079  * @param string $url The media element URL.
2080  * @return string Fallback HTML.
2081  */
2082 function wp_mediaelement_fallback( $url ) {
2083         /**
2084          * Filter the Mediaelement fallback output for no-JS.
2085          *
2086          * @since 3.6.0
2087          *
2088          * @param string $output Fallback output for no-JS.
2089          * @param string $url    Media file URL.
2090          */
2091         return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
2092 }
2093
2094 /**
2095  * Returns a filtered list of WP-supported audio formats.
2096  *
2097  * @since 3.6.0
2098  *
2099  * @return array Supported audio formats.
2100  */
2101 function wp_get_audio_extensions() {
2102         /**
2103          * Filter the list of supported audio formats.
2104          *
2105          * @since 3.6.0
2106          *
2107          * @param array $extensions An array of support audio formats. Defaults are
2108          *                          'mp3', 'ogg', 'wma', 'm4a', 'wav'.
2109          */
2110         return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
2111 }
2112
2113 /**
2114  * Returns useful keys to use to lookup data from an attachment's stored metadata.
2115  *
2116  * @since 3.9.0
2117  *
2118  * @param WP_Post $attachment The current attachment, provided for context.
2119  * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
2120  * @return array Key/value pairs of field keys to labels.
2121  */
2122 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
2123         $fields = array(
2124                 'artist' => __( 'Artist' ),
2125                 'album' => __( 'Album' ),
2126         );
2127
2128         if ( 'display' === $context ) {
2129                 $fields['genre']            = __( 'Genre' );
2130                 $fields['year']             = __( 'Year' );
2131                 $fields['length_formatted'] = _x( 'Length', 'video or audio' );
2132         } elseif ( 'js' === $context ) {
2133                 $fields['bitrate']          = __( 'Bitrate' );
2134                 $fields['bitrate_mode']     = __( 'Bitrate Mode' );
2135         }
2136
2137         /**
2138          * Filter the editable list of keys to look up data from an attachment's metadata.
2139          *
2140          * @since 3.9.0
2141          *
2142          * @param array   $fields     Key/value pairs of field keys to labels.
2143          * @param WP_Post $attachment Attachment object.
2144          * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
2145          */
2146         return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
2147 }
2148 /**
2149  * Builds the Audio shortcode output.
2150  *
2151  * This implements the functionality of the Audio Shortcode for displaying
2152  * WordPress mp3s in a post.
2153  *
2154  * @since 3.6.0
2155  *
2156  * @staticvar int $instance
2157  *
2158  * @param array  $attr {
2159  *     Attributes of the audio shortcode.
2160  *
2161  *     @type string $src      URL to the source of the audio file. Default empty.
2162  *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
2163  *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
2164  *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default 'none'.
2165  *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
2166  *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%; visibility: hidden;'.
2167  * }
2168  * @param string $content Shortcode content.
2169  * @return string|void HTML content to display audio.
2170  */
2171 function wp_audio_shortcode( $attr, $content = '' ) {
2172         $post_id = get_post() ? get_the_ID() : 0;
2173
2174         static $instance = 0;
2175         $instance++;
2176
2177         /**
2178          * Filter the default audio shortcode output.
2179          *
2180          * If the filtered output isn't empty, it will be used instead of generating the default audio template.
2181          *
2182          * @since 3.6.0
2183          *
2184          * @param string $html     Empty variable to be replaced with shortcode markup.
2185          * @param array  $attr     Attributes of the shortcode. @see wp_audio_shortcode()
2186          * @param string $content  Shortcode content.
2187          * @param int    $instance Unique numeric ID of this audio shortcode instance.
2188          */
2189         $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
2190         if ( '' !== $override ) {
2191                 return $override;
2192         }
2193
2194         $audio = null;
2195
2196         $default_types = wp_get_audio_extensions();
2197         $defaults_atts = array(
2198                 'src'      => '',
2199                 'loop'     => '',
2200                 'autoplay' => '',
2201                 'preload'  => 'none',
2202                 'class'    => 'wp-audio-shortcode',
2203                 'style'    => 'width: 100%; visibility: hidden;'
2204         );
2205         foreach ( $default_types as $type ) {
2206                 $defaults_atts[$type] = '';
2207         }
2208
2209         $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
2210
2211         $primary = false;
2212         if ( ! empty( $atts['src'] ) ) {
2213                 $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2214                 if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2215                         return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2216                 }
2217                 $primary = true;
2218                 array_unshift( $default_types, 'src' );
2219         } else {
2220                 foreach ( $default_types as $ext ) {
2221                         if ( ! empty( $atts[ $ext ] ) ) {
2222                                 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2223                                 if ( strtolower( $type['ext'] ) === $ext ) {
2224                                         $primary = true;
2225                                 }
2226                         }
2227                 }
2228         }
2229
2230         if ( ! $primary ) {
2231                 $audios = get_attached_media( 'audio', $post_id );
2232                 if ( empty( $audios ) ) {
2233                         return;
2234                 }
2235
2236                 $audio = reset( $audios );
2237                 $atts['src'] = wp_get_attachment_url( $audio->ID );
2238                 if ( empty( $atts['src'] ) ) {
2239                         return;
2240                 }
2241
2242                 array_unshift( $default_types, 'src' );
2243         }
2244
2245         /**
2246          * Filter the media library used for the audio shortcode.
2247          *
2248          * @since 3.6.0
2249          *
2250          * @param string $library Media library used for the audio shortcode.
2251          */
2252         $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
2253         if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2254                 wp_enqueue_style( 'wp-mediaelement' );
2255                 wp_enqueue_script( 'wp-mediaelement' );
2256         }
2257
2258         /**
2259          * Filter the class attribute for the audio shortcode output container.
2260          *
2261          * @since 3.6.0
2262          *
2263          * @param string $class CSS class or list of space-separated classes.
2264          */
2265         $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'] );
2266
2267         $html_atts = array(
2268                 'class'    => $atts['class'],
2269                 'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
2270                 'loop'     => wp_validate_boolean( $atts['loop'] ),
2271                 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2272                 'preload'  => $atts['preload'],
2273                 'style'    => $atts['style'],
2274         );
2275
2276         // These ones should just be omitted altogether if they are blank
2277         foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
2278                 if ( empty( $html_atts[$a] ) ) {
2279                         unset( $html_atts[$a] );
2280                 }
2281         }
2282
2283         $attr_strings = array();
2284         foreach ( $html_atts as $k => $v ) {
2285                 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2286         }
2287
2288         $html = '';
2289         if ( 'mediaelement' === $library && 1 === $instance ) {
2290                 $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
2291         }
2292         $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
2293
2294         $fileurl = '';
2295         $source = '<source type="%s" src="%s" />';
2296         foreach ( $default_types as $fallback ) {
2297                 if ( ! empty( $atts[ $fallback ] ) ) {
2298                         if ( empty( $fileurl ) ) {
2299                                 $fileurl = $atts[ $fallback ];
2300                         }
2301                         $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2302                         $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2303                         $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2304                 }
2305         }
2306
2307         if ( 'mediaelement' === $library ) {
2308                 $html .= wp_mediaelement_fallback( $fileurl );
2309         }
2310         $html .= '</audio>';
2311
2312         /**
2313          * Filter the audio shortcode output.
2314          *
2315          * @since 3.6.0
2316          *
2317          * @param string $html    Audio shortcode HTML output.
2318          * @param array  $atts    Array of audio shortcode attributes.
2319          * @param string $audio   Audio file.
2320          * @param int    $post_id Post ID.
2321          * @param string $library Media library used for the audio shortcode.
2322          */
2323         return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
2324 }
2325 add_shortcode( 'audio', 'wp_audio_shortcode' );
2326
2327 /**
2328  * Returns a filtered list of WP-supported video formats.
2329  *
2330  * @since 3.6.0
2331  *
2332  * @return array List of supported video formats.
2333  */
2334 function wp_get_video_extensions() {
2335         /**
2336          * Filter the list of supported video formats.
2337          *
2338          * @since 3.6.0
2339          *
2340          * @param array $extensions An array of support video formats. Defaults are
2341          *                          'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
2342          */
2343         return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
2344 }
2345
2346 /**
2347  * Builds the Video shortcode output.
2348  *
2349  * This implements the functionality of the Video Shortcode for displaying
2350  * WordPress mp4s in a post.
2351  *
2352  * @since 3.6.0
2353  *
2354  * @global int $content_width
2355  * @staticvar int $instance
2356  *
2357  * @param array  $attr {
2358  *     Attributes of the shortcode.
2359  *
2360  *     @type string $src      URL to the source of the video file. Default empty.
2361  *     @type int    $height   Height of the video embed in pixels. Default 360.
2362  *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
2363  *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
2364  *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
2365  *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
2366  *     @type string $preload  The 'preload' attribute for the `<video>` element.
2367  *                            Default 'metadata'.
2368  *     @type string $class    The 'class' attribute for the `<video>` element.
2369  *                            Default 'wp-video-shortcode'.
2370  * }
2371  * @param string $content Shortcode content.
2372  * @return string|void HTML content to display video.
2373  */
2374 function wp_video_shortcode( $attr, $content = '' ) {
2375         global $content_width;
2376         $post_id = get_post() ? get_the_ID() : 0;
2377
2378         static $instance = 0;
2379         $instance++;
2380
2381         /**
2382          * Filter the default video shortcode output.
2383          *
2384          * If the filtered output isn't empty, it will be used instead of generating
2385          * the default video template.
2386          *
2387          * @since 3.6.0
2388          *
2389          * @see wp_video_shortcode()
2390          *
2391          * @param string $html     Empty variable to be replaced with shortcode markup.
2392          * @param array  $attr     Attributes of the video shortcode.
2393          * @param string $content  Video shortcode content.
2394          * @param int    $instance Unique numeric ID of this video shortcode instance.
2395          */
2396         $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
2397         if ( '' !== $override ) {
2398                 return $override;
2399         }
2400
2401         $video = null;
2402
2403         $default_types = wp_get_video_extensions();
2404         $defaults_atts = array(
2405                 'src'      => '',
2406                 'poster'   => '',
2407                 'loop'     => '',
2408                 'autoplay' => '',
2409                 'preload'  => 'metadata',
2410                 'width'    => 640,
2411                 'height'   => 360,
2412                 'class'    => 'wp-video-shortcode',
2413         );
2414
2415         foreach ( $default_types as $type ) {
2416                 $defaults_atts[$type] = '';
2417         }
2418
2419         $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
2420
2421         if ( is_admin() ) {
2422                 // shrink the video so it isn't huge in the admin
2423                 if ( $atts['width'] > $defaults_atts['width'] ) {
2424                         $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
2425                         $atts['width'] = $defaults_atts['width'];
2426                 }
2427         } else {
2428                 // if the video is bigger than the theme
2429                 if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
2430                         $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
2431                         $atts['width'] = $content_width;
2432                 }
2433         }
2434
2435         $is_vimeo = $is_youtube = false;
2436         $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
2437         $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
2438
2439         $primary = false;
2440         if ( ! empty( $atts['src'] ) ) {
2441                 $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
2442                 $is_youtube = (  preg_match( $yt_pattern, $atts['src'] ) );
2443                 if ( ! $is_youtube && ! $is_vimeo ) {
2444                         $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
2445                         if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
2446                                 return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
2447                         }
2448                 }
2449
2450                 if ( $is_vimeo ) {
2451                         wp_enqueue_script( 'froogaloop' );
2452                 }
2453
2454                 $primary = true;
2455                 array_unshift( $default_types, 'src' );
2456         } else {
2457                 foreach ( $default_types as $ext ) {
2458                         if ( ! empty( $atts[ $ext ] ) ) {
2459                                 $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
2460                                 if ( strtolower( $type['ext'] ) === $ext ) {
2461                                         $primary = true;
2462                                 }
2463                         }
2464                 }
2465         }
2466
2467         if ( ! $primary ) {
2468                 $videos = get_attached_media( 'video', $post_id );
2469                 if ( empty( $videos ) ) {
2470                         return;
2471                 }
2472
2473                 $video = reset( $videos );
2474                 $atts['src'] = wp_get_attachment_url( $video->ID );
2475                 if ( empty( $atts['src'] ) ) {
2476                         return;
2477                 }
2478
2479                 array_unshift( $default_types, 'src' );
2480         }
2481
2482         /**
2483          * Filter the media library used for the video shortcode.
2484          *
2485          * @since 3.6.0
2486          *
2487          * @param string $library Media library used for the video shortcode.
2488          */
2489         $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
2490         if ( 'mediaelement' === $library && did_action( 'init' ) ) {
2491                 wp_enqueue_style( 'wp-mediaelement' );
2492                 wp_enqueue_script( 'wp-mediaelement' );
2493         }
2494
2495         /**
2496          * Filter the class attribute for the video shortcode output container.
2497          *
2498          * @since 3.6.0
2499          *
2500          * @param string $class CSS class or list of space-separated classes.
2501          */
2502         $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'] );
2503
2504         $html_atts = array(
2505                 'class'    => $atts['class'],
2506                 'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
2507                 'width'    => absint( $atts['width'] ),
2508                 'height'   => absint( $atts['height'] ),
2509                 'poster'   => esc_url( $atts['poster'] ),
2510                 'loop'     => wp_validate_boolean( $atts['loop'] ),
2511                 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
2512                 'preload'  => $atts['preload'],
2513         );
2514
2515         // These ones should just be omitted altogether if they are blank
2516         foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
2517                 if ( empty( $html_atts[$a] ) ) {
2518                         unset( $html_atts[$a] );
2519                 }
2520         }
2521
2522         $attr_strings = array();
2523         foreach ( $html_atts as $k => $v ) {
2524                 $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
2525         }
2526
2527         $html = '';
2528         if ( 'mediaelement' === $library && 1 === $instance ) {
2529                 $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
2530         }
2531         $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
2532
2533         $fileurl = '';
2534         $source = '<source type="%s" src="%s" />';
2535         foreach ( $default_types as $fallback ) {
2536                 if ( ! empty( $atts[ $fallback ] ) ) {
2537                         if ( empty( $fileurl ) ) {
2538                                 $fileurl = $atts[ $fallback ];
2539                         }
2540                         if ( 'src' === $fallback && $is_youtube ) {
2541                                 $type = array( 'type' => 'video/youtube' );
2542                         } elseif ( 'src' === $fallback && $is_vimeo ) {
2543                                 $type = array( 'type' => 'video/vimeo' );
2544                         } else {
2545                                 $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
2546                         }
2547                         $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
2548                         $html .= sprintf( $source, $type['type'], esc_url( $url ) );
2549                 }
2550         }
2551
2552         if ( ! empty( $content ) ) {
2553                 if ( false !== strpos( $content, "\n" ) ) {
2554                         $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
2555                 }
2556                 $html .= trim( $content );
2557         }
2558
2559         if ( 'mediaelement' === $library ) {
2560                 $html .= wp_mediaelement_fallback( $fileurl );
2561         }
2562         $html .= '</video>';
2563
2564         $width_rule = '';
2565         if ( ! empty( $atts['width'] ) ) {
2566                 $width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
2567         }
2568         $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
2569
2570         /**
2571          * Filter the output of the video shortcode.
2572          *
2573          * @since 3.6.0
2574          *
2575          * @param string $output  Video shortcode HTML output.
2576          * @param array  $atts    Array of video shortcode attributes.
2577          * @param string $video   Video file.
2578          * @param int    $post_id Post ID.
2579          * @param string $library Media library used for the video shortcode.
2580          */
2581         return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
2582 }
2583 add_shortcode( 'video', 'wp_video_shortcode' );
2584
2585 /**
2586  * Displays previous image link that has the same post parent.
2587  *
2588  * @since 2.5.0
2589  *
2590  * @see adjacent_image_link()
2591  *
2592  * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2593  *                           height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2594  *                           default to 'post_title' or `$text`. Default 'thumbnail'.
2595  * @param string       $text Optional. Link text. Default false.
2596  */
2597 function previous_image_link( $size = 'thumbnail', $text = false ) {
2598         adjacent_image_link(true, $size, $text);
2599 }
2600
2601 /**
2602  * Displays next image link that has the same post parent.
2603  *
2604  * @since 2.5.0
2605  *
2606  * @see adjacent_image_link()
2607  *
2608  * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
2609  *                           height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
2610  *                           default to 'post_title' or `$text`. Default 'thumbnail'.
2611  * @param string       $text Optional. Link text. Default false.
2612  */
2613 function next_image_link( $size = 'thumbnail', $text = false ) {
2614         adjacent_image_link(false, $size, $text);
2615 }
2616
2617 /**
2618  * Displays next or previous image link that has the same post parent.
2619  *
2620  * Retrieves the current attachment object from the $post global.
2621  *
2622  * @since 2.5.0
2623  *
2624  * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
2625  * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
2626  *                           values in pixels (in that order). Default 'thumbnail'.
2627  * @param bool         $text Optional. Link text. Default false.
2628  */
2629 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
2630         $post = get_post();
2631         $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' ) ) );
2632
2633         foreach ( $attachments as $k => $attachment ) {
2634                 if ( $attachment->ID == $post->ID ) {
2635                         break;
2636                 }
2637         }
2638
2639         $output = '';
2640         $attachment_id = 0;
2641
2642         if ( $attachments ) {
2643                 $k = $prev ? $k - 1 : $k + 1;
2644
2645                 if ( isset( $attachments[ $k ] ) ) {
2646                         $attachment_id = $attachments[ $k ]->ID;
2647                         $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
2648                 }
2649         }
2650
2651         $adjacent = $prev ? 'previous' : 'next';
2652
2653         /**
2654          * Filter the adjacent image link.
2655          *
2656          * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
2657          * either 'next', or 'previous'.
2658          *
2659          * @since 3.5.0
2660          *
2661          * @param string $output        Adjacent image HTML markup.
2662          * @param int    $attachment_id Attachment ID
2663          * @param string $size          Image size.
2664          * @param string $text          Link text.
2665          */
2666         echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
2667 }
2668
2669 /**
2670  * Retrieves taxonomies attached to given the attachment.
2671  *
2672  * @since 2.5.0
2673  *
2674  * @param int|array|object $attachment Attachment ID, data array, or data object.
2675  * @return array Empty array on failure. List of taxonomies on success.
2676  */
2677 function get_attachment_taxonomies( $attachment ) {
2678         if ( is_int( $attachment ) ) {
2679                 $attachment = get_post( $attachment );
2680         } elseif ( is_array( $attachment ) ) {
2681                 $attachment = (object) $attachment;
2682         }
2683         if ( ! is_object($attachment) )
2684                 return array();
2685
2686         $file = get_attached_file( $attachment->ID );
2687         $filename = basename( $file );
2688
2689         $objects = array('attachment');
2690
2691         if ( false !== strpos($filename, '.') )
2692                 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
2693         if ( !empty($attachment->post_mime_type) ) {
2694                 $objects[] = 'attachment:' . $attachment->post_mime_type;
2695                 if ( false !== strpos($attachment->post_mime_type, '/') )
2696                         foreach ( explode('/', $attachment->post_mime_type) as $token )
2697                                 if ( !empty($token) )
2698                                         $objects[] = "attachment:$token";
2699         }
2700
2701         $taxonomies = array();
2702         foreach ( $objects as $object )
2703                 if ( $taxes = get_object_taxonomies($object) )
2704                         $taxonomies = array_merge($taxonomies, $taxes);
2705
2706         return array_unique($taxonomies);
2707 }
2708
2709 /**
2710  * Retrieves all of the taxonomy names that are registered for attachments.
2711  *
2712  * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
2713  *
2714  * @since 3.5.0
2715  *
2716  * @see get_taxonomies()
2717  *
2718  * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
2719  *                       Default 'names'.
2720  * @return array The names of all taxonomy of $object_type.
2721  */
2722 function get_taxonomies_for_attachments( $output = 'names' ) {
2723         $taxonomies = array();
2724         foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
2725                 foreach ( $taxonomy->object_type as $object_type ) {
2726                         if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
2727                                 if ( 'names' == $output )
2728                                         $taxonomies[] = $taxonomy->name;
2729                                 else
2730                                         $taxonomies[ $taxonomy->name ] = $taxonomy;
2731                                 break;
2732                         }
2733                 }
2734         }
2735
2736         return $taxonomies;
2737 }
2738
2739 /**
2740  * Create new GD image resource with transparency support
2741  *
2742  * @todo: Deprecate if possible.
2743  *
2744  * @since 2.9.0
2745  *
2746  * @param int $width  Image width in pixels.
2747  * @param int $height Image height in pixels..
2748  * @return resource The GD image resource.
2749  */
2750 function wp_imagecreatetruecolor($width, $height) {
2751         $img = imagecreatetruecolor($width, $height);
2752         if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
2753                 imagealphablending($img, false);
2754                 imagesavealpha($img, true);
2755         }
2756         return $img;
2757 }
2758
2759 /**
2760  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
2761  *
2762  * @since 2.9.0
2763  *
2764  * @see wp_constrain_dimensions()
2765  *
2766  * @param int $example_width  The width of an example embed.
2767  * @param int $example_height The height of an example embed.
2768  * @param int $max_width      The maximum allowed width.
2769  * @param int $max_height     The maximum allowed height.
2770  * @return array The maximum possible width and height based on the example ratio.
2771  */
2772 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
2773         $example_width  = (int) $example_width;
2774         $example_height = (int) $example_height;
2775         $max_width      = (int) $max_width;
2776         $max_height     = (int) $max_height;
2777
2778         return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
2779 }
2780
2781 /**
2782  * Converts a shorthand byte value to an integer byte value.
2783  *
2784  * @since 2.3.0
2785  *
2786  * @param string $size A shorthand byte value.
2787  * @return int An integer byte value.
2788  */
2789 function wp_convert_hr_to_bytes( $size ) {
2790         $size  = strtolower( $size );
2791         $bytes = (int) $size;
2792         if ( strpos( $size, 'k' ) !== false )
2793                 $bytes = intval( $size ) * KB_IN_BYTES;
2794         elseif ( strpos( $size, 'm' ) !== false )
2795                 $bytes = intval($size) * MB_IN_BYTES;
2796         elseif ( strpos( $size, 'g' ) !== false )
2797                 $bytes = intval( $size ) * GB_IN_BYTES;
2798         return $bytes;
2799 }
2800
2801 /**
2802  * Determines the maximum upload size allowed in php.ini.
2803  *
2804  * @since 2.5.0
2805  *
2806  * @return int Allowed upload size.
2807  */
2808 function wp_max_upload_size() {
2809         $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
2810         $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
2811
2812         /**
2813          * Filter the maximum upload size allowed in php.ini.
2814          *
2815          * @since 2.5.0
2816          *
2817          * @param int $size    Max upload size limit in bytes.
2818          * @param int $u_bytes Maximum upload filesize in bytes.
2819          * @param int $p_bytes Maximum size of POST data in bytes.
2820          */
2821         return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
2822 }
2823
2824 /**
2825  * Returns a WP_Image_Editor instance and loads file into it.
2826  *
2827  * @since 3.5.0
2828  *
2829  * @param string $path Path to the file to load.
2830  * @param array  $args Optional. Additional arguments for retrieving the image editor.
2831  *                     Default empty array.
2832  * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
2833  *                                  object otherwise.
2834  */
2835 function wp_get_image_editor( $path, $args = array() ) {
2836         $args['path'] = $path;
2837
2838         if ( ! isset( $args['mime_type'] ) ) {
2839                 $file_info = wp_check_filetype( $args['path'] );
2840
2841                 // If $file_info['type'] is false, then we let the editor attempt to
2842                 // figure out the file type, rather than forcing a failure based on extension.
2843                 if ( isset( $file_info ) && $file_info['type'] )
2844                         $args['mime_type'] = $file_info['type'];
2845         }
2846
2847         $implementation = _wp_image_editor_choose( $args );
2848
2849         if ( $implementation ) {
2850                 $editor = new $implementation( $path );
2851                 $loaded = $editor->load();
2852
2853                 if ( is_wp_error( $loaded ) )
2854                         return $loaded;
2855
2856                 return $editor;
2857         }
2858
2859         return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
2860 }
2861
2862 /**
2863  * Tests whether there is an editor that supports a given mime type or methods.
2864  *
2865  * @since 3.5.0
2866  *
2867  * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
2868  *                           Default empty array.
2869  * @return bool True if an eligible editor is found; false otherwise.
2870  */
2871 function wp_image_editor_supports( $args = array() ) {
2872         return (bool) _wp_image_editor_choose( $args );
2873 }
2874
2875 /**
2876  * Tests which editors are capable of supporting the request.
2877  *
2878  * @ignore
2879  * @since 3.5.0
2880  *
2881  * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
2882  * @return string|false Class name for the first editor that claims to support the request. False if no
2883  *                     editor claims to support the request.
2884  */
2885 function _wp_image_editor_choose( $args = array() ) {
2886         require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
2887         require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
2888         require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
2889
2890         /**
2891          * Filter the list of image editing library classes.
2892          *
2893          * @since 3.5.0
2894          *
2895          * @param array $image_editors List of available image editors. Defaults are
2896          *                             'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
2897          */
2898         $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
2899
2900         foreach ( $implementations as $implementation ) {
2901                 if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
2902                         continue;
2903
2904                 if ( isset( $args['mime_type'] ) &&
2905                         ! call_user_func(
2906                                 array( $implementation, 'supports_mime_type' ),
2907                                 $args['mime_type'] ) ) {
2908                         continue;
2909                 }
2910
2911                 if ( isset( $args['methods'] ) &&
2912                          array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
2913                         continue;
2914                 }
2915
2916                 return $implementation;
2917         }
2918
2919         return false;
2920 }
2921
2922 /**
2923  * Prints default plupload arguments.
2924  *
2925  * @since 3.4.0
2926  */
2927 function wp_plupload_default_settings() {
2928         $wp_scripts = wp_scripts();
2929
2930         $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
2931         if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
2932                 return;
2933
2934         $max_upload_size = wp_max_upload_size();
2935
2936         $defaults = array(
2937                 'runtimes'            => 'html5,flash,silverlight,html4',
2938                 'file_data_name'      => 'async-upload', // key passed to $_FILE.
2939                 'url'                 => admin_url( 'async-upload.php', 'relative' ),
2940                 'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
2941                 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
2942                 'filters' => array(
2943                         'max_file_size'   => $max_upload_size . 'b',
2944                 ),
2945         );
2946
2947         // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
2948         // when enabled. See #29602.
2949         if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
2950                 strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
2951
2952                 $defaults['multi_selection'] = false;
2953         }
2954
2955         /**
2956          * Filter the Plupload default settings.
2957          *
2958          * @since 3.4.0
2959          *
2960          * @param array $defaults Default Plupload settings array.
2961          */
2962         $defaults = apply_filters( 'plupload_default_settings', $defaults );
2963
2964         $params = array(
2965                 'action' => 'upload-attachment',
2966         );
2967
2968         /**
2969          * Filter the Plupload default parameters.
2970          *
2971          * @since 3.4.0
2972          *
2973          * @param array $params Default Plupload parameters array.
2974          */
2975         $params = apply_filters( 'plupload_default_params', $params );
2976         $params['_wpnonce'] = wp_create_nonce( 'media-form' );
2977         $defaults['multipart_params'] = $params;
2978
2979         $settings = array(
2980                 'defaults' => $defaults,
2981                 'browser'  => array(
2982                         'mobile'    => wp_is_mobile(),
2983                         'supported' => _device_can_upload(),
2984                 ),
2985                 'limitExceeded' => is_multisite() && ! is_upload_space_available()
2986         );
2987
2988         $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
2989
2990         if ( $data )
2991                 $script = "$data\n$script";
2992
2993         $wp_scripts->add_data( 'wp-plupload', 'data', $script );
2994 }
2995
2996 /**
2997  * Prepares an attachment post object for JS, where it is expected
2998  * to be JSON-encoded and fit into an Attachment model.
2999  *
3000  * @since 3.5.0
3001  *
3002  * @param mixed $attachment Attachment ID or object.
3003  * @return array|void Array of attachment details.
3004  */
3005 function wp_prepare_attachment_for_js( $attachment ) {
3006         if ( ! $attachment = get_post( $attachment ) )
3007                 return;
3008
3009         if ( 'attachment' != $attachment->post_type )
3010                 return;
3011
3012         $meta = wp_get_attachment_metadata( $attachment->ID );
3013         if ( false !== strpos( $attachment->post_mime_type, '/' ) )
3014                 list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
3015         else
3016                 list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
3017
3018         $attachment_url = wp_get_attachment_url( $attachment->ID );
3019
3020         $response = array(
3021                 'id'          => $attachment->ID,
3022                 'title'       => $attachment->post_title,
3023                 'filename'    => wp_basename( get_attached_file( $attachment->ID ) ),
3024                 'url'         => $attachment_url,
3025                 'link'        => get_attachment_link( $attachment->ID ),
3026                 'alt'         => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
3027                 'author'      => $attachment->post_author,
3028                 'description' => $attachment->post_content,
3029                 'caption'     => $attachment->post_excerpt,
3030                 'name'        => $attachment->post_name,
3031                 'status'      => $attachment->post_status,
3032                 'uploadedTo'  => $attachment->post_parent,
3033                 'date'        => strtotime( $attachment->post_date_gmt ) * 1000,
3034                 'modified'    => strtotime( $attachment->post_modified_gmt ) * 1000,
3035                 'menuOrder'   => $attachment->menu_order,
3036                 'mime'        => $attachment->post_mime_type,
3037                 'type'        => $type,
3038                 'subtype'     => $subtype,
3039                 'icon'        => wp_mime_type_icon( $attachment->ID ),
3040                 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
3041                 'nonces'      => array(
3042                         'update' => false,
3043                         'delete' => false,
3044                         'edit'   => false
3045                 ),
3046                 'editLink'   => false,
3047                 'meta'       => false,
3048         );
3049
3050         $author = new WP_User( $attachment->post_author );
3051         $response['authorName'] = $author->display_name;
3052
3053         if ( $attachment->post_parent ) {
3054                 $post_parent = get_post( $attachment->post_parent );
3055         } else {
3056                 $post_parent = false;
3057         }
3058
3059         if ( $post_parent ) {
3060                 $parent_type = get_post_type_object( $post_parent->post_type );
3061                 if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
3062                         $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
3063                 }
3064                 $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
3065         }
3066
3067         $attached_file = get_attached_file( $attachment->ID );
3068
3069         if ( isset( $meta['filesize'] ) ) {
3070                 $bytes = $meta['filesize'];
3071         } elseif ( file_exists( $attached_file ) ) {
3072                 $bytes = filesize( $attached_file );
3073         } else {
3074                 $bytes = '';
3075         }
3076
3077         if ( $bytes ) {
3078                 $response['filesizeInBytes'] = $bytes;
3079                 $response['filesizeHumanReadable'] = size_format( $bytes );
3080         }
3081
3082         if ( current_user_can( 'edit_post', $attachment->ID ) ) {
3083                 $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
3084                 $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
3085                 $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
3086         }
3087
3088         if ( current_user_can( 'delete_post', $attachment->ID ) )
3089                 $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
3090
3091         if ( $meta && 'image' === $type ) {
3092                 $sizes = array();
3093
3094                 /** This filter is documented in wp-admin/includes/media.php */
3095                 $possible_sizes = apply_filters( 'image_size_names_choose', array(
3096                         'thumbnail' => __('Thumbnail'),
3097                         'medium'    => __('Medium'),
3098                         'large'     => __('Large'),
3099                         'full'      => __('Full Size'),
3100                 ) );
3101                 unset( $possible_sizes['full'] );
3102
3103                 // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
3104                 // First: run the image_downsize filter. If it returns something, we can use its data.
3105                 // If the filter does not return something, then image_downsize() is just an expensive
3106                 // way to check the image metadata, which we do second.
3107                 foreach ( $possible_sizes as $size => $label ) {
3108
3109                         /** This filter is documented in wp-includes/media.php */
3110                         if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
3111                                 if ( ! $downsize[3] )
3112                                         continue;
3113                                 $sizes[ $size ] = array(
3114                                         'height'      => $downsize[2],
3115                                         'width'       => $downsize[1],
3116                                         'url'         => $downsize[0],
3117                                         'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
3118                                 );
3119                         } elseif ( isset( $meta['sizes'][ $size ] ) ) {
3120                                 if ( ! isset( $base_url ) )
3121                                         $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
3122
3123                                 // Nothing from the filter, so consult image metadata if we have it.
3124                                 $size_meta = $meta['sizes'][ $size ];
3125
3126                                 // We have the actual image size, but might need to further constrain it if content_width is narrower.
3127                                 // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
3128                                 list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
3129
3130                                 $sizes[ $size ] = array(
3131                                         'height'      => $height,
3132                                         'width'       => $width,
3133                                         'url'         => $base_url . $size_meta['file'],
3134                                         'orientation' => $height > $width ? 'portrait' : 'landscape',
3135                                 );
3136                         }
3137                 }
3138
3139                 $sizes['full'] = array( 'url' => $attachment_url );
3140
3141                 if ( isset( $meta['height'], $meta['width'] ) ) {
3142                         $sizes['full']['height'] = $meta['height'];
3143                         $sizes['full']['width'] = $meta['width'];
3144                         $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
3145                 }
3146
3147                 $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
3148         } elseif ( $meta && 'video' === $type ) {
3149                 if ( isset( $meta['width'] ) )
3150                         $response['width'] = (int) $meta['width'];
3151                 if ( isset( $meta['height'] ) )
3152                         $response['height'] = (int) $meta['height'];
3153         }
3154
3155         if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
3156                 if ( isset( $meta['length_formatted'] ) )
3157                         $response['fileLength'] = $meta['length_formatted'];
3158
3159                 $response['meta'] = array();
3160                 foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
3161                         $response['meta'][ $key ] = false;
3162
3163                         if ( ! empty( $meta[ $key ] ) ) {
3164                                 $response['meta'][ $key ] = $meta[ $key ];
3165                         }
3166                 }
3167
3168                 $id = get_post_thumbnail_id( $attachment->ID );
3169                 if ( ! empty( $id ) ) {
3170                         list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
3171                         $response['image'] = compact( 'src', 'width', 'height' );
3172                         list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
3173                         $response['thumb'] = compact( 'src', 'width', 'height' );
3174                 } else {
3175                         $src = wp_mime_type_icon( $attachment->ID );
3176                         $width = 48;
3177                         $height = 64;
3178                         $response['image'] = compact( 'src', 'width', 'height' );
3179                         $response['thumb'] = compact( 'src', 'width', 'height' );
3180                 }
3181         }
3182
3183         if ( function_exists('get_compat_media_markup') )
3184                 $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
3185
3186         /**
3187          * Filter the attachment data prepared for JavaScript.
3188          *
3189          * @since 3.5.0
3190          *
3191          * @param array      $response   Array of prepared attachment data.
3192          * @param int|object $attachment Attachment ID or object.
3193          * @param array      $meta       Array of attachment meta data.
3194          */
3195         return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
3196 }
3197
3198 /**
3199  * Enqueues all scripts, styles, settings, and templates necessary to use
3200  * all media JS APIs.
3201  *
3202  * @since 3.5.0
3203  *
3204  * @global int       $content_width
3205  * @global wpdb      $wpdb
3206  * @global WP_Locale $wp_locale
3207  *
3208  * @param array $args {
3209  *     Arguments for enqueuing media scripts.
3210  *
3211  *     @type int|WP_Post A post object or ID.
3212  * }
3213  */
3214 function wp_enqueue_media( $args = array() ) {
3215         // Enqueue me just once per page, please.
3216         if ( did_action( 'wp_enqueue_media' ) )
3217                 return;
3218
3219         global $content_width, $wpdb, $wp_locale;
3220
3221         $defaults = array(
3222                 'post' => null,
3223         );
3224         $args = wp_parse_args( $args, $defaults );
3225
3226         // We're going to pass the old thickbox media tabs to `media_upload_tabs`
3227         // to ensure plugins will work. We will then unset those tabs.
3228         $tabs = array(
3229                 // handler action suffix => tab label
3230                 'type'     => '',
3231                 'type_url' => '',
3232                 'gallery'  => '',
3233                 'library'  => '',
3234         );
3235
3236         /** This filter is documented in wp-admin/includes/media.php */
3237         $tabs = apply_filters( 'media_upload_tabs', $tabs );
3238         unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
3239
3240         $props = array(
3241                 'link'  => get_option( 'image_default_link_type' ), // db default is 'file'
3242                 'align' => get_option( 'image_default_align' ), // empty default
3243                 'size'  => get_option( 'image_default_size' ),  // empty default
3244         );
3245
3246         $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
3247         $mimes = get_allowed_mime_types();
3248         $ext_mimes = array();
3249         foreach ( $exts as $ext ) {
3250                 foreach ( $mimes as $ext_preg => $mime_match ) {
3251                         if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
3252                                 $ext_mimes[ $ext ] = $mime_match;
3253                                 break;
3254                         }
3255                 }
3256         }
3257
3258         $has_audio = $wpdb->get_var( "
3259                 SELECT ID
3260                 FROM $wpdb->posts
3261                 WHERE post_type = 'attachment'
3262                 AND post_mime_type LIKE 'audio%'
3263                 LIMIT 1
3264         " );
3265         $has_video = $wpdb->get_var( "
3266                 SELECT ID
3267                 FROM $wpdb->posts
3268                 WHERE post_type = 'attachment'
3269                 AND post_mime_type LIKE 'video%'
3270                 LIMIT 1
3271         " );
3272         $months = $wpdb->get_results( $wpdb->prepare( "
3273                 SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
3274                 FROM $wpdb->posts
3275                 WHERE post_type = %s
3276                 ORDER BY post_date DESC
3277         ", 'attachment' ) );
3278         foreach ( $months as $month_year ) {
3279                 $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
3280         }
3281
3282         $settings = array(
3283                 'tabs'      => $tabs,
3284                 'tabUrl'    => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
3285                 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
3286                 /** This filter is documented in wp-admin/includes/media.php */
3287                 'captions'  => ! apply_filters( 'disable_captions', '' ),
3288                 'nonce'     => array(
3289                         'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
3290                 ),
3291                 'post'    => array(
3292                         'id' => 0,
3293                 ),
3294                 'defaultProps' => $props,
3295                 'attachmentCounts' => array(
3296                         'audio' => ( $has_audio ) ? 1 : 0,
3297                         'video' => ( $has_video ) ? 1 : 0
3298                 ),
3299                 'embedExts'    => $exts,
3300                 'embedMimes'   => $ext_mimes,
3301                 'contentWidth' => $content_width,
3302                 'months'       => $months,
3303                 'mediaTrash'   => MEDIA_TRASH ? 1 : 0
3304         );
3305
3306         $post = null;
3307         if ( isset( $args['post'] ) ) {
3308                 $post = get_post( $args['post'] );
3309                 $settings['post'] = array(
3310                         'id' => $post->ID,
3311                         'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
3312                 );
3313
3314                 $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
3315                 if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
3316                         if ( wp_attachment_is( 'audio', $post ) ) {
3317                                 $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
3318                         } elseif ( wp_attachment_is( 'video', $post ) ) {
3319                                 $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
3320                         }
3321                 }
3322
3323                 if ( $thumbnail_support ) {
3324                         $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
3325                         $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
3326                 }
3327         }
3328
3329         if ( $post ) {
3330                 $post_type_object = get_post_type_object( $post->post_type );
3331         } else {
3332                 $post_type_object = get_post_type_object( 'post' );
3333         }
3334
3335         $strings = array(
3336                 // Generic
3337                 'url'         => __( 'URL' ),
3338                 'addMedia'    => __( 'Add Media' ),
3339                 'search'      => __( 'Search' ),
3340                 'select'      => __( 'Select' ),
3341                 'cancel'      => __( 'Cancel' ),
3342                 'update'      => __( 'Update' ),
3343                 'replace'     => __( 'Replace' ),
3344                 'remove'      => __( 'Remove' ),
3345                 'back'        => __( 'Back' ),
3346                 /* translators: This is a would-be plural string used in the media manager.
3347                    If there is not a word you can use in your language to avoid issues with the
3348                    lack of plural support here, turn it into "selected: %d" then translate it.
3349                  */
3350                 'selected'    => __( '%d selected' ),
3351                 'dragInfo'    => __( 'Drag and drop to reorder media files.' ),
3352
3353                 // Upload
3354                 'uploadFilesTitle'  => __( 'Upload Files' ),
3355                 'uploadImagesTitle' => __( 'Upload Images' ),
3356
3357                 // Library
3358                 'mediaLibraryTitle'      => __( 'Media Library' ),
3359                 'insertMediaTitle'       => __( 'Insert Media' ),
3360                 'createNewGallery'       => __( 'Create a new gallery' ),
3361                 'createNewPlaylist'      => __( 'Create a new playlist' ),
3362                 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
3363                 'returnToLibrary'        => __( '&#8592; Return to library' ),
3364                 'allMediaItems'          => __( 'All media items' ),
3365                 'allDates'               => __( 'All dates' ),
3366                 'noItemsFound'           => __( 'No items found.' ),
3367                 'insertIntoPost'         => $post_type_object->labels->insert_into_item,
3368                 'unattached'             => __( 'Unattached' ),
3369                 'trash'                  => _x( 'Trash', 'noun' ),
3370                 'uploadedToThisPost'     => $post_type_object->labels->uploaded_to_this_item,
3371                 'warnDelete'             => __( "You are about to permanently delete this item.\n  'Cancel' to stop, 'OK' to delete." ),
3372                 'warnBulkDelete'         => __( "You are about to permanently delete these items.\n  'Cancel' to stop, 'OK' to delete." ),
3373                 'warnBulkTrash'          => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
3374                 'bulkSelect'             => __( 'Bulk Select' ),
3375                 'cancelSelection'        => __( 'Cancel Selection' ),
3376                 'trashSelected'          => __( 'Trash Selected' ),
3377                 'untrashSelected'        => __( 'Untrash Selected' ),
3378                 'deleteSelected'         => __( 'Delete Selected' ),
3379                 'deletePermanently'      => __( 'Delete Permanently' ),
3380                 'apply'                  => __( 'Apply' ),
3381                 'filterByDate'           => __( 'Filter by date' ),
3382                 'filterByType'           => __( 'Filter by type' ),
3383                 'searchMediaLabel'       => __( 'Search Media' ),
3384                 'noMedia'                => __( 'No media files found.' ),
3385
3386                 // Library Details
3387                 'attachmentDetails'  => __( 'Attachment Details' ),
3388
3389                 // From URL
3390                 'insertFromUrlTitle' => __( 'Insert from URL' ),
3391
3392                 // Featured Images
3393                 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
3394                 'setFeaturedImage'      => $post_type_object->labels->set_featured_image,
3395
3396                 // Gallery
3397                 'createGalleryTitle' => __( 'Create Gallery' ),
3398                 'editGalleryTitle'   => __( 'Edit Gallery' ),
3399                 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
3400                 'insertGallery'      => __( 'Insert gallery' ),
3401                 'updateGallery'      => __( 'Update gallery' ),
3402                 'addToGallery'       => __( 'Add to gallery' ),
3403                 'addToGalleryTitle'  => __( 'Add to Gallery' ),
3404                 'reverseOrder'       => __( 'Reverse order' ),
3405
3406                 // Edit Image
3407                 'imageDetailsTitle'     => __( 'Image Details' ),
3408                 'imageReplaceTitle'     => __( 'Replace Image' ),
3409                 'imageDetailsCancel'    => __( 'Cancel Edit' ),
3410                 'editImage'             => __( 'Edit Image' ),
3411
3412                 // Crop Image
3413                 'chooseImage' => __( 'Choose Image' ),
3414                 'selectAndCrop' => __( 'Select and Crop' ),
3415                 'skipCropping' => __( 'Skip Cropping' ),
3416                 'cropImage' => __( 'Crop Image' ),
3417                 'cropYourImage' => __( 'Crop your image' ),
3418                 'cropping' => __( 'Cropping&hellip;' ),
3419                 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
3420                 'cropError' => __( 'There has been an error cropping your image.' ),
3421
3422                 // Edit Audio
3423                 'audioDetailsTitle'     => __( 'Audio Details' ),
3424                 'audioReplaceTitle'     => __( 'Replace Audio' ),
3425                 'audioAddSourceTitle'   => __( 'Add Audio Source' ),
3426                 'audioDetailsCancel'    => __( 'Cancel Edit' ),
3427
3428                 // Edit Video
3429                 'videoDetailsTitle'     => __( 'Video Details' ),
3430                 'videoReplaceTitle'     => __( 'Replace Video' ),
3431                 'videoAddSourceTitle'   => __( 'Add Video Source' ),
3432                 'videoDetailsCancel'    => __( 'Cancel Edit' ),
3433                 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
3434                 'videoAddTrackTitle'    => __( 'Add Subtitles' ),
3435
3436                 // Playlist
3437                 'playlistDragInfo'    => __( 'Drag and drop to reorder tracks.' ),
3438                 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
3439                 'editPlaylistTitle'   => __( 'Edit Audio Playlist' ),
3440                 'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
3441                 'insertPlaylist'      => __( 'Insert audio playlist' ),
3442                 'updatePlaylist'      => __( 'Update audio playlist' ),
3443                 'addToPlaylist'       => __( 'Add to audio playlist' ),
3444                 'addToPlaylistTitle'  => __( 'Add to Audio Playlist' ),
3445
3446                 // Video Playlist
3447                 'videoPlaylistDragInfo'    => __( 'Drag and drop to reorder videos.' ),
3448                 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
3449                 'editVideoPlaylistTitle'   => __( 'Edit Video Playlist' ),
3450                 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
3451                 'insertVideoPlaylist'      => __( 'Insert video playlist' ),
3452                 'updateVideoPlaylist'      => __( 'Update video playlist' ),
3453                 'addToVideoPlaylist'       => __( 'Add to video playlist' ),
3454                 'addToVideoPlaylistTitle'  => __( 'Add to Video Playlist' ),
3455         );
3456
3457         /**
3458          * Filter the media view settings.
3459          *
3460          * @since 3.5.0
3461          *
3462          * @param array   $settings List of media view settings.
3463          * @param WP_Post $post     Post object.
3464          */
3465         $settings = apply_filters( 'media_view_settings', $settings, $post );
3466
3467         /**
3468          * Filter the media view strings.
3469          *
3470          * @since 3.5.0
3471          *
3472          * @param array   $strings List of media view strings.
3473          * @param WP_Post $post    Post object.
3474          */
3475         $strings = apply_filters( 'media_view_strings', $strings,  $post );
3476
3477         $strings['settings'] = $settings;
3478
3479         // Ensure we enqueue media-editor first, that way media-views is
3480         // registered internally before we try to localize it. see #24724.
3481         wp_enqueue_script( 'media-editor' );
3482         wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
3483
3484         wp_enqueue_script( 'media-audiovideo' );
3485         wp_enqueue_style( 'media-views' );
3486         if ( is_admin() ) {
3487                 wp_enqueue_script( 'mce-view' );
3488                 wp_enqueue_script( 'image-edit' );
3489         }
3490         wp_enqueue_style( 'imgareaselect' );
3491         wp_plupload_default_settings();
3492
3493         require_once ABSPATH . WPINC . '/media-template.php';
3494         add_action( 'admin_footer', 'wp_print_media_templates' );
3495         add_action( 'wp_footer', 'wp_print_media_templates' );
3496         add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
3497
3498         /**
3499          * Fires at the conclusion of wp_enqueue_media().
3500          *
3501          * @since 3.5.0
3502          */
3503         do_action( 'wp_enqueue_media' );
3504 }
3505
3506 /**
3507  * Retrieves media attached to the passed post.
3508  *
3509  * @since 3.6.0
3510  *
3511  * @param string      $type Mime type.
3512  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3513  * @return array Found attachments.
3514  */
3515 function get_attached_media( $type, $post = 0 ) {
3516         if ( ! $post = get_post( $post ) )
3517                 return array();
3518
3519         $args = array(
3520                 'post_parent' => $post->ID,
3521                 'post_type' => 'attachment',
3522                 'post_mime_type' => $type,
3523                 'posts_per_page' => -1,
3524                 'orderby' => 'menu_order',
3525                 'order' => 'ASC',
3526         );
3527
3528         /**
3529          * Filter arguments used to retrieve media attached to the given post.
3530          *
3531          * @since 3.6.0
3532          *
3533          * @param array  $args Post query arguments.
3534          * @param string $type Mime type of the desired media.
3535          * @param mixed  $post Post ID or object.
3536          */
3537         $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
3538
3539         $children = get_children( $args );
3540
3541         /**
3542          * Filter the list of media attached to the given post.
3543          *
3544          * @since 3.6.0
3545          *
3546          * @param array  $children Associative array of media attached to the given post.
3547          * @param string $type     Mime type of the media desired.
3548          * @param mixed  $post     Post ID or object.
3549          */
3550         return (array) apply_filters( 'get_attached_media', $children, $type, $post );
3551 }
3552
3553 /**
3554  * Check the content blob for an audio, video, object, embed, or iframe tags.
3555  *
3556  * @since 3.6.0
3557  *
3558  * @param string $content A string which might contain media data.
3559  * @param array  $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
3560  * @return array A list of found HTML media embeds.
3561  */
3562 function get_media_embedded_in_content( $content, $types = null ) {
3563         $html = array();
3564
3565         /**
3566          * Filter the embedded media types that are allowed to be returned from the content blob.
3567          *
3568          * @since 4.2.0
3569          *
3570          * @param array $allowed_media_types An array of allowed media types. Default media types are
3571          *                                   'audio', 'video', 'object', 'embed', and 'iframe'.
3572          */
3573         $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
3574
3575         if ( ! empty( $types ) ) {
3576                 if ( ! is_array( $types ) ) {
3577                         $types = array( $types );
3578                 }
3579
3580                 $allowed_media_types = array_intersect( $allowed_media_types, $types );
3581         }
3582
3583         $tags = implode( '|', $allowed_media_types );
3584
3585         if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
3586                 foreach ( $matches[0] as $match ) {
3587                         $html[] = $match;
3588                 }
3589         }
3590
3591         return $html;
3592 }
3593
3594 /**
3595  * Retrieves galleries from the passed post's content.
3596  *
3597  * @since 3.6.0
3598  *
3599  * @param int|WP_Post $post Post ID or object.
3600  * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
3601  * @return array A list of arrays, each containing gallery data and srcs parsed
3602  *               from the expanded shortcode.
3603  */
3604 function get_post_galleries( $post, $html = true ) {
3605         if ( ! $post = get_post( $post ) )
3606                 return array();
3607
3608         if ( ! has_shortcode( $post->post_content, 'gallery' ) )
3609                 return array();
3610
3611         $galleries = array();
3612         if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
3613                 foreach ( $matches as $shortcode ) {
3614                         if ( 'gallery' === $shortcode[2] ) {
3615                                 $srcs = array();
3616
3617                                 $gallery = do_shortcode_tag( $shortcode );
3618                                 if ( $html ) {
3619                                         $galleries[] = $gallery;
3620                                 } else {
3621                                         preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
3622                                         if ( ! empty( $src ) ) {
3623                                                 foreach ( $src as $s )
3624                                                         $srcs[] = $s[2];
3625                                         }
3626
3627                                         $data = shortcode_parse_atts( $shortcode[3] );
3628                                         $data['src'] = array_values( array_unique( $srcs ) );
3629                                         $galleries[] = $data;
3630                                 }
3631                         }
3632                 }
3633         }
3634
3635         /**
3636          * Filter the list of all found galleries in the given post.
3637          *
3638          * @since 3.6.0
3639          *
3640          * @param array   $galleries Associative array of all found post galleries.
3641          * @param WP_Post $post      Post object.
3642          */
3643         return apply_filters( 'get_post_galleries', $galleries, $post );
3644 }
3645
3646 /**
3647  * Check a specified post's content for gallery and, if present, return the first
3648  *
3649  * @since 3.6.0
3650  *
3651  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
3652  * @param bool        $html Optional. Whether to return HTML or data. Default is true.
3653  * @return string|array Gallery data and srcs parsed from the expanded shortcode.
3654  */
3655 function get_post_gallery( $post = 0, $html = true ) {
3656         $galleries = get_post_galleries( $post, $html );
3657         $gallery = reset( $galleries );
3658
3659         /**
3660          * Filter the first-found post gallery.
3661          *
3662          * @since 3.6.0
3663          *
3664          * @param array       $gallery   The first-found post gallery.
3665          * @param int|WP_Post $post      Post ID or object.
3666          * @param array       $galleries Associative array of all found post galleries.
3667          */
3668         return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
3669 }
3670
3671 /**
3672  * Retrieve the image srcs from galleries from a post's content, if present
3673  *
3674  * @since 3.6.0
3675  *
3676  * @see get_post_galleries()
3677  *
3678  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3679  * @return array A list of lists, each containing image srcs parsed.
3680  *               from an expanded shortcode
3681  */
3682 function get_post_galleries_images( $post = 0 ) {
3683         $galleries = get_post_galleries( $post, false );
3684         return wp_list_pluck( $galleries, 'src' );
3685 }
3686
3687 /**
3688  * Checks a post's content for galleries and return the image srcs for the first found gallery
3689  *
3690  * @since 3.6.0
3691  *
3692  * @see get_post_gallery()
3693  *
3694  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
3695  * @return array A list of a gallery's image srcs in order.
3696  */
3697 function get_post_gallery_images( $post = 0 ) {
3698         $gallery = get_post_gallery( $post, false );
3699         return empty( $gallery['src'] ) ? array() : $gallery['src'];
3700 }
3701
3702 /**
3703  * Maybe attempts to generate attachment metadata, if missing.
3704  *
3705  * @since 3.9.0
3706  *
3707  * @param WP_Post $attachment Attachment object.
3708  */
3709 function wp_maybe_generate_attachment_metadata( $attachment ) {
3710         if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
3711                 return;
3712         }
3713
3714         $file = get_attached_file( $attachment_id );
3715         $meta = wp_get_attachment_metadata( $attachment_id );
3716         if ( empty( $meta ) && file_exists( $file ) ) {
3717                 $_meta = get_post_meta( $attachment_id );
3718                 $regeneration_lock = 'wp_generating_att_' . $attachment_id;
3719                 if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
3720                         set_transient( $regeneration_lock, $file );
3721                         wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
3722                         delete_transient( $regeneration_lock );
3723                 }
3724         }
3725 }
3726
3727 /**
3728  * Tries to convert an attachment URL into a post ID.
3729  *
3730  * @since 4.0.0
3731  *
3732  * @global wpdb $wpdb WordPress database abstraction object.
3733  *
3734  * @param string $url The URL to resolve.
3735  * @return int The found post ID, or 0 on failure.
3736  */
3737 function attachment_url_to_postid( $url ) {
3738         global $wpdb;
3739
3740         $dir = wp_get_upload_dir();
3741         $path = $url;
3742
3743         $site_url = parse_url( $dir['url'] );
3744         $image_path = parse_url( $path );
3745
3746         //force the protocols to match if needed
3747         if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
3748                 $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
3749         }
3750
3751         if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
3752                 $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
3753         }
3754
3755         $sql = $wpdb->prepare(
3756                 "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
3757                 $path
3758         );
3759         $post_id = $wpdb->get_var( $sql );
3760
3761         /**
3762          * Filter an attachment id found by URL.
3763          *
3764          * @since 4.2.0
3765          *
3766          * @param int|null $post_id The post_id (if any) found by the function.
3767          * @param string   $url     The URL being looked up.
3768          */
3769         return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
3770 }
3771
3772 /**
3773  * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
3774  *
3775  * @since 4.0.0
3776  *
3777  * @global string $wp_version
3778  *
3779  * @return array The relevant CSS file URLs.
3780  */
3781 function wpview_media_sandbox_styles() {
3782         $version = 'ver=' . $GLOBALS['wp_version'];
3783         $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
3784         $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
3785
3786         return array( $mediaelement, $wpmediaelement );
3787 }