Make WordPress Core

Ticket #31614: media.php

File media.php, 111.5 KB (added by andrewgstreet, 12 years ago)

Add actions to playlist templates

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