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