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