wp/wp-includes/media.php
changeset 5 5e2f62d02dcd
parent 0 d970ebf37754
child 7 cf61fcea0001
equal deleted inserted replaced
4:346c88efed21 5:5e2f62d02dcd
     9 /**
     9 /**
    10  * Scale down the default size of an image.
    10  * Scale down the default size of an image.
    11  *
    11  *
    12  * This is so that the image is a better fit for the editor and theme.
    12  * This is so that the image is a better fit for the editor and theme.
    13  *
    13  *
    14  * The $size parameter accepts either an array or a string. The supported string
    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
    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
    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
    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
    18  * than the supported will result in the content_width size or 500 if that is
    19  * not set.
    19  * not set.
    20  *
    20  *
    21  * Finally, there is a filter named 'editor_max_image_size', that will be called
    21  * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
    22  * on the calculated array for width and height, respectively. The second
    22  * called 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
    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
    24  * type for the hook is an array with the width as the first element and the
    25  * height as the second element.
    25  * height as the second element.
    26  *
    26  *
    27  * @since 2.5.0
    27  * @since 2.5.0
    28  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
    28  *
    29  *
    29  * @param int          $width   Width of the image in pixels.
    30  * @param int $width Width of the image
    30  * @param int          $height  Height of the image in pixels.
    31  * @param int $height Height of the image
    31  * @param string|array $size    Optional. Size or array of sizes of what the result image
    32  * @param string|array $size Size of what the result image should be.
    32  *                              should be. Accepts any valid image size name. Default 'medium'.
    33  * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
    33  * @param string       $context Optional. Could be 'display' (like in a theme) or 'edit'
       
    34  *                              (like inserting into an editor). Default null.
    34  * @return array Width and height of what the result image should resize to.
    35  * @return array Width and height of what the result image should resize to.
    35  */
    36  */
    36 function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
    37 function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
    37 	global $content_width, $_wp_additional_image_sizes;
    38 	global $content_width, $_wp_additional_image_sizes;
    38 
    39 
    39 	if ( ! $context )
    40 	if ( ! $context )
    40 		$context = is_admin() ? 'edit' : 'display';
    41 		$context = is_admin() ? 'edit' : 'display';
    41 
    42 
    56 		$max_width = intval(get_option('medium_size_w'));
    57 		$max_width = intval(get_option('medium_size_w'));
    57 		$max_height = intval(get_option('medium_size_h'));
    58 		$max_height = intval(get_option('medium_size_h'));
    58 		// if no width is set, default to the theme content width if available
    59 		// if no width is set, default to the theme content width if available
    59 	}
    60 	}
    60 	elseif ( $size == 'large' ) {
    61 	elseif ( $size == 'large' ) {
    61 		// We're inserting a large size image into the editor. If it's a really
    62 		/*
    62 		// big image we'll scale it down to fit reasonably within the editor
    63 		 * We're inserting a large size image into the editor. If it's a really
    63 		// itself, and within the theme's content width if it's known. The user
    64 		 * big image we'll scale it down to fit reasonably within the editor
    64 		// can resize it in the editor if they wish.
    65 		 * itself, and within the theme's content width if it's known. The user
       
    66 		 * can resize it in the editor if they wish.
       
    67 		 */
    65 		$max_width = intval(get_option('large_size_w'));
    68 		$max_width = intval(get_option('large_size_w'));
    66 		$max_height = intval(get_option('large_size_h'));
    69 		$max_height = intval(get_option('large_size_h'));
    67 		if ( intval($content_width) > 0 )
    70 		if ( intval($content_width) > 0 )
    68 			$max_width = min( intval($content_width), $max_width );
    71 			$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 ) ) ) {
    72 	} elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
    76 	else {
    79 	else {
    77 		$max_width = $width;
    80 		$max_width = $width;
    78 		$max_height = $height;
    81 		$max_height = $height;
    79 	}
    82 	}
    80 
    83 
       
    84 	/**
       
    85 	 * Filter the maximum image size dimensions for the editor.
       
    86 	 *
       
    87 	 * @since 2.5.0
       
    88 	 *
       
    89 	 * @param array        $max_image_size An array with the width as the first element,
       
    90 	 *                                     and the height as the second element.
       
    91 	 * @param string|array $size           Size of what the result image should be.
       
    92 	 * @param string       $context        The context the image is being resized for.
       
    93 	 *                                     Possible values are 'display' (like in a theme)
       
    94 	 *                                     or 'edit' (like inserting into an editor).
       
    95 	 */
    81 	list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
    96 	list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
    82 
    97 
    83 	return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
    98 	return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
    84 }
    99 }
    85 
   100 
    94  * If you wish to put 'px' after the numbers, then it will be stripped out of
   109  * If you wish to put 'px' after the numbers, then it will be stripped out of
    95  * the return.
   110  * the return.
    96  *
   111  *
    97  * @since 2.5.0
   112  * @since 2.5.0
    98  *
   113  *
    99  * @param int|string $width Optional. Width attribute value.
   114  * @param int|string $width  Image width in pixels.
   100  * @param int|string $height Optional. Height attribute value.
   115  * @param int|string $height Image height in pixels.
   101  * @return string HTML attributes for width and, or height.
   116  * @return string HTML attributes for width and, or height.
   102  */
   117  */
   103 function image_hwstring($width, $height) {
   118 function image_hwstring( $width, $height ) {
   104 	$out = '';
   119 	$out = '';
   105 	if ($width)
   120 	if ($width)
   106 		$out .= 'width="'.intval($width).'" ';
   121 		$out .= 'width="'.intval($width).'" ';
   107 	if ($height)
   122 	if ($height)
   108 		$out .= 'height="'.intval($height).'" ';
   123 		$out .= 'height="'.intval($height).'" ';
   124  * resizing services for images. The hook must return an array with the same
   139  * 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
   140  * elements that are returned in the function. The first element being the URL
   126  * to the new image that was resized.
   141  * to the new image that was resized.
   127  *
   142  *
   128  * @since 2.5.0
   143  * @since 2.5.0
   129  * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide
   144  *
   130  *		resize services.
   145  * @param int          $id   Attachment ID for image.
   131  *
   146  * @param array|string $size Optional. Image size to scale to. Accepts a registered image size
   132  * @param int $id Attachment ID for image.
   147  *                           or flat array of height and width values. Default 'medium'.
   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.
   148  * @return bool|array False on failure, array on success.
   135  */
   149  */
   136 function image_downsize($id, $size = 'medium') {
   150 function image_downsize( $id, $size = 'medium' ) {
   137 
   151 
   138 	if ( !wp_attachment_is_image($id) )
   152 	if ( !wp_attachment_is_image($id) )
   139 		return false;
   153 		return false;
   140 
   154 
   141 	// plugins can use this to provide resize services
   155 	/**
   142 	if ( $out = apply_filters( 'image_downsize', false, $id, $size ) )
   156 	 * Filter whether to preempt the output of image_downsize().
       
   157 	 *
       
   158 	 * Passing a truthy value to the filter will effectively short-circuit
       
   159 	 * down-sizing the image, returning that value as output instead.
       
   160 	 *
       
   161 	 * @since 2.5.0
       
   162 	 *
       
   163 	 * @param bool         $downsize Whether to short-circuit the image downsize. Default false.
       
   164 	 * @param int          $id       Attachment ID for image.
       
   165 	 * @param array|string $size     Size of image, either array or string. Default 'medium'.
       
   166 	 */
       
   167 	if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
   143 		return $out;
   168 		return $out;
       
   169 	}
   144 
   170 
   145 	$img_url = wp_get_attachment_url($id);
   171 	$img_url = wp_get_attachment_url($id);
   146 	$meta = wp_get_attachment_metadata($id);
   172 	$meta = wp_get_attachment_metadata($id);
   147 	$width = $height = 0;
   173 	$width = $height = 0;
   148 	$is_intermediate = false;
   174 	$is_intermediate = false;
   179 	return false;
   205 	return false;
   180 
   206 
   181 }
   207 }
   182 
   208 
   183 /**
   209 /**
   184  * Registers a new image size
   210  * Register a new image size.
       
   211  *
       
   212  * Cropping behavior for the image size is dependent on the value of $crop:
       
   213  * 1. If false (default), images will be scaled, not cropped.
       
   214  * 2. If an array in the form of array( x_crop_position, y_crop_position ):
       
   215  *    - x_crop_position accepts 'left' 'center', or 'right'.
       
   216  *    - y_crop_position accepts 'top', 'center', or 'bottom'.
       
   217  *    Images will be cropped to the specified dimensions within the defined crop area.
       
   218  * 3. If true, images will be cropped to the specified dimensions using center positions.
   185  *
   219  *
   186  * @since 2.9.0
   220  * @since 2.9.0
       
   221  *
       
   222  * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
       
   223  *
       
   224  * @param string     $name   Image size identifier.
       
   225  * @param int        $width  Image width in pixels.
       
   226  * @param int        $height Image height in pixels.
       
   227  * @param bool|array $crop   Optional. Whether to crop images to specified height and width or resize.
       
   228  *                           An array can specify positioning of the crop area. Default false.
   187  */
   229  */
   188 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
   230 function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
   189 	global $_wp_additional_image_sizes;
   231 	global $_wp_additional_image_sizes;
   190 	$_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
   232 
   191 }
   233 	$_wp_additional_image_sizes[ $name ] = array(
   192 
   234 		'width'  => absint( $width ),
   193 /**
   235 		'height' => absint( $height ),
   194  * Registers an image size for the post thumbnail
   236 		'crop'   => $crop,
       
   237 	);
       
   238 }
       
   239 
       
   240 /**
       
   241  * Check if an image size exists.
       
   242  *
       
   243  * @since 3.9.0
       
   244  *
       
   245  * @param string $name The image size to check.
       
   246  * @return bool True if the image size exists, false if not.
       
   247  */
       
   248 function has_image_size( $name ) {
       
   249 	global $_wp_additional_image_sizes;
       
   250 
       
   251 	return isset( $_wp_additional_image_sizes[ $name ] );
       
   252 }
       
   253 
       
   254 /**
       
   255  * Remove a new image size.
       
   256  *
       
   257  * @since 3.9.0
       
   258  *
       
   259  * @param string $name The image size to remove.
       
   260  * @return bool True if the image size was successfully removed, false on failure.
       
   261  */
       
   262 function remove_image_size( $name ) {
       
   263 	global $_wp_additional_image_sizes;
       
   264 
       
   265 	if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
       
   266 		unset( $_wp_additional_image_sizes[ $name ] );
       
   267 		return true;
       
   268 	}
       
   269 
       
   270 	return false;
       
   271 }
       
   272 
       
   273 /**
       
   274  * Registers an image size for the post thumbnail.
   195  *
   275  *
   196  * @since 2.9.0
   276  * @since 2.9.0
       
   277  *
       
   278  * @see add_image_size() for details on cropping behavior.
       
   279  *
       
   280  * @param int        $width  Image width in pixels.
       
   281  * @param int        $height Image height in pixels.
       
   282  * @param bool|array $crop   Optional. Whether to crop images to specified height and width or resize.
       
   283  *                           An array can specify positioning of the crop area. Default false.
   197  */
   284  */
   198 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
   285 function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
   199 	add_image_size( 'post-thumbnail', $width, $height, $crop );
   286 	add_image_size( 'post-thumbnail', $width, $height, $crop );
   200 }
   287 }
   201 
   288 
   202 /**
   289 /**
   203  * An <img src /> tag for an image attachment, scaling it down if requested.
   290  * Gets an img tag for an image attachment, scaling it down if requested.
   204  *
   291  *
   205  * The filter 'get_image_tag_class' allows for changing the class name for the
   292  * 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
   293  * 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,
   294  * parameters are: what WordPress will use for the class, the Attachment ID,
   208  * image align value, and the size the image should be.
   295  * image align value, and the size the image should be.
   211  * further manipulated by a plugin to change all attribute values and even HTML
   298  * further manipulated by a plugin to change all attribute values and even HTML
   212  * content.
   299  * content.
   213  *
   300  *
   214  * @since 2.5.0
   301  * @since 2.5.0
   215  *
   302  *
   216  * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element
   303  * @param int          $id    Attachment ID.
   217  *		class attribute.
   304  * @param string       $alt   Image Description for the alt attribute.
   218  * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with
   305  * @param string       $title Image Description for the title attribute.
   219  *		all attributes.
   306  * @param string       $align Part of the class name for aligning the image.
   220  *
   307  * @param string|array $size  Optional. Registered image size to retrieve a tag for, or flat array
   221  * @param int $id Attachment ID.
   308  *                            of height and width values. Default 'medium'.
   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
   309  * @return string HTML IMG element for given image attachment
   227  */
   310  */
   228 function get_image_tag($id, $alt, $title, $align, $size='medium') {
   311 function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
   229 
   312 
   230 	list( $img_src, $width, $height ) = image_downsize($id, $size);
   313 	list( $img_src, $width, $height ) = image_downsize($id, $size);
   231 	$hwstring = image_hwstring($width, $height);
   314 	$hwstring = image_hwstring($width, $height);
   232 
   315 
   233 	$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
   316 	$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
   234 
   317 
   235 	$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
   318 	$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
   236 	$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
   319 
       
   320 	/**
       
   321 	 * Filter the value of the attachment's image tag class attribute.
       
   322 	 *
       
   323 	 * @since 2.6.0
       
   324 	 *
       
   325 	 * @param string $class CSS class name or space-separated list of classes.
       
   326 	 * @param int    $id    Attachment ID.
       
   327 	 * @param string $align Part of the class name for aligning the image.
       
   328 	 * @param string $size  Optional. Default is 'medium'.
       
   329 	 */
       
   330 	$class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
   237 
   331 
   238 	$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
   332 	$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
   239 
   333 
       
   334 	/**
       
   335 	 * Filter the HTML content for the image tag.
       
   336 	 *
       
   337 	 * @since 2.6.0
       
   338 	 *
       
   339 	 * @param string $html  HTML content for the image.
       
   340 	 * @param int    $id    Attachment ID.
       
   341 	 * @param string $alt   Alternate text.
       
   342 	 * @param string $title Attachment title.
       
   343 	 * @param string $align Part of the class name for aligning the image.
       
   344 	 * @param string $size  Optional. Default is 'medium'.
       
   345 	 */
   240 	$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
   346 	$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
   241 
   347 
   242 	return $html;
   348 	return $html;
   243 }
   349 }
   244 
   350 
   245 /**
   351 /**
   246  * Calculates the new dimensions for a downsampled image.
   352  * Calculates the new dimensions for a down-sampled image.
   247  *
   353  *
   248  * If either width or height are empty, no constraint is applied on
   354  * If either width or height are empty, no constraint is applied on
   249  * that dimension.
   355  * that dimension.
   250  *
   356  *
   251  * @since 2.5.0
   357  * @since 2.5.0
   252  *
   358  *
   253  * @param int $current_width Current width of the image.
   359  * @param int $current_width  Current width of the image.
   254  * @param int $current_height Current height of the image.
   360  * @param int $current_height Current height of the image.
   255  * @param int $max_width Optional. Maximum wanted width.
   361  * @param int $max_width      Optional. Max width in pixels to constrain to. Default 0.
   256  * @param int $max_height Optional. Maximum wanted height.
   362  * @param int $max_height     Optional. Max height in pixels to constrain to. Default 0.
   257  * @return array First item is the width, the second item is the height.
   363  * @return array First item is the width, the second item is the height.
   258  */
   364  */
   259 function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
   365 function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
   260 	if ( !$max_width and !$max_height )
   366 	if ( !$max_width && !$max_height )
   261 		return array( $current_width, $current_height );
   367 		return array( $current_width, $current_height );
   262 
   368 
   263 	$width_ratio = $height_ratio = 1.0;
   369 	$width_ratio = $height_ratio = 1.0;
   264 	$did_width = $did_height = false;
   370 	$did_width = $did_height = false;
   265 
   371 
   275 
   381 
   276 	// Calculate the larger/smaller ratios
   382 	// Calculate the larger/smaller ratios
   277 	$smaller_ratio = min( $width_ratio, $height_ratio );
   383 	$smaller_ratio = min( $width_ratio, $height_ratio );
   278 	$larger_ratio  = max( $width_ratio, $height_ratio );
   384 	$larger_ratio  = max( $width_ratio, $height_ratio );
   279 
   385 
   280 	if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
   386 	if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
   281  		// The larger ratio is too big. It would result in an overflow.
   387  		// The larger ratio is too big. It would result in an overflow.
   282 		$ratio = $smaller_ratio;
   388 		$ratio = $smaller_ratio;
   283 	else
   389 	} else {
   284 		// The larger ratio fits, and is likely to be a more "snug" fit.
   390 		// The larger ratio fits, and is likely to be a more "snug" fit.
   285 		$ratio = $larger_ratio;
   391 		$ratio = $larger_ratio;
       
   392 	}
   286 
   393 
   287 	// Very small dimensions may result in 0, 1 should be the minimum.
   394 	// Very small dimensions may result in 0, 1 should be the minimum.
   288 	$w = max ( 1, intval( $current_width  * $ratio ) );
   395 	$w = max ( 1, (int) round( $current_width  * $ratio ) );
   289 	$h = max ( 1, intval( $current_height * $ratio ) );
   396 	$h = max ( 1, (int) round( $current_height * $ratio ) );
   290 
   397 
   291 	// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
   398 	// Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
   292 	// 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.
   399 	// 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.
   293 	// Thus we look for dimensions that are one pixel shy of the max value and bump them up
   400 	// Thus we look for dimensions that are one pixel shy of the max value and bump them up
   294 	if ( $did_width && $w == $max_width - 1 )
   401 
       
   402 	// Note: $did_width means it is possible $smaller_ratio == $width_ratio.
       
   403 	if ( $did_width && $w == $max_width - 1 ) {
   295 		$w = $max_width; // Round it up
   404 		$w = $max_width; // Round it up
   296 	if ( $did_height && $h == $max_height - 1 )
   405 	}
       
   406 
       
   407 	// Note: $did_height means it is possible $smaller_ratio == $height_ratio.
       
   408 	if ( $did_height && $h == $max_height - 1 ) {
   297 		$h = $max_height; // Round it up
   409 		$h = $max_height; // Round it up
   298 
   410 	}
   299 	return array( $w, $h );
   411 
   300 }
   412 	/**
   301 
   413 	 * Filter dimensions to constrain down-sampled images to.
   302 /**
   414 	 *
   303  * Retrieve calculated resized dimensions for use in WP_Image_Editor.
   415 	 * @since 4.1.0
   304  *
   416 	 *
   305  * Calculate dimensions and coordinates for a resized image that fits within a
   417 	 * @param array $dimensions     The image width and height.
   306  * specified width and height. If $crop is true, the largest matching central
   418 	 * @param int 	$current_width  The current width of the image.
   307  * portion of the image will be cropped out and resized to the required size.
   419 	 * @param int 	$current_height The current height of the image.
       
   420 	 * @param int 	$max_width      The maximum width permitted.
       
   421 	 * @param int 	$max_height     The maximum height permitted.
       
   422 	 */
       
   423 	return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
       
   424 }
       
   425 
       
   426 /**
       
   427  * Retrieves calculated resize dimensions for use in WP_Image_Editor.
       
   428  *
       
   429  * Calculates dimensions and coordinates for a resized image that fits
       
   430  * within a specified width and height.
       
   431  *
       
   432  * Cropping behavior is dependent on the value of $crop:
       
   433  * 1. If false (default), images will not be cropped.
       
   434  * 2. If an array in the form of array( x_crop_position, y_crop_position ):
       
   435  *    - x_crop_position accepts 'left' 'center', or 'right'.
       
   436  *    - y_crop_position accepts 'top', 'center', or 'bottom'.
       
   437  *    Images will be cropped to the specified dimensions within the defined crop area.
       
   438  * 3. If true, images will be cropped to the specified dimensions using center positions.
   308  *
   439  *
   309  * @since 2.5.0
   440  * @since 2.5.0
   310  * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and
   441  *
   311  *		$crop to provide custom resize dimensions.
   442  * @param int        $orig_w Original width in pixels.
   312  *
   443  * @param int        $orig_h Original height in pixels.
   313  * @param int $orig_w Original width.
   444  * @param int        $dest_w New width in pixels.
   314  * @param int $orig_h Original height.
   445  * @param int        $dest_h New height in pixels.
   315  * @param int $dest_w New width.
   446  * @param bool|array $crop   Optional. Whether to crop image to specified height and width or resize.
   316  * @param int $dest_h New height.
   447  *                           An array can specify positioning of the crop area. Default false.
   317  * @param bool $crop Optional, default is false. Whether to crop image or resize.
   448  * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
   318  * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function.
       
   319  */
   449  */
   320 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
   450 function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
   321 
   451 
   322 	if ($orig_w <= 0 || $orig_h <= 0)
   452 	if ($orig_w <= 0 || $orig_h <= 0)
   323 		return false;
   453 		return false;
   324 	// at least one of dest_w or dest_h must be specific
   454 	// at least one of dest_w or dest_h must be specific
   325 	if ($dest_w <= 0 && $dest_h <= 0)
   455 	if ($dest_w <= 0 && $dest_h <= 0)
   326 		return false;
   456 		return false;
   327 
   457 
   328 	// plugins can use this to provide custom resize dimensions
   458 	/**
       
   459 	 * Filter whether to preempt calculating the image resize dimensions.
       
   460 	 *
       
   461 	 * Passing a non-null value to the filter will effectively short-circuit
       
   462 	 * image_resize_dimensions(), returning that value instead.
       
   463 	 *
       
   464 	 * @since 3.4.0
       
   465 	 *
       
   466 	 * @param null|mixed $null   Whether to preempt output of the resize dimensions.
       
   467 	 * @param int        $orig_w Original width in pixels.
       
   468 	 * @param int        $orig_h Original height in pixels.
       
   469 	 * @param int        $dest_w New width in pixels.
       
   470 	 * @param int        $dest_h New height in pixels.
       
   471 	 * @param bool|array $crop   Whether to crop image to specified height and width or resize.
       
   472 	 *                           An array can specify positioning of the crop area. Default false.
       
   473 	 */
   329 	$output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
   474 	$output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
   330 	if ( null !== $output )
   475 	if ( null !== $output )
   331 		return $output;
   476 		return $output;
   332 
   477 
   333 	if ( $crop ) {
   478 	if ( $crop ) {
   334 		// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
   479 		// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
   335 		$aspect_ratio = $orig_w / $orig_h;
   480 		$aspect_ratio = $orig_w / $orig_h;
   336 		$new_w = min($dest_w, $orig_w);
   481 		$new_w = min($dest_w, $orig_w);
   337 		$new_h = min($dest_h, $orig_h);
   482 		$new_h = min($dest_h, $orig_h);
   338 
   483 
   339 		if ( !$new_w ) {
   484 		if ( ! $new_w ) {
   340 			$new_w = intval($new_h * $aspect_ratio);
   485 			$new_w = (int) round( $new_h * $aspect_ratio );
   341 		}
   486 		}
   342 
   487 
   343 		if ( !$new_h ) {
   488 		if ( ! $new_h ) {
   344 			$new_h = intval($new_w / $aspect_ratio);
   489 			$new_h = (int) round( $new_w / $aspect_ratio );
   345 		}
   490 		}
   346 
   491 
   347 		$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
   492 		$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
   348 
   493 
   349 		$crop_w = round($new_w / $size_ratio);
   494 		$crop_w = round($new_w / $size_ratio);
   350 		$crop_h = round($new_h / $size_ratio);
   495 		$crop_h = round($new_h / $size_ratio);
   351 
   496 
   352 		$s_x = floor( ($orig_w - $crop_w) / 2 );
   497 		if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
   353 		$s_y = floor( ($orig_h - $crop_h) / 2 );
   498 			$crop = array( 'center', 'center' );
       
   499 		}
       
   500 
       
   501 		list( $x, $y ) = $crop;
       
   502 
       
   503 		if ( 'left' === $x ) {
       
   504 			$s_x = 0;
       
   505 		} elseif ( 'right' === $x ) {
       
   506 			$s_x = $orig_w - $crop_w;
       
   507 		} else {
       
   508 			$s_x = floor( ( $orig_w - $crop_w ) / 2 );
       
   509 		}
       
   510 
       
   511 		if ( 'top' === $y ) {
       
   512 			$s_y = 0;
       
   513 		} elseif ( 'bottom' === $y ) {
       
   514 			$s_y = $orig_h - $crop_h;
       
   515 		} else {
       
   516 			$s_y = floor( ( $orig_h - $crop_h ) / 2 );
       
   517 		}
   354 	} else {
   518 	} else {
   355 		// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
   519 		// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
   356 		$crop_w = $orig_w;
   520 		$crop_w = $orig_w;
   357 		$crop_h = $orig_h;
   521 		$crop_h = $orig_h;
   358 
   522 
   361 
   525 
   362 		list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
   526 		list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
   363 	}
   527 	}
   364 
   528 
   365 	// if the resulting image would be the same size or larger we don't want to resize it
   529 	// if the resulting image would be the same size or larger we don't want to resize it
   366 	if ( $new_w >= $orig_w && $new_h >= $orig_h )
   530 	if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
   367 		return false;
   531 		return false;
       
   532 	}
   368 
   533 
   369 	// the return array matches the parameters to imagecopyresampled()
   534 	// the return array matches the parameters to imagecopyresampled()
   370 	// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
   535 	// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
   371 	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
   536 	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
   372 
   537 
   373 }
   538 }
   374 
   539 
   375 /**
   540 /**
   376  * Resize an image to make a thumbnail or intermediate size.
   541  * Resizes an image to make a thumbnail or intermediate size.
   377  *
   542  *
   378  * The returned array has the file size, the image width, and image height. The
   543  * The returned array has the file size, the image width, and image height. The
   379  * filter 'image_make_intermediate_size' can be used to hook in and change the
   544  * filter 'image_make_intermediate_size' can be used to hook in and change the
   380  * values of the returned array. The only parameter is the resized file path.
   545  * values of the returned array. The only parameter is the resized file path.
   381  *
   546  *
   382  * @since 2.5.0
   547  * @since 2.5.0
   383  *
   548  *
   384  * @param string $file File path.
   549  * @param string $file   File path.
   385  * @param int $width Image width.
   550  * @param int    $width  Image width.
   386  * @param int $height Image height.
   551  * @param int    $height Image height.
   387  * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
   552  * @param bool   $crop   Optional. Whether to crop image to specified height and width or resize.
       
   553  *                       Default false.
   388  * @return bool|array False, if no image was created. Metadata array on success.
   554  * @return bool|array False, if no image was created. Metadata array on success.
   389  */
   555  */
   390 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
   556 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
   391 	if ( $width || $height ) {
   557 	if ( $width || $height ) {
   392 		$editor = wp_get_image_editor( $file );
   558 		$editor = wp_get_image_editor( $file );
   403 	}
   569 	}
   404 	return false;
   570 	return false;
   405 }
   571 }
   406 
   572 
   407 /**
   573 /**
   408  * Retrieve the image's intermediate size (resized) path, width, and height.
   574  * Retrieves the image's intermediate size (resized) path, width, and height.
   409  *
   575  *
   410  * The $size parameter can be an array with the width and height respectively.
   576  * The $size parameter can be an array with the width and height respectively.
   411  * If the size matches the 'sizes' metadata array for width and height, then it
   577  * If the size matches the 'sizes' metadata array for width and height, then it
   412  * will be used. If there is no direct match, then the nearest image size larger
   578  * will be used. If there is no direct match, then the nearest image size larger
   413  * than the specified size will be used. If nothing is found, then the function
   579  * than the specified size will be used. If nothing is found, then the function
   422  * add_image_size() so that a cropped version is generated. It's much more
   588  * add_image_size() so that a cropped version is generated. It's much more
   423  * efficient than having to find the closest-sized image and then having the
   589  * efficient than having to find the closest-sized image and then having the
   424  * browser scale down the image.
   590  * browser scale down the image.
   425  *
   591  *
   426  * @since 2.5.0
   592  * @since 2.5.0
   427  * @see add_image_size()
   593  *
   428  *
   594  * @param int          $post_id Attachment ID.
   429  * @param int $post_id Attachment ID for image.
   595  * @param array|string $size    Optional. Registered image size to retrieve or flat array of height
   430  * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
   596  *                              and width dimensions. Default 'thumbnail'.
   431  * @return bool|array False on failure or array of file path, width, and height on success.
   597  * @return bool|array False on failure or array of file path, width, and height on success.
   432  */
   598  */
   433 function image_get_intermediate_size($post_id, $size='thumbnail') {
   599 function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
   434 	if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
   600 	if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
   435 		return false;
   601 		return false;
   436 
   602 
   437 	// get the best one for a specified set of dimensions
   603 	// get the best one for a specified set of dimensions
   438 	if ( is_array($size) && !empty($imagedata['sizes']) ) {
   604 	if ( is_array($size) && !empty($imagedata['sizes']) ) {
       
   605 		$areas = array();
       
   606 
   439 		foreach ( $imagedata['sizes'] as $_size => $data ) {
   607 		foreach ( $imagedata['sizes'] as $_size => $data ) {
   440 			// already cropped to width or height; so use this size
   608 			// already cropped to width or height; so use this size
   441 			if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
   609 			if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
   442 				$file = $data['file'];
   610 				$file = $data['file'];
   443 				list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
   611 				list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
   479 	}
   647 	}
   480 	return $data;
   648 	return $data;
   481 }
   649 }
   482 
   650 
   483 /**
   651 /**
   484  * Get the available image sizes
   652  * Gets the available intermediate image sizes.
       
   653  *
   485  * @since 3.0.0
   654  * @since 3.0.0
   486  * @return array Returns a filtered array of image size strings
   655  *
       
   656  * @global array $_wp_additional_image_sizes
       
   657  *
       
   658  * @return array Returns a filtered array of image size strings.
   487  */
   659  */
   488 function get_intermediate_image_sizes() {
   660 function get_intermediate_image_sizes() {
   489 	global $_wp_additional_image_sizes;
   661 	global $_wp_additional_image_sizes;
   490 	$image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
   662 	$image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
   491 	if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
   663 	if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
   492 		$image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
   664 		$image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
   493 
   665 
       
   666 	/**
       
   667 	 * Filter the list of intermediate image sizes.
       
   668 	 *
       
   669 	 * @since 2.5.0
       
   670 	 *
       
   671 	 * @param array $image_sizes An array of intermediate image sizes. Defaults
       
   672 	 *                           are 'thumbnail', 'medium', 'large'.
       
   673 	 */
   494 	return apply_filters( 'intermediate_image_sizes', $image_sizes );
   674 	return apply_filters( 'intermediate_image_sizes', $image_sizes );
   495 }
   675 }
   496 
   676 
   497 /**
   677 /**
   498  * Retrieve an image to represent an attachment.
   678  * Retrieve an image to represent an attachment.
   499  *
   679  *
   500  * A mime icon for files, thumbnail or intermediate size for images.
   680  * A mime icon for files, thumbnail or intermediate size for images.
   501  *
   681  *
   502  * @since 2.5.0
   682  * @since 2.5.0
   503  *
   683  *
   504  * @param int $attachment_id Image attachment ID.
   684  * @param int          $attachment_id Image attachment ID.
   505  * @param string $size Optional, default is 'thumbnail'.
   685  * @param string|array $size          Optional. Registered image size to retrieve the source for or a flat
   506  * @param bool $icon Optional, default is false. Whether it is an icon.
   686  *                                    array of height and width dimensions. Default 'thumbnail'.
       
   687  * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
   507  * @return bool|array Returns an array (url, width, height), or false, if no image is available.
   688  * @return bool|array Returns an array (url, width, height), or false, if no image is available.
   508  */
   689  */
   509 function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
   690 function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
   510 
   691 
   511 	// get a thumbnail or intermediate image if there is one
   692 	// get a thumbnail or intermediate image if there is one
   512 	if ( $image = image_downsize($attachment_id, $size) )
   693 	if ( $image = image_downsize($attachment_id, $size) )
   513 		return $image;
   694 		return $image;
   514 
   695 
   515 	$src = false;
   696 	$src = false;
   516 
   697 
   517 	if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
   698 	if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
   518 		$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
   699 		/** This filter is documented in wp-includes/post.php */
       
   700 		$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
       
   701 
   519 		$src_file = $icon_dir . '/' . wp_basename($src);
   702 		$src_file = $icon_dir . '/' . wp_basename($src);
   520 		@list($width, $height) = getimagesize($src_file);
   703 		@list($width, $height) = getimagesize($src_file);
   521 	}
   704 	}
   522 	if ( $src && $width && $height )
   705 	if ( $src && $width && $height )
   523 		return array( $src, $width, $height );
   706 		return array( $src, $width, $height );
   525 }
   708 }
   526 
   709 
   527 /**
   710 /**
   528  * Get an HTML img element representing an image attachment
   711  * Get an HTML img element representing an image attachment
   529  *
   712  *
   530  * While $size will accept an array, it is better to register a size with
   713  * While `$size` will accept an array, it is better to register a size with
   531  * add_image_size() so that a cropped version is generated. It's much more
   714  * add_image_size() so that a cropped version is generated. It's much more
   532  * efficient than having to find the closest-sized image and then having the
   715  * efficient than having to find the closest-sized image and then having the
   533  * browser scale down the image.
   716  * browser scale down the image.
   534  *
   717  *
   535  * @see add_image_size()
       
   536  * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
       
   537  * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
       
   538  * @since 2.5.0
   718  * @since 2.5.0
   539  *
   719  *
   540  * @param int $attachment_id Image attachment ID.
   720  * @param int          $attachment_id Image attachment ID.
   541  * @param string $size Optional, default is 'thumbnail'.
   721  * @param string|array $size          Optional. Registered image size or flat array of height and width
   542  * @param bool $icon Optional, default is false. Whether it is an icon.
   722  *                                    dimensions. Default 'thumbnail'.
   543  * @param mixed $attr Optional, attributes for the image markup.
   723  * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
       
   724  * @param string|array $attr          Optional. Attributes for the image markup. Default empty.
   544  * @return string HTML img element or empty string on failure.
   725  * @return string HTML img element or empty string on failure.
   545  */
   726  */
   546 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
   727 function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
   547 
   728 
   548 	$html = '';
   729 	$html = '';
   549 	$image = wp_get_attachment_image_src($attachment_id, $size, $icon);
   730 	$image = wp_get_attachment_image_src($attachment_id, $size, $icon);
   550 	if ( $image ) {
   731 	if ( $image ) {
   551 		list($src, $width, $height) = $image;
   732 		list($src, $width, $height) = $image;
   552 		$hwstring = image_hwstring($width, $height);
   733 		$hwstring = image_hwstring($width, $height);
   553 		if ( is_array($size) )
   734 		$size_class = $size;
   554 			$size = join('x', $size);
   735 		if ( is_array( $size_class ) ) {
       
   736 			$size_class = join( 'x', $size_class );
       
   737 		}
   555 		$attachment = get_post($attachment_id);
   738 		$attachment = get_post($attachment_id);
   556 		$default_attr = array(
   739 		$default_attr = array(
   557 			'src'	=> $src,
   740 			'src'	=> $src,
   558 			'class'	=> "attachment-$size",
   741 			'class'	=> "attachment-$size_class",
   559 			'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
   742 			'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
   560 		);
   743 		);
   561 		if ( empty($default_attr['alt']) )
   744 		if ( empty($default_attr['alt']) )
   562 			$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
   745 			$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
   563 		if ( empty($default_attr['alt']) )
   746 		if ( empty($default_attr['alt']) )
   564 			$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
   747 			$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
   565 
   748 
   566 		$attr = wp_parse_args($attr, $default_attr);
   749 		$attr = wp_parse_args($attr, $default_attr);
   567 		$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
   750 
       
   751 		/**
       
   752 		 * Filter the list of attachment image attributes.
       
   753 		 *
       
   754 		 * @since 2.8.0
       
   755 		 *
       
   756 		 * @param array        $attr       Attributes for the image markup.
       
   757 		 * @param WP_Post      $attachment Image attachment post.
       
   758 		 * @param string|array $size       Requested size.
       
   759 		 */
       
   760 		$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
   568 		$attr = array_map( 'esc_attr', $attr );
   761 		$attr = array_map( 'esc_attr', $attr );
   569 		$html = rtrim("<img $hwstring");
   762 		$html = rtrim("<img $hwstring");
   570 		foreach ( $attr as $name => $value ) {
   763 		foreach ( $attr as $name => $value ) {
   571 			$html .= " $name=" . '"' . $value . '"';
   764 			$html .= " $name=" . '"' . $value . '"';
   572 		}
   765 		}
   575 
   768 
   576 	return $html;
   769 	return $html;
   577 }
   770 }
   578 
   771 
   579 /**
   772 /**
   580  * Adds a 'wp-post-image' class to post thumbnails
   773  * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
   581  * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
   774  *
   582  * dynamically add/remove itself so as to only filter post thumbnails
   775  * Uses the 'begin_fetch_post_thumbnail_html' and 'end_fetch_post_thumbnail_html' action hooks to
   583  *
   776  * dynamically add/remove itself so as to only filter post thumbnails.
       
   777  *
       
   778  * @ignore
   584  * @since 2.9.0
   779  * @since 2.9.0
   585  * @param array $attr Attributes including src, class, alt, title
   780  *
   586  * @return array
   781  * @param array $attr Thumbnail attributes including src, class, alt, title.
       
   782  * @return array Modified array of attributes including the new 'wp-post-image' class.
   587  */
   783  */
   588 function _wp_post_thumbnail_class_filter( $attr ) {
   784 function _wp_post_thumbnail_class_filter( $attr ) {
   589 	$attr['class'] .= ' wp-post-image';
   785 	$attr['class'] .= ' wp-post-image';
   590 	return $attr;
   786 	return $attr;
   591 }
   787 }
   592 
   788 
   593 /**
   789 /**
   594  * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
   790  * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
   595  *
   791  * filter hook. Internal use only.
       
   792  *
       
   793  * @ignore
   596  * @since 2.9.0
   794  * @since 2.9.0
       
   795  *
       
   796  * @param array $attr Thumbnail attributes including src, class, alt, title.
   597  */
   797  */
   598 function _wp_post_thumbnail_class_filter_add( $attr ) {
   798 function _wp_post_thumbnail_class_filter_add( $attr ) {
   599 	add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
   799 	add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
   600 }
   800 }
   601 
   801 
   602 /**
   802 /**
   603  * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
   803  * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
   604  *
   804  * filter hook. Internal use only.
       
   805  *
       
   806  * @ignore
   605  * @since 2.9.0
   807  * @since 2.9.0
       
   808  *
       
   809  * @param array $attr Thumbnail attributes including src, class, alt, title.
   606  */
   810  */
   607 function _wp_post_thumbnail_class_filter_remove( $attr ) {
   811 function _wp_post_thumbnail_class_filter_remove( $attr ) {
   608 	remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
   812 	remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
   609 }
   813 }
   610 
   814 
   611 add_shortcode('wp_caption', 'img_caption_shortcode');
   815 add_shortcode('wp_caption', 'img_caption_shortcode');
   612 add_shortcode('caption', 'img_caption_shortcode');
   816 add_shortcode('caption', 'img_caption_shortcode');
   613 
   817 
   614 /**
   818 /**
   615  * The Caption shortcode.
   819  * Builds the Caption shortcode output.
   616  *
   820  *
   617  * Allows a plugin to replace the content that would otherwise be returned. The
   821  * Allows a plugin to replace the content that would otherwise be returned. The
   618  * filter is 'img_caption_shortcode' and passes an empty string, the attr
   822  * filter is 'img_caption_shortcode' and passes an empty string, the attr
   619  * parameter and the content parameter values.
   823  * parameter and the content parameter values.
   620  *
   824  *
   621  * The supported attributes for the shortcode are 'id', 'align', 'width', and
   825  * The supported attributes for the shortcode are 'id', 'align', 'width', and
   622  * 'caption'.
   826  * 'caption'.
   623  *
   827  *
   624  * @since 2.6.0
   828  * @since 2.6.0
   625  *
   829  *
   626  * @param array $attr Attributes attributed to the shortcode.
   830  * @param array  $attr {
   627  * @param string $content Optional. Shortcode content.
   831  *     Attributes of the caption shortcode.
   628  * @return string
   832  *
   629  */
   833  *     @type string $id      ID of the div element for the caption.
   630 function img_caption_shortcode($attr, $content = null) {
   834  *     @type string $align   Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
       
   835  *                           'aligncenter', alignright', 'alignnone'.
       
   836  *     @type int    $width   The width of the caption, in pixels.
       
   837  *     @type string $caption The caption text.
       
   838  *     @type string $class   Additional class name(s) added to the caption container.
       
   839  * }
       
   840  * @param string $content Shortcode content.
       
   841  * @return string HTML content to display the caption.
       
   842  */
       
   843 function img_caption_shortcode( $attr, $content = null ) {
   631 	// New-style shortcode with the caption inside the shortcode with the link and image tags.
   844 	// New-style shortcode with the caption inside the shortcode with the link and image tags.
   632 	if ( ! isset( $attr['caption'] ) ) {
   845 	if ( ! isset( $attr['caption'] ) ) {
   633 		if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
   846 		if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
   634 			$content = $matches[1];
   847 			$content = $matches[1];
   635 			$attr['caption'] = trim( $matches[2] );
   848 			$attr['caption'] = trim( $matches[2] );
   636 		}
   849 		}
   637 	}
   850 	}
   638 
   851 
   639 	// Allow plugins/themes to override the default caption template.
   852 	/**
   640 	$output = apply_filters('img_caption_shortcode', '', $attr, $content);
   853 	 * Filter the default caption shortcode output.
       
   854 	 *
       
   855 	 * If the filtered output isn't empty, it will be used instead of generating
       
   856 	 * the default caption template.
       
   857 	 *
       
   858 	 * @since 2.6.0
       
   859 	 *
       
   860 	 * @see img_caption_shortcode()
       
   861 	 *
       
   862 	 * @param string $output  The caption output. Default empty.
       
   863 	 * @param array  $attr    Attributes of the caption shortcode.
       
   864 	 * @param string $content The image element, possibly wrapped in a hyperlink.
       
   865 	 */
       
   866 	$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
   641 	if ( $output != '' )
   867 	if ( $output != '' )
   642 		return $output;
   868 		return $output;
   643 
   869 
   644 	$atts = shortcode_atts( array(
   870 	$atts = shortcode_atts( array(
   645 		'id'	  => '',
   871 		'id'	  => '',
   646 		'align'	  => 'alignnone',
   872 		'align'	  => 'alignnone',
   647 		'width'	  => '',
   873 		'width'	  => '',
   648 		'caption' => ''
   874 		'caption' => '',
       
   875 		'class'   => '',
   649 	), $attr, 'caption' );
   876 	), $attr, 'caption' );
   650 
   877 
   651 	$atts['width'] = (int) $atts['width'];
   878 	$atts['width'] = (int) $atts['width'];
   652 	if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
   879 	if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
   653 		return $content;
   880 		return $content;
   654 
   881 
   655 	if ( ! empty( $atts['id'] ) )
   882 	if ( ! empty( $atts['id'] ) )
   656 		$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
   883 		$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
   657 
   884 
       
   885 	$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
       
   886 
       
   887 	if ( current_theme_supports( 'html5', 'caption' ) ) {
       
   888 		return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
       
   889 		. do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
       
   890 	}
       
   891 
   658 	$caption_width = 10 + $atts['width'];
   892 	$caption_width = 10 + $atts['width'];
   659 
   893 
   660 	/**
   894 	/**
   661 	 * Filter the width of an image's caption.
   895 	 * Filter the width of an image's caption.
   662 	 *
   896 	 *
   663 	 * By default, the caption is 10 pixels greater than the width of the image,
   897 	 * By default, the caption is 10 pixels greater than the width of the image,
   664 	 * to prevent post content from running up against a floated image.
   898 	 * to prevent post content from running up against a floated image.
   665 	 *
   899 	 *
   666 	 * @since 3.7.0
   900 	 * @since 3.7.0
   667 	 *
   901 	 *
   668 	 * @param int $caption_width Width in pixels. To remove this inline style, return zero.
   902 	 * @see img_caption_shortcode()
   669 	 * @param array $atts {
   903 	 *
   670 	 *     The attributes of the caption shortcode.
   904 	 * @param int    $caption_width Width of the caption in pixels. To remove this inline style,
   671 	 *
   905 	 *                              return zero.
   672 	 *     @type string 'id'      The ID of the div element for the caption.
   906 	 * @param array  $atts          Attributes of the caption shortcode.
   673 	 *     @type string 'align'   The class name that aligns the caption. Default 'alignnone'.
   907 	 * @param string $content       The image element, possibly wrapped in a hyperlink.
   674 	 *     @type int    'width'   The width of the image being captioned.
       
   675 	 *     @type string 'caption' The image's caption.
       
   676 	 * }
       
   677 	 * @param string $content The image element, possibly wrapped in a hyperlink.
       
   678 	 */
   908 	 */
   679 	$caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
   909 	$caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
   680 
   910 
   681 	$style = '';
   911 	$style = '';
   682 	if ( $caption_width )
   912 	if ( $caption_width )
   683 		$style = 'style="width: ' . (int) $caption_width . 'px" ';
   913 		$style = 'style="width: ' . (int) $caption_width . 'px" ';
   684 
   914 
   685 	return '<div ' . $atts['id'] . $style . 'class="wp-caption ' . esc_attr( $atts['align'] ) . '">'
   915 	return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
   686 	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
   916 	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
   687 }
   917 }
   688 
   918 
   689 add_shortcode('gallery', 'gallery_shortcode');
   919 add_shortcode('gallery', 'gallery_shortcode');
   690 
   920 
   691 /**
   921 /**
   692  * The Gallery shortcode.
   922  * Builds the Gallery shortcode output.
   693  *
   923  *
   694  * This implements the functionality of the Gallery Shortcode for displaying
   924  * This implements the functionality of the Gallery Shortcode for displaying
   695  * WordPress images on a post.
   925  * WordPress images on a post.
   696  *
   926  *
   697  * @since 2.5.0
   927  * @since 2.5.0
   698  *
   928  *
   699  * @param array $attr Attributes of the shortcode.
   929  * @param array $attr {
       
   930  *     Attributes of the gallery shortcode.
       
   931  *
       
   932  *     @type string $order      Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
       
   933  *     @type string $orderby    The field to use when ordering the images. Default 'menu_order ID'.
       
   934  *                              Accepts any valid SQL ORDERBY statement.
       
   935  *     @type int    $id         Post ID.
       
   936  *     @type string $itemtag    HTML tag to use for each image in the gallery.
       
   937  *                              Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
       
   938  *     @type string $icontag    HTML tag to use for each image's icon.
       
   939  *                              Default 'dt', or 'div' when the theme registers HTML5 gallery support.
       
   940  *     @type string $captiontag HTML tag to use for each image's caption.
       
   941  *                              Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
       
   942  *     @type int    $columns    Number of columns of images to display. Default 3.
       
   943  *     @type string $size       Size of the images to display. Default 'thumbnail'.
       
   944  *     @type string $ids        A comma-separated list of IDs of attachments to display. Default empty.
       
   945  *     @type string $include    A comma-separated list of IDs of attachments to include. Default empty.
       
   946  *     @type string $exclude    A comma-separated list of IDs of attachments to exclude. Default empty.
       
   947  *     @type string $link       What to link each image to. Default empty (links to the attachment page).
       
   948  *                              Accepts 'file', 'none'.
       
   949  * }
   700  * @return string HTML content to display gallery.
   950  * @return string HTML content to display gallery.
   701  */
   951  */
   702 function gallery_shortcode($attr) {
   952 function gallery_shortcode( $attr ) {
   703 	$post = get_post();
   953 	$post = get_post();
   704 
   954 
   705 	static $instance = 0;
   955 	static $instance = 0;
   706 	$instance++;
   956 	$instance++;
   707 
   957 
   708 	if ( ! empty( $attr['ids'] ) ) {
   958 	if ( ! empty( $attr['ids'] ) ) {
   709 		// 'ids' is explicitly ordered, unless you specify otherwise.
   959 		// 'ids' is explicitly ordered, unless you specify otherwise.
   710 		if ( empty( $attr['orderby'] ) )
   960 		if ( empty( $attr['orderby'] ) ) {
   711 			$attr['orderby'] = 'post__in';
   961 			$attr['orderby'] = 'post__in';
       
   962 		}
   712 		$attr['include'] = $attr['ids'];
   963 		$attr['include'] = $attr['ids'];
   713 	}
   964 	}
   714 
   965 
   715 	// Allow plugins/themes to override the default gallery template.
   966 	/**
   716 	$output = apply_filters('post_gallery', '', $attr);
   967 	 * Filter the default gallery shortcode output.
   717 	if ( $output != '' )
   968 	 *
       
   969 	 * If the filtered output isn't empty, it will be used instead of generating
       
   970 	 * the default gallery template.
       
   971 	 *
       
   972 	 * @since 2.5.0
       
   973 	 * @since 4.2.0 The `$instance` parameter was added.
       
   974 	 *
       
   975 	 * @see gallery_shortcode()
       
   976 	 *
       
   977 	 * @param string $output   The gallery output. Default empty.
       
   978 	 * @param array  $attr     Attributes of the gallery shortcode.
       
   979 	 * @param int    $instance Unique numeric ID of this gallery shortcode instance.
       
   980 	 */
       
   981 	$output = apply_filters( 'post_gallery', '', $attr, $instance );
       
   982 	if ( $output != '' ) {
   718 		return $output;
   983 		return $output;
   719 
   984 	}
   720 	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
   985 
   721 	if ( isset( $attr['orderby'] ) ) {
   986 	$html5 = current_theme_supports( 'html5', 'gallery' );
   722 		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
   987 	$atts = shortcode_atts( array(
   723 		if ( !$attr['orderby'] )
       
   724 			unset( $attr['orderby'] );
       
   725 	}
       
   726 
       
   727 	extract(shortcode_atts(array(
       
   728 		'order'      => 'ASC',
   988 		'order'      => 'ASC',
   729 		'orderby'    => 'menu_order ID',
   989 		'orderby'    => 'menu_order ID',
   730 		'id'         => $post ? $post->ID : 0,
   990 		'id'         => $post ? $post->ID : 0,
   731 		'itemtag'    => 'dl',
   991 		'itemtag'    => $html5 ? 'figure'     : 'dl',
   732 		'icontag'    => 'dt',
   992 		'icontag'    => $html5 ? 'div'        : 'dt',
   733 		'captiontag' => 'dd',
   993 		'captiontag' => $html5 ? 'figcaption' : 'dd',
   734 		'columns'    => 3,
   994 		'columns'    => 3,
   735 		'size'       => 'thumbnail',
   995 		'size'       => 'thumbnail',
   736 		'include'    => '',
   996 		'include'    => '',
   737 		'exclude'    => '',
   997 		'exclude'    => '',
   738 		'link'       => ''
   998 		'link'       => ''
   739 	), $attr, 'gallery'));
   999 	), $attr, 'gallery' );
   740 
  1000 
   741 	$id = intval($id);
  1001 	$id = intval( $atts['id'] );
   742 	if ( 'RAND' == $order )
  1002 
   743 		$orderby = 'none';
  1003 	if ( ! empty( $atts['include'] ) ) {
   744 
  1004 		$_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
   745 	if ( !empty($include) ) {
       
   746 		$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
       
   747 
  1005 
   748 		$attachments = array();
  1006 		$attachments = array();
   749 		foreach ( $_attachments as $key => $val ) {
  1007 		foreach ( $_attachments as $key => $val ) {
   750 			$attachments[$val->ID] = $_attachments[$key];
  1008 			$attachments[$val->ID] = $_attachments[$key];
   751 		}
  1009 		}
   752 	} elseif ( !empty($exclude) ) {
  1010 	} elseif ( ! empty( $atts['exclude'] ) ) {
   753 		$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  1011 		$attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
   754 	} else {
  1012 	} else {
   755 		$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  1013 		$attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
   756 	}
  1014 	}
   757 
  1015 
   758 	if ( empty($attachments) )
  1016 	if ( empty( $attachments ) ) {
   759 		return '';
  1017 		return '';
       
  1018 	}
   760 
  1019 
   761 	if ( is_feed() ) {
  1020 	if ( is_feed() ) {
   762 		$output = "\n";
  1021 		$output = "\n";
   763 		foreach ( $attachments as $att_id => $attachment )
  1022 		foreach ( $attachments as $att_id => $attachment ) {
   764 			$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  1023 			$output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
       
  1024 		}
   765 		return $output;
  1025 		return $output;
   766 	}
  1026 	}
   767 
  1027 
   768 	$itemtag = tag_escape($itemtag);
  1028 	$itemtag = tag_escape( $atts['itemtag'] );
   769 	$captiontag = tag_escape($captiontag);
  1029 	$captiontag = tag_escape( $atts['captiontag'] );
   770 	$icontag = tag_escape($icontag);
  1030 	$icontag = tag_escape( $atts['icontag'] );
   771 	$valid_tags = wp_kses_allowed_html( 'post' );
  1031 	$valid_tags = wp_kses_allowed_html( 'post' );
   772 	if ( ! isset( $valid_tags[ $itemtag ] ) )
  1032 	if ( ! isset( $valid_tags[ $itemtag ] ) ) {
   773 		$itemtag = 'dl';
  1033 		$itemtag = 'dl';
   774 	if ( ! isset( $valid_tags[ $captiontag ] ) )
  1034 	}
       
  1035 	if ( ! isset( $valid_tags[ $captiontag ] ) ) {
   775 		$captiontag = 'dd';
  1036 		$captiontag = 'dd';
   776 	if ( ! isset( $valid_tags[ $icontag ] ) )
  1037 	}
       
  1038 	if ( ! isset( $valid_tags[ $icontag ] ) ) {
   777 		$icontag = 'dt';
  1039 		$icontag = 'dt';
   778 
  1040 	}
   779 	$columns = intval($columns);
  1041 
       
  1042 	$columns = intval( $atts['columns'] );
   780 	$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  1043 	$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
   781 	$float = is_rtl() ? 'right' : 'left';
  1044 	$float = is_rtl() ? 'right' : 'left';
   782 
  1045 
   783 	$selector = "gallery-{$instance}";
  1046 	$selector = "gallery-{$instance}";
   784 
  1047 
   785 	$gallery_style = $gallery_div = '';
  1048 	$gallery_style = '';
   786 	if ( apply_filters( 'use_default_gallery_style', true ) )
  1049 
       
  1050 	/**
       
  1051 	 * Filter whether to print default gallery styles.
       
  1052 	 *
       
  1053 	 * @since 3.1.0
       
  1054 	 *
       
  1055 	 * @param bool $print Whether to print default gallery styles.
       
  1056 	 *                    Defaults to false if the theme supports HTML5 galleries.
       
  1057 	 *                    Otherwise, defaults to true.
       
  1058 	 */
       
  1059 	if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
   787 		$gallery_style = "
  1060 		$gallery_style = "
   788 		<style type='text/css'>
  1061 		<style type='text/css'>
   789 			#{$selector} {
  1062 			#{$selector} {
   790 				margin: auto;
  1063 				margin: auto;
   791 			}
  1064 			}
   800 			}
  1073 			}
   801 			#{$selector} .gallery-caption {
  1074 			#{$selector} .gallery-caption {
   802 				margin-left: 0;
  1075 				margin-left: 0;
   803 			}
  1076 			}
   804 			/* see gallery_shortcode() in wp-includes/media.php */
  1077 			/* see gallery_shortcode() in wp-includes/media.php */
   805 		</style>";
  1078 		</style>\n\t\t";
   806 	$size_class = sanitize_html_class( $size );
  1079 	}
       
  1080 
       
  1081 	$size_class = sanitize_html_class( $atts['size'] );
   807 	$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  1082 	$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
   808 	$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
  1083 
       
  1084 	/**
       
  1085 	 * Filter the default gallery shortcode CSS styles.
       
  1086 	 *
       
  1087 	 * @since 2.5.0
       
  1088 	 *
       
  1089 	 * @param string $gallery_style Default CSS styles and opening HTML div container
       
  1090 	 *                              for the gallery shortcode output.
       
  1091 	 */
       
  1092 	$output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
   809 
  1093 
   810 	$i = 0;
  1094 	$i = 0;
   811 	foreach ( $attachments as $id => $attachment ) {
  1095 	foreach ( $attachments as $id => $attachment ) {
   812 		if ( ! empty( $link ) && 'file' === $link )
  1096 
   813 			$image_output = wp_get_attachment_link( $id, $size, false, false );
  1097 		$attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
   814 		elseif ( ! empty( $link ) && 'none' === $link )
  1098 		if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
   815 			$image_output = wp_get_attachment_image( $id, $size, false );
  1099 			$image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
   816 		else
  1100 		} elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
   817 			$image_output = wp_get_attachment_link( $id, $size, true, false );
  1101 			$image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
   818 
  1102 		} else {
       
  1103 			$image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
       
  1104 		}
   819 		$image_meta  = wp_get_attachment_metadata( $id );
  1105 		$image_meta  = wp_get_attachment_metadata( $id );
   820 
  1106 
   821 		$orientation = '';
  1107 		$orientation = '';
   822 		if ( isset( $image_meta['height'], $image_meta['width'] ) )
  1108 		if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
   823 			$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  1109 			$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
   824 
  1110 		}
   825 		$output .= "<{$itemtag} class='gallery-item'>";
  1111 		$output .= "<{$itemtag} class='gallery-item'>";
   826 		$output .= "
  1112 		$output .= "
   827 			<{$icontag} class='gallery-icon {$orientation}'>
  1113 			<{$icontag} class='gallery-icon {$orientation}'>
   828 				$image_output
  1114 				$image_output
   829 			</{$icontag}>";
  1115 			</{$icontag}>";
   830 		if ( $captiontag && trim($attachment->post_excerpt) ) {
  1116 		if ( $captiontag && trim($attachment->post_excerpt) ) {
   831 			$output .= "
  1117 			$output .= "
   832 				<{$captiontag} class='wp-caption-text gallery-caption'>
  1118 				<{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
   833 				" . wptexturize($attachment->post_excerpt) . "
  1119 				" . wptexturize($attachment->post_excerpt) . "
   834 				</{$captiontag}>";
  1120 				</{$captiontag}>";
   835 		}
  1121 		}
   836 		$output .= "</{$itemtag}>";
  1122 		$output .= "</{$itemtag}>";
   837 		if ( $columns > 0 && ++$i % $columns == 0 )
  1123 		if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
   838 			$output .= '<br style="clear: both" />';
  1124 			$output .= '<br style="clear: both" />';
       
  1125 		}
       
  1126 	}
       
  1127 
       
  1128 	if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
       
  1129 		$output .= "
       
  1130 			<br style='clear: both' />";
   839 	}
  1131 	}
   840 
  1132 
   841 	$output .= "
  1133 	$output .= "
   842 			<br style='clear: both;' />
       
   843 		</div>\n";
  1134 		</div>\n";
   844 
  1135 
   845 	return $output;
  1136 	return $output;
   846 }
  1137 }
   847 
  1138 
   848 /**
  1139 /**
   849  * Provide a No-JS Flash fallback as a last resort for audio / video
  1140  * Outputs the templates used by playlists.
       
  1141  *
       
  1142  * @since 3.9.0
       
  1143  */
       
  1144 function wp_underscore_playlist_templates() {
       
  1145 ?>
       
  1146 <script type="text/html" id="tmpl-wp-playlist-current-item">
       
  1147 	<# if ( data.image ) { #>
       
  1148 	<img src="{{ data.thumb.src }}"/>
       
  1149 	<# } #>
       
  1150 	<div class="wp-playlist-caption">
       
  1151 		<span class="wp-playlist-item-meta wp-playlist-item-title">&#8220;{{ data.title }}&#8221;</span>
       
  1152 		<# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
       
  1153 		<# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
       
  1154 	</div>
       
  1155 </script>
       
  1156 <script type="text/html" id="tmpl-wp-playlist-item">
       
  1157 	<div class="wp-playlist-item">
       
  1158 		<a class="wp-playlist-caption" href="{{ data.src }}">
       
  1159 			{{ data.index ? ( data.index + '. ' ) : '' }}
       
  1160 			<# if ( data.caption ) { #>
       
  1161 				{{ data.caption }}
       
  1162 			<# } else { #>
       
  1163 				<span class="wp-playlist-item-title">&#8220;{{{ data.title }}}&#8221;</span>
       
  1164 				<# if ( data.artists && data.meta.artist ) { #>
       
  1165 				<span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
       
  1166 				<# } #>
       
  1167 			<# } #>
       
  1168 		</a>
       
  1169 		<# if ( data.meta.length_formatted ) { #>
       
  1170 		<div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
       
  1171 		<# } #>
       
  1172 	</div>
       
  1173 </script>
       
  1174 <?php
       
  1175 }
       
  1176 
       
  1177 /**
       
  1178  * Outputs and enqueue default scripts and styles for playlists.
       
  1179  *
       
  1180  * @since 3.9.0
       
  1181  *
       
  1182  * @param string $type Type of playlist. Accepts 'audio' or 'video'.
       
  1183  */
       
  1184 function wp_playlist_scripts( $type ) {
       
  1185 	wp_enqueue_style( 'wp-mediaelement' );
       
  1186 	wp_enqueue_script( 'wp-playlist' );
       
  1187 ?>
       
  1188 <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
       
  1189 <?php
       
  1190 	add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
       
  1191 	add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
       
  1192 }
       
  1193 
       
  1194 /**
       
  1195  * Builds the Playlist shortcode output.
       
  1196  *
       
  1197  * This implements the functionality of the playlist shortcode for displaying
       
  1198  * a collection of WordPress audio or video files in a post.
       
  1199  *
       
  1200  * @since 3.9.0
       
  1201  *
       
  1202  * @param array $attr {
       
  1203  *     Array of default playlist attributes.
       
  1204  *
       
  1205  *     @type string  $type         Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
       
  1206  *     @type string  $order        Designates ascending or descending order of items in the playlist.
       
  1207  *                                 Accepts 'ASC', 'DESC'. Default 'ASC'.
       
  1208  *     @type string  $orderby      Any column, or columns, to sort the playlist. If $ids are
       
  1209  *                                 passed, this defaults to the order of the $ids array ('post__in').
       
  1210  *                                 Otherwise default is 'menu_order ID'.
       
  1211  *     @type int     $id           If an explicit $ids array is not present, this parameter
       
  1212  *                                 will determine which attachments are used for the playlist.
       
  1213  *                                 Default is the current post ID.
       
  1214  *     @type array   $ids          Create a playlist out of these explicit attachment IDs. If empty,
       
  1215  *                                 a playlist will be created from all $type attachments of $id.
       
  1216  *                                 Default empty.
       
  1217  *     @type array   $exclude      List of specific attachment IDs to exclude from the playlist. Default empty.
       
  1218  *     @type string  $style        Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
       
  1219  *     @type bool    $tracklist    Whether to show or hide the playlist. Default true.
       
  1220  *     @type bool    $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
       
  1221  *     @type bool    $images       Show or hide the video or audio thumbnail (Featured Image/post
       
  1222  *                                 thumbnail). Default true.
       
  1223  *     @type bool    $artists      Whether to show or hide artist name in the playlist. Default true.
       
  1224  * }
       
  1225  *
       
  1226  * @return string Playlist output. Empty string if the passed type is unsupported.
       
  1227  */
       
  1228 function wp_playlist_shortcode( $attr ) {
       
  1229 	global $content_width;
       
  1230 	$post = get_post();
       
  1231 
       
  1232 	static $instance = 0;
       
  1233 	$instance++;
       
  1234 
       
  1235 	if ( ! empty( $attr['ids'] ) ) {
       
  1236 		// 'ids' is explicitly ordered, unless you specify otherwise.
       
  1237 		if ( empty( $attr['orderby'] ) ) {
       
  1238 			$attr['orderby'] = 'post__in';
       
  1239 		}
       
  1240 		$attr['include'] = $attr['ids'];
       
  1241 	}
       
  1242 
       
  1243 	/**
       
  1244 	 * Filter the playlist output.
       
  1245 	 *
       
  1246 	 * Passing a non-empty value to the filter will short-circuit generation
       
  1247 	 * of the default playlist output, returning the passed value instead.
       
  1248 	 *
       
  1249 	 * @since 3.9.0
       
  1250 	 * @since 4.2.0 The `$instance` parameter was added.
       
  1251 	 *
       
  1252 	 * @param string $output   Playlist output. Default empty.
       
  1253 	 * @param array  $attr     An array of shortcode attributes.
       
  1254 	 * @param int    $instance Unique numeric ID of this playlist shortcode instance.
       
  1255 	 */
       
  1256 	$output = apply_filters( 'post_playlist', '', $attr, $instance );
       
  1257 	if ( $output != '' ) {
       
  1258 		return $output;
       
  1259 	}
       
  1260 
       
  1261 	$atts = shortcode_atts( array(
       
  1262 		'type'		=> 'audio',
       
  1263 		'order'		=> 'ASC',
       
  1264 		'orderby'	=> 'menu_order ID',
       
  1265 		'id'		=> $post ? $post->ID : 0,
       
  1266 		'include'	=> '',
       
  1267 		'exclude'   => '',
       
  1268 		'style'		=> 'light',
       
  1269 		'tracklist' => true,
       
  1270 		'tracknumbers' => true,
       
  1271 		'images'	=> true,
       
  1272 		'artists'	=> true
       
  1273 	), $attr, 'playlist' );
       
  1274 
       
  1275 	$id = intval( $atts['id'] );
       
  1276 
       
  1277 	if ( $atts['type'] !== 'audio' ) {
       
  1278 		$atts['type'] = 'video';
       
  1279 	}
       
  1280 
       
  1281 	$args = array(
       
  1282 		'post_status' => 'inherit',
       
  1283 		'post_type' => 'attachment',
       
  1284 		'post_mime_type' => $atts['type'],
       
  1285 		'order' => $atts['order'],
       
  1286 		'orderby' => $atts['orderby']
       
  1287 	);
       
  1288 
       
  1289 	if ( ! empty( $atts['include'] ) ) {
       
  1290 		$args['include'] = $atts['include'];
       
  1291 		$_attachments = get_posts( $args );
       
  1292 
       
  1293 		$attachments = array();
       
  1294 		foreach ( $_attachments as $key => $val ) {
       
  1295 			$attachments[$val->ID] = $_attachments[$key];
       
  1296 		}
       
  1297 	} elseif ( ! empty( $atts['exclude'] ) ) {
       
  1298 		$args['post_parent'] = $id;
       
  1299 		$args['exclude'] = $atts['exclude'];
       
  1300 		$attachments = get_children( $args );
       
  1301 	} else {
       
  1302 		$args['post_parent'] = $id;
       
  1303 		$attachments = get_children( $args );
       
  1304 	}
       
  1305 
       
  1306 	if ( empty( $attachments ) ) {
       
  1307 		return '';
       
  1308 	}
       
  1309 
       
  1310 	if ( is_feed() ) {
       
  1311 		$output = "\n";
       
  1312 		foreach ( $attachments as $att_id => $attachment ) {
       
  1313 			$output .= wp_get_attachment_link( $att_id ) . "\n";
       
  1314 		}
       
  1315 		return $output;
       
  1316 	}
       
  1317 
       
  1318 	$outer = 22; // default padding and border of wrapper
       
  1319 
       
  1320 	$default_width = 640;
       
  1321 	$default_height = 360;
       
  1322 
       
  1323 	$theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
       
  1324 	$theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
       
  1325 
       
  1326 	$data = array(
       
  1327 		'type' => $atts['type'],
       
  1328 		// don't pass strings to JSON, will be truthy in JS
       
  1329 		'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
       
  1330 		'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
       
  1331 		'images' => wp_validate_boolean( $atts['images'] ),
       
  1332 		'artists' => wp_validate_boolean( $atts['artists'] ),
       
  1333 	);
       
  1334 
       
  1335 	$tracks = array();
       
  1336 	foreach ( $attachments as $attachment ) {
       
  1337 		$url = wp_get_attachment_url( $attachment->ID );
       
  1338 		$ftype = wp_check_filetype( $url, wp_get_mime_types() );
       
  1339 		$track = array(
       
  1340 			'src' => $url,
       
  1341 			'type' => $ftype['type'],
       
  1342 			'title' => $attachment->post_title,
       
  1343 			'caption' => $attachment->post_excerpt,
       
  1344 			'description' => $attachment->post_content
       
  1345 		);
       
  1346 
       
  1347 		$track['meta'] = array();
       
  1348 		$meta = wp_get_attachment_metadata( $attachment->ID );
       
  1349 		if ( ! empty( $meta ) ) {
       
  1350 
       
  1351 			foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
       
  1352 				if ( ! empty( $meta[ $key ] ) ) {
       
  1353 					$track['meta'][ $key ] = $meta[ $key ];
       
  1354 				}
       
  1355 			}
       
  1356 
       
  1357 			if ( 'video' === $atts['type'] ) {
       
  1358 				if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
       
  1359 					$width = $meta['width'];
       
  1360 					$height = $meta['height'];
       
  1361 					$theme_height = round( ( $height * $theme_width ) / $width );
       
  1362 				} else {
       
  1363 					$width = $default_width;
       
  1364 					$height = $default_height;
       
  1365 				}
       
  1366 
       
  1367 				$track['dimensions'] = array(
       
  1368 					'original' => compact( 'width', 'height' ),
       
  1369 					'resized' => array(
       
  1370 						'width' => $theme_width,
       
  1371 						'height' => $theme_height
       
  1372 					)
       
  1373 				);
       
  1374 			}
       
  1375 		}
       
  1376 
       
  1377 		if ( $atts['images'] ) {
       
  1378 			$thumb_id = get_post_thumbnail_id( $attachment->ID );
       
  1379 			if ( ! empty( $thumb_id ) ) {
       
  1380 				list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
       
  1381 				$track['image'] = compact( 'src', 'width', 'height' );
       
  1382 				list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
       
  1383 				$track['thumb'] = compact( 'src', 'width', 'height' );
       
  1384 			} else {
       
  1385 				$src = wp_mime_type_icon( $attachment->ID );
       
  1386 				$width = 48;
       
  1387 				$height = 64;
       
  1388 				$track['image'] = compact( 'src', 'width', 'height' );
       
  1389 				$track['thumb'] = compact( 'src', 'width', 'height' );
       
  1390 			}
       
  1391 		}
       
  1392 
       
  1393 		$tracks[] = $track;
       
  1394 	}
       
  1395 	$data['tracks'] = $tracks;
       
  1396 
       
  1397 	$safe_type = esc_attr( $atts['type'] );
       
  1398 	$safe_style = esc_attr( $atts['style'] );
       
  1399 
       
  1400 	ob_start();
       
  1401 
       
  1402 	if ( 1 === $instance ) {
       
  1403 		/**
       
  1404 		 * Print and enqueue playlist scripts, styles, and JavaScript templates.
       
  1405 		 *
       
  1406 		 * @since 3.9.0
       
  1407 		 *
       
  1408 		 * @param string $type  Type of playlist. Possible values are 'audio' or 'video'.
       
  1409 		 * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
       
  1410 		 */
       
  1411 		do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
       
  1412 	} ?>
       
  1413 <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
       
  1414 	<?php if ( 'audio' === $atts['type'] ): ?>
       
  1415 	<div class="wp-playlist-current-item"></div>
       
  1416 	<?php endif ?>
       
  1417 	<<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
       
  1418 		echo (int) $theme_width;
       
  1419 	?>"<?php if ( 'video' === $safe_type ):
       
  1420 		echo ' height="', (int) $theme_height, '"';
       
  1421 	else:
       
  1422 		echo ' style="visibility: hidden"';
       
  1423 	endif; ?>></<?php echo $safe_type ?>>
       
  1424 	<div class="wp-playlist-next"></div>
       
  1425 	<div class="wp-playlist-prev"></div>
       
  1426 	<noscript>
       
  1427 	<ol><?php
       
  1428 	foreach ( $attachments as $att_id => $attachment ) {
       
  1429 		printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
       
  1430 	}
       
  1431 	?></ol>
       
  1432 	</noscript>
       
  1433 	<script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
       
  1434 </div>
       
  1435 	<?php
       
  1436 	return ob_get_clean();
       
  1437 }
       
  1438 add_shortcode( 'playlist', 'wp_playlist_shortcode' );
       
  1439 
       
  1440 /**
       
  1441  * Provides a No-JS Flash fallback as a last resort for audio / video.
   850  *
  1442  *
   851  * @since 3.6.0
  1443  * @since 3.6.0
   852  *
  1444  *
   853  * @param string $url
  1445  * @param string $url The media element URL.
   854  * @return string Fallback HTML
  1446  * @return string Fallback HTML.
   855  */
  1447  */
   856 function wp_mediaelement_fallback( $url ) {
  1448 function wp_mediaelement_fallback( $url ) {
       
  1449 	/**
       
  1450 	 * Filter the Mediaelement fallback output for no-JS.
       
  1451 	 *
       
  1452 	 * @since 3.6.0
       
  1453 	 *
       
  1454 	 * @param string $output Fallback output for no-JS.
       
  1455 	 * @param string $url    Media file URL.
       
  1456 	 */
   857 	return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  1457 	return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
   858 }
  1458 }
   859 
  1459 
   860 /**
  1460 /**
   861  * Return a filtered list of WP-supported audio formats
  1461  * Returns a filtered list of WP-supported audio formats.
   862  *
  1462  *
   863  * @since 3.6.0
  1463  * @since 3.6.0
   864  * @return array
  1464  *
       
  1465  * @return array Supported audio formats.
   865  */
  1466  */
   866 function wp_get_audio_extensions() {
  1467 function wp_get_audio_extensions() {
       
  1468 	/**
       
  1469 	 * Filter the list of supported audio formats.
       
  1470 	 *
       
  1471 	 * @since 3.6.0
       
  1472 	 *
       
  1473 	 * @param array $extensions An array of support audio formats. Defaults are
       
  1474 	 *                          'mp3', 'ogg', 'wma', 'm4a', 'wav'.
       
  1475 	 */
   867 	return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
  1476 	return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
   868 }
  1477 }
   869 
  1478 
   870 /**
  1479 /**
   871  * The Audio shortcode.
  1480  * Returns useful keys to use to lookup data from an attachment's stored metadata.
       
  1481  *
       
  1482  * @since 3.9.0
       
  1483  *
       
  1484  * @param WP_Post $attachment The current attachment, provided for context.
       
  1485  * @param string  $context    Optional. The context. Accepts 'edit', 'display'. Default 'display'.
       
  1486  * @return array Key/value pairs of field keys to labels.
       
  1487  */
       
  1488 function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
       
  1489 	$fields = array(
       
  1490 		'artist' => __( 'Artist' ),
       
  1491 		'album' => __( 'Album' ),
       
  1492 	);
       
  1493 
       
  1494 	if ( 'display' === $context ) {
       
  1495 		$fields['genre']            = __( 'Genre' );
       
  1496 		$fields['year']             = __( 'Year' );
       
  1497 		$fields['length_formatted'] = _x( 'Length', 'video or audio' );
       
  1498 	} elseif ( 'js' === $context ) {
       
  1499 		$fields['bitrate']          = __( 'Bitrate' );
       
  1500 		$fields['bitrate_mode']     = __( 'Bitrate Mode' );
       
  1501 	}
       
  1502 
       
  1503 	/**
       
  1504 	 * Filter the editable list of keys to look up data from an attachment's metadata.
       
  1505 	 *
       
  1506 	 * @since 3.9.0
       
  1507 	 *
       
  1508 	 * @param array   $fields     Key/value pairs of field keys to labels.
       
  1509 	 * @param WP_Post $attachment Attachment object.
       
  1510 	 * @param string  $context    The context. Accepts 'edit', 'display'. Default 'display'.
       
  1511 	 */
       
  1512 	return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
       
  1513 }
       
  1514 /**
       
  1515  * Builds the Audio shortcode output.
   872  *
  1516  *
   873  * This implements the functionality of the Audio Shortcode for displaying
  1517  * This implements the functionality of the Audio Shortcode for displaying
   874  * WordPress mp3s in a post.
  1518  * WordPress mp3s in a post.
   875  *
  1519  *
   876  * @since 3.6.0
  1520  * @since 3.6.0
   877  *
  1521  *
   878  * @param array  $attr    Attributes of the shortcode.
  1522  * @param array  $attr {
   879  * @param string $content Optional. Shortcode content.
  1523  *     Attributes of the audio shortcode.
       
  1524  *
       
  1525  *     @type string $src      URL to the source of the audio file. Default empty.
       
  1526  *     @type string $loop     The 'loop' attribute for the `<audio>` element. Default empty.
       
  1527  *     @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
       
  1528  *     @type string $preload  The 'preload' attribute for the `<audio>` element. Default empty.
       
  1529  *     @type string $class    The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
       
  1530  *     @type string $id       The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instance}'.
       
  1531  *     @type string $style    The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
       
  1532  * }
       
  1533  * @param string $content Shortcode content.
   880  * @return string HTML content to display audio.
  1534  * @return string HTML content to display audio.
   881  */
  1535  */
   882 function wp_audio_shortcode( $attr, $content = '' ) {
  1536 function wp_audio_shortcode( $attr, $content = '' ) {
   883 	$post_id = get_post() ? get_the_ID() : 0;
  1537 	$post_id = get_post() ? get_the_ID() : 0;
   884 
  1538 
   885 	static $instances = 0;
  1539 	static $instance = 0;
   886 	$instances++;
  1540 	$instance++;
   887 
  1541 
   888 	/**
  1542 	/**
   889 	 * Override the default audio shortcode.
  1543 	 * Filter the default audio shortcode output.
   890 	 *
  1544 	 *
   891 	 * @since 3.7.0
  1545 	 * If the filtered output isn't empty, it will be used instead of generating the default audio template.
   892 	 *
  1546 	 *
   893 	 * @param null              Empty variable to be replaced with shortcode markup.
  1547 	 * @since 3.6.0
   894 	 * @param array  $attr      Attributes of the shortcode.
  1548 	 *
   895 	 * @param string $content   Shortcode content.
  1549 	 * @param string $html     Empty variable to be replaced with shortcode markup.
   896 	 * @param int    $instances Unique numeric ID of this audio shortcode instance.
  1550 	 * @param array  $attr     Attributes of the shortcode. @see wp_audio_shortcode()
   897 	 */
  1551 	 * @param string $content  Shortcode content.
   898 	$html = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instances );
  1552 	 * @param int    $instance Unique numeric ID of this audio shortcode instance.
   899 	if ( '' !== $html )
  1553 	 */
   900 		return $html;
  1554 	$override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
       
  1555 	if ( '' !== $override ) {
       
  1556 		return $override;
       
  1557 	}
   901 
  1558 
   902 	$audio = null;
  1559 	$audio = null;
   903 
  1560 
   904 	$default_types = wp_get_audio_extensions();
  1561 	$default_types = wp_get_audio_extensions();
   905 	$defaults_atts = array(
  1562 	$defaults_atts = array(
   906 		'src'      => '',
  1563 		'src'      => '',
   907 		'loop'     => '',
  1564 		'loop'     => '',
   908 		'autoplay' => '',
  1565 		'autoplay' => '',
   909 		'preload'  => 'none'
  1566 		'preload'  => 'none'
   910 	);
  1567 	);
   911 	foreach ( $default_types as $type )
  1568 	foreach ( $default_types as $type ) {
   912 		$defaults_atts[$type] = '';
  1569 		$defaults_atts[$type] = '';
       
  1570 	}
   913 
  1571 
   914 	$atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  1572 	$atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
   915 	extract( $atts );
       
   916 
  1573 
   917 	$primary = false;
  1574 	$primary = false;
   918 	if ( ! empty( $src ) ) {
  1575 	if ( ! empty( $atts['src'] ) ) {
   919 		$type = wp_check_filetype( $src, wp_get_mime_types() );
  1576 		$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
   920 		if ( ! in_array( strtolower( $type['ext'] ), $default_types ) )
  1577 		if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
   921 			return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  1578 			return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
       
  1579 		}
   922 		$primary = true;
  1580 		$primary = true;
   923 		array_unshift( $default_types, 'src' );
  1581 		array_unshift( $default_types, 'src' );
   924 	} else {
  1582 	} else {
   925 		foreach ( $default_types as $ext ) {
  1583 		foreach ( $default_types as $ext ) {
   926 			if ( ! empty( $$ext ) ) {
  1584 			if ( ! empty( $atts[ $ext ] ) ) {
   927 				$type = wp_check_filetype( $$ext, wp_get_mime_types() );
  1585 				$type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
   928 				if ( strtolower( $type['ext'] ) === $ext )
  1586 				if ( strtolower( $type['ext'] ) === $ext ) {
   929 					$primary = true;
  1587 					$primary = true;
       
  1588 				}
   930 			}
  1589 			}
   931 		}
  1590 		}
   932 	}
  1591 	}
   933 
  1592 
   934 	if ( ! $primary ) {
  1593 	if ( ! $primary ) {
   935 		$audios = get_attached_media( 'audio', $post_id );
  1594 		$audios = get_attached_media( 'audio', $post_id );
   936 		if ( empty( $audios ) )
  1595 		if ( empty( $audios ) ) {
   937 			return;
  1596 			return;
       
  1597 		}
   938 
  1598 
   939 		$audio = reset( $audios );
  1599 		$audio = reset( $audios );
   940 		$src = wp_get_attachment_url( $audio->ID );
  1600 		$atts['src'] = wp_get_attachment_url( $audio->ID );
   941 		if ( empty( $src ) )
  1601 		if ( empty( $atts['src'] ) ) {
   942 			return;
  1602 			return;
       
  1603 		}
   943 
  1604 
   944 		array_unshift( $default_types, 'src' );
  1605 		array_unshift( $default_types, 'src' );
   945 	}
  1606 	}
   946 
  1607 
       
  1608 	/**
       
  1609 	 * Filter the media library used for the audio shortcode.
       
  1610 	 *
       
  1611 	 * @since 3.6.0
       
  1612 	 *
       
  1613 	 * @param string $library Media library used for the audio shortcode.
       
  1614 	 */
   947 	$library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  1615 	$library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
   948 	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1616 	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
   949 		wp_enqueue_style( 'wp-mediaelement' );
  1617 		wp_enqueue_style( 'wp-mediaelement' );
   950 		wp_enqueue_script( 'wp-mediaelement' );
  1618 		wp_enqueue_script( 'wp-mediaelement' );
   951 	}
  1619 	}
   952 
  1620 
   953 	$atts = array(
  1621 	/**
       
  1622 	 * Filter the class attribute for the audio shortcode output container.
       
  1623 	 *
       
  1624 	 * @since 3.6.0
       
  1625 	 *
       
  1626 	 * @param string $class CSS class or list of space-separated classes.
       
  1627 	 */
       
  1628 	$html_atts = array(
   954 		'class'    => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
  1629 		'class'    => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
   955 		'id'       => sprintf( 'audio-%d-%d', $post_id, $instances ),
  1630 		'id'       => sprintf( 'audio-%d-%d', $post_id, $instance ),
   956 		'loop'     => $loop,
  1631 		'loop'     => wp_validate_boolean( $atts['loop'] ),
   957 		'autoplay' => $autoplay,
  1632 		'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
   958 		'preload'  => $preload,
  1633 		'preload'  => $atts['preload'],
   959 		'style'    => 'width: 100%',
  1634 		'style'    => 'width: 100%; visibility: hidden;',
   960 	);
  1635 	);
   961 
  1636 
   962 	// These ones should just be omitted altogether if they are blank
  1637 	// These ones should just be omitted altogether if they are blank
   963 	foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  1638 	foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
   964 		if ( empty( $atts[$a] ) )
  1639 		if ( empty( $html_atts[$a] ) ) {
   965 			unset( $atts[$a] );
  1640 			unset( $html_atts[$a] );
       
  1641 		}
   966 	}
  1642 	}
   967 
  1643 
   968 	$attr_strings = array();
  1644 	$attr_strings = array();
   969 	foreach ( $atts as $k => $v ) {
  1645 	foreach ( $html_atts as $k => $v ) {
   970 		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1646 		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
   971 	}
  1647 	}
   972 
  1648 
   973 	$html = '';
  1649 	$html = '';
   974 	if ( 'mediaelement' === $library && 1 === $instances )
  1650 	if ( 'mediaelement' === $library && 1 === $instance ) {
   975 		$html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  1651 		$html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
       
  1652 	}
   976 	$html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
  1653 	$html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
   977 
  1654 
   978 	$fileurl = '';
  1655 	$fileurl = '';
   979 	$source = '<source type="%s" src="%s" />';
  1656 	$source = '<source type="%s" src="%s" />';
   980 	foreach ( $default_types as $fallback ) {
  1657 	foreach ( $default_types as $fallback ) {
   981 		if ( ! empty( $$fallback ) ) {
  1658 		if ( ! empty( $atts[ $fallback ] ) ) {
   982 			if ( empty( $fileurl ) )
  1659 			if ( empty( $fileurl ) ) {
   983 				$fileurl = $$fallback;
  1660 				$fileurl = $atts[ $fallback ];
   984 			$type = wp_check_filetype( $$fallback, wp_get_mime_types() );
  1661 			}
   985 			$html .= sprintf( $source, $type['type'], esc_url( $$fallback ) );
  1662 			$type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
   986 		}
  1663 			$url = add_query_arg( '_', $instance, $atts[ $fallback ] );
   987 	}
  1664 			$html .= sprintf( $source, $type['type'], esc_url( $url ) );
   988 
  1665 		}
   989 	if ( 'mediaelement' === $library )
  1666 	}
       
  1667 
       
  1668 	if ( 'mediaelement' === $library ) {
   990 		$html .= wp_mediaelement_fallback( $fileurl );
  1669 		$html .= wp_mediaelement_fallback( $fileurl );
       
  1670 	}
   991 	$html .= '</audio>';
  1671 	$html .= '</audio>';
   992 
  1672 
       
  1673 	/**
       
  1674 	 * Filter the audio shortcode output.
       
  1675 	 *
       
  1676 	 * @since 3.6.0
       
  1677 	 *
       
  1678 	 * @param string $html    Audio shortcode HTML output.
       
  1679 	 * @param array  $atts    Array of audio shortcode attributes.
       
  1680 	 * @param string $audio   Audio file.
       
  1681 	 * @param int    $post_id Post ID.
       
  1682 	 * @param string $library Media library used for the audio shortcode.
       
  1683 	 */
   993 	return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  1684 	return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
   994 }
  1685 }
   995 add_shortcode( 'audio', 'wp_audio_shortcode' );
  1686 add_shortcode( 'audio', 'wp_audio_shortcode' );
   996 
  1687 
   997 /**
  1688 /**
   998  * Return a filtered list of WP-supported video formats
  1689  * Returns a filtered list of WP-supported video formats.
   999  *
  1690  *
  1000  * @since 3.6.0
  1691  * @since 3.6.0
  1001  * @return array
  1692  *
       
  1693  * @return array List of supported video formats.
  1002  */
  1694  */
  1003 function wp_get_video_extensions() {
  1695 function wp_get_video_extensions() {
       
  1696 	/**
       
  1697 	 * Filter the list of supported video formats.
       
  1698 	 *
       
  1699 	 * @since 3.6.0
       
  1700 	 *
       
  1701 	 * @param array $extensions An array of support video formats. Defaults are
       
  1702 	 *                          'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
       
  1703 	 */
  1004 	return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  1704 	return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  1005 }
  1705 }
  1006 
  1706 
  1007 /**
  1707 /**
  1008  * The Video shortcode.
  1708  * Builds the Video shortcode output.
  1009  *
  1709  *
  1010  * This implements the functionality of the Video Shortcode for displaying
  1710  * This implements the functionality of the Video Shortcode for displaying
  1011  * WordPress mp4s in a post.
  1711  * WordPress mp4s in a post.
  1012  *
  1712  *
  1013  * @since 3.6.0
  1713  * @since 3.6.0
  1014  *
  1714  *
  1015  * @param array  $attr    Attributes of the shortcode.
  1715  * @param array  $attr {
  1016  * @param string $content Optional. Shortcode content.
  1716  *     Attributes of the shortcode.
       
  1717  *
       
  1718  *     @type string $src      URL to the source of the video file. Default empty.
       
  1719  *     @type int    $height   Height of the video embed in pixels. Default 360.
       
  1720  *     @type int    $width    Width of the video embed in pixels. Default $content_width or 640.
       
  1721  *     @type string $poster   The 'poster' attribute for the `<video>` element. Default empty.
       
  1722  *     @type string $loop     The 'loop' attribute for the `<video>` element. Default empty.
       
  1723  *     @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
       
  1724  *     @type string $preload  The 'preload' attribute for the `<video>` element.
       
  1725  *                            Default 'metadata'.
       
  1726  *     @type string $class    The 'class' attribute for the `<video>` element.
       
  1727  *                            Default 'wp-video-shortcode'.
       
  1728  *     @type string $id       The 'id' attribute for the `<video>` element.
       
  1729  *                            Default 'video-{$post_id}-{$instance}'.
       
  1730  * }
       
  1731  * @param string $content Shortcode content.
  1017  * @return string HTML content to display video.
  1732  * @return string HTML content to display video.
  1018  */
  1733  */
  1019 function wp_video_shortcode( $attr, $content = '' ) {
  1734 function wp_video_shortcode( $attr, $content = '' ) {
  1020 	global $content_width;
  1735 	global $content_width;
  1021 	$post_id = get_post() ? get_the_ID() : 0;
  1736 	$post_id = get_post() ? get_the_ID() : 0;
  1022 
  1737 
  1023 	static $instances = 0;
  1738 	static $instance = 0;
  1024 	$instances++;
  1739 	$instance++;
  1025 
  1740 
  1026 	/**
  1741 	/**
  1027 	 * Override the default video shortcode.
  1742 	 * Filter the default video shortcode output.
  1028 	 *
  1743 	 *
  1029 	 * @since 3.7.0
  1744 	 * If the filtered output isn't empty, it will be used instead of generating
  1030 	 *
  1745 	 * the default video template.
  1031 	 * @param null              Empty variable to be replaced with shortcode markup.
  1746 	 *
  1032 	 * @param array  $attr      Attributes of the shortcode.
  1747 	 * @since 3.6.0
  1033 	 * @param string $content   Shortcode content.
  1748 	 *
  1034 	 * @param int    $instances Unique numeric ID of this video shortcode instance.
  1749 	 * @see wp_video_shortcode()
  1035 	 */
  1750 	 *
  1036 	$html = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instances );
  1751 	 * @param string $html     Empty variable to be replaced with shortcode markup.
  1037 	if ( '' !== $html )
  1752 	 * @param array  $attr     Attributes of the video shortcode.
  1038 		return $html;
  1753 	 * @param string $content  Video shortcode content.
       
  1754 	 * @param int    $instance Unique numeric ID of this video shortcode instance.
       
  1755 	 */
       
  1756 	$override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
       
  1757 	if ( '' !== $override ) {
       
  1758 		return $override;
       
  1759 	}
  1039 
  1760 
  1040 	$video = null;
  1761 	$video = null;
  1041 
  1762 
  1042 	$default_types = wp_get_video_extensions();
  1763 	$default_types = wp_get_video_extensions();
  1043 	$defaults_atts = array(
  1764 	$defaults_atts = array(
  1044 		'src'      => '',
  1765 		'src'      => '',
  1045 		'poster'   => '',
  1766 		'poster'   => '',
  1046 		'loop'     => '',
  1767 		'loop'     => '',
  1047 		'autoplay' => '',
  1768 		'autoplay' => '',
  1048 		'preload'  => 'metadata',
  1769 		'preload'  => 'metadata',
       
  1770 		'width'    => 640,
  1049 		'height'   => 360,
  1771 		'height'   => 360,
  1050 		'width'    => empty( $content_width ) ? 640 : $content_width,
       
  1051 	);
  1772 	);
  1052 
  1773 
  1053 	foreach ( $default_types as $type )
  1774 	foreach ( $default_types as $type ) {
  1054 		$defaults_atts[$type] = '';
  1775 		$defaults_atts[$type] = '';
       
  1776 	}
  1055 
  1777 
  1056 	$atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  1778 	$atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  1057 	extract( $atts );
  1779 
  1058 
  1780 	if ( is_admin() ) {
  1059 	$w = $width;
  1781 		// shrink the video so it isn't huge in the admin
  1060 	$h = $height;
  1782 		if ( $atts['width'] > $defaults_atts['width'] ) {
  1061 	if ( is_admin() && $width > 600 )
  1783 			$atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
  1062 		$w = 600;
  1784 			$atts['width'] = $defaults_atts['width'];
  1063 	elseif ( ! is_admin() && $w > $defaults_atts['width'] )
  1785 		}
  1064 		$w = $defaults_atts['width'];
  1786 	} else {
  1065 
  1787 		// if the video is bigger than the theme
  1066 	if ( $w < $width )
  1788 		if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
  1067 		$height = round( ( $h * $w ) / $width );
  1789 			$atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
  1068 
  1790 			$atts['width'] = $content_width;
  1069 	$width = $w;
  1791 		}
       
  1792 	}
       
  1793 
       
  1794 	$is_vimeo = $is_youtube = false;
       
  1795 	$yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
       
  1796 	$vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
  1070 
  1797 
  1071 	$primary = false;
  1798 	$primary = false;
  1072 	if ( ! empty( $src ) ) {
  1799 	if ( ! empty( $atts['src'] ) ) {
  1073 		$type = wp_check_filetype( $src, wp_get_mime_types() );
  1800 		$is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
  1074 		if ( ! in_array( strtolower( $type['ext'] ), $default_types ) )
  1801 		$is_youtube = (  preg_match( $yt_pattern, $atts['src'] ) );
  1075 			return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  1802 		if ( ! $is_youtube && ! $is_vimeo ) {
       
  1803 			$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
       
  1804 			if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
       
  1805 				return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
       
  1806 			}
       
  1807 		}
       
  1808 
       
  1809 		if ( $is_vimeo ) {
       
  1810 			wp_enqueue_script( 'froogaloop' );
       
  1811 		}
       
  1812 
  1076 		$primary = true;
  1813 		$primary = true;
  1077 		array_unshift( $default_types, 'src' );
  1814 		array_unshift( $default_types, 'src' );
  1078 	} else {
  1815 	} else {
  1079 		foreach ( $default_types as $ext ) {
  1816 		foreach ( $default_types as $ext ) {
  1080 			if ( ! empty( $$ext ) ) {
  1817 			if ( ! empty( $atts[ $ext ] ) ) {
  1081 				$type = wp_check_filetype( $$ext, wp_get_mime_types() );
  1818 				$type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  1082 				if ( strtolower( $type['ext'] ) === $ext )
  1819 				if ( strtolower( $type['ext'] ) === $ext ) {
  1083 					$primary = true;
  1820 					$primary = true;
       
  1821 				}
  1084 			}
  1822 			}
  1085 		}
  1823 		}
  1086 	}
  1824 	}
  1087 
  1825 
  1088 	if ( ! $primary ) {
  1826 	if ( ! $primary ) {
  1089 		$videos = get_attached_media( 'video', $post_id );
  1827 		$videos = get_attached_media( 'video', $post_id );
  1090 		if ( empty( $videos ) )
  1828 		if ( empty( $videos ) ) {
  1091 			return;
  1829 			return;
       
  1830 		}
  1092 
  1831 
  1093 		$video = reset( $videos );
  1832 		$video = reset( $videos );
  1094 		$src = wp_get_attachment_url( $video->ID );
  1833 		$atts['src'] = wp_get_attachment_url( $video->ID );
  1095 		if ( empty( $src ) )
  1834 		if ( empty( $atts['src'] ) ) {
  1096 			return;
  1835 			return;
       
  1836 		}
  1097 
  1837 
  1098 		array_unshift( $default_types, 'src' );
  1838 		array_unshift( $default_types, 'src' );
  1099 	}
  1839 	}
  1100 
  1840 
       
  1841 	/**
       
  1842 	 * Filter the media library used for the video shortcode.
       
  1843 	 *
       
  1844 	 * @since 3.6.0
       
  1845 	 *
       
  1846 	 * @param string $library Media library used for the video shortcode.
       
  1847 	 */
  1101 	$library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  1848 	$library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  1102 	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1849 	if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1103 		wp_enqueue_style( 'wp-mediaelement' );
  1850 		wp_enqueue_style( 'wp-mediaelement' );
  1104 		wp_enqueue_script( 'wp-mediaelement' );
  1851 		wp_enqueue_script( 'wp-mediaelement' );
  1105 	}
  1852 	}
  1106 
  1853 
  1107 	$atts = array(
  1854 	/**
       
  1855 	 * Filter the class attribute for the video shortcode output container.
       
  1856 	 *
       
  1857 	 * @since 3.6.0
       
  1858 	 *
       
  1859 	 * @param string $class CSS class or list of space-separated classes.
       
  1860 	 */
       
  1861 	$html_atts = array(
  1108 		'class'    => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
  1862 		'class'    => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
  1109 		'id'       => sprintf( 'video-%d-%d', $post_id, $instances ),
  1863 		'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
  1110 		'width'    => absint( $width ),
  1864 		'width'    => absint( $atts['width'] ),
  1111 		'height'   => absint( $height ),
  1865 		'height'   => absint( $atts['height'] ),
  1112 		'poster'   => esc_url( $poster ),
  1866 		'poster'   => esc_url( $atts['poster'] ),
  1113 		'loop'     => $loop,
  1867 		'loop'     => wp_validate_boolean( $atts['loop'] ),
  1114 		'autoplay' => $autoplay,
  1868 		'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  1115 		'preload'  => $preload,
  1869 		'preload'  => $atts['preload'],
  1116 	);
  1870 	);
  1117 
  1871 
  1118 	// These ones should just be omitted altogether if they are blank
  1872 	// These ones should just be omitted altogether if they are blank
  1119 	foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  1873 	foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  1120 		if ( empty( $atts[$a] ) )
  1874 		if ( empty( $html_atts[$a] ) ) {
  1121 			unset( $atts[$a] );
  1875 			unset( $html_atts[$a] );
       
  1876 		}
  1122 	}
  1877 	}
  1123 
  1878 
  1124 	$attr_strings = array();
  1879 	$attr_strings = array();
  1125 	foreach ( $atts as $k => $v ) {
  1880 	foreach ( $html_atts as $k => $v ) {
  1126 		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1881 		$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1127 	}
  1882 	}
  1128 
  1883 
  1129 	$html = '';
  1884 	$html = '';
  1130 	if ( 'mediaelement' === $library && 1 === $instances )
  1885 	if ( 'mediaelement' === $library && 1 === $instance ) {
  1131 		$html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  1886 		$html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
       
  1887 	}
  1132 	$html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  1888 	$html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  1133 
  1889 
  1134 	$fileurl = '';
  1890 	$fileurl = '';
  1135 	$source = '<source type="%s" src="%s" />';
  1891 	$source = '<source type="%s" src="%s" />';
  1136 	foreach ( $default_types as $fallback ) {
  1892 	foreach ( $default_types as $fallback ) {
  1137 		if ( ! empty( $$fallback ) ) {
  1893 		if ( ! empty( $atts[ $fallback ] ) ) {
  1138 			if ( empty( $fileurl ) )
  1894 			if ( empty( $fileurl ) ) {
  1139 				$fileurl = $$fallback;
  1895 				$fileurl = $atts[ $fallback ];
  1140 			$type = wp_check_filetype( $$fallback, wp_get_mime_types() );
  1896 			}
  1141 			// m4v sometimes shows up as video/mpeg which collides with mp4
  1897 			if ( 'src' === $fallback && $is_youtube ) {
  1142 			if ( 'm4v' === $type['ext'] )
  1898 				$type = array( 'type' => 'video/youtube' );
  1143 				$type['type'] = 'video/m4v';
  1899 			} elseif ( 'src' === $fallback && $is_vimeo ) {
  1144 			$html .= sprintf( $source, $type['type'], esc_url( $$fallback ) );
  1900 				$type = array( 'type' => 'video/vimeo' );
  1145 		}
  1901 			} else {
  1146 	}
  1902 				$type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  1147 	if ( 'mediaelement' === $library )
  1903 			}
       
  1904 			$url = add_query_arg( '_', $instance, $atts[ $fallback ] );
       
  1905 			$html .= sprintf( $source, $type['type'], esc_url( $url ) );
       
  1906 		}
       
  1907 	}
       
  1908 
       
  1909 	if ( ! empty( $content ) ) {
       
  1910 		if ( false !== strpos( $content, "\n" ) ) {
       
  1911 			$content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
       
  1912 		}
       
  1913 		$html .= trim( $content );
       
  1914 	}
       
  1915 
       
  1916 	if ( 'mediaelement' === $library ) {
  1148 		$html .= wp_mediaelement_fallback( $fileurl );
  1917 		$html .= wp_mediaelement_fallback( $fileurl );
       
  1918 	}
  1149 	$html .= '</video>';
  1919 	$html .= '</video>';
  1150 
  1920 
  1151 	$html = sprintf( '<div style="width: %dpx; max-width: 100%%;">%s</div>', $width, $html );
  1921 	$width_rule = '';
  1152 	return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id, $library );
  1922 	if ( ! empty( $atts['width'] ) ) {
       
  1923 		$width_rule = sprintf( 'width: %dpx; ', $atts['width'] );
       
  1924 	}
       
  1925 	$output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
       
  1926 
       
  1927 	/**
       
  1928 	 * Filter the output of the video shortcode.
       
  1929 	 *
       
  1930 	 * @since 3.6.0
       
  1931 	 *
       
  1932 	 * @param string $output  Video shortcode HTML output.
       
  1933 	 * @param array  $atts    Array of video shortcode attributes.
       
  1934 	 * @param string $video   Video file.
       
  1935 	 * @param int    $post_id Post ID.
       
  1936 	 * @param string $library Media library used for the video shortcode.
       
  1937 	 */
       
  1938 	return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
  1153 }
  1939 }
  1154 add_shortcode( 'video', 'wp_video_shortcode' );
  1940 add_shortcode( 'video', 'wp_video_shortcode' );
  1155 
  1941 
  1156 /**
  1942 /**
  1157  * Display previous image link that has the same post parent.
  1943  * Displays previous image link that has the same post parent.
  1158  *
  1944  *
  1159  * @since 2.5.0
  1945  * @since 2.5.0
  1160  * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1946  *
  1161  * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1947  * @see adjacent_image_link()
  1162  * @return string HTML content.
  1948  *
  1163  */
  1949  * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
  1164 function previous_image_link($size = 'thumbnail', $text = false) {
  1950  *                           0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
       
  1951  * @param string       $text Optional. Link text. Default false.
       
  1952  * @return string HTML output for the previous image link.
       
  1953  */
       
  1954 function previous_image_link( $size = 'thumbnail', $text = false ) {
  1165 	adjacent_image_link(true, $size, $text);
  1955 	adjacent_image_link(true, $size, $text);
  1166 }
  1956 }
  1167 
  1957 
  1168 /**
  1958 /**
  1169  * Display next image link that has the same post parent.
  1959  * Displays next image link that has the same post parent.
  1170  *
  1960  *
  1171  * @since 2.5.0
  1961  * @since 2.5.0
  1172  * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1962  *
  1173  * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1963  * @see adjacent_image_link()
  1174  * @return string HTML content.
  1964  *
       
  1965  * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
       
  1966  *                           0 or 'none' will default to 'post_title' or `$text`. Default 'thumbnail'.
       
  1967  * @param string       $text Optional. Link text. Default false.
       
  1968  * @return string HTML output for the next image link.
  1175  */
  1969  */
  1176 function next_image_link($size = 'thumbnail', $text = false) {
  1970 function next_image_link($size = 'thumbnail', $text = false) {
  1177 	adjacent_image_link(false, $size, $text);
  1971 	adjacent_image_link(false, $size, $text);
  1178 }
  1972 }
  1179 
  1973 
  1180 /**
  1974 /**
  1181  * Display next or previous image link that has the same post parent.
  1975  * Displays next or previous image link that has the same post parent.
  1182  *
  1976  *
  1183  * Retrieves the current attachment object from the $post global.
  1977  * Retrieves the current attachment object from the $post global.
  1184  *
  1978  *
  1185  * @since 2.5.0
  1979  * @since 2.5.0
  1186  *
  1980  *
  1187  * @param bool $prev Optional. Default is true to display previous link, false for next.
  1981  * @param bool         $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
  1188  */
  1982  * @param string|array $size Optional. Registered image size or flat array of height and width dimensions.
  1189 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  1983  *                                     Default 'thumbnail'.
       
  1984  * @param bool         $text Optional. Link text. Default false.
       
  1985  * @return string The adjacent image link.
       
  1986  */
       
  1987 function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
  1190 	$post = get_post();
  1988 	$post = get_post();
  1191 	$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' ) ) );
  1989 	$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' ) ) );
  1192 
  1990 
  1193 	foreach ( $attachments as $k => $attachment )
  1991 	foreach ( $attachments as $k => $attachment ) {
  1194 		if ( $attachment->ID == $post->ID )
  1992 		if ( $attachment->ID == $post->ID ) {
  1195 			break;
  1993 			break;
  1196 
  1994 		}
  1197 	$k = $prev ? $k - 1 : $k + 1;
  1995 	}
  1198 
  1996 
  1199 	$output = $attachment_id = null;
  1997 	$output = '';
  1200 	if ( isset( $attachments[ $k ] ) ) {
  1998 	$attachment_id = 0;
  1201 		$attachment_id = $attachments[ $k ]->ID;
  1999 
  1202 		$output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  2000 	if ( $attachments ) {
       
  2001 		$k = $prev ? $k - 1 : $k + 1;
       
  2002 
       
  2003 		if ( isset( $attachments[ $k ] ) ) {
       
  2004 			$attachment_id = $attachments[ $k ]->ID;
       
  2005 			$output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
       
  2006 		}
  1203 	}
  2007 	}
  1204 
  2008 
  1205 	$adjacent = $prev ? 'previous' : 'next';
  2009 	$adjacent = $prev ? 'previous' : 'next';
       
  2010 
       
  2011 	/**
       
  2012 	 * Filter the adjacent image link.
       
  2013 	 *
       
  2014 	 * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
       
  2015 	 * either 'next', or 'previous'.
       
  2016 	 *
       
  2017 	 * @since 3.5.0
       
  2018 	 *
       
  2019 	 * @param string $output        Adjacent image HTML markup.
       
  2020 	 * @param int    $attachment_id Attachment ID
       
  2021 	 * @param string $size          Image size.
       
  2022 	 * @param string $text          Link text.
       
  2023 	 */
  1206 	echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  2024 	echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  1207 }
  2025 }
  1208 
  2026 
  1209 /**
  2027 /**
  1210  * Retrieve taxonomies attached to the attachment.
  2028  * Retrieves taxonomies attached to given the attachment.
  1211  *
  2029  *
  1212  * @since 2.5.0
  2030  * @since 2.5.0
  1213  *
  2031  *
  1214  * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  2032  * @param int|array|object $attachment Attachment ID, data array, or data object.
  1215  * @return array Empty array on failure. List of taxonomies on success.
  2033  * @return array Empty array on failure. List of taxonomies on success.
  1216  */
  2034  */
  1217 function get_attachment_taxonomies($attachment) {
  2035 function get_attachment_taxonomies( $attachment ) {
  1218 	if ( is_int( $attachment ) )
  2036 	if ( is_int( $attachment ) ) {
  1219 		$attachment = get_post($attachment);
  2037 		$attachment = get_post( $attachment );
  1220 	else if ( is_array($attachment) )
  2038 	} elseif ( is_array( $attachment ) ) {
  1221 		$attachment = (object) $attachment;
  2039 		$attachment = (object) $attachment;
  1222 
  2040 	}
  1223 	if ( ! is_object($attachment) )
  2041 	if ( ! is_object($attachment) )
  1224 		return array();
  2042 		return array();
  1225 
  2043 
  1226 	$filename = basename($attachment->guid);
  2044 	$filename = basename($attachment->guid);
  1227 
  2045 
  1244 
  2062 
  1245 	return array_unique($taxonomies);
  2063 	return array_unique($taxonomies);
  1246 }
  2064 }
  1247 
  2065 
  1248 /**
  2066 /**
  1249  * Return all of the taxonomy names that are registered for attachments.
  2067  * Retrieves all of the taxonomy names that are registered for attachments.
  1250  *
  2068  *
  1251  * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  2069  * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  1252  *
  2070  *
  1253  * @since 3.5.0
  2071  * @since 3.5.0
  1254  * @see get_attachment_taxonomies()
  2072  *
  1255  * @uses get_taxonomies()
  2073  * @see get_taxonomies()
  1256  *
  2074  *
  1257  * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  2075  * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
       
  2076  *                       Default 'names'.
  1258  * @return array The names of all taxonomy of $object_type.
  2077  * @return array The names of all taxonomy of $object_type.
  1259  */
  2078  */
  1260 function get_taxonomies_for_attachments( $output = 'names' ) {
  2079 function get_taxonomies_for_attachments( $output = 'names' ) {
  1261 	$taxonomies = array();
  2080 	$taxonomies = array();
  1262 	foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  2081 	foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1274 	return $taxonomies;
  2093 	return $taxonomies;
  1275 }
  2094 }
  1276 
  2095 
  1277 /**
  2096 /**
  1278  * Create new GD image resource with transparency support
  2097  * Create new GD image resource with transparency support
  1279  * @TODO: Deprecate if possible.
  2098  *
       
  2099  * @todo: Deprecate if possible.
  1280  *
  2100  *
  1281  * @since 2.9.0
  2101  * @since 2.9.0
  1282  *
  2102  *
  1283  * @param int $width Image width
  2103  * @param int $width  Image width in pixels.
  1284  * @param int $height Image height
  2104  * @param int $height Image height in pixels..
  1285  * @return image resource
  2105  * @return resource The GD image resource.
  1286  */
  2106  */
  1287 function wp_imagecreatetruecolor($width, $height) {
  2107 function wp_imagecreatetruecolor($width, $height) {
  1288 	$img = imagecreatetruecolor($width, $height);
  2108 	$img = imagecreatetruecolor($width, $height);
  1289 	if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  2109 	if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1290 		imagealphablending($img, false);
  2110 		imagealphablending($img, false);
  1292 	}
  2112 	}
  1293 	return $img;
  2113 	return $img;
  1294 }
  2114 }
  1295 
  2115 
  1296 /**
  2116 /**
  1297  * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  2117  * Registers an embed handler.
       
  2118  *
       
  2119  * Should probably only be used for sites that do not support oEmbed.
  1298  *
  2120  *
  1299  * @since 2.9.0
  2121  * @since 2.9.0
       
  2122  *
  1300  * @see WP_Embed::register_handler()
  2123  * @see WP_Embed::register_handler()
       
  2124  *
       
  2125  * @param string   $id       An internal ID/name for the handler. Needs to be unique.
       
  2126  * @param string   $regex    The regex that will be used to see if this handler should be used for a URL.
       
  2127  * @param callback $callback The callback function that will be called if the regex is matched.
       
  2128  * @param int      $priority Optional. Used to specify the order in which the registered handlers will
       
  2129  *                           be tested. Default 10.
  1301  */
  2130  */
  1302 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  2131 function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1303 	global $wp_embed;
  2132 	global $wp_embed;
  1304 	$wp_embed->register_handler( $id, $regex, $callback, $priority );
  2133 	$wp_embed->register_handler( $id, $regex, $callback, $priority );
  1305 }
  2134 }
  1306 
  2135 
  1307 /**
  2136 /**
  1308  * Unregister a previously registered embed handler.
  2137  * Unregisters a previously-registered embed handler.
  1309  *
  2138  *
  1310  * @since 2.9.0
  2139  * @since 2.9.0
       
  2140  *
  1311  * @see WP_Embed::unregister_handler()
  2141  * @see WP_Embed::unregister_handler()
       
  2142  *
       
  2143  * @param string $id       The handler ID that should be removed.
       
  2144  * @param int    $priority Optional. The priority of the handler to be removed. Default 10.
  1312  */
  2145  */
  1313 function wp_embed_unregister_handler( $id, $priority = 10 ) {
  2146 function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1314 	global $wp_embed;
  2147 	global $wp_embed;
  1315 	$wp_embed->unregister_handler( $id, $priority );
  2148 	$wp_embed->unregister_handler( $id, $priority );
  1316 }
  2149 }
  1325  *
  2158  *
  1326  * The 'embed_defaults' filter can be used to adjust either of these values.
  2159  * The 'embed_defaults' filter can be used to adjust either of these values.
  1327  *
  2160  *
  1328  * @since 2.9.0
  2161  * @since 2.9.0
  1329  *
  2162  *
       
  2163  * @param string $url Optional. The URL that should be embedded. Default empty.
       
  2164  *
  1330  * @return array Default embed parameters.
  2165  * @return array Default embed parameters.
  1331  */
  2166  */
  1332 function wp_embed_defaults() {
  2167 function wp_embed_defaults( $url = '' ) {
  1333 	if ( ! empty( $GLOBALS['content_width'] ) )
  2168 	if ( ! empty( $GLOBALS['content_width'] ) )
  1334 		$width = (int) $GLOBALS['content_width'];
  2169 		$width = (int) $GLOBALS['content_width'];
  1335 
  2170 
  1336 	if ( empty( $width ) )
  2171 	if ( empty( $width ) )
  1337 		$width = 500;
  2172 		$width = 500;
  1338 
  2173 
  1339 	$height = min( ceil( $width * 1.5 ), 1000 );
  2174 	$height = min( ceil( $width * 1.5 ), 1000 );
  1340 
  2175 
  1341 	return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  2176 	/**
       
  2177 	 * Filter the default array of embed dimensions.
       
  2178 	 *
       
  2179 	 * @since 2.9.0
       
  2180 	 *
       
  2181 	 * @param int    $width  Width of the embed in pixels.
       
  2182 	 * @param int    $height Height of the embed in pixels.
       
  2183 	 * @param string $url    The URL that should be embedded.
       
  2184 	 */
       
  2185 	return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
  1342 }
  2186 }
  1343 
  2187 
  1344 /**
  2188 /**
  1345  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  2189  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1346  *
  2190  *
  1347  * @since 2.9.0
  2191  * @since 2.9.0
  1348  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  2192  *
  1349  *
  2193  * @see wp_constrain_dimensions()
  1350  * @param int $example_width The width of an example embed.
  2194  *
       
  2195  * @param int $example_width  The width of an example embed.
  1351  * @param int $example_height The height of an example embed.
  2196  * @param int $example_height The height of an example embed.
  1352  * @param int $max_width The maximum allowed width.
  2197  * @param int $max_width      The maximum allowed width.
  1353  * @param int $max_height The maximum allowed height.
  2198  * @param int $max_height     The maximum allowed height.
  1354  * @return array The maximum possible width and height based on the example ratio.
  2199  * @return array The maximum possible width and height based on the example ratio.
  1355  */
  2200  */
  1356 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  2201 function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1357 	$example_width  = (int) $example_width;
  2202 	$example_width  = (int) $example_width;
  1358 	$example_height = (int) $example_height;
  2203 	$example_height = (int) $example_height;
  1364 
  2209 
  1365 /**
  2210 /**
  1366  * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  2211  * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1367  *
  2212  *
  1368  * @since 2.9.0
  2213  * @since 2.9.0
       
  2214  *
  1369  * @see WP_oEmbed
  2215  * @see WP_oEmbed
  1370  *
  2216  *
  1371  * @uses _wp_oembed_get_object()
  2217  * @param string $url  The URL that should be embedded.
  1372  * @uses WP_oEmbed::get_html()
  2218  * @param array  $args Optional. Additional arguments and parameters for retrieving embed HTML.
  1373  *
  2219  *                     Default empty.
  1374  * @param string $url The URL that should be embedded.
  2220  * @return false|string False on failure or the embed HTML on success.
  1375  * @param array $args Additional arguments and parameters.
       
  1376  * @return bool|string False on failure or the embed HTML on success.
       
  1377  */
  2221  */
  1378 function wp_oembed_get( $url, $args = '' ) {
  2222 function wp_oembed_get( $url, $args = '' ) {
  1379 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  2223 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1380 	$oembed = _wp_oembed_get_object();
  2224 	$oembed = _wp_oembed_get_object();
  1381 	return $oembed->get_html( $url, $args );
  2225 	return $oembed->get_html( $url, $args );
  1383 
  2227 
  1384 /**
  2228 /**
  1385  * Adds a URL format and oEmbed provider URL pair.
  2229  * Adds a URL format and oEmbed provider URL pair.
  1386  *
  2230  *
  1387  * @since 2.9.0
  2231  * @since 2.9.0
       
  2232  *
  1388  * @see WP_oEmbed
  2233  * @see WP_oEmbed
  1389  *
  2234  *
  1390  * @uses _wp_oembed_get_object()
  2235  * @param string  $format   The format of URL that this provider can handle. You can use asterisks
  1391  *
  2236  *                          as wildcards.
  1392  * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  2237  * @param string  $provider The URL to the oEmbed provider.
  1393  * @param string $provider The URL to the oEmbed provider.
  2238  * @param boolean $regex    Optional. Whether the `$format` parameter is in a RegEx format. Default false.
  1394  * @param boolean $regex Whether the $format parameter is in a regex format.
       
  1395  */
  2239  */
  1396 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  2240 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1397 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  2241 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1398 	$oembed = _wp_oembed_get_object();
  2242 
  1399 	$oembed->providers[$format] = array( $provider, $regex );
  2243 	if ( did_action( 'plugins_loaded' ) ) {
       
  2244 		$oembed = _wp_oembed_get_object();
       
  2245 		$oembed->providers[$format] = array( $provider, $regex );
       
  2246 	} else {
       
  2247 		WP_oEmbed::_add_provider_early( $format, $provider, $regex );
       
  2248 	}
  1400 }
  2249 }
  1401 
  2250 
  1402 /**
  2251 /**
  1403  * Removes an oEmbed provider.
  2252  * Removes an oEmbed provider.
  1404  *
  2253  *
  1405  * @since 3.5.0
  2254  * @since 3.5.0
       
  2255  *
  1406  * @see WP_oEmbed
  2256  * @see WP_oEmbed
  1407  *
  2257  *
  1408  * @uses _wp_oembed_get_object()
       
  1409  *
       
  1410  * @param string $format The URL format for the oEmbed provider to remove.
  2258  * @param string $format The URL format for the oEmbed provider to remove.
       
  2259  * @return bool Was the provider removed successfully?
  1411  */
  2260  */
  1412 function wp_oembed_remove_provider( $format ) {
  2261 function wp_oembed_remove_provider( $format ) {
  1413 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  2262 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1414 
  2263 
  1415 	$oembed = _wp_oembed_get_object();
  2264 	if ( did_action( 'plugins_loaded' ) ) {
  1416 
  2265 		$oembed = _wp_oembed_get_object();
  1417 	if ( isset( $oembed->providers[ $format ] ) ) {
  2266 
  1418 		unset( $oembed->providers[ $format ] );
  2267 		if ( isset( $oembed->providers[ $format ] ) ) {
  1419 		return true;
  2268 			unset( $oembed->providers[ $format ] );
       
  2269 			return true;
       
  2270 		}
       
  2271 	} else {
       
  2272 		WP_oEmbed::_remove_provider_early( $format );
  1420 	}
  2273 	}
  1421 
  2274 
  1422 	return false;
  2275 	return false;
  1423 }
  2276 }
  1424 
  2277 
  1427  *
  2280  *
  1428  * Checks to make sure that the embeds library hasn't already been loaded. If
  2281  * Checks to make sure that the embeds library hasn't already been loaded. If
  1429  * it hasn't, then it will load the embeds library.
  2282  * it hasn't, then it will load the embeds library.
  1430  *
  2283  *
  1431  * @since 2.9.0
  2284  * @since 2.9.0
       
  2285  *
       
  2286  * @see wp_embed_register_handler()
  1432  */
  2287  */
  1433 function wp_maybe_load_embeds() {
  2288 function wp_maybe_load_embeds() {
  1434 	if ( ! apply_filters( 'load_default_embeds', true ) )
  2289 	/**
       
  2290 	 * Filter whether to load the default embed handlers.
       
  2291 	 *
       
  2292 	 * Returning a falsey value will prevent loading the default embed handlers.
       
  2293 	 *
       
  2294 	 * @since 2.9.0
       
  2295 	 *
       
  2296 	 * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
       
  2297 	 */
       
  2298 	if ( ! apply_filters( 'load_default_embeds', true ) ) {
  1435 		return;
  2299 		return;
       
  2300 	}
       
  2301 
       
  2302 	wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/embed/([^/]+)#i', 'wp_embed_handler_youtube' );
       
  2303 
  1436 	wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  2304 	wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
       
  2305 
       
  2306 	/**
       
  2307 	 * Filter the audio embed handler callback.
       
  2308 	 *
       
  2309 	 * @since 3.6.0
       
  2310 	 *
       
  2311 	 * @param callback $handler Audio embed handler callback function.
       
  2312 	 */
  1437 	wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
  2313 	wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
       
  2314 
       
  2315 	/**
       
  2316 	 * Filter the video embed handler callback.
       
  2317 	 *
       
  2318 	 * @since 3.6.0
       
  2319 	 *
       
  2320 	 * @param callback $handler Video embed handler callback function.
       
  2321 	 */
  1438 	wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  2322 	wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  1439 }
  2323 }
  1440 
  2324 
  1441 /**
  2325 /**
  1442  * The Google Video embed handler callback. Google Video does not support oEmbed.
  2326  * The Google Video embed handler callback.
       
  2327  *
       
  2328  * Google Video does not support oEmbed.
  1443  *
  2329  *
  1444  * @see WP_Embed::register_handler()
  2330  * @see WP_Embed::register_handler()
  1445  * @see WP_Embed::shortcode()
  2331  * @see WP_Embed::shortcode()
  1446  *
  2332  *
  1447  * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2333  * @param array  $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
  1448  * @param array $attr Embed attributes.
  2334  * @param array  $attr    Embed attributes.
  1449  * @param string $url The original URL that was matched by the regex.
  2335  * @param string $url     The original URL that was matched by the regex.
  1450  * @param array $rawattr The original unmodified attributes.
  2336  * @param array  $rawattr The original unmodified attributes.
  1451  * @return string The embed HTML.
  2337  * @return string The embed HTML.
  1452  */
  2338  */
  1453 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  2339 function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1454 	// If the user supplied a fixed width AND height, use it
  2340 	// If the user supplied a fixed width AND height, use it
  1455 	if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  2341 	if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1457 		$height = (int) $rawattr['height'];
  2343 		$height = (int) $rawattr['height'];
  1458 	} else {
  2344 	} else {
  1459 		list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  2345 		list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1460 	}
  2346 	}
  1461 
  2347 
       
  2348 	/**
       
  2349 	 * Filter the Google Video embed output.
       
  2350 	 *
       
  2351 	 * @since 2.9.0
       
  2352 	 *
       
  2353 	 * @param string $html    Google Video HTML embed markup.
       
  2354 	 * @param array  $matches The RegEx matches from the provided regex.
       
  2355 	 * @param array  $attr    An array of embed attributes.
       
  2356 	 * @param string $url     The original URL that was matched by the regex.
       
  2357 	 * @param array  $rawattr The original unmodified attributes.
       
  2358 	 */
  1462 	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 );
  2359 	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 );
  1463 }
  2360 }
  1464 
  2361 
  1465 /**
  2362 /**
       
  2363  * YouTube iframe embed handler callback.
       
  2364  *
       
  2365  * Catches YouTube iframe embed URLs that are not parsable by oEmbed but can be translated into a URL that is.
       
  2366  *
       
  2367  * @since 4.0.0
       
  2368  *
       
  2369  * @param array  $matches The RegEx matches from the provided regex when calling
       
  2370  *                        wp_embed_register_handler().
       
  2371  * @param array  $attr    Embed attributes.
       
  2372  * @param string $url     The original URL that was matched by the regex.
       
  2373  * @param array  $rawattr The original unmodified attributes.
       
  2374  * @return string The embed HTML.
       
  2375  */
       
  2376 function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
       
  2377 	global $wp_embed;
       
  2378 	$embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
       
  2379 
       
  2380 	/**
       
  2381 	 * Filter the YoutTube embed output.
       
  2382 	 *
       
  2383 	 * @since 4.0.0
       
  2384 	 *
       
  2385 	 * @see wp_embed_handler_youtube()
       
  2386 	 *
       
  2387 	 * @param string $embed   YouTube embed output.
       
  2388 	 * @param array  $attr    An array of embed attributes.
       
  2389 	 * @param string $url     The original URL that was matched by the regex.
       
  2390 	 * @param array  $rawattr The original unmodified attributes.
       
  2391 	 */
       
  2392 	return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
       
  2393 }
       
  2394 
       
  2395 /**
  1466  * Audio embed handler callback.
  2396  * Audio embed handler callback.
  1467  *
  2397  *
  1468  * @since 3.6.0
  2398  * @since 3.6.0
  1469  *
  2399  *
  1470  * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2400  * @param array $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
  1471  * @param array $attr Embed attributes.
  2401  * @param array $attr Embed attributes.
  1472  * @param string $url The original URL that was matched by the regex.
  2402  * @param string $url The original URL that was matched by the regex.
  1473  * @param array $rawattr The original unmodified attributes.
  2403  * @param array $rawattr The original unmodified attributes.
  1474  * @return string The embed HTML.
  2404  * @return string The embed HTML.
  1475  */
  2405  */
  1476 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  2406 function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  1477 	$audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
  2407 	$audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
       
  2408 
       
  2409 	/**
       
  2410 	 * Filter the audio embed output.
       
  2411 	 *
       
  2412 	 * @since 3.6.0
       
  2413 	 *
       
  2414 	 * @param string $audio   Audio embed output.
       
  2415 	 * @param array  $attr    An array of embed attributes.
       
  2416 	 * @param string $url     The original URL that was matched by the regex.
       
  2417 	 * @param array  $rawattr The original unmodified attributes.
       
  2418 	 */
  1478 	return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  2419 	return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  1479 }
  2420 }
  1480 
  2421 
  1481 /**
  2422 /**
  1482  * Video embed handler callback.
  2423  * Video embed handler callback.
  1483  *
  2424  *
  1484  * @since 3.6.0
  2425  * @since 3.6.0
  1485  *
  2426  *
  1486  * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2427  * @param array  $matches The RegEx matches from the provided regex when calling wp_embed_register_handler().
  1487  * @param array $attr Embed attributes.
  2428  * @param array  $attr    Embed attributes.
  1488  * @param string $url The original URL that was matched by the regex.
  2429  * @param string $url     The original URL that was matched by the regex.
  1489  * @param array $rawattr The original unmodified attributes.
  2430  * @param array  $rawattr The original unmodified attributes.
  1490  * @return string The embed HTML.
  2431  * @return string The embed HTML.
  1491  */
  2432  */
  1492 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  2433 function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  1493 	$dimensions = '';
  2434 	$dimensions = '';
  1494 	if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  2435 	if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  1495 		$dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  2436 		$dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  1496 		$dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  2437 		$dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  1497 	}
  2438 	}
  1498 	$video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
  2439 	$video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
       
  2440 
       
  2441 	/**
       
  2442 	 * Filter the video embed output.
       
  2443 	 *
       
  2444 	 * @since 3.6.0
       
  2445 	 *
       
  2446 	 * @param string $video   Video embed output.
       
  2447 	 * @param array  $attr    An array of embed attributes.
       
  2448 	 * @param string $url     The original URL that was matched by the regex.
       
  2449 	 * @param array  $rawattr The original unmodified attributes.
       
  2450 	 */
  1499 	return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  2451 	return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  1500 }
  2452 }
  1501 
  2453 
  1502 /**
  2454 /**
  1503  * Converts a shorthand byte value to an integer byte value.
  2455  * Converts a shorthand byte value to an integer byte value.
  1518 		$bytes = intval( $size ) * 1024 * 1024 * 1024;
  2470 		$bytes = intval( $size ) * 1024 * 1024 * 1024;
  1519 	return $bytes;
  2471 	return $bytes;
  1520 }
  2472 }
  1521 
  2473 
  1522 /**
  2474 /**
  1523  * Determine the maximum upload size allowed in php.ini.
  2475  * Determines the maximum upload size allowed in php.ini.
  1524  *
  2476  *
  1525  * @since 2.5.0
  2477  * @since 2.5.0
  1526  *
  2478  *
  1527  * @return int Allowed upload size.
  2479  * @return int Allowed upload size.
  1528  */
  2480  */
  1529 function wp_max_upload_size() {
  2481 function wp_max_upload_size() {
  1530 	$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  2482 	$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1531 	$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  2483 	$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1532 	$bytes   = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  2484 
  1533 	return $bytes;
  2485 	/**
       
  2486 	 * Filter the maximum upload size allowed in php.ini.
       
  2487 	 *
       
  2488 	 * @since 2.5.0
       
  2489 	 *
       
  2490 	 * @param int $size    Max upload size limit in bytes.
       
  2491 	 * @param int $u_bytes Maximum upload filesize in bytes.
       
  2492 	 * @param int $p_bytes Maximum size of POST data in bytes.
       
  2493 	 */
       
  2494 	return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1534 }
  2495 }
  1535 
  2496 
  1536 /**
  2497 /**
  1537  * Returns a WP_Image_Editor instance and loads file into it.
  2498  * Returns a WP_Image_Editor instance and loads file into it.
  1538  *
  2499  *
  1539  * @since 3.5.0
  2500  * @since 3.5.0
  1540  * @access public
  2501  *
  1541  *
  2502  * @param string $path Path to the file to load.
  1542  * @param string $path Path to file to load
  2503  * @param array  $args Optional. Additional arguments for retrieving the image editor.
  1543  * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2504  *                     Default empty array.
  1544  * @return WP_Image_Editor|WP_Error
  2505  * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
       
  2506  *                                  object otherwise.
  1545  */
  2507  */
  1546 function wp_get_image_editor( $path, $args = array() ) {
  2508 function wp_get_image_editor( $path, $args = array() ) {
  1547 	$args['path'] = $path;
  2509 	$args['path'] = $path;
  1548 
  2510 
  1549 	if ( ! isset( $args['mime_type'] ) ) {
  2511 	if ( ! isset( $args['mime_type'] ) ) {
  1572 
  2534 
  1573 /**
  2535 /**
  1574  * Tests whether there is an editor that supports a given mime type or methods.
  2536  * Tests whether there is an editor that supports a given mime type or methods.
  1575  *
  2537  *
  1576  * @since 3.5.0
  2538  * @since 3.5.0
  1577  * @access public
  2539  *
  1578  *
  2540  * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
  1579  * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2541  *                           Default empty array.
  1580  * @return boolean true if an eligible editor is found; false otherwise
  2542  * @return bool True if an eligible editor is found; false otherwise.
  1581  */
  2543  */
  1582 function wp_image_editor_supports( $args = array() ) {
  2544 function wp_image_editor_supports( $args = array() ) {
  1583 	return (bool) _wp_image_editor_choose( $args );
  2545 	return (bool) _wp_image_editor_choose( $args );
  1584 }
  2546 }
  1585 
  2547 
  1586 /**
  2548 /**
  1587  * Tests which editors are capable of supporting the request.
  2549  * Tests which editors are capable of supporting the request.
  1588  *
  2550  *
       
  2551  * @ignore
  1589  * @since 3.5.0
  2552  * @since 3.5.0
  1590  * @access private
  2553  *
  1591  *
  2554  * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
  1592  * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2555  * @return string|bool Class name for the first editor that claims to support the request. False if no
  1593  * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  2556  *                     editor claims to support the request.
  1594  */
  2557  */
  1595 function _wp_image_editor_choose( $args = array() ) {
  2558 function _wp_image_editor_choose( $args = array() ) {
  1596 	require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  2559 	require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  1597 	require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  2560 	require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  1598 	require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  2561 	require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  1599 
  2562 
  1600 	$implementations = apply_filters( 'wp_image_editors',
  2563 	/**
  1601 		array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  2564 	 * Filter the list of image editing library classes.
       
  2565 	 *
       
  2566 	 * @since 3.5.0
       
  2567 	 *
       
  2568 	 * @param array $image_editors List of available image editors. Defaults are
       
  2569 	 *                             'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
       
  2570 	 */
       
  2571 	$implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  1602 
  2572 
  1603 	foreach ( $implementations as $implementation ) {
  2573 	foreach ( $implementations as $implementation ) {
  1604 		if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  2574 		if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  1605 			continue;
  2575 			continue;
  1606 
  2576 
  1635 		return;
  2605 		return;
  1636 
  2606 
  1637 	$max_upload_size = wp_max_upload_size();
  2607 	$max_upload_size = wp_max_upload_size();
  1638 
  2608 
  1639 	$defaults = array(
  2609 	$defaults = array(
  1640 		'runtimes'            => 'html5,silverlight,flash,html4',
  2610 		'runtimes'            => 'html5,flash,silverlight,html4',
  1641 		'file_data_name'      => 'async-upload', // key passed to $_FILE.
  2611 		'file_data_name'      => 'async-upload', // key passed to $_FILE.
  1642 		'multiple_queues'     => true,
       
  1643 		'max_file_size'       => $max_upload_size . 'b',
       
  1644 		'url'                 => admin_url( 'async-upload.php', 'relative' ),
  2612 		'url'                 => admin_url( 'async-upload.php', 'relative' ),
  1645 		'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
  2613 		'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
  1646 		'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  2614 		'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1647 		'filters'             => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  2615 		'filters' => array(
  1648 		'multipart'           => true,
  2616 			'max_file_size'   => $max_upload_size . 'b',
  1649 		'urlstream_upload'    => true,
  2617 		),
  1650 	);
  2618 	);
  1651 
  2619 
  1652 	// Multi-file uploading doesn't currently work in iOS Safari,
  2620 	// Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
  1653 	// single-file allows the built-in camera to be used as source for images
  2621 	// when enabled. See #29602.
  1654 	if ( wp_is_mobile() )
  2622 	if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
       
  2623 		strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
       
  2624 
  1655 		$defaults['multi_selection'] = false;
  2625 		$defaults['multi_selection'] = false;
  1656 
  2626 	}
       
  2627 
       
  2628 	/**
       
  2629 	 * Filter the Plupload default settings.
       
  2630 	 *
       
  2631 	 * @since 3.4.0
       
  2632 	 *
       
  2633 	 * @param array $defaults Default Plupload settings array.
       
  2634 	 */
  1657 	$defaults = apply_filters( 'plupload_default_settings', $defaults );
  2635 	$defaults = apply_filters( 'plupload_default_settings', $defaults );
  1658 
  2636 
  1659 	$params = array(
  2637 	$params = array(
  1660 		'action' => 'upload-attachment',
  2638 		'action' => 'upload-attachment',
  1661 	);
  2639 	);
  1662 
  2640 
       
  2641 	/**
       
  2642 	 * Filter the Plupload default parameters.
       
  2643 	 *
       
  2644 	 * @since 3.4.0
       
  2645 	 *
       
  2646 	 * @param array $params Default Plupload parameters array.
       
  2647 	 */
  1663 	$params = apply_filters( 'plupload_default_params', $params );
  2648 	$params = apply_filters( 'plupload_default_params', $params );
  1664 	$params['_wpnonce'] = wp_create_nonce( 'media-form' );
  2649 	$params['_wpnonce'] = wp_create_nonce( 'media-form' );
  1665 	$defaults['multipart_params'] = $params;
  2650 	$defaults['multipart_params'] = $params;
  1666 
  2651 
  1667 	$settings = array(
  2652 	$settings = array(
  1671 			'supported' => _device_can_upload(),
  2656 			'supported' => _device_can_upload(),
  1672 		),
  2657 		),
  1673 		'limitExceeded' => is_multisite() && ! is_upload_space_available()
  2658 		'limitExceeded' => is_multisite() && ! is_upload_space_available()
  1674 	);
  2659 	);
  1675 
  2660 
  1676 	$script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  2661 	$script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
  1677 
  2662 
  1678 	if ( $data )
  2663 	if ( $data )
  1679 		$script = "$data\n$script";
  2664 		$script = "$data\n$script";
  1680 
  2665 
  1681 	$wp_scripts->add_data( 'wp-plupload', 'data', $script );
  2666 	$wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1682 }
  2667 }
  1683 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
       
  1684 
  2668 
  1685 /**
  2669 /**
  1686  * Prepares an attachment post object for JS, where it is expected
  2670  * Prepares an attachment post object for JS, where it is expected
  1687  * to be JSON-encoded and fit into an Attachment model.
  2671  * to be JSON-encoded and fit into an Attachment model.
  1688  *
  2672  *
  1728 		'icon'        => wp_mime_type_icon( $attachment->ID ),
  2712 		'icon'        => wp_mime_type_icon( $attachment->ID ),
  1729 		'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  2713 		'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  1730 		'nonces'      => array(
  2714 		'nonces'      => array(
  1731 			'update' => false,
  2715 			'update' => false,
  1732 			'delete' => false,
  2716 			'delete' => false,
       
  2717 			'edit'   => false
  1733 		),
  2718 		),
  1734 		'editLink'   => false,
  2719 		'editLink'   => false,
       
  2720 		'meta'       => false,
  1735 	);
  2721 	);
       
  2722 
       
  2723 	$author = new WP_User( $attachment->post_author );
       
  2724 	$response['authorName'] = $author->display_name;
       
  2725 
       
  2726 	if ( $attachment->post_parent ) {
       
  2727 		$post_parent = get_post( $attachment->post_parent );
       
  2728 	} else {
       
  2729 		$post_parent = false;
       
  2730 	}
       
  2731 
       
  2732 	if ( $post_parent ) {
       
  2733 		$parent_type = get_post_type_object( $post_parent->post_type );
       
  2734 		if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
       
  2735 			$response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
       
  2736 		}
       
  2737 		$response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
       
  2738 	}
       
  2739 
       
  2740 	$attached_file = get_attached_file( $attachment->ID );
       
  2741 	if ( file_exists( $attached_file ) ) {
       
  2742 		$bytes = filesize( $attached_file );
       
  2743 		$response['filesizeInBytes'] = $bytes;
       
  2744 		$response['filesizeHumanReadable'] = size_format( $bytes );
       
  2745 	}
  1736 
  2746 
  1737 	if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  2747 	if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  1738 		$response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  2748 		$response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
       
  2749 		$response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  1739 		$response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  2750 		$response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  1740 	}
  2751 	}
  1741 
  2752 
  1742 	if ( current_user_can( 'delete_post', $attachment->ID ) )
  2753 	if ( current_user_can( 'delete_post', $attachment->ID ) )
  1743 		$response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  2754 		$response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  1744 
  2755 
  1745 	if ( $meta && 'image' === $type ) {
  2756 	if ( $meta && 'image' === $type ) {
  1746 		$sizes = array();
  2757 		$sizes = array();
       
  2758 
  1747 		/** This filter is documented in wp-admin/includes/media.php */
  2759 		/** This filter is documented in wp-admin/includes/media.php */
  1748 		$possible_sizes = apply_filters( 'image_size_names_choose', array(
  2760 		$possible_sizes = apply_filters( 'image_size_names_choose', array(
  1749 			'thumbnail' => __('Thumbnail'),
  2761 			'thumbnail' => __('Thumbnail'),
  1750 			'medium'    => __('Medium'),
  2762 			'medium'    => __('Medium'),
  1751 			'large'     => __('Large'),
  2763 			'large'     => __('Large'),
  1756 		// Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  2768 		// Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  1757 		// First: run the image_downsize filter. If it returns something, we can use its data.
  2769 		// First: run the image_downsize filter. If it returns something, we can use its data.
  1758 		// If the filter does not return something, then image_downsize() is just an expensive
  2770 		// If the filter does not return something, then image_downsize() is just an expensive
  1759 		// way to check the image metadata, which we do second.
  2771 		// way to check the image metadata, which we do second.
  1760 		foreach ( $possible_sizes as $size => $label ) {
  2772 		foreach ( $possible_sizes as $size => $label ) {
       
  2773 
       
  2774 			/** This filter is documented in wp-includes/media.php */
  1761 			if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  2775 			if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  1762 				if ( ! $downsize[3] )
  2776 				if ( ! $downsize[3] )
  1763 					continue;
  2777 					continue;
  1764 				$sizes[ $size ] = array(
  2778 				$sizes[ $size ] = array(
  1765 					'height'      => $downsize[2],
  2779 					'height'      => $downsize[2],
  1804 	}
  2818 	}
  1805 
  2819 
  1806 	if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  2820 	if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  1807 		if ( isset( $meta['length_formatted'] ) )
  2821 		if ( isset( $meta['length_formatted'] ) )
  1808 			$response['fileLength'] = $meta['length_formatted'];
  2822 			$response['fileLength'] = $meta['length_formatted'];
       
  2823 
       
  2824 		$response['meta'] = array();
       
  2825 		foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
       
  2826 			$response['meta'][ $key ] = false;
       
  2827 
       
  2828 			if ( ! empty( $meta[ $key ] ) ) {
       
  2829 				$response['meta'][ $key ] = $meta[ $key ];
       
  2830 			}
       
  2831 		}
       
  2832 
       
  2833 		$id = get_post_thumbnail_id( $attachment->ID );
       
  2834 		if ( ! empty( $id ) ) {
       
  2835 			list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
       
  2836 			$response['image'] = compact( 'src', 'width', 'height' );
       
  2837 			list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
       
  2838 			$response['thumb'] = compact( 'src', 'width', 'height' );
       
  2839 		} else {
       
  2840 			$src = wp_mime_type_icon( $attachment->ID );
       
  2841 			$width = 48;
       
  2842 			$height = 64;
       
  2843 			$response['image'] = compact( 'src', 'width', 'height' );
       
  2844 			$response['thumb'] = compact( 'src', 'width', 'height' );
       
  2845 		}
  1809 	}
  2846 	}
  1810 
  2847 
  1811 	if ( function_exists('get_compat_media_markup') )
  2848 	if ( function_exists('get_compat_media_markup') )
  1812 		$response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  2849 		$response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  1813 
  2850 
       
  2851 	/**
       
  2852 	 * Filter the attachment data prepared for JavaScript.
       
  2853 	 *
       
  2854 	 * @since 3.5.0
       
  2855 	 *
       
  2856 	 * @param array      $response   Array of prepared attachment data.
       
  2857 	 * @param int|object $attachment Attachment ID or object.
       
  2858 	 * @param array      $meta       Array of attachment meta data.
       
  2859 	 */
  1814 	return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  2860 	return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  1815 }
  2861 }
  1816 
  2862 
  1817 /**
  2863 /**
  1818  * Enqueues all scripts, styles, settings, and templates necessary to use
  2864  * Enqueues all scripts, styles, settings, and templates necessary to use
  1819  * all media JS APIs.
  2865  * all media JS APIs.
  1820  *
  2866  *
  1821  * @since 3.5.0
  2867  * @since 3.5.0
       
  2868  *
       
  2869  * @param array $args {
       
  2870  *     Arguments for enqueuing media scripts.
       
  2871  *
       
  2872  *     @type int|WP_Post A post object or ID.
       
  2873  * }
       
  2874  * @return array List of media view settings.
  1822  */
  2875  */
  1823 function wp_enqueue_media( $args = array() ) {
  2876 function wp_enqueue_media( $args = array() ) {
  1824 
  2877 
  1825 	// Enqueue me just once per page, please.
  2878 	// Enqueue me just once per page, please.
  1826 	if ( did_action( 'wp_enqueue_media' ) )
  2879 	if ( did_action( 'wp_enqueue_media' ) )
  1827 		return;
  2880 		return;
       
  2881 
       
  2882 	global $content_width, $wpdb, $wp_locale;
  1828 
  2883 
  1829 	$defaults = array(
  2884 	$defaults = array(
  1830 		'post' => null,
  2885 		'post' => null,
  1831 	);
  2886 	);
  1832 	$args = wp_parse_args( $args, $defaults );
  2887 	$args = wp_parse_args( $args, $defaults );
  1839 		'type_url' => '',
  2894 		'type_url' => '',
  1840 		'gallery'  => '',
  2895 		'gallery'  => '',
  1841 		'library'  => '',
  2896 		'library'  => '',
  1842 	);
  2897 	);
  1843 
  2898 
       
  2899 	/** This filter is documented in wp-admin/includes/media.php */
  1844 	$tabs = apply_filters( 'media_upload_tabs', $tabs );
  2900 	$tabs = apply_filters( 'media_upload_tabs', $tabs );
  1845 	unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  2901 	unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  1846 
  2902 
  1847 	$props = array(
  2903 	$props = array(
  1848 		'link'  => get_option( 'image_default_link_type' ), // db default is 'file'
  2904 		'link'  => get_option( 'image_default_link_type' ), // db default is 'file'
  1849 		'align' => get_option( 'image_default_align' ), // empty default
  2905 		'align' => get_option( 'image_default_align' ), // empty default
  1850 		'size'  => get_option( 'image_default_size' ),  // empty default
  2906 		'size'  => get_option( 'image_default_size' ),  // empty default
  1851 	);
  2907 	);
  1852 
  2908 
       
  2909 	$exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
       
  2910 	$mimes = get_allowed_mime_types();
       
  2911 	$ext_mimes = array();
       
  2912 	foreach ( $exts as $ext ) {
       
  2913 		foreach ( $mimes as $ext_preg => $mime_match ) {
       
  2914 			if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
       
  2915 				$ext_mimes[ $ext ] = $mime_match;
       
  2916 				break;
       
  2917 			}
       
  2918 		}
       
  2919 	}
       
  2920 
       
  2921 	$has_audio = $wpdb->get_var( "
       
  2922 		SELECT ID
       
  2923 		FROM $wpdb->posts
       
  2924 		WHERE post_type = 'attachment'
       
  2925 		AND post_mime_type LIKE 'audio%'
       
  2926 		LIMIT 1
       
  2927 	" );
       
  2928 	$has_video = $wpdb->get_var( "
       
  2929 		SELECT ID
       
  2930 		FROM $wpdb->posts
       
  2931 		WHERE post_type = 'attachment'
       
  2932 		AND post_mime_type LIKE 'video%'
       
  2933 		LIMIT 1
       
  2934 	" );
       
  2935 	$months = $wpdb->get_results( $wpdb->prepare( "
       
  2936 		SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
       
  2937 		FROM $wpdb->posts
       
  2938 		WHERE post_type = %s
       
  2939 		ORDER BY post_date DESC
       
  2940 	", 'attachment' ) );
       
  2941 	foreach ( $months as $month_year ) {
       
  2942 		$month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
       
  2943 	}
       
  2944 
  1853 	$settings = array(
  2945 	$settings = array(
  1854 		'tabs'      => $tabs,
  2946 		'tabs'      => $tabs,
  1855 		'tabUrl'    => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  2947 		'tabUrl'    => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  1856 		'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  2948 		'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
       
  2949 		/** This filter is documented in wp-admin/includes/media.php */
  1857 		'captions'  => ! apply_filters( 'disable_captions', '' ),
  2950 		'captions'  => ! apply_filters( 'disable_captions', '' ),
  1858 		'nonce'     => array(
  2951 		'nonce'     => array(
  1859 			'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  2952 			'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  1860 		),
  2953 		),
  1861 		'post'    => array(
  2954 		'post'    => array(
  1862 			'id' => 0,
  2955 			'id' => 0,
  1863 		),
  2956 		),
  1864 		'defaultProps' => $props,
  2957 		'defaultProps' => $props,
  1865 		'embedExts'    => array_merge( wp_get_audio_extensions(), wp_get_video_extensions() ),
  2958 		'attachmentCounts' => array(
       
  2959 			'audio' => ( $has_audio ) ? 1 : 0,
       
  2960 			'video' => ( $has_video ) ? 1 : 0
       
  2961 		),
       
  2962 		'embedExts'    => $exts,
       
  2963 		'embedMimes'   => $ext_mimes,
       
  2964 		'contentWidth' => $content_width,
       
  2965 		'months'       => $months,
       
  2966 		'mediaTrash'   => MEDIA_TRASH ? 1 : 0
  1866 	);
  2967 	);
  1867 
  2968 
  1868 	$post = null;
  2969 	$post = null;
  1869 	if ( isset( $args['post'] ) ) {
  2970 	if ( isset( $args['post'] ) ) {
  1870 		$post = get_post( $args['post'] );
  2971 		$post = get_post( $args['post'] );
  1871 		$settings['post'] = array(
  2972 		$settings['post'] = array(
  1872 			'id' => $post->ID,
  2973 			'id' => $post->ID,
  1873 			'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  2974 			'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  1874 		);
  2975 		);
  1875 
  2976 
  1876 		if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) {
  2977 		$thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
       
  2978 		if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
       
  2979 			if ( wp_attachment_is( 'audio', $post ) ) {
       
  2980 				$thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
       
  2981 			} elseif ( wp_attachment_is( 'video', $post ) ) {
       
  2982 				$thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
       
  2983 			}
       
  2984 		}
       
  2985 
       
  2986 		if ( $thumbnail_support ) {
  1877 			$featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  2987 			$featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  1878 			$settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  2988 			$settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  1879 		}
  2989 		}
  1880 	}
  2990 	}
  1881 
  2991 
  1886 		'url'         => __( 'URL' ),
  2996 		'url'         => __( 'URL' ),
  1887 		'addMedia'    => __( 'Add Media' ),
  2997 		'addMedia'    => __( 'Add Media' ),
  1888 		'search'      => __( 'Search' ),
  2998 		'search'      => __( 'Search' ),
  1889 		'select'      => __( 'Select' ),
  2999 		'select'      => __( 'Select' ),
  1890 		'cancel'      => __( 'Cancel' ),
  3000 		'cancel'      => __( 'Cancel' ),
       
  3001 		'update'      => __( 'Update' ),
       
  3002 		'replace'     => __( 'Replace' ),
       
  3003 		'remove'      => __( 'Remove' ),
       
  3004 		'back'        => __( 'Back' ),
  1891 		/* translators: This is a would-be plural string used in the media manager.
  3005 		/* translators: This is a would-be plural string used in the media manager.
  1892 		   If there is not a word you can use in your language to avoid issues with the
  3006 		   If there is not a word you can use in your language to avoid issues with the
  1893 		   lack of plural support here, turn it into "selected: %d" then translate it.
  3007 		   lack of plural support here, turn it into "selected: %d" then translate it.
  1894 		 */
  3008 		 */
  1895 		'selected'    => __( '%d selected' ),
  3009 		'selected'    => __( '%d selected' ),
  1896 		'dragInfo'    => __( 'Drag and drop to reorder images.' ),
  3010 		'dragInfo'    => __( 'Drag and drop to reorder media files.' ),
  1897 
  3011 
  1898 		// Upload
  3012 		// Upload
  1899 		'uploadFilesTitle'  => __( 'Upload Files' ),
  3013 		'uploadFilesTitle'  => __( 'Upload Files' ),
  1900 		'uploadImagesTitle' => __( 'Upload Images' ),
  3014 		'uploadImagesTitle' => __( 'Upload Images' ),
  1901 
  3015 
  1902 		// Library
  3016 		// Library
  1903 		'mediaLibraryTitle'  => __( 'Media Library' ),
  3017 		'mediaLibraryTitle'      => __( 'Media Library' ),
  1904 		'insertMediaTitle'   => __( 'Insert Media' ),
  3018 		'insertMediaTitle'       => __( 'Insert Media' ),
  1905 		'createNewGallery'   => __( 'Create a new gallery' ),
  3019 		'createNewGallery'       => __( 'Create a new gallery' ),
  1906 		'returnToLibrary'    => __( '&#8592; Return to library' ),
  3020 		'createNewPlaylist'      => __( 'Create a new playlist' ),
  1907 		'allMediaItems'      => __( 'All media items' ),
  3021 		'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  1908 		'noItemsFound'       => __( 'No items found.' ),
  3022 		'returnToLibrary'        => __( '&#8592; Return to library' ),
  1909 		'insertIntoPost'     => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
  3023 		'allMediaItems'          => __( 'All media items' ),
  1910 		'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
  3024 		'allDates'               => __( 'All dates' ),
  1911 		'warnDelete' =>      __( "You are about to permanently delete this item.\n  'Cancel' to stop, 'OK' to delete." ),
  3025 		'noItemsFound'           => __( 'No items found.' ),
       
  3026 		'insertIntoPost'         => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
       
  3027 		'unattached'             => __( 'Unattached' ),
       
  3028 		'trash'                  => _x( 'Trash', 'noun' ),
       
  3029 		'uploadedToThisPost'     => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
       
  3030 		'warnDelete'             => __( "You are about to permanently delete this item.\n  'Cancel' to stop, 'OK' to delete." ),
       
  3031 		'warnBulkDelete'         => __( "You are about to permanently delete these items.\n  'Cancel' to stop, 'OK' to delete." ),
       
  3032 		'warnBulkTrash'          => __( "You are about to trash these items.\n  'Cancel' to stop, 'OK' to delete." ),
       
  3033 		'bulkSelect'             => __( 'Bulk Select' ),
       
  3034 		'cancelSelection'        => __( 'Cancel Selection' ),
       
  3035 		'trashSelected'          => __( 'Trash Selected' ),
       
  3036 		'untrashSelected'        => __( 'Untrash Selected' ),
       
  3037 		'deleteSelected'         => __( 'Delete Selected' ),
       
  3038 		'deletePermanently'      => __( 'Delete Permanently' ),
       
  3039 		'apply'                  => __( 'Apply' ),
       
  3040 		'filterByDate'           => __( 'Filter by date' ),
       
  3041 		'filterByType'           => __( 'Filter by type' ),
       
  3042 		'searchMediaLabel'       => __( 'Search Media' ),
       
  3043 		'noMedia'                => __( 'No media attachments found.' ),
       
  3044 
       
  3045 		// Library Details
       
  3046 		'attachmentDetails'  => __( 'Attachment Details' ),
  1912 
  3047 
  1913 		// From URL
  3048 		// From URL
  1914 		'insertFromUrlTitle' => __( 'Insert from URL' ),
  3049 		'insertFromUrlTitle' => __( 'Insert from URL' ),
  1915 
  3050 
  1916 		// Featured Images
  3051 		// Featured Images
  1924 		'insertGallery'      => __( 'Insert gallery' ),
  3059 		'insertGallery'      => __( 'Insert gallery' ),
  1925 		'updateGallery'      => __( 'Update gallery' ),
  3060 		'updateGallery'      => __( 'Update gallery' ),
  1926 		'addToGallery'       => __( 'Add to gallery' ),
  3061 		'addToGallery'       => __( 'Add to gallery' ),
  1927 		'addToGalleryTitle'  => __( 'Add to Gallery' ),
  3062 		'addToGalleryTitle'  => __( 'Add to Gallery' ),
  1928 		'reverseOrder'       => __( 'Reverse order' ),
  3063 		'reverseOrder'       => __( 'Reverse order' ),
       
  3064 
       
  3065 		// Edit Image
       
  3066 		'imageDetailsTitle'     => __( 'Image Details' ),
       
  3067 		'imageReplaceTitle'     => __( 'Replace Image' ),
       
  3068 		'imageDetailsCancel'    => __( 'Cancel Edit' ),
       
  3069 		'editImage'             => __( 'Edit Image' ),
       
  3070 
       
  3071 		// Crop Image
       
  3072 		'chooseImage' => __( 'Choose Image' ),
       
  3073 		'selectAndCrop' => __( 'Select and Crop' ),
       
  3074 		'skipCropping' => __( 'Skip Cropping' ),
       
  3075 		'cropImage' => __( 'Crop Image' ),
       
  3076 		'cropYourImage' => __( 'Crop your image' ),
       
  3077 		'cropping' => __( 'Cropping&hellip;' ),
       
  3078 		'suggestedDimensions' => __( 'Suggested image dimensions:' ),
       
  3079 		'cropError' => __( 'There has been an error cropping your image.' ),
       
  3080 
       
  3081 		// Edit Audio
       
  3082 		'audioDetailsTitle'     => __( 'Audio Details' ),
       
  3083 		'audioReplaceTitle'     => __( 'Replace Audio' ),
       
  3084 		'audioAddSourceTitle'   => __( 'Add Audio Source' ),
       
  3085 		'audioDetailsCancel'    => __( 'Cancel Edit' ),
       
  3086 
       
  3087 		// Edit Video
       
  3088 		'videoDetailsTitle'     => __( 'Video Details' ),
       
  3089 		'videoReplaceTitle'     => __( 'Replace Video' ),
       
  3090 		'videoAddSourceTitle'   => __( 'Add Video Source' ),
       
  3091 		'videoDetailsCancel'    => __( 'Cancel Edit' ),
       
  3092 		'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
       
  3093 		'videoAddTrackTitle'	=> __( 'Add Subtitles' ),
       
  3094 
       
  3095  		// Playlist
       
  3096  		'playlistDragInfo'    => __( 'Drag and drop to reorder tracks.' ),
       
  3097  		'createPlaylistTitle' => __( 'Create Audio Playlist' ),
       
  3098  		'editPlaylistTitle'   => __( 'Edit Audio Playlist' ),
       
  3099  		'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
       
  3100  		'insertPlaylist'      => __( 'Insert audio playlist' ),
       
  3101  		'updatePlaylist'      => __( 'Update audio playlist' ),
       
  3102  		'addToPlaylist'       => __( 'Add to audio playlist' ),
       
  3103  		'addToPlaylistTitle'  => __( 'Add to Audio Playlist' ),
       
  3104 
       
  3105  		// Video Playlist
       
  3106  		'videoPlaylistDragInfo'    => __( 'Drag and drop to reorder videos.' ),
       
  3107  		'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
       
  3108  		'editVideoPlaylistTitle'   => __( 'Edit Video Playlist' ),
       
  3109  		'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
       
  3110  		'insertVideoPlaylist'      => __( 'Insert video playlist' ),
       
  3111  		'updateVideoPlaylist'      => __( 'Update video playlist' ),
       
  3112  		'addToVideoPlaylist'       => __( 'Add to video playlist' ),
       
  3113  		'addToVideoPlaylistTitle'  => __( 'Add to Video Playlist' ),
  1929 	);
  3114 	);
  1930 
  3115 
       
  3116 	/**
       
  3117 	 * Filter the media view settings.
       
  3118 	 *
       
  3119 	 * @since 3.5.0
       
  3120 	 *
       
  3121 	 * @param array   $settings List of media view settings.
       
  3122 	 * @param WP_Post $post     Post object.
       
  3123 	 */
  1931 	$settings = apply_filters( 'media_view_settings', $settings, $post );
  3124 	$settings = apply_filters( 'media_view_settings', $settings, $post );
  1932 	$strings  = apply_filters( 'media_view_strings',  $strings,  $post );
  3125 
       
  3126 	/**
       
  3127 	 * Filter the media view strings.
       
  3128 	 *
       
  3129 	 * @since 3.5.0
       
  3130 	 *
       
  3131 	 * @param array   $strings List of media view strings.
       
  3132 	 * @param WP_Post $post    Post object.
       
  3133 	 */
       
  3134 	$strings = apply_filters( 'media_view_strings', $strings,  $post );
  1933 
  3135 
  1934 	$strings['settings'] = $settings;
  3136 	$strings['settings'] = $settings;
  1935 
  3137 
       
  3138 	// Ensure we enqueue media-editor first, that way media-views is
       
  3139 	// registered internally before we try to localize it. see #24724.
       
  3140 	wp_enqueue_script( 'media-editor' );
  1936 	wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  3141 	wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  1937 
  3142 
  1938 	wp_enqueue_script( 'media-editor' );
  3143 	wp_enqueue_script( 'media-audiovideo' );
  1939 	wp_enqueue_style( 'media-views' );
  3144 	wp_enqueue_style( 'media-views' );
       
  3145 	if ( is_admin() ) {
       
  3146 		wp_enqueue_script( 'mce-view' );
       
  3147 		wp_enqueue_script( 'image-edit' );
       
  3148 	}
       
  3149 	wp_enqueue_style( 'imgareaselect' );
  1940 	wp_plupload_default_settings();
  3150 	wp_plupload_default_settings();
  1941 
  3151 
  1942 	require_once ABSPATH . WPINC . '/media-template.php';
  3152 	require_once ABSPATH . WPINC . '/media-template.php';
  1943 	add_action( 'admin_footer', 'wp_print_media_templates' );
  3153 	add_action( 'admin_footer', 'wp_print_media_templates' );
  1944 	add_action( 'wp_footer', 'wp_print_media_templates' );
  3154 	add_action( 'wp_footer', 'wp_print_media_templates' );
  1945 
  3155 	add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
       
  3156 
       
  3157 	/**
       
  3158 	 * Fires at the conclusion of wp_enqueue_media().
       
  3159 	 *
       
  3160 	 * @since 3.5.0
       
  3161 	 */
  1946 	do_action( 'wp_enqueue_media' );
  3162 	do_action( 'wp_enqueue_media' );
  1947 }
  3163 }
  1948 
  3164 
  1949 /**
  3165 /**
  1950  * Retrieve media attached to the passed post
  3166  * Retrieves media attached to the passed post.
  1951  *
  3167  *
  1952  * @since 3.6.0
  3168  * @since 3.6.0
  1953  *
  3169  *
  1954  * @param string $type (Mime) type of media desired
  3170  * @param string      $type Mime type.
  1955  * @param mixed $post Post ID or object
  3171  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  1956  * @return array Found attachments
  3172  * @return array Found attachments.
  1957  */
  3173  */
  1958 function get_attached_media( $type, $post = 0 ) {
  3174 function get_attached_media( $type, $post = 0 ) {
  1959 	if ( ! $post = get_post( $post ) )
  3175 	if ( ! $post = get_post( $post ) )
  1960 		return array();
  3176 		return array();
  1961 
  3177 
  1966 		'posts_per_page' => -1,
  3182 		'posts_per_page' => -1,
  1967 		'orderby' => 'menu_order',
  3183 		'orderby' => 'menu_order',
  1968 		'order' => 'ASC',
  3184 		'order' => 'ASC',
  1969 	);
  3185 	);
  1970 
  3186 
       
  3187 	/**
       
  3188 	 * Filter arguments used to retrieve media attached to the given post.
       
  3189 	 *
       
  3190 	 * @since 3.6.0
       
  3191 	 *
       
  3192 	 * @param array  $args Post query arguments.
       
  3193 	 * @param string $type Mime type of the desired media.
       
  3194 	 * @param mixed  $post Post ID or object.
       
  3195 	 */
  1971 	$args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  3196 	$args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  1972 
  3197 
  1973 	$children = get_children( $args );
  3198 	$children = get_children( $args );
  1974 
  3199 
       
  3200 	/**
       
  3201 	 * Filter the list of media attached to the given post.
       
  3202 	 *
       
  3203 	 * @since 3.6.0
       
  3204 	 *
       
  3205 	 * @param array  $children Associative array of media attached to the given post.
       
  3206 	 * @param string $type     Mime type of the media desired.
       
  3207 	 * @param mixed  $post     Post ID or object.
       
  3208 	 */
  1975 	return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  3209 	return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  1976 }
  3210 }
  1977 
  3211 
  1978 /**
  3212 /**
  1979  * Check the content blob for an <audio>, <video> <object>, <embed>, or <iframe>
  3213  * Check the content blob for an audio, video, object, embed, or iframe tags.
  1980  *
  3214  *
  1981  * @since 3.6.0
  3215  * @since 3.6.0
  1982  *
  3216  *
  1983  * @param string $content A string which might contain media data.
  3217  * @param string $content A string which might contain media data.
  1984  * @param array $types array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'
  3218  * @param array  $types   An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
  1985  * @return array A list of found HTML media embeds
  3219  * @return array A list of found HTML media embeds.
  1986  */
  3220  */
  1987 function get_media_embedded_in_content( $content, $types = null ) {
  3221 function get_media_embedded_in_content( $content, $types = null ) {
  1988 	$html = array();
  3222 	$html = array();
  1989 	$allowed_media_types = array( 'audio', 'video', 'object', 'embed', 'iframe' );
  3223 
       
  3224 	/**
       
  3225 	 * Filter the embedded media types that are allowed to be returned from the content blob.
       
  3226 	 *
       
  3227 	 * @since 4.2.0
       
  3228 	 *
       
  3229 	 * @param array $allowed_media_types An array of allowed media types. Default media types are
       
  3230 	 *                                   'audio', 'video', 'object', 'embed', and 'iframe'.
       
  3231 	 */
       
  3232 	$allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
       
  3233 
  1990 	if ( ! empty( $types ) ) {
  3234 	if ( ! empty( $types ) ) {
  1991 		if ( ! is_array( $types ) )
  3235 		if ( ! is_array( $types ) ) {
  1992 			$types = array( $types );
  3236 			$types = array( $types );
       
  3237 		}
       
  3238 
  1993 		$allowed_media_types = array_intersect( $allowed_media_types, $types );
  3239 		$allowed_media_types = array_intersect( $allowed_media_types, $types );
  1994 	}
  3240 	}
  1995 
  3241 
  1996 	foreach ( $allowed_media_types as $tag ) {
  3242 	$tags = implode( '|', $allowed_media_types );
  1997 		if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
  3243 
  1998 			$html[] = $matches[0];
  3244 	if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
       
  3245 		foreach ( $matches[0] as $match ) {
       
  3246 			$html[] = $match;
  1999 		}
  3247 		}
  2000 	}
  3248 	}
  2001 
  3249 
  2002 	return $html;
  3250 	return $html;
  2003 }
  3251 }
  2004 
  3252 
  2005 /**
  3253 /**
  2006  * Retrieve galleries from the passed post's content
  3254  * Retrieves galleries from the passed post's content.
  2007  *
  3255  *
  2008  * @since 3.6.0
  3256  * @since 3.6.0
  2009  *
  3257  *
  2010  * @param mixed $post Optional. Post ID or object.
  3258  * @param int|WP_Post $post Post ID or object.
  2011  * @param boolean $html Whether to return HTML or data in the array
  3259  * @param bool        $html Optional. Whether to return HTML or data in the array. Default true.
  2012  * @return array A list of arrays, each containing gallery data and srcs parsed
  3260  * @return array A list of arrays, each containing gallery data and srcs parsed
  2013  *		from the expanded shortcode
  3261  *               from the expanded shortcode.
  2014  */
  3262  */
  2015 function get_post_galleries( $post, $html = true ) {
  3263 function get_post_galleries( $post, $html = true ) {
  2016 	if ( ! $post = get_post( $post ) )
  3264 	if ( ! $post = get_post( $post ) )
  2017 		return array();
  3265 		return array();
  2018 
  3266 
  2022 	$galleries = array();
  3270 	$galleries = array();
  2023 	if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  3271 	if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  2024 		foreach ( $matches as $shortcode ) {
  3272 		foreach ( $matches as $shortcode ) {
  2025 			if ( 'gallery' === $shortcode[2] ) {
  3273 			if ( 'gallery' === $shortcode[2] ) {
  2026 				$srcs = array();
  3274 				$srcs = array();
  2027 				$count = 1;
       
  2028 
  3275 
  2029 				$gallery = do_shortcode_tag( $shortcode );
  3276 				$gallery = do_shortcode_tag( $shortcode );
  2030 				if ( $html ) {
  3277 				if ( $html ) {
  2031 					$galleries[] = $gallery;
  3278 					$galleries[] = $gallery;
  2032 				} else {
  3279 				} else {
  2042 				}
  3289 				}
  2043 			}
  3290 			}
  2044 		}
  3291 		}
  2045 	}
  3292 	}
  2046 
  3293 
       
  3294 	/**
       
  3295 	 * Filter the list of all found galleries in the given post.
       
  3296 	 *
       
  3297 	 * @since 3.6.0
       
  3298 	 *
       
  3299 	 * @param array   $galleries Associative array of all found post galleries.
       
  3300 	 * @param WP_Post $post      Post object.
       
  3301 	 */
  2047 	return apply_filters( 'get_post_galleries', $galleries, $post );
  3302 	return apply_filters( 'get_post_galleries', $galleries, $post );
  2048 }
  3303 }
  2049 
  3304 
  2050 /**
  3305 /**
  2051  * Check a specified post's content for gallery and, if present, return the first
  3306  * Check a specified post's content for gallery and, if present, return the first
  2052  *
  3307  *
  2053  * @since 3.6.0
  3308  * @since 3.6.0
  2054  *
  3309  *
  2055  * @param mixed $post Optional. Post ID or object.
  3310  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  2056  * @param boolean $html Whether to return HTML or data
  3311  * @param bool        $html Optional. Whether to return HTML or data. Default is true.
  2057  * @return string|array Gallery data and srcs parsed from the expanded shortcode
  3312  * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  2058  */
  3313  */
  2059 function get_post_gallery( $post = 0, $html = true ) {
  3314 function get_post_gallery( $post = 0, $html = true ) {
  2060 	$galleries = get_post_galleries( $post, $html );
  3315 	$galleries = get_post_galleries( $post, $html );
  2061 	$gallery = reset( $galleries );
  3316 	$gallery = reset( $galleries );
  2062 
  3317 
       
  3318 	/**
       
  3319 	 * Filter the first-found post gallery.
       
  3320 	 *
       
  3321 	 * @since 3.6.0
       
  3322 	 *
       
  3323 	 * @param array       $gallery   The first-found post gallery.
       
  3324 	 * @param int|WP_Post $post      Post ID or object.
       
  3325 	 * @param array       $galleries Associative array of all found post galleries.
       
  3326 	 */
  2063 	return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  3327 	return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  2064 }
  3328 }
  2065 
  3329 
  2066 /**
  3330 /**
  2067  * Retrieve the image srcs from galleries from a post's content, if present
  3331  * Retrieve the image srcs from galleries from a post's content, if present
  2068  *
  3332  *
  2069  * @since 3.6.0
  3333  * @since 3.6.0
  2070  *
  3334  *
  2071  * @param mixed $post Optional. Post ID or object.
  3335  * @see get_post_galleries()
  2072  * @return array A list of lists, each containing image srcs parsed
  3336  *
  2073  *		from an expanded shortcode
  3337  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
       
  3338  * @return array A list of lists, each containing image srcs parsed.
       
  3339  *               from an expanded shortcode
  2074  */
  3340  */
  2075 function get_post_galleries_images( $post = 0 ) {
  3341 function get_post_galleries_images( $post = 0 ) {
  2076 	$galleries = get_post_galleries( $post, false );
  3342 	$galleries = get_post_galleries( $post, false );
  2077 	return wp_list_pluck( $galleries, 'src' );
  3343 	return wp_list_pluck( $galleries, 'src' );
  2078 }
  3344 }
  2079 
  3345 
  2080 /**
  3346 /**
  2081  * Check a post's content for galleries and return the image srcs for the first found gallery
  3347  * Checks a post's content for galleries and return the image srcs for the first found gallery
  2082  *
  3348  *
  2083  * @since 3.6.0
  3349  * @since 3.6.0
  2084  *
  3350  *
  2085  * @param mixed $post Optional. Post ID or object.
  3351  * @see get_post_gallery()
  2086  * @return array A list of a gallery's image srcs in order
  3352  *
       
  3353  * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
       
  3354  * @return array A list of a gallery's image srcs in order.
  2087  */
  3355  */
  2088 function get_post_gallery_images( $post = 0 ) {
  3356 function get_post_gallery_images( $post = 0 ) {
  2089 	$gallery = get_post_gallery( $post, false );
  3357 	$gallery = get_post_gallery( $post, false );
  2090 	return empty( $gallery['src'] ) ? array() : $gallery['src'];
  3358 	return empty( $gallery['src'] ) ? array() : $gallery['src'];
  2091 }
  3359 }
       
  3360 
       
  3361 /**
       
  3362  * Maybe attempts to generate attachment metadata, if missing.
       
  3363  *
       
  3364  * @since 3.9.0
       
  3365  *
       
  3366  * @param WP_Post $attachment Attachment object.
       
  3367  */
       
  3368 function wp_maybe_generate_attachment_metadata( $attachment ) {
       
  3369 	if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
       
  3370 		return;
       
  3371 	}
       
  3372 
       
  3373 	$file = get_attached_file( $attachment_id );
       
  3374 	$meta = wp_get_attachment_metadata( $attachment_id );
       
  3375 	if ( empty( $meta ) && file_exists( $file ) ) {
       
  3376 		$_meta = get_post_meta( $attachment_id );
       
  3377 		$regeneration_lock = 'wp_generating_att_' . $attachment_id;
       
  3378 		if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
       
  3379 			set_transient( $regeneration_lock, $file );
       
  3380 			wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
       
  3381 			delete_transient( $regeneration_lock );
       
  3382 		}
       
  3383 	}
       
  3384 }
       
  3385 
       
  3386 /**
       
  3387  * Tries to convert an attachment URL into a post ID.
       
  3388  *
       
  3389  * @since 4.0.0
       
  3390  *
       
  3391  * @global wpdb $wpdb WordPress database abstraction object.
       
  3392  *
       
  3393  * @param string $url The URL to resolve.
       
  3394  * @return int The found post ID, or 0 on failure.
       
  3395  */
       
  3396 function attachment_url_to_postid( $url ) {
       
  3397 	global $wpdb;
       
  3398 
       
  3399 	$dir = wp_upload_dir();
       
  3400 	$path = $url;
       
  3401 
       
  3402 	if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
       
  3403 		$path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
       
  3404 	}
       
  3405 
       
  3406 	$sql = $wpdb->prepare(
       
  3407 		"SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
       
  3408 		$path
       
  3409 	);
       
  3410 	$post_id = $wpdb->get_var( $sql );
       
  3411 
       
  3412 	/**
       
  3413 	 * Filter an attachment id found by URL.
       
  3414 	 *
       
  3415 	 * @since 4.2.0
       
  3416 	 *
       
  3417 	 * @param int|null $post_id The post_id (if any) found by the function.
       
  3418 	 * @param string   $url     The URL being looked up.
       
  3419 	 */
       
  3420 	$post_id = apply_filters( 'attachment_url_to_postid', $post_id, $url );
       
  3421 
       
  3422 	return (int) $post_id;
       
  3423 }
       
  3424 
       
  3425 /**
       
  3426  * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
       
  3427  *
       
  3428  * @since 4.0.0
       
  3429  *
       
  3430  * @global $wp_version
       
  3431  *
       
  3432  * @return array The relevant CSS file URLs.
       
  3433  */
       
  3434 function wpview_media_sandbox_styles() {
       
  3435  	$version = 'ver=' . $GLOBALS['wp_version'];
       
  3436  	$mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
       
  3437  	$wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
       
  3438 
       
  3439 	return array( $mediaelement, $wpmediaelement );
       
  3440 }