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