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