PageRenderTime 324ms CodeModel.GetById 80ms app.highlight 106ms RepoModel.GetById 45ms app.codeStats 1ms

/wp-includes/media.php

https://bitbucket.org/aqge/deptandashboard
PHP | 1445 lines | 682 code | 181 blank | 582 comment | 193 complexity | b7d1b16bcc11b81069bd906ec2be412f MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file