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