]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/media.php
WordPress 3.4
[autoinstalls/wordpress.git] / wp-includes / media.php
1 <?php
2 /**
3  * WordPress API for media display.
4  *
5  * @package WordPress
6  */
7
8 /**
9  * Scale down the default size of an image.
10  *
11  * This is so that the image is a better fit for the editor and theme.
12  *
13  * The $size parameter accepts either an array or a string. The supported string
14  * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
15  * 128 width and 96 height in pixels. Also supported for the string value is
16  * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
17  * than the supported will result in the content_width size or 500 if that is
18  * not set.
19  *
20  * Finally, there is a filter named 'editor_max_image_size', that will be called
21  * on the calculated array for width and height, respectively. The second
22  * parameter will be the value that was in the $size parameter. The returned
23  * type for the hook is an array with the width as the first element and the
24  * height as the second element.
25  *
26  * @since 2.5.0
27  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
28  *
29  * @param int $width Width of the image
30  * @param int $height Height of the image
31  * @param string|array $size Size of what the result image should be.
32  * @return array Width and height of what the result image should resize to.
33  */
34 function image_constrain_size_for_editor($width, $height, $size = 'medium') {
35         global $content_width, $_wp_additional_image_sizes;
36
37         if ( is_array($size) ) {
38                 $max_width = $size[0];
39                 $max_height = $size[1];
40         }
41         elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
42                 $max_width = intval(get_option('thumbnail_size_w'));
43                 $max_height = intval(get_option('thumbnail_size_h'));
44                 // last chance thumbnail size defaults
45                 if ( !$max_width && !$max_height ) {
46                         $max_width = 128;
47                         $max_height = 96;
48                 }
49         }
50         elseif ( $size == 'medium' ) {
51                 $max_width = intval(get_option('medium_size_w'));
52                 $max_height = intval(get_option('medium_size_h'));
53                 // if no width is set, default to the theme content width if available
54         }
55         elseif ( $size == 'large' ) {
56                 // We're inserting a large size image into the editor. If it's a really
57                 // big image we'll scale it down to fit reasonably within the editor
58                 // itself, and within the theme's content width if it's known. The user
59                 // can resize it in the editor if they wish.
60                 $max_width = intval(get_option('large_size_w'));
61                 $max_height = intval(get_option('large_size_h'));
62                 if ( intval($content_width) > 0 )
63                         $max_width = min( intval($content_width), $max_width );
64         } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
65                 $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
66                 $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
67                 if ( intval($content_width) > 0 && is_admin() ) // Only in admin. Assume that theme authors know what they're doing.
68                         $max_width = min( intval($content_width), $max_width );
69         }
70         // $size == 'full' has no constraint
71         else {
72                 $max_width = $width;
73                 $max_height = $height;
74         }
75
76         list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size );
77
78         return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
79 }
80
81 /**
82  * Retrieve width and height attributes using given width and height values.
83  *
84  * Both attributes are required in the sense that both parameters must have a
85  * value, but are optional in that if you set them to false or null, then they
86  * will not be added to the returned string.
87  *
88  * You can set the value using a string, but it will only take numeric values.
89  * If you wish to put 'px' after the numbers, then it will be stripped out of
90  * the return.
91  *
92  * @since 2.5.0
93  *
94  * @param int|string $width Optional. Width attribute value.
95  * @param int|string $height Optional. Height attribute value.
96  * @return string HTML attributes for width and, or height.
97  */
98 function image_hwstring($width, $height) {
99         $out = '';
100         if ($width)
101                 $out .= 'width="'.intval($width).'" ';
102         if ($height)
103                 $out .= 'height="'.intval($height).'" ';
104         return $out;
105 }
106
107 /**
108  * Scale an image to fit a particular size (such as 'thumb' or 'medium').
109  *
110  * Array with image url, width, height, and whether is intermediate size, in
111  * that order is returned on success is returned. $is_intermediate is true if
112  * $url is a resized image, false if it is the original.
113  *
114  * The URL might be the original image, or it might be a resized version. This
115  * function won't create a new resized copy, it will just return an already
116  * resized one if it exists.
117  *
118  * A plugin may use the 'image_downsize' filter to hook into and offer image
119  * resizing services for images. The hook must return an array with the same
120  * elements that are returned in the function. The first element being the URL
121  * to the new image that was resized.
122  *
123  * @since 2.5.0
124  * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide
125  *              resize services.
126  *
127  * @param int $id Attachment ID for image.
128  * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
129  * @return bool|array False on failure, array on success.
130  */
131 function image_downsize($id, $size = 'medium') {
132
133         if ( !wp_attachment_is_image($id) )
134                 return false;
135
136         $img_url = wp_get_attachment_url($id);
137         $meta = wp_get_attachment_metadata($id);
138         $width = $height = 0;
139         $is_intermediate = false;
140         $img_url_basename = wp_basename($img_url);
141
142         // plugins can use this to provide resize services
143         if ( $out = apply_filters('image_downsize', false, $id, $size) )
144                 return $out;
145
146         // try for a new style intermediate size
147         if ( $intermediate = image_get_intermediate_size($id, $size) ) {
148                 $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
149                 $width = $intermediate['width'];
150                 $height = $intermediate['height'];
151                 $is_intermediate = true;
152         }
153         elseif ( $size == 'thumbnail' ) {
154                 // fall back to the old thumbnail
155                 if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
156                         $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
157                         $width = $info[0];
158                         $height = $info[1];
159                         $is_intermediate = true;
160                 }
161         }
162         if ( !$width && !$height && isset($meta['width'], $meta['height']) ) {
163                 // any other type: use the real image
164                 $width = $meta['width'];
165                 $height = $meta['height'];
166         }
167
168         if ( $img_url) {
169                 // we have the actual image size, but might need to further constrain it if content_width is narrower
170                 list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
171
172                 return array( $img_url, $width, $height, $is_intermediate );
173         }
174         return false;
175
176 }
177
178 /**
179  * Registers a new image size
180  *
181  * @since 2.9.0
182  */
183 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
184         global $_wp_additional_image_sizes;
185         $_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
186 }
187
188 /**
189  * Registers an image size for the post thumbnail
190  *
191  * @since 2.9.0
192  */
193 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
194         add_image_size( 'post-thumbnail', $width, $height, $crop );
195 }
196
197 /**
198  * An <img src /> tag for an image attachment, scaling it down if requested.
199  *
200  * The filter 'get_image_tag_class' allows for changing the class name for the
201  * image without having to use regular expressions on the HTML content. The
202  * parameters are: what WordPress will use for the class, the Attachment ID,
203  * image align value, and the size the image should be.
204  *
205  * The second filter 'get_image_tag' has the HTML content, which can then be
206  * further manipulated by a plugin to change all attribute values and even HTML
207  * content.
208  *
209  * @since 2.5.0
210  *
211  * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element
212  *              class attribute.
213  * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with
214  *              all attributes.
215  *
216  * @param int $id Attachment ID.
217  * @param string $alt Image Description for the alt attribute.
218  * @param string $title Image Description for the title attribute.
219  * @param string $align Part of the class name for aligning the image.
220  * @param string $size Optional. Default is 'medium'.
221  * @return string HTML IMG element for given image attachment
222  */
223 function get_image_tag($id, $alt, $title, $align, $size='medium') {
224
225         list( $img_src, $width, $height ) = image_downsize($id, $size);
226         $hwstring = image_hwstring($width, $height);
227
228         $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
229         $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
230
231         $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />';
232
233         $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
234
235         return $html;
236 }
237
238 /**
239  * Load an image from a string, if PHP supports it.
240  *
241  * @since 2.1.0
242  *
243  * @param string $file Filename of the image to load.
244  * @return resource The resulting image resource on success, Error string on failure.
245  */
246 function wp_load_image( $file ) {
247         if ( is_numeric( $file ) )
248                 $file = get_attached_file( $file );
249
250         if ( ! file_exists( $file ) )
251                 return sprintf(__('File &#8220;%s&#8221; doesn&#8217;t exist?'), $file);
252
253         if ( ! function_exists('imagecreatefromstring') )
254                 return __('The GD image library is not installed.');
255
256         // Set artificially high because GD uses uncompressed images in memory
257         @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
258         $image = imagecreatefromstring( file_get_contents( $file ) );
259
260         if ( !is_resource( $image ) )
261                 return sprintf(__('File &#8220;%s&#8221; is not an image.'), $file);
262
263         return $image;
264 }
265
266 /**
267  * Calculates the new dimensions for a downsampled image.
268  *
269  * If either width or height are empty, no constraint is applied on
270  * that dimension.
271  *
272  * @since 2.5.0
273  *
274  * @param int $current_width Current width of the image.
275  * @param int $current_height Current height of the image.
276  * @param int $max_width Optional. Maximum wanted width.
277  * @param int $max_height Optional. Maximum wanted height.
278  * @return array First item is the width, the second item is the height.
279  */
280 function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
281         if ( !$max_width and !$max_height )
282                 return array( $current_width, $current_height );
283
284         $width_ratio = $height_ratio = 1.0;
285         $did_width = $did_height = false;
286
287         if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
288                 $width_ratio = $max_width / $current_width;
289                 $did_width = true;
290         }
291
292         if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
293                 $height_ratio = $max_height / $current_height;
294                 $did_height = true;
295         }
296
297         // Calculate the larger/smaller ratios
298         $smaller_ratio = min( $width_ratio, $height_ratio );
299         $larger_ratio  = max( $width_ratio, $height_ratio );
300
301         if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
302                 // The larger ratio is too big. It would result in an overflow.
303                 $ratio = $smaller_ratio;
304         else
305                 // The larger ratio fits, and is likely to be a more "snug" fit.
306                 $ratio = $larger_ratio;
307
308         $w = intval( $current_width  * $ratio );
309         $h = intval( $current_height * $ratio );
310
311         // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
312         // 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.
313         // Thus we look for dimensions that are one pixel shy of the max value and bump them up
314         if ( $did_width && $w == $max_width - 1 )
315                 $w = $max_width; // Round it up
316         if ( $did_height && $h == $max_height - 1 )
317                 $h = $max_height; // Round it up
318
319         return array( $w, $h );
320 }
321
322 /**
323  * Retrieve calculated resized dimensions for use in imagecopyresampled().
324  *
325  * Calculate dimensions and coordinates for a resized image that fits within a
326  * specified width and height. If $crop is true, the largest matching central
327  * portion of the image will be cropped out and resized to the required size.
328  *
329  * @since 2.5.0
330  * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and
331  *              $crop to provide custom resize dimensions.
332  *
333  * @param int $orig_w Original width.
334  * @param int $orig_h Original height.
335  * @param int $dest_w New width.
336  * @param int $dest_h New height.
337  * @param bool $crop Optional, default is false. Whether to crop image or resize.
338  * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function.
339  */
340 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
341
342         if ($orig_w <= 0 || $orig_h <= 0)
343                 return false;
344         // at least one of dest_w or dest_h must be specific
345         if ($dest_w <= 0 && $dest_h <= 0)
346                 return false;
347
348         // plugins can use this to provide custom resize dimensions
349         $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
350         if ( null !== $output )
351                 return $output;
352
353         if ( $crop ) {
354                 // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
355                 $aspect_ratio = $orig_w / $orig_h;
356                 $new_w = min($dest_w, $orig_w);
357                 $new_h = min($dest_h, $orig_h);
358
359                 if ( !$new_w ) {
360                         $new_w = intval($new_h * $aspect_ratio);
361                 }
362
363                 if ( !$new_h ) {
364                         $new_h = intval($new_w / $aspect_ratio);
365                 }
366
367                 $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
368
369                 $crop_w = round($new_w / $size_ratio);
370                 $crop_h = round($new_h / $size_ratio);
371
372                 $s_x = floor( ($orig_w - $crop_w) / 2 );
373                 $s_y = floor( ($orig_h - $crop_h) / 2 );
374         } else {
375                 // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
376                 $crop_w = $orig_w;
377                 $crop_h = $orig_h;
378
379                 $s_x = 0;
380                 $s_y = 0;
381
382                 list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
383         }
384
385         // if the resulting image would be the same size or larger we don't want to resize it
386         if ( $new_w >= $orig_w && $new_h >= $orig_h )
387                 return false;
388
389         // the return array matches the parameters to imagecopyresampled()
390         // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
391         return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
392
393 }
394
395 /**
396  * Scale down an image to fit a particular size and save a new copy of the image.
397  *
398  * The PNG transparency will be preserved using the function, as well as the
399  * image type. If the file going in is PNG, then the resized image is going to
400  * be PNG. The only supported image types are PNG, GIF, and JPEG.
401  *
402  * Some functionality requires API to exist, so some PHP version may lose out
403  * support. This is not the fault of WordPress (where functionality is
404  * downgraded, not actual defects), but of your PHP version.
405  *
406  * @since 2.5.0
407  *
408  * @param string $file Image file path.
409  * @param int $max_w Maximum width to resize to.
410  * @param int $max_h Maximum height to resize to.
411  * @param bool $crop Optional. Whether to crop image or resize.
412  * @param string $suffix Optional. File suffix.
413  * @param string $dest_path Optional. New image file path.
414  * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
415  * @return mixed WP_Error on failure. String with new destination path.
416  */
417 function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
418
419         $image = wp_load_image( $file );
420         if ( !is_resource( $image ) )
421                 return new WP_Error( 'error_loading_image', $image, $file );
422
423         $size = @getimagesize( $file );
424         if ( !$size )
425                 return new WP_Error('invalid_image', __('Could not read image size'), $file);
426         list($orig_w, $orig_h, $orig_type) = $size;
427
428         $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
429         if ( !$dims )
430                 return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
431         list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
432
433         $newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
434
435         imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
436
437         // convert from full colors to index colors, like original PNG.
438         if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
439                 imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
440
441         // we don't need the original in memory anymore
442         imagedestroy( $image );
443
444         // $suffix will be appended to the destination filename, just before the extension
445         if ( !$suffix )
446                 $suffix = "{$dst_w}x{$dst_h}";
447
448         $info = pathinfo($file);
449         $dir = $info['dirname'];
450         $ext = $info['extension'];
451         $name = wp_basename($file, ".$ext");
452
453         if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
454                 $dir = $_dest_path;
455         $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
456
457         if ( IMAGETYPE_GIF == $orig_type ) {
458                 if ( !imagegif( $newimage, $destfilename ) )
459                         return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
460         } elseif ( IMAGETYPE_PNG == $orig_type ) {
461                 if ( !imagepng( $newimage, $destfilename ) )
462                         return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
463         } else {
464                 // all other formats are converted to jpg
465                 if ( 'jpg' != $ext && 'jpeg' != $ext )
466                         $destfilename = "{$dir}/{$name}-{$suffix}.jpg";
467                 if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
468                         return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
469         }
470
471         imagedestroy( $newimage );
472
473         // Set correct file permissions
474         $stat = stat( dirname( $destfilename ));
475         $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
476         @ chmod( $destfilename, $perms );
477
478         return $destfilename;
479 }
480
481 /**
482  * Resize an image to make a thumbnail or intermediate size.
483  *
484  * The returned array has the file size, the image width, and image height. The
485  * filter 'image_make_intermediate_size' can be used to hook in and change the
486  * values of the returned array. The only parameter is the resized file path.
487  *
488  * @since 2.5.0
489  *
490  * @param string $file File path.
491  * @param int $width Image width.
492  * @param int $height Image height.
493  * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
494  * @return bool|array False, if no image was created. Metadata array on success.
495  */
496 function image_make_intermediate_size($file, $width, $height, $crop=false) {
497         if ( $width || $height ) {
498                 $resized_file = image_resize($file, $width, $height, $crop);
499                 if ( !is_wp_error($resized_file) && $resized_file && $info = getimagesize($resized_file) ) {
500                         $resized_file = apply_filters('image_make_intermediate_size', $resized_file);
501                         return array(
502                                 'file' => wp_basename( $resized_file ),
503                                 'width' => $info[0],
504                                 'height' => $info[1],
505                         );
506                 }
507         }
508         return false;
509 }
510
511 /**
512  * Retrieve the image's intermediate size (resized) path, width, and height.
513  *
514  * The $size parameter can be an array with the width and height respectively.
515  * If the size matches the 'sizes' metadata array for width and height, then it
516  * will be used. If there is no direct match, then the nearest image size larger
517  * than the specified size will be used. If nothing is found, then the function
518  * will break out and return false.
519  *
520  * The metadata 'sizes' is used for compatible sizes that can be used for the
521  * parameter $size value.
522  *
523  * The url path will be given, when the $size parameter is a string.
524  *
525  * If you are passing an array for the $size, you should consider using
526  * add_image_size() so that a cropped version is generated. It's much more
527  * efficient than having to find the closest-sized image and then having the
528  * browser scale down the image.
529  *
530  * @since 2.5.0
531  * @see add_image_size()
532  *
533  * @param int $post_id Attachment ID for image.
534  * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
535  * @return bool|array False on failure or array of file path, width, and height on success.
536  */
537 function image_get_intermediate_size($post_id, $size='thumbnail') {
538         if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
539                 return false;
540
541         // get the best one for a specified set of dimensions
542         if ( is_array($size) && !empty($imagedata['sizes']) ) {
543                 foreach ( $imagedata['sizes'] as $_size => $data ) {
544                         // already cropped to width or height; so use this size
545                         if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
546                                 $file = $data['file'];
547                                 list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
548                                 return compact( 'file', 'width', 'height' );
549                         }
550                         // add to lookup table: area => size
551                         $areas[$data['width'] * $data['height']] = $_size;
552                 }
553                 if ( !$size || !empty($areas) ) {
554                         // find for the smallest image not smaller than the desired size
555                         ksort($areas);
556                         foreach ( $areas as $_size ) {
557                                 $data = $imagedata['sizes'][$_size];
558                                 if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
559                                         // Skip images with unexpectedly divergent aspect ratios (crops)
560                                         // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
561                                         $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
562                                         // 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
563                                         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'] ) ) )
564                                                 continue;
565                                         // If we're still here, then we're going to use this size
566                                         $file = $data['file'];
567                                         list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
568                                         return compact( 'file', 'width', 'height' );
569                                 }
570                         }
571                 }
572         }
573
574         if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
575                 return false;
576
577         $data = $imagedata['sizes'][$size];
578         // include the full filesystem path of the intermediate file
579         if ( empty($data['path']) && !empty($data['file']) ) {
580                 $file_url = wp_get_attachment_url($post_id);
581                 $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
582                 $data['url'] = path_join( dirname($file_url), $data['file'] );
583         }
584         return $data;
585 }
586
587 /**
588  * Get the available image sizes
589  * @since 3.0.0
590  * @return array Returns a filtered array of image size strings
591  */
592 function get_intermediate_image_sizes() {
593         global $_wp_additional_image_sizes;
594         $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
595         if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
596                 $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
597
598         return apply_filters( 'intermediate_image_sizes', $image_sizes );
599 }
600
601 /**
602  * Retrieve an image to represent an attachment.
603  *
604  * A mime icon for files, thumbnail or intermediate size for images.
605  *
606  * @since 2.5.0
607  *
608  * @param int $attachment_id Image attachment ID.
609  * @param string $size Optional, default is 'thumbnail'.
610  * @param bool $icon Optional, default is false. Whether it is an icon.
611  * @return bool|array Returns an array (url, width, height), or false, if no image is available.
612  */
613 function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
614
615         // get a thumbnail or intermediate image if there is one
616         if ( $image = image_downsize($attachment_id, $size) )
617                 return $image;
618
619         $src = false;
620
621         if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
622                 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
623                 $src_file = $icon_dir . '/' . wp_basename($src);
624                 @list($width, $height) = getimagesize($src_file);
625         }
626         if ( $src && $width && $height )
627                 return array( $src, $width, $height );
628         return false;
629 }
630
631 /**
632  * Get an HTML img element representing an image attachment
633  *
634  * While $size will accept an array, it is better to register a size with
635  * add_image_size() so that a cropped version is generated. It's much more
636  * efficient than having to find the closest-sized image and then having the
637  * browser scale down the image.
638  *
639  * @see add_image_size()
640  * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
641  * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
642  * @since 2.5.0
643  *
644  * @param int $attachment_id Image attachment ID.
645  * @param string $size Optional, default is 'thumbnail'.
646  * @param bool $icon Optional, default is false. Whether it is an icon.
647  * @return string HTML img element or empty string on failure.
648  */
649 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
650
651         $html = '';
652         $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
653         if ( $image ) {
654                 list($src, $width, $height) = $image;
655                 $hwstring = image_hwstring($width, $height);
656                 if ( is_array($size) )
657                         $size = join('x', $size);
658                 $attachment =& get_post($attachment_id);
659                 $default_attr = array(
660                         'src'   => $src,
661                         'class' => "attachment-$size",
662                         'alt'   => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
663                         'title' => trim(strip_tags( $attachment->post_title )),
664                 );
665                 if ( empty($default_attr['alt']) )
666                         $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
667                 if ( empty($default_attr['alt']) )
668                         $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
669
670                 $attr = wp_parse_args($attr, $default_attr);
671                 $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
672                 $attr = array_map( 'esc_attr', $attr );
673                 $html = rtrim("<img $hwstring");
674                 foreach ( $attr as $name => $value ) {
675                         $html .= " $name=" . '"' . $value . '"';
676                 }
677                 $html .= ' />';
678         }
679
680         return $html;
681 }
682
683 /**
684  * Adds a 'wp-post-image' class to post thumbnails
685  * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
686  * dynamically add/remove itself so as to only filter post thumbnails
687  *
688  * @since 2.9.0
689  * @param array $attr Attributes including src, class, alt, title
690  * @return array
691  */
692 function _wp_post_thumbnail_class_filter( $attr ) {
693         $attr['class'] .= ' wp-post-image';
694         return $attr;
695 }
696
697 /**
698  * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
699  *
700  * @since 2.9.0
701  */
702 function _wp_post_thumbnail_class_filter_add( $attr ) {
703         add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
704 }
705
706 /**
707  * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
708  *
709  * @since 2.9.0
710  */
711 function _wp_post_thumbnail_class_filter_remove( $attr ) {
712         remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
713 }
714
715 add_shortcode('wp_caption', 'img_caption_shortcode');
716 add_shortcode('caption', 'img_caption_shortcode');
717
718 /**
719  * The Caption shortcode.
720  *
721  * Allows a plugin to replace the content that would otherwise be returned. The
722  * filter is 'img_caption_shortcode' and passes an empty string, the attr
723  * parameter and the content parameter values.
724  *
725  * The supported attributes for the shortcode are 'id', 'align', 'width', and
726  * 'caption'.
727  *
728  * @since 2.6.0
729  *
730  * @param array $attr Attributes attributed to the shortcode.
731  * @param string $content Optional. Shortcode content.
732  * @return string
733  */
734 function img_caption_shortcode($attr, $content = null) {
735         // New-style shortcode with the caption inside the shortcode with the link and image tags.
736         if ( ! isset( $attr['caption'] ) ) {
737                 if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
738                         $content = $matches[1];
739                         $attr['caption'] = trim( $matches[2] );
740                 }
741         }
742
743         // Allow plugins/themes to override the default caption template.
744         $output = apply_filters('img_caption_shortcode', '', $attr, $content);
745         if ( $output != '' )
746                 return $output;
747
748         extract(shortcode_atts(array(
749                 'id'    => '',
750                 'align' => 'alignnone',
751                 'width' => '',
752                 'caption' => ''
753         ), $attr));
754
755         if ( 1 > (int) $width || empty($caption) )
756                 return $content;
757
758         if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
759
760         return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
761         . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
762 }
763
764 add_shortcode('gallery', 'gallery_shortcode');
765
766 /**
767  * The Gallery shortcode.
768  *
769  * This implements the functionality of the Gallery Shortcode for displaying
770  * WordPress images on a post.
771  *
772  * @since 2.5.0
773  *
774  * @param array $attr Attributes of the shortcode.
775  * @return string HTML content to display gallery.
776  */
777 function gallery_shortcode($attr) {
778         global $post;
779
780         static $instance = 0;
781         $instance++;
782
783         // Allow plugins/themes to override the default gallery template.
784         $output = apply_filters('post_gallery', '', $attr);
785         if ( $output != '' )
786                 return $output;
787
788         // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
789         if ( isset( $attr['orderby'] ) ) {
790                 $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
791                 if ( !$attr['orderby'] )
792                         unset( $attr['orderby'] );
793         }
794
795         extract(shortcode_atts(array(
796                 'order'      => 'ASC',
797                 'orderby'    => 'menu_order ID',
798                 'id'         => $post->ID,
799                 'itemtag'    => 'dl',
800                 'icontag'    => 'dt',
801                 'captiontag' => 'dd',
802                 'columns'    => 3,
803                 'size'       => 'thumbnail',
804                 'include'    => '',
805                 'exclude'    => ''
806         ), $attr));
807
808         $id = intval($id);
809         if ( 'RAND' == $order )
810                 $orderby = 'none';
811
812         if ( !empty($include) ) {
813                 $include = preg_replace( '/[^0-9,]+/', '', $include );
814                 $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
815
816                 $attachments = array();
817                 foreach ( $_attachments as $key => $val ) {
818                         $attachments[$val->ID] = $_attachments[$key];
819                 }
820         } elseif ( !empty($exclude) ) {
821                 $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
822                 $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
823         } else {
824                 $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
825         }
826
827         if ( empty($attachments) )
828                 return '';
829
830         if ( is_feed() ) {
831                 $output = "\n";
832                 foreach ( $attachments as $att_id => $attachment )
833                         $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
834                 return $output;
835         }
836
837         $itemtag = tag_escape($itemtag);
838         $captiontag = tag_escape($captiontag);
839         $columns = intval($columns);
840         $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
841         $float = is_rtl() ? 'right' : 'left';
842
843         $selector = "gallery-{$instance}";
844
845         $gallery_style = $gallery_div = '';
846         if ( apply_filters( 'use_default_gallery_style', true ) )
847                 $gallery_style = "
848                 <style type='text/css'>
849                         #{$selector} {
850                                 margin: auto;
851                         }
852                         #{$selector} .gallery-item {
853                                 float: {$float};
854                                 margin-top: 10px;
855                                 text-align: center;
856                                 width: {$itemwidth}%;
857                         }
858                         #{$selector} img {
859                                 border: 2px solid #cfcfcf;
860                         }
861                         #{$selector} .gallery-caption {
862                                 margin-left: 0;
863                         }
864                 </style>
865                 <!-- see gallery_shortcode() in wp-includes/media.php -->";
866         $size_class = sanitize_html_class( $size );
867         $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
868         $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
869
870         $i = 0;
871         foreach ( $attachments as $id => $attachment ) {
872                 $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
873
874                 $output .= "<{$itemtag} class='gallery-item'>";
875                 $output .= "
876                         <{$icontag} class='gallery-icon'>
877                                 $link
878                         </{$icontag}>";
879                 if ( $captiontag && trim($attachment->post_excerpt) ) {
880                         $output .= "
881                                 <{$captiontag} class='wp-caption-text gallery-caption'>
882                                 " . wptexturize($attachment->post_excerpt) . "
883                                 </{$captiontag}>";
884                 }
885                 $output .= "</{$itemtag}>";
886                 if ( $columns > 0 && ++$i % $columns == 0 )
887                         $output .= '<br style="clear: both" />';
888         }
889
890         $output .= "
891                         <br style='clear: both;' />
892                 </div>\n";
893
894         return $output;
895 }
896
897 /**
898  * Display previous image link that has the same post parent.
899  *
900  * @since 2.5.0
901  * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
902  * @param string $text Optional, default is false. If included, link will reflect $text variable.
903  * @return string HTML content.
904  */
905 function previous_image_link($size = 'thumbnail', $text = false) {
906         adjacent_image_link(true, $size, $text);
907 }
908
909 /**
910  * Display next image link that has the same post parent.
911  *
912  * @since 2.5.0
913  * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
914  * @param string $text Optional, default is false. If included, link will reflect $text variable.
915  * @return string HTML content.
916  */
917 function next_image_link($size = 'thumbnail', $text = false) {
918         adjacent_image_link(false, $size, $text);
919 }
920
921 /**
922  * Display next or previous image link that has the same post parent.
923  *
924  * Retrieves the current attachment object from the $post global.
925  *
926  * @since 2.5.0
927  *
928  * @param bool $prev Optional. Default is true to display previous link, false for next.
929  */
930 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
931         global $post;
932         $post = get_post($post);
933         $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') ));
934
935         foreach ( $attachments as $k => $attachment )
936                 if ( $attachment->ID == $post->ID )
937                         break;
938
939         $k = $prev ? $k - 1 : $k + 1;
940
941         if ( isset($attachments[$k]) )
942                 echo wp_get_attachment_link($attachments[$k]->ID, $size, true, false, $text);
943 }
944
945 /**
946  * Retrieve taxonomies attached to the attachment.
947  *
948  * @since 2.5.0
949  *
950  * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
951  * @return array Empty array on failure. List of taxonomies on success.
952  */
953 function get_attachment_taxonomies($attachment) {
954         if ( is_int( $attachment ) )
955                 $attachment = get_post($attachment);
956         else if ( is_array($attachment) )
957                 $attachment = (object) $attachment;
958
959         if ( ! is_object($attachment) )
960                 return array();
961
962         $filename = basename($attachment->guid);
963
964         $objects = array('attachment');
965
966         if ( false !== strpos($filename, '.') )
967                 $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
968         if ( !empty($attachment->post_mime_type) ) {
969                 $objects[] = 'attachment:' . $attachment->post_mime_type;
970                 if ( false !== strpos($attachment->post_mime_type, '/') )
971                         foreach ( explode('/', $attachment->post_mime_type) as $token )
972                                 if ( !empty($token) )
973                                         $objects[] = "attachment:$token";
974         }
975
976         $taxonomies = array();
977         foreach ( $objects as $object )
978                 if ( $taxes = get_object_taxonomies($object) )
979                         $taxonomies = array_merge($taxonomies, $taxes);
980
981         return array_unique($taxonomies);
982 }
983
984 /**
985  * Check if the installed version of GD supports particular image type
986  *
987  * @since 2.9.0
988  *
989  * @param string $mime_type
990  * @return bool
991  */
992 function gd_edit_image_support($mime_type) {
993         if ( function_exists('imagetypes') ) {
994                 switch( $mime_type ) {
995                         case 'image/jpeg':
996                                 return (imagetypes() & IMG_JPG) != 0;
997                         case 'image/png':
998                                 return (imagetypes() & IMG_PNG) != 0;
999                         case 'image/gif':
1000                                 return (imagetypes() & IMG_GIF) != 0;
1001                 }
1002         } else {
1003                 switch( $mime_type ) {
1004                         case 'image/jpeg':
1005                                 return function_exists('imagecreatefromjpeg');
1006                         case 'image/png':
1007                                 return function_exists('imagecreatefrompng');
1008                         case 'image/gif':
1009                                 return function_exists('imagecreatefromgif');
1010                 }
1011         }
1012         return false;
1013 }
1014
1015 /**
1016  * Create new GD image resource with transparency support
1017  *
1018  * @since 2.9.0
1019  *
1020  * @param int $width Image width
1021  * @param int $height Image height
1022  * @return image resource
1023  */
1024 function wp_imagecreatetruecolor($width, $height) {
1025         $img = imagecreatetruecolor($width, $height);
1026         if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
1027                 imagealphablending($img, false);
1028                 imagesavealpha($img, true);
1029         }
1030         return $img;
1031 }
1032
1033 /**
1034  * API for easily embedding rich media such as videos and images into content.
1035  *
1036  * @package WordPress
1037  * @subpackage Embed
1038  * @since 2.9.0
1039  */
1040 class WP_Embed {
1041         var $handlers = array();
1042         var $post_ID;
1043         var $usecache = true;
1044         var $linkifunknown = true;
1045
1046         /**
1047          * Constructor
1048          */
1049         function __construct() {
1050                 // Hack to get the [embed] shortcode to run before wpautop()
1051                 add_filter( 'the_content', array(&$this, 'run_shortcode'), 8 );
1052
1053                 // Shortcode placeholder for strip_shortcodes()
1054                 add_shortcode( 'embed', '__return_false' );
1055
1056                 // Attempts to embed all URLs in a post
1057                 if ( get_option('embed_autourls') )
1058                         add_filter( 'the_content', array(&$this, 'autoembed'), 8 );
1059
1060                 // After a post is saved, invalidate the oEmbed cache
1061                 add_action( 'save_post', array(&$this, 'delete_oembed_caches') );
1062
1063                 // After a post is saved, cache oEmbed items via AJAX
1064                 add_action( 'edit_form_advanced', array(&$this, 'maybe_run_ajax_cache') );
1065         }
1066
1067         /**
1068          * Process the [embed] shortcode.
1069          *
1070          * Since the [embed] shortcode needs to be run earlier than other shortcodes,
1071          * this function removes all existing shortcodes, registers the [embed] shortcode,
1072          * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
1073          *
1074          * @uses $shortcode_tags
1075          * @uses remove_all_shortcodes()
1076          * @uses add_shortcode()
1077          * @uses do_shortcode()
1078          *
1079          * @param string $content Content to parse
1080          * @return string Content with shortcode parsed
1081          */
1082         function run_shortcode( $content ) {
1083                 global $shortcode_tags;
1084
1085                 // Back up current registered shortcodes and clear them all out
1086                 $orig_shortcode_tags = $shortcode_tags;
1087                 remove_all_shortcodes();
1088
1089                 add_shortcode( 'embed', array(&$this, 'shortcode') );
1090
1091                 // Do the shortcode (only the [embed] one is registered)
1092                 $content = do_shortcode( $content );
1093
1094                 // Put the original shortcodes back
1095                 $shortcode_tags = $orig_shortcode_tags;
1096
1097                 return $content;
1098         }
1099
1100         /**
1101          * If a post/page was saved, then output JavaScript to make
1102          * an AJAX request that will call WP_Embed::cache_oembed().
1103          */
1104         function maybe_run_ajax_cache() {
1105                 global $post_ID;
1106
1107                 if ( empty($post_ID) || empty($_GET['message']) || 1 != $_GET['message'] )
1108                         return;
1109
1110 ?>
1111 <script type="text/javascript">
1112 /* <![CDATA[ */
1113         jQuery(document).ready(function($){
1114                 $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post_ID, 'relative' ); ?>");
1115         });
1116 /* ]]> */
1117 </script>
1118 <?php
1119         }
1120
1121         /**
1122          * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead.
1123          * This function should probably also only be used for sites that do not support oEmbed.
1124          *
1125          * @param string $id An internal ID/name for the handler. Needs to be unique.
1126          * @param string $regex The regex that will be used to see if this handler should be used for a URL.
1127          * @param callback $callback The callback function that will be called if the regex is matched.
1128          * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
1129          */
1130         function register_handler( $id, $regex, $callback, $priority = 10 ) {
1131                 $this->handlers[$priority][$id] = array(
1132                         'regex'    => $regex,
1133                         'callback' => $callback,
1134                 );
1135         }
1136
1137         /**
1138          * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead.
1139          *
1140          * @param string $id The handler ID that should be removed.
1141          * @param int $priority Optional. The priority of the handler to be removed (default: 10).
1142          */
1143         function unregister_handler( $id, $priority = 10 ) {
1144                 if ( isset($this->handlers[$priority][$id]) )
1145                         unset($this->handlers[$priority][$id]);
1146         }
1147
1148         /**
1149          * The {@link do_shortcode()} callback function.
1150          *
1151          * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers.
1152          * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class.
1153          *
1154          * @uses wp_oembed_get()
1155          * @uses wp_parse_args()
1156          * @uses wp_embed_defaults()
1157          * @uses WP_Embed::maybe_make_link()
1158          * @uses get_option()
1159          * @uses current_user_can()
1160          * @uses wp_cache_get()
1161          * @uses wp_cache_set()
1162          * @uses get_post_meta()
1163          * @uses update_post_meta()
1164          *
1165          * @param array $attr Shortcode attributes.
1166          * @param string $url The URL attempting to be embedded.
1167          * @return string The embed HTML on success, otherwise the original URL.
1168          */
1169         function shortcode( $attr, $url = '' ) {
1170                 global $post;
1171
1172                 if ( empty($url) )
1173                         return '';
1174
1175                 $rawattr = $attr;
1176                 $attr = wp_parse_args( $attr, wp_embed_defaults() );
1177
1178                 // kses converts & into &amp; and we need to undo this
1179                 // See http://core.trac.wordpress.org/ticket/11311
1180                 $url = str_replace( '&amp;', '&', $url );
1181
1182                 // Look for known internal handlers
1183                 ksort( $this->handlers );
1184                 foreach ( $this->handlers as $priority => $handlers ) {
1185                         foreach ( $handlers as $id => $handler ) {
1186                                 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
1187                                         if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
1188                                                 return apply_filters( 'embed_handler_html', $return, $url, $attr );
1189                                 }
1190                         }
1191                 }
1192
1193                 $post_ID = ( !empty($post->ID) ) ? $post->ID : null;
1194                 if ( !empty($this->post_ID) ) // Potentially set by WP_Embed::cache_oembed()
1195                         $post_ID = $this->post_ID;
1196
1197                 // Unknown URL format. Let oEmbed have a go.
1198                 if ( $post_ID ) {
1199
1200                         // Check for a cached result (stored in the post meta)
1201                         $cachekey = '_oembed_' . md5( $url . serialize( $attr ) );
1202                         if ( $this->usecache ) {
1203                                 $cache = get_post_meta( $post_ID, $cachekey, true );
1204
1205                                 // Failures are cached
1206                                 if ( '{{unknown}}' === $cache )
1207                                         return $this->maybe_make_link( $url );
1208
1209                                 if ( !empty($cache) )
1210                                         return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
1211                         }
1212
1213                         // Use oEmbed to get the HTML
1214                         $attr['discover'] = ( apply_filters('embed_oembed_discover', false) && author_can( $post_ID, 'unfiltered_html' ) );
1215                         $html = wp_oembed_get( $url, $attr );
1216
1217                         // Cache the result
1218                         $cache = ( $html ) ? $html : '{{unknown}}';
1219                         update_post_meta( $post_ID, $cachekey, $cache );
1220
1221                         // If there was a result, return it
1222                         if ( $html )
1223                                 return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
1224                 }
1225
1226                 // Still unknown
1227                 return $this->maybe_make_link( $url );
1228         }
1229
1230         /**
1231          * Delete all oEmbed caches.
1232          *
1233          * @param int $post_ID Post ID to delete the caches for.
1234          */
1235         function delete_oembed_caches( $post_ID ) {
1236                 $post_metas = get_post_custom_keys( $post_ID );
1237                 if ( empty($post_metas) )
1238                         return;
1239
1240                 foreach( $post_metas as $post_meta_key ) {
1241                         if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
1242                                 delete_post_meta( $post_ID, $post_meta_key );
1243                 }
1244         }
1245
1246         /**
1247          * Triggers a caching of all oEmbed results.
1248          *
1249          * @param int $post_ID Post ID to do the caching for.
1250          */
1251         function cache_oembed( $post_ID ) {
1252                 $post = get_post( $post_ID );
1253
1254                 if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', array( 'post', 'page' ) ) ) )
1255                         return;
1256
1257                 // Trigger a caching
1258                 if ( !empty($post->post_content) ) {
1259                         $this->post_ID = $post->ID;
1260                         $this->usecache = false;
1261
1262                         $content = $this->run_shortcode( $post->post_content );
1263                         if ( get_option('embed_autourls') )
1264                                 $this->autoembed( $content );
1265
1266                         $this->usecache = true;
1267                 }
1268         }
1269
1270         /**
1271          * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
1272          *
1273          * @uses WP_Embed::autoembed_callback()
1274          *
1275          * @param string $content The content to be searched.
1276          * @return string Potentially modified $content.
1277          */
1278         function autoembed( $content ) {
1279                 return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array(&$this, 'autoembed_callback'), $content );
1280         }
1281
1282         /**
1283          * Callback function for {@link WP_Embed::autoembed()}.
1284          *
1285          * @uses WP_Embed::shortcode()
1286          *
1287          * @param array $match A regex match array.
1288          * @return string The embed HTML on success, otherwise the original URL.
1289          */
1290         function autoembed_callback( $match ) {
1291                 $oldval = $this->linkifunknown;
1292                 $this->linkifunknown = false;
1293                 $return = $this->shortcode( array(), $match[1] );
1294                 $this->linkifunknown = $oldval;
1295
1296                 return "\n$return\n";
1297         }
1298
1299         /**
1300          * Conditionally makes a hyperlink based on an internal class variable.
1301          *
1302          * @param string $url URL to potentially be linked.
1303          * @return string Linked URL or the original URL.
1304          */
1305         function maybe_make_link( $url ) {
1306                 $output = ( $this->linkifunknown ) ? '<a href="' . esc_attr($url) . '">' . esc_html($url) . '</a>' : $url;
1307                 return apply_filters( 'embed_maybe_make_link', $output, $url );
1308         }
1309 }
1310 $GLOBALS['wp_embed'] = new WP_Embed();
1311
1312 /**
1313  * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
1314  *
1315  * @since 2.9.0
1316  * @see WP_Embed::register_handler()
1317  */
1318 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
1319         global $wp_embed;
1320         $wp_embed->register_handler( $id, $regex, $callback, $priority );
1321 }
1322
1323 /**
1324  * Unregister a previously registered embed handler.
1325  *
1326  * @since 2.9.0
1327  * @see WP_Embed::unregister_handler()
1328  */
1329 function wp_embed_unregister_handler( $id, $priority = 10 ) {
1330         global $wp_embed;
1331         $wp_embed->unregister_handler( $id, $priority );
1332 }
1333
1334 /**
1335  * Create default array of embed parameters.
1336  *
1337  * @since 2.9.0
1338  *
1339  * @return array Default embed parameters.
1340  */
1341 function wp_embed_defaults() {
1342         if ( !empty($GLOBALS['content_width']) )
1343                 $theme_width = (int) $GLOBALS['content_width'];
1344
1345         $width = get_option('embed_size_w');
1346
1347         if ( empty($width) && !empty($theme_width) )
1348                 $width = $theme_width;
1349
1350         if ( empty($width) )
1351                 $width = 500;
1352
1353         $height = get_option('embed_size_h');
1354
1355         if ( empty($height) )
1356                 $height = 700;
1357
1358         return apply_filters( 'embed_defaults', array(
1359                 'width'  => $width,
1360                 'height' => $height,
1361         ) );
1362 }
1363
1364 /**
1365  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
1366  *
1367  * @since 2.9.0
1368  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
1369  *
1370  * @param int $example_width The width of an example embed.
1371  * @param int $example_height The height of an example embed.
1372  * @param int $max_width The maximum allowed width.
1373  * @param int $max_height The maximum allowed height.
1374  * @return array The maximum possible width and height based on the example ratio.
1375  */
1376 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
1377         $example_width  = (int) $example_width;
1378         $example_height = (int) $example_height;
1379         $max_width      = (int) $max_width;
1380         $max_height     = (int) $max_height;
1381
1382         return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
1383 }
1384
1385 /**
1386  * Attempts to fetch the embed HTML for a provided URL using oEmbed.
1387  *
1388  * @since 2.9.0
1389  * @see WP_oEmbed
1390  *
1391  * @uses _wp_oembed_get_object()
1392  * @uses WP_oEmbed::get_html()
1393  *
1394  * @param string $url The URL that should be embedded.
1395  * @param array $args Additional arguments and parameters.
1396  * @return bool|string False on failure or the embed HTML on success.
1397  */
1398 function wp_oembed_get( $url, $args = '' ) {
1399         require_once( ABSPATH . WPINC . '/class-oembed.php' );
1400         $oembed = _wp_oembed_get_object();
1401         return $oembed->get_html( $url, $args );
1402 }
1403
1404 /**
1405  * Adds a URL format and oEmbed provider URL pair.
1406  *
1407  * @since 2.9.0
1408  * @see WP_oEmbed
1409  *
1410  * @uses _wp_oembed_get_object()
1411  *
1412  * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
1413  * @param string $provider The URL to the oEmbed provider.
1414  * @param boolean $regex Whether the $format parameter is in a regex format.
1415  */
1416 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
1417         require_once( ABSPATH . WPINC . '/class-oembed.php' );
1418         $oembed = _wp_oembed_get_object();
1419         $oembed->providers[$format] = array( $provider, $regex );
1420 }
1421
1422 /**
1423  * Determines if default embed handlers should be loaded.
1424  *
1425  * Checks to make sure that the embeds library hasn't already been loaded. If
1426  * it hasn't, then it will load the embeds library.
1427  *
1428  * @since 2.9.0
1429  */
1430 function wp_maybe_load_embeds() {
1431         if ( ! apply_filters( 'load_default_embeds', true ) )
1432                 return;
1433         wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
1434 }
1435
1436 /**
1437  * The Google Video embed handler callback. Google Video does not support oEmbed.
1438  *
1439  * @see WP_Embed::register_handler()
1440  * @see WP_Embed::shortcode()
1441  *
1442  * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
1443  * @param array $attr Embed attributes.
1444  * @param string $url The original URL that was matched by the regex.
1445  * @param array $rawattr The original unmodified attributes.
1446  * @return string The embed HTML.
1447  */
1448 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
1449         // If the user supplied a fixed width AND height, use it
1450         if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
1451                 $width  = (int) $rawattr['width'];
1452                 $height = (int) $rawattr['height'];
1453         } else {
1454                 list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
1455         }
1456
1457         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 );
1458 }
1459
1460 /**
1461  * Prints default plupload arguments.
1462  *
1463  * @since 3.4.0
1464  */
1465 function wp_plupload_default_settings() {
1466         global $wp_scripts;
1467
1468         $max_upload_size = wp_max_upload_size();
1469
1470         $defaults = array(
1471                 'runtimes'            => 'html5,silverlight,flash,html4',
1472                 'file_data_name'      => 'async-upload', // key passed to $_FILE.
1473                 'multiple_queues'     => true,
1474                 'max_file_size'       => $max_upload_size . 'b',
1475                 'url'                 => admin_url( 'admin-ajax.php', 'relative' ),
1476                 'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
1477                 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
1478                 'filters'             => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
1479                 'multipart'           => true,
1480                 'urlstream_upload'    => true,
1481         );
1482
1483         $defaults = apply_filters( 'plupload_default_settings', $defaults );
1484
1485         $params = array(
1486                 'action' => 'upload-attachment',
1487         );
1488
1489         $params = apply_filters( 'plupload_default_params', $params );
1490         $params['_wpnonce'] = wp_create_nonce( 'media-form' );
1491         $defaults['multipart_params'] = $params;
1492
1493         $settings = array(
1494                 'defaults' => $defaults,
1495                 'browser'  => array(
1496                         'mobile'    => wp_is_mobile(),
1497                         'supported' => _device_can_upload(),
1498                 ),
1499         );
1500
1501         $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
1502
1503         $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
1504         if ( $data )
1505                 $script = "$data\n$script";
1506
1507         $wp_scripts->add_data( 'wp-plupload', 'data', $script );
1508 }
1509 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );