PageRenderTime 112ms CodeModel.GetById 24ms app.highlight 66ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/media.php

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

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