PageRenderTime 414ms CodeModel.GetById 91ms app.highlight 189ms RepoModel.GetById 71ms app.codeStats 1ms

/APP/wp-includes/media.php

https://bitbucket.org/AFelipeTrujillo/goblog
PHP | 3105 lines | 1512 code | 341 blank | 1252 comment | 314 complexity | 8fa567db388bf940d839361afc3cc6a4 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	/**
  82	 * Filter the maximum image size dimensions for the editor.
  83	 *
  84	 * @since 2.5.0
  85	 *
  86	 * @param array        $max_image_size An array with the width as the first element,
  87	 *                                     and the height as the second element.
  88	 * @param string|array $size           Size of what the result image should be.
  89	 * @param string       $context        The context the image is being resized for.
  90	 *                                     Possible values are 'display' (like in a theme)
  91	 *                                     or 'edit' (like inserting into an editor).
  92	 */
  93	list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  94
  95	return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  96}
  97
  98/**
  99 * Retrieve width and height attributes using given width and height values.
 100 *
 101 * Both attributes are required in the sense that both parameters must have a
 102 * value, but are optional in that if you set them to false or null, then they
 103 * will not be added to the returned string.
 104 *
 105 * You can set the value using a string, but it will only take numeric values.
 106 * If you wish to put 'px' after the numbers, then it will be stripped out of
 107 * the return.
 108 *
 109 * @since 2.5.0
 110 *
 111 * @param int|string $width Optional. Width attribute value.
 112 * @param int|string $height Optional. Height attribute value.
 113 * @return string HTML attributes for width and, or height.
 114 */
 115function image_hwstring($width, $height) {
 116	$out = '';
 117	if ($width)
 118		$out .= 'width="'.intval($width).'" ';
 119	if ($height)
 120		$out .= 'height="'.intval($height).'" ';
 121	return $out;
 122}
 123
 124/**
 125 * Scale an image to fit a particular size (such as 'thumb' or 'medium').
 126 *
 127 * Array with image url, width, height, and whether is intermediate size, in
 128 * that order is returned on success is returned. $is_intermediate is true if
 129 * $url is a resized image, false if it is the original.
 130 *
 131 * The URL might be the original image, or it might be a resized version. This
 132 * function won't create a new resized copy, it will just return an already
 133 * resized one if it exists.
 134 *
 135 * A plugin may use the 'image_downsize' filter to hook into and offer image
 136 * resizing services for images. The hook must return an array with the same
 137 * elements that are returned in the function. The first element being the URL
 138 * to the new image that was resized.
 139 *
 140 * @since 2.5.0
 141 *
 142 * @param int $id Attachment ID for image.
 143 * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
 144 * @return bool|array False on failure, array on success.
 145 */
 146function image_downsize($id, $size = 'medium') {
 147
 148	if ( !wp_attachment_is_image($id) )
 149		return false;
 150
 151	/**
 152	 * Filter whether to preempt the output of image_downsize().
 153	 *
 154	 * Passing a truthy value to the filter will effectively short-circuit
 155	 * down-sizing the image, returning that value as output instead.
 156	 *
 157	 * @since 2.5.0
 158	 *
 159	 * @param bool         $downsize Whether to short-circuit the image downsize. Default false.
 160	 * @param int          $id       Attachment ID for image.
 161	 * @param array|string $size     Size of image, either array or string. Default 'medium'.
 162	 */
 163	if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
 164		return $out;
 165	}
 166
 167	$img_url = wp_get_attachment_url($id);
 168	$meta = wp_get_attachment_metadata($id);
 169	$width = $height = 0;
 170	$is_intermediate = false;
 171	$img_url_basename = wp_basename($img_url);
 172
 173	// try for a new style intermediate size
 174	if ( $intermediate = image_get_intermediate_size($id, $size) ) {
 175		$img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
 176		$width = $intermediate['width'];
 177		$height = $intermediate['height'];
 178		$is_intermediate = true;
 179	}
 180	elseif ( $size == 'thumbnail' ) {
 181		// fall back to the old thumbnail
 182		if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
 183			$img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
 184			$width = $info[0];
 185			$height = $info[1];
 186			$is_intermediate = true;
 187		}
 188	}
 189	if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
 190		// any other type: use the real image
 191		$width = $meta['width'];
 192		$height = $meta['height'];
 193	}
 194
 195	if ( $img_url) {
 196		// we have the actual image size, but might need to further constrain it if content_width is narrower
 197		list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
 198
 199		return array( $img_url, $width, $height, $is_intermediate );
 200	}
 201	return false;
 202
 203}
 204
 205/**
 206 * Register a new image size.
 207 *
 208 * Cropping behavior for the image size is dependent on the value of $crop:
 209 * 1. If false (default), images will be scaled, not cropped.
 210 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
 211 *    - x_crop_position accepts 'left' 'center', or 'right'.
 212 *    - y_crop_position accepts 'top', 'center', or 'bottom'.
 213 *    Images will be cropped to the specified dimensions within the defined crop area.
 214 * 3. If true, images will be cropped to the specified dimensions using center positions.
 215 *
 216 * @since 2.9.0
 217 *
 218 * @param string     $name   Image size identifier.
 219 * @param int        $width  Image width in pixels.
 220 * @param int        $height Image height in pixels.
 221 * @param bool|array $crop   Optional. Whether to crop images to specified height and width or resize.
 222 *                           An array can specify positioning of the crop area. Default false.
 223 * @return bool|array False, if no image was created. Metadata array on success.
 224 */
 225function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
 226	global $_wp_additional_image_sizes;
 227
 228	$_wp_additional_image_sizes[ $name ] = array(
 229		'width'  => absint( $width ),
 230		'height' => absint( $height ),
 231		'crop'   => $crop,
 232	);
 233}
 234
 235/**
 236 * Check if an image size exists.
 237 *
 238 * @since 3.9.0
 239 *
 240 * @param string $name The image size to check.
 241 * @return bool True if the image size exists, false if not.
 242 */
 243function has_image_size( $name ) {
 244	global $_wp_additional_image_sizes;
 245
 246	return isset( $_wp_additional_image_sizes[ $name ] );
 247}
 248
 249/**
 250 * Remove a new image size.
 251 *
 252 * @since 3.9.0
 253 *
 254 * @param string $name The image size to remove.
 255 * @return bool True if the image size was successfully removed, false on failure.
 256 */
 257function remove_image_size( $name ) {
 258	global $_wp_additional_image_sizes;
 259
 260	if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
 261		unset( $_wp_additional_image_sizes[ $name ] );
 262		return true;
 263	}
 264
 265	return false;
 266}
 267
 268/**
 269 * Registers an image size for the post thumbnail.
 270 *
 271 * @since 2.9.0
 272 * @see add_image_size() for details on cropping behavior.
 273 *
 274 * @param int        $width  Image width in pixels.
 275 * @param int        $height Image height in pixels.
 276 * @param bool|array $crop   Optional. Whether to crop images to specified height and width or resize.
 277 *                           An array can specify positioning of the crop area. Default false.
 278 * @return bool|array False, if no image was created. Metadata array on success.
 279 */
 280function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
 281	add_image_size( 'post-thumbnail', $width, $height, $crop );
 282}
 283
 284/**
 285 * An <img src /> tag for an image attachment, scaling it down if requested.
 286 *
 287 * The filter 'get_image_tag_class' allows for changing the class name for the
 288 * image without having to use regular expressions on the HTML content. The
 289 * parameters are: what WordPress will use for the class, the Attachment ID,
 290 * image align value, and the size the image should be.
 291 *
 292 * The second filter 'get_image_tag' has the HTML content, which can then be
 293 * further manipulated by a plugin to change all attribute values and even HTML
 294 * content.
 295 *
 296 * @since 2.5.0
 297 *
 298 * @param int $id Attachment ID.
 299 * @param string $alt Image Description for the alt attribute.
 300 * @param string $title Image Description for the title attribute.
 301 * @param string $align Part of the class name for aligning the image.
 302 * @param string $size Optional. Default is 'medium'.
 303 * @return string HTML IMG element for given image attachment
 304 */
 305function get_image_tag($id, $alt, $title, $align, $size='medium') {
 306
 307	list( $img_src, $width, $height ) = image_downsize($id, $size);
 308	$hwstring = image_hwstring($width, $height);
 309
 310	$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
 311
 312	$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
 313
 314	/**
 315	 * Filter the value of the attachment's image tag class attribute.
 316	 *
 317	 * @since 2.6.0
 318	 *
 319	 * @param string $class CSS class name or space-separated list of classes.
 320	 * @param int    $id    Attachment ID.
 321	 * @param string $align Part of the class name for aligning the image.
 322	 * @param string $size  Optional. Default is 'medium'.
 323	 */
 324	$class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
 325
 326	$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
 327
 328	/**
 329	 * Filter the HTML content for the image tag.
 330	 *
 331	 * @since 2.6.0
 332	 *
 333	 * @param string $html  HTML content for the image.
 334	 * @param int    $id    Attachment ID.
 335	 * @param string $alt   Alternate text.
 336	 * @param string $title Attachment title.
 337	 * @param string $align Part of the class name for aligning the image.
 338	 * @param string $size  Optional. Default is 'medium'.
 339	 */
 340	$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
 341
 342	return $html;
 343}
 344
 345/**
 346 * Calculates the new dimensions for a downsampled image.
 347 *
 348 * If either width or height are empty, no constraint is applied on
 349 * that dimension.
 350 *
 351 * @since 2.5.0
 352 *
 353 * @param int $current_width Current width of the image.
 354 * @param int $current_height Current height of the image.
 355 * @param int $max_width Optional. Maximum wanted width.
 356 * @param int $max_height Optional. Maximum wanted height.
 357 * @return array First item is the width, the second item is the height.
 358 */
 359function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
 360	if ( !$max_width and !$max_height )
 361		return array( $current_width, $current_height );
 362
 363	$width_ratio = $height_ratio = 1.0;
 364	$did_width = $did_height = false;
 365
 366	if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
 367		$width_ratio = $max_width / $current_width;
 368		$did_width = true;
 369	}
 370
 371	if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
 372		$height_ratio = $max_height / $current_height;
 373		$did_height = true;
 374	}
 375
 376	// Calculate the larger/smaller ratios
 377	$smaller_ratio = min( $width_ratio, $height_ratio );
 378	$larger_ratio  = max( $width_ratio, $height_ratio );
 379
 380	if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
 381 		// The larger ratio is too big. It would result in an overflow.
 382		$ratio = $smaller_ratio;
 383	else
 384		// The larger ratio fits, and is likely to be a more "snug" fit.
 385		$ratio = $larger_ratio;
 386
 387	// Very small dimensions may result in 0, 1 should be the minimum.
 388	$w = max ( 1, intval( $current_width  * $ratio ) );
 389	$h = max ( 1, intval( $current_height * $ratio ) );
 390
 391	// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
 392	// 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.
 393	// Thus we look for dimensions that are one pixel shy of the max value and bump them up
 394	if ( $did_width && $w == $max_width - 1 )
 395		$w = $max_width; // Round it up
 396	if ( $did_height && $h == $max_height - 1 )
 397		$h = $max_height; // Round it up
 398
 399	return array( $w, $h );
 400}
 401
 402/**
 403 * Retrieve calculated resize dimensions for use in WP_Image_Editor.
 404 *
 405 * Calculates dimensions and coordinates for a resized image that fits
 406 * within a specified width and height.
 407 *
 408 * Cropping behavior is dependent on the value of $crop:
 409 * 1. If false (default), images will not be cropped.
 410 * 2. If an array in the form of array( x_crop_position, y_crop_position ):
 411 *    - x_crop_position accepts 'left' 'center', or 'right'.
 412 *    - y_crop_position accepts 'top', 'center', or 'bottom'.
 413 *    Images will be cropped to the specified dimensions within the defined crop area.
 414 * 3. If true, images will be cropped to the specified dimensions using center positions.
 415 *
 416 * @since 2.5.0
 417 *
 418 * @param int        $orig_w Original width in pixels.
 419 * @param int        $orig_h Original height in pixels.
 420 * @param int        $dest_w New width in pixels.
 421 * @param int        $dest_h New height in pixels.
 422 * @param bool|array $crop   Optional. Whether to crop image to specified height and width or resize.
 423 *                           An array can specify positioning of the crop area. Default false.
 424 * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
 425 */
 426function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
 427
 428	if ($orig_w <= 0 || $orig_h <= 0)
 429		return false;
 430	// at least one of dest_w or dest_h must be specific
 431	if ($dest_w <= 0 && $dest_h <= 0)
 432		return false;
 433
 434	/**
 435	 * Filter whether to preempt calculating the image resize dimensions.
 436	 *
 437	 * Passing a non-null value to the filter will effectively short-circuit
 438	 * image_resize_dimensions(), returning that value instead.
 439	 *
 440	 * @since 3.4.0
 441	 *
 442	 * @param null|mixed $null   Whether to preempt output of the resize dimensions.
 443	 * @param int        $orig_w Original width in pixels.
 444	 * @param int        $orig_h Original height in pixels.
 445	 * @param int        $dest_w New width in pixels.
 446	 * @param int        $dest_h New height in pixels.
 447	 * @param bool|array $crop   Whether to crop image to specified height and width or resize.
 448	 *                           An array can specify positioning of the crop area. Default false.
 449	 */
 450	$output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
 451	if ( null !== $output )
 452		return $output;
 453
 454	if ( $crop ) {
 455		// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
 456		$aspect_ratio = $orig_w / $orig_h;
 457		$new_w = min($dest_w, $orig_w);
 458		$new_h = min($dest_h, $orig_h);
 459
 460		if ( !$new_w ) {
 461			$new_w = intval($new_h * $aspect_ratio);
 462		}
 463
 464		if ( !$new_h ) {
 465			$new_h = intval($new_w / $aspect_ratio);
 466		}
 467
 468		$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
 469
 470		$crop_w = round($new_w / $size_ratio);
 471		$crop_h = round($new_h / $size_ratio);
 472
 473		if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
 474			$crop = array( 'center', 'center' );
 475		}
 476
 477		list( $x, $y ) = $crop;
 478
 479		if ( 'left' === $x ) {
 480			$s_x = 0;
 481		} elseif ( 'right' === $x ) {
 482			$s_x = $orig_w - $crop_w;
 483		} else {
 484			$s_x = floor( ( $orig_w - $crop_w ) / 2 );
 485		}
 486
 487		if ( 'top' === $y ) {
 488			$s_y = 0;
 489		} elseif ( 'bottom' === $y ) {
 490			$s_y = $orig_h - $crop_h;
 491		} else {
 492			$s_y = floor( ( $orig_h - $crop_h ) / 2 );
 493		}
 494	} else {
 495		// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
 496		$crop_w = $orig_w;
 497		$crop_h = $orig_h;
 498
 499		$s_x = 0;
 500		$s_y = 0;
 501
 502		list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
 503	}
 504
 505	// if the resulting image would be the same size or larger we don't want to resize it
 506	if ( $new_w >= $orig_w && $new_h >= $orig_h )
 507		return false;
 508
 509	// the return array matches the parameters to imagecopyresampled()
 510	// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
 511	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
 512
 513}
 514
 515/**
 516 * Resize an image to make a thumbnail or intermediate size.
 517 *
 518 * The returned array has the file size, the image width, and image height. The
 519 * filter 'image_make_intermediate_size' can be used to hook in and change the
 520 * values of the returned array. The only parameter is the resized file path.
 521 *
 522 * @since 2.5.0
 523 *
 524 * @param string $file File path.
 525 * @param int $width Image width.
 526 * @param int $height Image height.
 527 * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
 528 * @return bool|array False, if no image was created. Metadata array on success.
 529 */
 530function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
 531	if ( $width || $height ) {
 532		$editor = wp_get_image_editor( $file );
 533
 534		if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
 535			return false;
 536
 537		$resized_file = $editor->save();
 538
 539		if ( ! is_wp_error( $resized_file ) && $resized_file ) {
 540			unset( $resized_file['path'] );
 541			return $resized_file;
 542		}
 543	}
 544	return false;
 545}
 546
 547/**
 548 * Retrieve the image's intermediate size (resized) path, width, and height.
 549 *
 550 * The $size parameter can be an array with the width and height respectively.
 551 * If the size matches the 'sizes' metadata array for width and height, then it
 552 * will be used. If there is no direct match, then the nearest image size larger
 553 * than the specified size will be used. If nothing is found, then the function
 554 * will break out and return false.
 555 *
 556 * The metadata 'sizes' is used for compatible sizes that can be used for the
 557 * parameter $size value.
 558 *
 559 * The url path will be given, when the $size parameter is a string.
 560 *
 561 * If you are passing an array for the $size, you should consider using
 562 * add_image_size() so that a cropped version is generated. It's much more
 563 * efficient than having to find the closest-sized image and then having the
 564 * browser scale down the image.
 565 *
 566 * @since 2.5.0
 567 * @see add_image_size()
 568 *
 569 * @param int $post_id Attachment ID for image.
 570 * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
 571 * @return bool|array False on failure or array of file path, width, and height on success.
 572 */
 573function image_get_intermediate_size($post_id, $size='thumbnail') {
 574	if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
 575		return false;
 576
 577	// get the best one for a specified set of dimensions
 578	if ( is_array($size) && !empty($imagedata['sizes']) ) {
 579		foreach ( $imagedata['sizes'] as $_size => $data ) {
 580			// already cropped to width or height; so use this size
 581			if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
 582				$file = $data['file'];
 583				list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
 584				return compact( 'file', 'width', 'height' );
 585			}
 586			// add to lookup table: area => size
 587			$areas[$data['width'] * $data['height']] = $_size;
 588		}
 589		if ( !$size || !empty($areas) ) {
 590			// find for the smallest image not smaller than the desired size
 591			ksort($areas);
 592			foreach ( $areas as $_size ) {
 593				$data = $imagedata['sizes'][$_size];
 594				if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
 595					// Skip images with unexpectedly divergent aspect ratios (crops)
 596					// First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
 597					$maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
 598					// 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
 599					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'] ) ) )
 600						continue;
 601					// If we're still here, then we're going to use this size
 602					$file = $data['file'];
 603					list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
 604					return compact( 'file', 'width', 'height' );
 605				}
 606			}
 607		}
 608	}
 609
 610	if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
 611		return false;
 612
 613	$data = $imagedata['sizes'][$size];
 614	// include the full filesystem path of the intermediate file
 615	if ( empty($data['path']) && !empty($data['file']) ) {
 616		$file_url = wp_get_attachment_url($post_id);
 617		$data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
 618		$data['url'] = path_join( dirname($file_url), $data['file'] );
 619	}
 620	return $data;
 621}
 622
 623/**
 624 * Get the available image sizes
 625 * @since 3.0.0
 626 * @return array Returns a filtered array of image size strings
 627 */
 628function get_intermediate_image_sizes() {
 629	global $_wp_additional_image_sizes;
 630	$image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
 631	if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
 632		$image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
 633
 634	/**
 635	 * Filter the list of intermediate image sizes.
 636	 *
 637	 * @since 2.5.0
 638	 *
 639	 * @param array $image_sizes An array of intermediate image sizes. Defaults
 640	 *                           are 'thumbnail', 'medium', 'large'.
 641	 */
 642	return apply_filters( 'intermediate_image_sizes', $image_sizes );
 643}
 644
 645/**
 646 * Retrieve an image to represent an attachment.
 647 *
 648 * A mime icon for files, thumbnail or intermediate size for images.
 649 *
 650 * @since 2.5.0
 651 *
 652 * @param int $attachment_id Image attachment ID.
 653 * @param string $size Optional, default is 'thumbnail'.
 654 * @param bool $icon Optional, default is false. Whether it is an icon.
 655 * @return bool|array Returns an array (url, width, height), or false, if no image is available.
 656 */
 657function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
 658
 659	// get a thumbnail or intermediate image if there is one
 660	if ( $image = image_downsize($attachment_id, $size) )
 661		return $image;
 662
 663	$src = false;
 664
 665	if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
 666		/** This filter is documented in wp-includes/post.php */
 667		$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
 668		$src_file = $icon_dir . '/' . wp_basename($src);
 669		@list($width, $height) = getimagesize($src_file);
 670	}
 671	if ( $src && $width && $height )
 672		return array( $src, $width, $height );
 673	return false;
 674}
 675
 676/**
 677 * Get an HTML img element representing an image attachment
 678 *
 679 * While $size will accept an array, it is better to register a size with
 680 * add_image_size() so that a cropped version is generated. It's much more
 681 * efficient than having to find the closest-sized image and then having the
 682 * browser scale down the image.
 683 *
 684 * @since 2.5.0
 685 *
 686 * @see add_image_size()
 687 * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
 688 *
 689 * @param int $attachment_id Image attachment ID.
 690 * @param string $size Optional, default is 'thumbnail'.
 691 * @param bool $icon Optional, default is false. Whether it is an icon.
 692 * @param mixed $attr Optional, attributes for the image markup.
 693 * @return string HTML img element or empty string on failure.
 694 */
 695function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
 696
 697	$html = '';
 698	$image = wp_get_attachment_image_src($attachment_id, $size, $icon);
 699	if ( $image ) {
 700		list($src, $width, $height) = $image;
 701		$hwstring = image_hwstring($width, $height);
 702		if ( is_array($size) )
 703			$size = join('x', $size);
 704		$attachment = get_post($attachment_id);
 705		$default_attr = array(
 706			'src'	=> $src,
 707			'class'	=> "attachment-$size",
 708			'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
 709		);
 710		if ( empty($default_attr['alt']) )
 711			$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
 712		if ( empty($default_attr['alt']) )
 713			$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
 714
 715		$attr = wp_parse_args($attr, $default_attr);
 716
 717		/**
 718		 * Filter the list of attachment image attributes.
 719		 *
 720		 * @since 2.8.0
 721		 *
 722		 * @param mixed $attr          Attributes for the image markup.
 723		 * @param int   $attachment_id Image attachment ID.
 724		 */
 725		$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
 726		$attr = array_map( 'esc_attr', $attr );
 727		$html = rtrim("<img $hwstring");
 728		foreach ( $attr as $name => $value ) {
 729			$html .= " $name=" . '"' . $value . '"';
 730		}
 731		$html .= ' />';
 732	}
 733
 734	return $html;
 735}
 736
 737/**
 738 * Adds a 'wp-post-image' class to post thumbnails
 739 * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
 740 * dynamically add/remove itself so as to only filter post thumbnails
 741 *
 742 * @since 2.9.0
 743 * @param array $attr Attributes including src, class, alt, title
 744 * @return array
 745 */
 746function _wp_post_thumbnail_class_filter( $attr ) {
 747	$attr['class'] .= ' wp-post-image';
 748	return $attr;
 749}
 750
 751/**
 752 * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
 753 *
 754 * @since 2.9.0
 755 */
 756function _wp_post_thumbnail_class_filter_add( $attr ) {
 757	add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
 758}
 759
 760/**
 761 * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
 762 *
 763 * @since 2.9.0
 764 */
 765function _wp_post_thumbnail_class_filter_remove( $attr ) {
 766	remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
 767}
 768
 769add_shortcode('wp_caption', 'img_caption_shortcode');
 770add_shortcode('caption', 'img_caption_shortcode');
 771
 772/**
 773 * The Caption shortcode.
 774 *
 775 * Allows a plugin to replace the content that would otherwise be returned. The
 776 * filter is 'img_caption_shortcode' and passes an empty string, the attr
 777 * parameter and the content parameter values.
 778 *
 779 * The supported attributes for the shortcode are 'id', 'align', 'width', and
 780 * 'caption'.
 781 *
 782 * @since 2.6.0
 783 *
 784 * @param array $attr {
 785 *     Attributes of the caption shortcode.
 786 *
 787 *     @type string $id      ID of the div element for the caption.
 788 *     @type string $align   Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
 789 *                           'aligncenter', alignright', 'alignnone'.
 790 *     @type int    $width   The width of the caption, in pixels.
 791 *     @type string $caption The caption text.
 792 *     @type string $class   Additional class name(s) added to the caption container.
 793 * }
 794 * @param string $content Optional. Shortcode content.
 795 * @return string HTML content to display the caption.
 796 */
 797function img_caption_shortcode( $attr, $content = null ) {
 798	// New-style shortcode with the caption inside the shortcode with the link and image tags.
 799	if ( ! isset( $attr['caption'] ) ) {
 800		if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
 801			$content = $matches[1];
 802			$attr['caption'] = trim( $matches[2] );
 803		}
 804	}
 805
 806	/**
 807	 * Filter the default caption shortcode output.
 808	 *
 809	 * If the filtered output isn't empty, it will be used instead of generating
 810	 * the default caption template.
 811	 *
 812	 * @since 2.6.0
 813	 *
 814	 * @see img_caption_shortcode()
 815	 *
 816	 * @param string $output  The caption output. Default empty.
 817	 * @param array  $attr    Attributes of the caption shortcode.
 818	 * @param string $content The image element, possibly wrapped in a hyperlink.
 819	 */
 820	$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
 821	if ( $output != '' )
 822		return $output;
 823
 824	$atts = shortcode_atts( array(
 825		'id'	  => '',
 826		'align'	  => 'alignnone',
 827		'width'	  => '',
 828		'caption' => '',
 829		'class'   => '',
 830	), $attr, 'caption' );
 831
 832	$atts['width'] = (int) $atts['width'];
 833	if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
 834		return $content;
 835
 836	if ( ! empty( $atts['id'] ) )
 837		$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
 838
 839	$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
 840
 841	if ( current_theme_supports( 'html5', 'caption' ) ) {
 842		return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
 843		. do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
 844	}
 845
 846	$caption_width = 10 + $atts['width'];
 847
 848	/**
 849	 * Filter the width of an image's caption.
 850	 *
 851	 * By default, the caption is 10 pixels greater than the width of the image,
 852	 * to prevent post content from running up against a floated image.
 853	 *
 854	 * @since 3.7.0
 855	 *
 856	 * @see img_caption_shortcode()
 857	 *
 858	 * @param int    $caption_width Width of the caption in pixels. To remove this inline style,
 859	 *                              return zero.
 860	 * @param array  $atts          Attributes of the caption shortcode.
 861	 * @param string $content       The image element, possibly wrapped in a hyperlink.
 862	 */
 863	$caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
 864
 865	$style = '';
 866	if ( $caption_width )
 867		$style = 'style="width: ' . (int) $caption_width . 'px" ';
 868
 869	return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
 870	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
 871}
 872
 873add_shortcode('gallery', 'gallery_shortcode');
 874
 875/**
 876 * The Gallery shortcode.
 877 *
 878 * This implements the functionality of the Gallery Shortcode for displaying
 879 * WordPress images on a post.
 880 *
 881 * @since 2.5.0
 882 *
 883 * @param array $attr {
 884 *     Attributes of the gallery shortcode.
 885 *
 886 *     @type string $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
 887 *     @type string $orderby    The field to use when ordering the images. Default 'menu_order ID'.
 888 *                              Accepts any valid SQL ORDERBY statement.
 889 *     @type int    $id         Post ID.
 890 *     @type string $itemtag    HTML tag to use for each image in the gallery.
 891 *                              Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
 892 *     @type string $icontag    HTML tag to use for each image's icon.
 893 *                              Default 'dt', or 'div' when the theme registers HTML5 gallery support.
 894 *     @type string $captiontag HTML tag to use for each image's caption.
 895 *                              Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
 896 *     @type int    $columns    Number of columns of images to display. Default 3.
 897 *     @type string $size       Size of the images to display. Default 'thumbnail'.
 898 *     @type string $ids        A comma-separated list of IDs of attachments to display. Default empty.
 899 *     @type string $include    A comma-separated list of IDs of attachments to include. Default empty.
 900 *     @type string $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
 901 *     @type string $link       What to link each image to. Default empty (links to the attachment page).
 902 *                              Accepts 'file', 'none'.
 903 * }
 904 * @return string HTML content to display gallery.
 905 */
 906function gallery_shortcode( $attr ) {
 907	$post = get_post();
 908
 909	static $instance = 0;
 910	$instance++;
 911
 912	if ( ! empty( $attr['ids'] ) ) {
 913		// 'ids' is explicitly ordered, unless you specify otherwise.
 914		if ( empty( $attr['orderby'] ) )
 915			$attr['orderby'] = 'post__in';
 916		$attr['include'] = $attr['ids'];
 917	}
 918
 919	/**
 920	 * Filter the default gallery shortcode output.
 921	 *
 922	 * If the filtered output isn't empty, it will be used instead of generating
 923	 * the default gallery template.
 924	 *
 925	 * @since 2.5.0
 926	 *
 927	 * @see gallery_shortcode()
 928	 *
 929	 * @param string $output The gallery output. Default empty.
 930	 * @param array  $attr   Attributes of the gallery shortcode.
 931	 */
 932	$output = apply_filters( 'post_gallery', '', $attr );
 933	if ( $output != '' )
 934		return $output;
 935
 936	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
 937	if ( isset( $attr['orderby'] ) ) {
 938		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
 939		if ( !$attr['orderby'] )
 940			unset( $attr['orderby'] );
 941	}
 942
 943	$html5 = current_theme_supports( 'html5', 'gallery' );
 944	extract(shortcode_atts(array(
 945		'order'      => 'ASC',
 946		'orderby'    => 'menu_order ID',
 947		'id'         => $post ? $post->ID : 0,
 948		'itemtag'    => $html5 ? 'figure'     : 'dl',
 949		'icontag'    => $html5 ? 'div'        : 'dt',
 950		'captiontag' => $html5 ? 'figcaption' : 'dd',
 951		'columns'    => 3,
 952		'size'       => 'thumbnail',
 953		'include'    => '',
 954		'exclude'    => '',
 955		'link'       => ''
 956	), $attr, 'gallery'));
 957
 958	$id = intval($id);
 959	if ( 'RAND' == $order )
 960		$orderby = 'none';
 961
 962	if ( !empty($include) ) {
 963		$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
 964
 965		$attachments = array();
 966		foreach ( $_attachments as $key => $val ) {
 967			$attachments[$val->ID] = $_attachments[$key];
 968		}
 969	} elseif ( !empty($exclude) ) {
 970		$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
 971	} else {
 972		$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
 973	}
 974
 975	if ( empty($attachments) )
 976		return '';
 977
 978	if ( is_feed() ) {
 979		$output = "\n";
 980		foreach ( $attachments as $att_id => $attachment )
 981			$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
 982		return $output;
 983	}
 984
 985	$itemtag = tag_escape($itemtag);
 986	$captiontag = tag_escape($captiontag);
 987	$icontag = tag_escape($icontag);
 988	$valid_tags = wp_kses_allowed_html( 'post' );
 989	if ( ! isset( $valid_tags[ $itemtag ] ) )
 990		$itemtag = 'dl';
 991	if ( ! isset( $valid_tags[ $captiontag ] ) )
 992		$captiontag = 'dd';
 993	if ( ! isset( $valid_tags[ $icontag ] ) )
 994		$icontag = 'dt';
 995
 996	$columns = intval($columns);
 997	$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
 998	$float = is_rtl() ? 'right' : 'left';
 999
1000	$selector = "gallery-{$instance}";
1001
1002	$gallery_style = $gallery_div = '';
1003
1004	/**
1005	 * Filter whether to print default gallery styles.
1006	 *
1007	 * @since 3.1.0
1008	 *
1009	 * @param bool $print Whether to print default gallery styles.
1010	 *                    Defaults to false if the theme supports HTML5 galleries.
1011	 *                    Otherwise, defaults to true.
1012	 */
1013	if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
1014		$gallery_style = "
1015		<style type='text/css'>
1016			#{$selector} {
1017				margin: auto;
1018			}
1019			#{$selector} .gallery-item {
1020				float: {$float};
1021				margin-top: 10px;
1022				text-align: center;
1023				width: {$itemwidth}%;
1024			}
1025			#{$selector} img {
1026				border: 2px solid #cfcfcf;
1027			}
1028			#{$selector} .gallery-caption {
1029				margin-left: 0;
1030			}
1031			/* see gallery_shortcode() in wp-includes/media.php */
1032		</style>\n\t\t";
1033	}
1034
1035	$size_class = sanitize_html_class( $size );
1036	$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
1037
1038	/**
1039	 * Filter the default gallery shortcode CSS styles.
1040	 *
1041	 * @since 2.5.0
1042	 *
1043	 * @param string $gallery_style Default gallery shortcode CSS styles.
1044	 * @param string $gallery_div   Opening HTML div container for the gallery shortcode output.
1045	 */
1046	$output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
1047
1048	$i = 0;
1049	foreach ( $attachments as $id => $attachment ) {
1050		if ( ! empty( $link ) && 'file' === $link )
1051			$image_output = wp_get_attachment_link( $id, $size, false, false );
1052		elseif ( ! empty( $link ) && 'none' === $link )
1053			$image_output = wp_get_attachment_image( $id, $size, false );
1054		else
1055			$image_output = wp_get_attachment_link( $id, $size, true, false );
1056
1057		$image_meta  = wp_get_attachment_metadata( $id );
1058
1059		$orientation = '';
1060		if ( isset( $image_meta['height'], $image_meta['width'] ) )
1061			$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
1062
1063		$output .= "<{$itemtag} class='gallery-item'>";
1064		$output .= "
1065			<{$icontag} class='gallery-icon {$orientation}'>
1066				$image_output
1067			</{$icontag}>";
1068		if ( $captiontag && trim($attachment->post_excerpt) ) {
1069			$output .= "
1070				<{$captiontag} class='wp-caption-text gallery-caption'>
1071				" . wptexturize($attachment->post_excerpt) . "
1072				</{$captiontag}>";
1073		}
1074		$output .= "</{$itemtag}>";
1075		if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
1076			$output .= '<br style="clear: both" />';
1077		}
1078	}
1079
1080	if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
1081		$output .= "
1082			<br style='clear: both' />";
1083	}
1084
1085	$output .= "
1086		</div>\n";
1087
1088	return $output;
1089}
1090
1091/**
1092 * Output the templates used by playlists.
1093 *
1094 * @since 3.9.0
1095 */
1096function wp_underscore_playlist_templates() {
1097?>
1098<script type="text/html" id="tmpl-wp-playlist-current-item">
1099	<# if ( data.image ) { #>
1100	<img src="{{ data.thumb.src }}"/>
1101	<# } #>
1102	<div class="wp-playlist-caption">
1103		<span class="wp-playlist-item-meta wp-playlist-item-title">&#8220;{{ data.title }}&#8221;</span>
1104		<# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
1105		<# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
1106	</div>
1107</script>
1108<script type="text/html" id="tmpl-wp-playlist-item">
1109	<div class="wp-playlist-item">
1110		<a class="wp-playlist-caption" href="{{ data.src }}">
1111			{{ data.index ? ( data.index + '. ' ) : '' }}
1112			<# if ( data.caption ) { #>
1113				{{ data.caption }}
1114			<# } else { #>
1115				<span class="wp-playlist-item-title">&#8220;{{{ data.title }}}&#8221;</span>
1116				<# if ( data.artists && data.meta.artist ) { #>
1117				<span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
1118				<# } #>
1119			<# } #>
1120		</a>
1121		<# if ( data.meta.length_formatted ) { #>
1122		<div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
1123		<# } #>
1124	</div>
1125</script>
1126<?php
1127}
1128
1129/**
1130 * Output and enqueue default scripts and styles for playlists.
1131 *
1132 * @since 3.9.0
1133 *
1134 * @param string $type Type of playlist. Accepts 'audio' or 'video'.
1135 */
1136function wp_playlist_scripts( $type ) {
1137	wp_enqueue_style( 'wp-mediaelement' );
1138	wp_enqueue_script( 'wp-playlist' );
1139?>
1140<!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
1141<?php
1142	add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
1143	add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
1144}
1145add_action( 'wp_playlist_scripts', 'wp_playlist_scripts' );
1146
1147/**
1148 * The playlist shortcode.
1149 *
1150 * This implements the functionality of the playlist shortcode for displaying
1151 * a collection of WordPress audio or video files in a post.
1152 *
1153 * @since 3.9.0
1154 *
1155 * @param array $attr Playlist shortcode attributes.
1156 * @return string Playlist output. Empty string if the passed type is unsupported.
1157 */
1158function wp_playlist_shortcode( $attr ) {
1159	global $content_width;
1160	$post = get_post();
1161
1162	static $instance = 0;
1163	$instance++;
1164
1165	if ( ! empty( $attr['ids'] ) ) {
1166		// 'ids' is explicitly ordered, unless you specify otherwise.
1167		if ( empty( $attr['orderby'] ) ) {
1168			$attr['orderby'] = 'post__in';
1169		}
1170		$attr['include'] = $attr['ids'];
1171	}
1172
1173	/**
1174	 * Filter the playlist output.
1175	 *
1176	 * Passing a non-empty value to the filter will short-circuit generation
1177	 * of the default playlist output, returning the passed value instead.
1178	 *
1179	 * @since 3.9.0
1180	 *
1181	 * @param string $output Playlist output. Default empty.
1182	 * @param array  $attr   An array of shortcode attributes.
1183	 */
1184	$output = apply_filters( 'post_playlist', '', $attr );
1185	if ( $output != '' ) {
1186		return $output;
1187	}
1188
1189	/*
1190	 * We're trusting author input, so let's at least make sure it looks
1191	 * like a valid orderby statement.
1192	 */
1193	if ( isset( $attr['orderby'] ) ) {
1194		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
1195		if ( ! $attr['orderby'] )
1196			unset( $attr['orderby'] );
1197	}
1198
1199	extract( shortcode_atts( array(
1200		'type'		=> 'audio',
1201		'order'		=> 'ASC',
1202		'orderby'	=> 'menu_order ID',
1203		'id'		=> $post ? $post->ID : 0,
1204		'include'	=> '',
1205		'exclude'   => '',
1206		'style'		=> 'light',
1207		'tracklist' => true,
1208		'tracknumbers' => true,
1209		'images'	=> true,
1210		'artists'	=> true
1211	), $attr, 'playlist' ) );
1212
1213	$id = intval( $id );
1214	if ( 'RAND' == $order ) {
1215		$orderby = 'none';
1216	}
1217
1218	$args = array(
1219		'post_status' => 'inherit',
1220		'post_type' => 'attachment',
1221		'post_mime_type' => $type,
1222		'order' => $order,
1223		'orderby' => $orderby
1224	);
1225
1226	if ( ! empty( $include ) ) {
1227		$args['include'] = $include;
1228		$_attachments = get_posts( $args );
1229
1230		$attachments = array();
1231		foreach ( $_attachments as $key => $val ) {
1232			$attachments[$val->ID] = $_attachments[$key];
1233		}
1234	} elseif ( ! empty( $exclude ) ) {
1235		$args['post_parent'] = $id;
1236		$args['exclude'] = $exclude;
1237		$attachments = get_children( $args );
1238	} else {
1239		$args['post_parent'] = $id;
1240		$attachments = get_children( $args );
1241	}
1242
1243	if ( empty( $attachments ) ) {
1244		return '';
1245	}
1246
1247	if ( is_feed() ) {
1248		$output = "\n";
1249		foreach ( $attachments as $att_id => $attachment ) {
1250			$output .= wp_get_attachment_link( $att_id ) . "\n";
1251		}
1252		return $output;
1253	}
1254
1255	$outer = 22; // default padding and border of wrapper
1256
1257	$default_width = 640;
1258	$default_height = 360;
1259
1260	$theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
1261	$theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
1262
1263	$data = compact( 'type' );
1264
1265	// don't pass strings to JSON, will be truthy in JS
1266	foreach ( array( 'tracklist', 'tracknumbers', 'images', 'artists' ) as $key ) {
1267		$data[$key] = filter_var( $$key, FILTER_VALIDATE_BOOLEAN );
1268	}
1269
1270	$tracks = array();
1271	foreach ( $attachments as $attachment ) {
1272		$url = wp_get_attachment_url( $attachment->ID );
1273		$ftype = wp_check_filetype( $url, wp_get_mime_types() );
1274		$track = array(
1275			'src' => $url,
1276			'type' => $ftype['type'],
1277			'title' => $attachment->post_title,
1278			'caption' => $attachment->post_excerpt,
1279			'description' => $attachment->post_content
1280		);
1281
1282		$track['meta'] = array();
1283		$meta = wp_get_attachment_metadata( $attachment->ID );
1284		if ( ! empty( $meta ) ) {
1285
1286			foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
1287				if ( ! empty( $meta[ $key ] ) ) {
1288					$track['meta'][ $key ] = $meta[ $key ];
1289				}
1290			}
1291
1292			if ( 'video' === $type ) {
1293				if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
1294					$width = $meta['width'];
1295					$height = $meta['height'];
1296					$theme_height = round( ( $height * $theme_width ) / $width );
1297				} else {
1298					$width = $default_width;
1299					$height = $default_height;
1300				}
1301
1302				$track['dimensions'] = array(
1303					'original' => compact( 'width', 'height' ),
1304					'resized' => array(
1305						'width' => $theme_width,
1306						'height' => $theme_height
1307					)
1308				);
1309			}
1310		}
1311
1312		if ( $images ) {
1313			$id = get_post_thumbnail_id( $attachment->ID );
1314			if ( ! empty( $id ) ) {
1315				list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
1316				$track['image'] = compact( 'src', 'width', 'height' );
1317				list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
1318				$track['thumb'] = compact( 'src', 'width', 'height' );
1319			} else {
1320				$src = wp_mime_type_icon( $attachment->ID );
1321				$width = 48;
1322				$height = 64;
1323				$track['image'] = compact( 'src', 'width', 'height' );
1324				$track['thumb'] = compact( 'src', 'width', 'height' );
1325			}
1326		}
1327
1328		$tracks[] = $track;
1329	}
1330	$data['tracks'] = $tracks;
1331
1332	$safe_type = esc_attr( $type );
1333	$safe_style = esc_attr( $style );
1334
1335	ob_start();
1336
1337	if ( 1 === $instance ) {
1338		/**
1339		 * Print and enqueue playlist scripts, styles, and JavaScript templates.
1340		 *
1341		 * @since 3.9.0
1342		 *
1343		 * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
1344		 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
1345		 */
1346		do_action( 'wp_playlist_scripts', $type, $style );
1347	} ?>
1348<div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
1349	<?php if ( 'audio' === $type ): ?>
1350	<div class="wp-playlist-current-item"></div>
1351	<?php endif ?>
1352	<<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
1353		echo (int) $theme_width;
1354	?>"<?php if ( 'video' === $safe_type ):
1355		echo ' height="', (int) $theme_height, '"';
1356	endif; ?>></<?php echo $safe_type ?>>
1357	<div class="wp-playlist-next"></div>
1358	<div class="wp-playlist-prev"></div>
1359	<noscript>
1360	<ol><?php
1361	foreach ( $attachments as $att_id => $attachment ) {
1362		printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
1363	}
1364	?></ol>
1365	</noscript>
1366	<script type="application/json"><?php echo json_encode( $data ) ?></script>
1367</div>
1368	<?php
1369	return ob_get_clean();
1370}
1371add_shortcode( 'playlist', 'wp_playlist_shortcode' );
1372
1373/**
1374 * Provide a No-JS Flash fallback as a last resort for audio / video
1375 *
1376 * @since 3.6.0
1377 *
1378 * @param string $url
1379 * @return string Fallback HTML
1380 */
1381function wp_mediaelement_fallback( $url ) {
1382	/**
1383	 * Filter the Mediaelement fallback output for no-JS.
1384	 *
1385	 * @since 3.6.0
1386	 *
1387	 * @param string $output Fallback output for no-JS.
1388	 * @param string $url    Media file URL.
1389	 */
1390	return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
1391}
1392
1393/**
1394 * Return a filtered list of WP-supported audio formats.
1395 *
1396 * @since 3.6.0
1397 * @return array
1398 */
1399function wp_get_audio_extensions() {
1400	/**
1401	 * Filter the list of supported audio formats.
1402	 *
1403	 * @since 3.6.0
1404	 *
1405	 * @param array $extensions An array of support audio formats. Defaults are
1406	 *                          'mp3', 'ogg', 'wma', 'm4a', 'wav'.
1407	 */
1408	return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
1409}
1410
1411/**
1412 * Return useful keys to use to lookup data from an attachment's stored metadata.
1413 *
1414 * @since 3.9.0
1415 *
1416 * @param WP_Post $attachment The current attachment, provided for context.
1417 * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
1418 * @return array Key/value pairs of field keys to labels.
1419 */
1420function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
1421	$fields = array(
1422		'artist' => __( 'Artist' ),
1423		'album' => __( 'Album' ),
1424	);
1425
1426	if ( 'display' === $context ) {
1427		$fields['genre']            = __( 'Genre' );
1428		$fields['year']             = __( 'Year' );
1429		$fields['length_formatted'] = _x( 'Length', 'video or audio' );
1430	}
1431
1432	/**
1433	 * Filter the editable list of keys to look up data from an attachment's metadata.
1434	 *
1435	 * @since 3.9.0
1436	 *
1437	 * @param array   $fields     Key/value pairs of field keys to labels.
1438	 * @param WP_Post $attachment A…

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