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