web/wp-includes/media.php
changeset 204 09a1c134465b
parent 194 32102edaa81b
equal deleted inserted replaced
203:f507feede89a 204:09a1c134465b
     1 <?php
     1 <?php
     2 /**
     2 /**
     3  * WordPress API for media display.
     3  * WordPress API for media display.
     4  *
     4  *
     5  * @package WordPress
     5  * @package WordPress
       
     6  * @subpackage Media
     6  */
     7  */
     7 
     8 
     8 /**
     9 /**
     9  * Scale down the default size of an image.
    10  * Scale down the default size of an image.
    10  *
    11  *
    27  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
    28  * @uses wp_constrain_dimensions() This function passes the widths and the heights.
    28  *
    29  *
    29  * @param int $width Width of the image
    30  * @param int $width Width of the image
    30  * @param int $height Height of the image
    31  * @param int $height Height of the image
    31  * @param string|array $size Size of what the result image should be.
    32  * @param string|array $size Size of what the result image should be.
       
    33  * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
    32  * @return array Width and height of what the result image should resize to.
    34  * @return array Width and height of what the result image should resize to.
    33  */
    35  */
    34 function image_constrain_size_for_editor($width, $height, $size = 'medium') {
    36 function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
    35 	global $content_width, $_wp_additional_image_sizes;
    37 	global $content_width, $_wp_additional_image_sizes;
       
    38 
       
    39 	if ( ! $context )
       
    40 		$context = is_admin() ? 'edit' : 'display';
    36 
    41 
    37 	if ( is_array($size) ) {
    42 	if ( is_array($size) ) {
    38 		$max_width = $size[0];
    43 		$max_width = $size[0];
    39 		$max_height = $size[1];
    44 		$max_height = $size[1];
    40 	}
    45 	}
    62 		if ( intval($content_width) > 0 )
    67 		if ( intval($content_width) > 0 )
    63 			$max_width = min( intval($content_width), $max_width );
    68 			$max_width = min( intval($content_width), $max_width );
    64 	} elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
    69 	} elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
    65 		$max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
    70 		$max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
    66 		$max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
    71 		$max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
    67 		if ( intval($content_width) > 0 && is_admin() ) // Only in admin. Assume that theme authors know what they're doing.
    72 		if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
    68 			$max_width = min( intval($content_width), $max_width );
    73 			$max_width = min( intval($content_width), $max_width );
    69 	}
    74 	}
    70 	// $size == 'full' has no constraint
    75 	// $size == 'full' has no constraint
    71 	else {
    76 	else {
    72 		$max_width = $width;
    77 		$max_width = $width;
    73 		$max_height = $height;
    78 		$max_height = $height;
    74 	}
    79 	}
    75 
    80 
    76 	list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size );
    81 	list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
    77 
    82 
    78 	return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
    83 	return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
    79 }
    84 }
    80 
    85 
    81 /**
    86 /**
   223 function get_image_tag($id, $alt, $title, $align, $size='medium') {
   228 function get_image_tag($id, $alt, $title, $align, $size='medium') {
   224 
   229 
   225 	list( $img_src, $width, $height ) = image_downsize($id, $size);
   230 	list( $img_src, $width, $height ) = image_downsize($id, $size);
   226 	$hwstring = image_hwstring($width, $height);
   231 	$hwstring = image_hwstring($width, $height);
   227 
   232 
       
   233 	$title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
       
   234 
   228 	$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
   235 	$class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
   229 	$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
   236 	$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
   230 
   237 
   231 	$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />';
   238 	$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
   232 
   239 
   233 	$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
   240 	$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
   234 
   241 
   235 	return $html;
   242 	return $html;
   236 }
       
   237 
       
   238 /**
       
   239  * Load an image from a string, if PHP supports it.
       
   240  *
       
   241  * @since 2.1.0
       
   242  *
       
   243  * @param string $file Filename of the image to load.
       
   244  * @return resource The resulting image resource on success, Error string on failure.
       
   245  */
       
   246 function wp_load_image( $file ) {
       
   247 	if ( is_numeric( $file ) )
       
   248 		$file = get_attached_file( $file );
       
   249 
       
   250 	if ( ! file_exists( $file ) )
       
   251 		return sprintf(__('File &#8220;%s&#8221; doesn&#8217;t exist?'), $file);
       
   252 
       
   253 	if ( ! function_exists('imagecreatefromstring') )
       
   254 		return __('The GD image library is not installed.');
       
   255 
       
   256 	// Set artificially high because GD uses uncompressed images in memory
       
   257 	@ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
       
   258 	$image = imagecreatefromstring( file_get_contents( $file ) );
       
   259 
       
   260 	if ( !is_resource( $image ) )
       
   261 		return sprintf(__('File &#8220;%s&#8221; is not an image.'), $file);
       
   262 
       
   263 	return $image;
       
   264 }
   243 }
   265 
   244 
   266 /**
   245 /**
   267  * Calculates the new dimensions for a downsampled image.
   246  * Calculates the new dimensions for a downsampled image.
   268  *
   247  *
   318 
   297 
   319 	return array( $w, $h );
   298 	return array( $w, $h );
   320 }
   299 }
   321 
   300 
   322 /**
   301 /**
   323  * Retrieve calculated resized dimensions for use in imagecopyresampled().
   302  * Retrieve calculated resized dimensions for use in WP_Image_Editor.
   324  *
   303  *
   325  * Calculate dimensions and coordinates for a resized image that fits within a
   304  * Calculate dimensions and coordinates for a resized image that fits within a
   326  * specified width and height. If $crop is true, the largest matching central
   305  * specified width and height. If $crop is true, the largest matching central
   327  * portion of the image will be cropped out and resized to the required size.
   306  * portion of the image will be cropped out and resized to the required size.
   328  *
   307  *
   391 	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
   370 	return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
   392 
   371 
   393 }
   372 }
   394 
   373 
   395 /**
   374 /**
   396  * Scale down an image to fit a particular size and save a new copy of the image.
       
   397  *
       
   398  * The PNG transparency will be preserved using the function, as well as the
       
   399  * image type. If the file going in is PNG, then the resized image is going to
       
   400  * be PNG. The only supported image types are PNG, GIF, and JPEG.
       
   401  *
       
   402  * Some functionality requires API to exist, so some PHP version may lose out
       
   403  * support. This is not the fault of WordPress (where functionality is
       
   404  * downgraded, not actual defects), but of your PHP version.
       
   405  *
       
   406  * @since 2.5.0
       
   407  *
       
   408  * @param string $file Image file path.
       
   409  * @param int $max_w Maximum width to resize to.
       
   410  * @param int $max_h Maximum height to resize to.
       
   411  * @param bool $crop Optional. Whether to crop image or resize.
       
   412  * @param string $suffix Optional. File suffix.
       
   413  * @param string $dest_path Optional. New image file path.
       
   414  * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
       
   415  * @return mixed WP_Error on failure. String with new destination path.
       
   416  */
       
   417 function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
       
   418 
       
   419 	$image = wp_load_image( $file );
       
   420 	if ( !is_resource( $image ) )
       
   421 		return new WP_Error( 'error_loading_image', $image, $file );
       
   422 
       
   423 	$size = @getimagesize( $file );
       
   424 	if ( !$size )
       
   425 		return new WP_Error('invalid_image', __('Could not read image size'), $file);
       
   426 	list($orig_w, $orig_h, $orig_type) = $size;
       
   427 
       
   428 	$dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
       
   429 	if ( !$dims )
       
   430 		return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
       
   431 	list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
       
   432 
       
   433 	$newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
       
   434 
       
   435 	imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
       
   436 
       
   437 	// convert from full colors to index colors, like original PNG.
       
   438 	if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
       
   439 		imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
       
   440 
       
   441 	// we don't need the original in memory anymore
       
   442 	imagedestroy( $image );
       
   443 
       
   444 	// $suffix will be appended to the destination filename, just before the extension
       
   445 	if ( !$suffix )
       
   446 		$suffix = "{$dst_w}x{$dst_h}";
       
   447 
       
   448 	$info = pathinfo($file);
       
   449 	$dir = $info['dirname'];
       
   450 	$ext = $info['extension'];
       
   451 	$name = wp_basename($file, ".$ext");
       
   452 
       
   453 	if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
       
   454 		$dir = $_dest_path;
       
   455 	$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
       
   456 
       
   457 	if ( IMAGETYPE_GIF == $orig_type ) {
       
   458 		if ( !imagegif( $newimage, $destfilename ) )
       
   459 			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
       
   460 	} elseif ( IMAGETYPE_PNG == $orig_type ) {
       
   461 		if ( !imagepng( $newimage, $destfilename ) )
       
   462 			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
       
   463 	} else {
       
   464 		// all other formats are converted to jpg
       
   465 		if ( 'jpg' != $ext && 'jpeg' != $ext )
       
   466 			$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
       
   467 		if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
       
   468 			return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
       
   469 	}
       
   470 
       
   471 	imagedestroy( $newimage );
       
   472 
       
   473 	// Set correct file permissions
       
   474 	$stat = stat( dirname( $destfilename ));
       
   475 	$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
       
   476 	@ chmod( $destfilename, $perms );
       
   477 
       
   478 	return $destfilename;
       
   479 }
       
   480 
       
   481 /**
       
   482  * Resize an image to make a thumbnail or intermediate size.
   375  * Resize an image to make a thumbnail or intermediate size.
   483  *
   376  *
   484  * The returned array has the file size, the image width, and image height. The
   377  * The returned array has the file size, the image width, and image height. The
   485  * filter 'image_make_intermediate_size' can be used to hook in and change the
   378  * filter 'image_make_intermediate_size' can be used to hook in and change the
   486  * values of the returned array. The only parameter is the resized file path.
   379  * values of the returned array. The only parameter is the resized file path.
   491  * @param int $width Image width.
   384  * @param int $width Image width.
   492  * @param int $height Image height.
   385  * @param int $height Image height.
   493  * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
   386  * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
   494  * @return bool|array False, if no image was created. Metadata array on success.
   387  * @return bool|array False, if no image was created. Metadata array on success.
   495  */
   388  */
   496 function image_make_intermediate_size($file, $width, $height, $crop=false) {
   389 function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
   497 	if ( $width || $height ) {
   390 	if ( $width || $height ) {
   498 		$resized_file = image_resize($file, $width, $height, $crop);
   391 		$editor = wp_get_image_editor( $file );
   499 		if ( !is_wp_error($resized_file) && $resized_file && $info = getimagesize($resized_file) ) {
   392 
   500 			$resized_file = apply_filters('image_make_intermediate_size', $resized_file);
   393 		if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
   501 			return array(
   394 			return false;
   502 				'file' => wp_basename( $resized_file ),
   395 
   503 				'width' => $info[0],
   396 		$resized_file = $editor->save();
   504 				'height' => $info[1],
   397 
   505 			);
   398 		if ( ! is_wp_error( $resized_file ) && $resized_file ) {
       
   399 			unset( $resized_file['path'] );
       
   400 			return $resized_file;
   506 		}
   401 		}
   507 	}
   402 	}
   508 	return false;
   403 	return false;
   509 }
   404 }
   510 
   405 
   653 	if ( $image ) {
   548 	if ( $image ) {
   654 		list($src, $width, $height) = $image;
   549 		list($src, $width, $height) = $image;
   655 		$hwstring = image_hwstring($width, $height);
   550 		$hwstring = image_hwstring($width, $height);
   656 		if ( is_array($size) )
   551 		if ( is_array($size) )
   657 			$size = join('x', $size);
   552 			$size = join('x', $size);
   658 		$attachment =& get_post($attachment_id);
   553 		$attachment = get_post($attachment_id);
   659 		$default_attr = array(
   554 		$default_attr = array(
   660 			'src'	=> $src,
   555 			'src'	=> $src,
   661 			'class'	=> "attachment-$size",
   556 			'class'	=> "attachment-$size",
   662 			'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
   557 			'alt'	=> trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
   663 			'title'	=> trim(strip_tags( $attachment->post_title )),
       
   664 		);
   558 		);
   665 		if ( empty($default_attr['alt']) )
   559 		if ( empty($default_attr['alt']) )
   666 			$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
   560 			$default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
   667 		if ( empty($default_attr['alt']) )
   561 		if ( empty($default_attr['alt']) )
   668 			$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
   562 			$default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
   773  *
   667  *
   774  * @param array $attr Attributes of the shortcode.
   668  * @param array $attr Attributes of the shortcode.
   775  * @return string HTML content to display gallery.
   669  * @return string HTML content to display gallery.
   776  */
   670  */
   777 function gallery_shortcode($attr) {
   671 function gallery_shortcode($attr) {
   778 	global $post;
   672 	$post = get_post();
   779 
   673 
   780 	static $instance = 0;
   674 	static $instance = 0;
   781 	$instance++;
   675 	$instance++;
       
   676 
       
   677 	if ( ! empty( $attr['ids'] ) ) {
       
   678 		// 'ids' is explicitly ordered, unless you specify otherwise.
       
   679 		if ( empty( $attr['orderby'] ) )
       
   680 			$attr['orderby'] = 'post__in';
       
   681 		$attr['include'] = $attr['ids'];
       
   682 	}
   782 
   683 
   783 	// Allow plugins/themes to override the default gallery template.
   684 	// Allow plugins/themes to override the default gallery template.
   784 	$output = apply_filters('post_gallery', '', $attr);
   685 	$output = apply_filters('post_gallery', '', $attr);
   785 	if ( $output != '' )
   686 	if ( $output != '' )
   786 		return $output;
   687 		return $output;
   808 	$id = intval($id);
   709 	$id = intval($id);
   809 	if ( 'RAND' == $order )
   710 	if ( 'RAND' == $order )
   810 		$orderby = 'none';
   711 		$orderby = 'none';
   811 
   712 
   812 	if ( !empty($include) ) {
   713 	if ( !empty($include) ) {
   813 		$include = preg_replace( '/[^0-9,]+/', '', $include );
       
   814 		$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   714 		$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   815 
   715 
   816 		$attachments = array();
   716 		$attachments = array();
   817 		foreach ( $_attachments as $key => $val ) {
   717 		foreach ( $_attachments as $key => $val ) {
   818 			$attachments[$val->ID] = $_attachments[$key];
   718 			$attachments[$val->ID] = $_attachments[$key];
   819 		}
   719 		}
   820 	} elseif ( !empty($exclude) ) {
   720 	} elseif ( !empty($exclude) ) {
   821 		$exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
       
   822 		$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   721 		$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   823 	} else {
   722 	} else {
   824 		$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   723 		$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
   825 	}
   724 	}
   826 
   725 
   926  * @since 2.5.0
   825  * @since 2.5.0
   927  *
   826  *
   928  * @param bool $prev Optional. Default is true to display previous link, false for next.
   827  * @param bool $prev Optional. Default is true to display previous link, false for next.
   929  */
   828  */
   930 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
   829 function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
   931 	global $post;
   830 	$post = get_post();
   932 	$post = get_post($post);
   831 	$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' ) ) );
   933 	$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') ));
       
   934 
   832 
   935 	foreach ( $attachments as $k => $attachment )
   833 	foreach ( $attachments as $k => $attachment )
   936 		if ( $attachment->ID == $post->ID )
   834 		if ( $attachment->ID == $post->ID )
   937 			break;
   835 			break;
   938 
   836 
   939 	$k = $prev ? $k - 1 : $k + 1;
   837 	$k = $prev ? $k - 1 : $k + 1;
   940 
   838 
   941 	if ( isset($attachments[$k]) )
   839 	$output = $attachment_id = null;
   942 		echo wp_get_attachment_link($attachments[$k]->ID, $size, true, false, $text);
   840 	if ( isset( $attachments[ $k ] ) ) {
       
   841 		$attachment_id = $attachments[ $k ]->ID;
       
   842 		$output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
       
   843 	}
       
   844 
       
   845 	$adjacent = $prev ? 'previous' : 'next';
       
   846 	echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
   943 }
   847 }
   944 
   848 
   945 /**
   849 /**
   946  * Retrieve taxonomies attached to the attachment.
   850  * Retrieve taxonomies attached to the attachment.
   947  *
   851  *
   980 
   884 
   981 	return array_unique($taxonomies);
   885 	return array_unique($taxonomies);
   982 }
   886 }
   983 
   887 
   984 /**
   888 /**
   985  * Check if the installed version of GD supports particular image type
   889  * Return all of the taxonomy names that are registered for attachments.
   986  *
   890  *
   987  * @since 2.9.0
   891  * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
   988  *
   892  *
   989  * @param string $mime_type
   893  * @since 3.5.0
   990  * @return bool
   894  * @see get_attachment_taxonomies()
   991  */
   895  * @uses get_taxonomies()
   992 function gd_edit_image_support($mime_type) {
   896  *
   993 	if ( function_exists('imagetypes') ) {
   897  * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
   994 		switch( $mime_type ) {
   898  * @return array The names of all taxonomy of $object_type.
   995 			case 'image/jpeg':
   899  */
   996 				return (imagetypes() & IMG_JPG) != 0;
   900 function get_taxonomies_for_attachments( $output = 'names' ) {
   997 			case 'image/png':
   901 	$taxonomies = array();
   998 				return (imagetypes() & IMG_PNG) != 0;
   902 	foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
   999 			case 'image/gif':
   903 		foreach ( $taxonomy->object_type as $object_type ) {
  1000 				return (imagetypes() & IMG_GIF) != 0;
   904 			if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
       
   905 				if ( 'names' == $output )
       
   906 					$taxonomies[] = $taxonomy->name;
       
   907 				else
       
   908 					$taxonomies[ $taxonomy->name ] = $taxonomy;
       
   909 				break;
       
   910 			}
  1001 		}
   911 		}
  1002 	} else {
   912 	}
  1003 		switch( $mime_type ) {
   913 
  1004 			case 'image/jpeg':
   914 	return $taxonomies;
  1005 				return function_exists('imagecreatefromjpeg');
       
  1006 			case 'image/png':
       
  1007 				return function_exists('imagecreatefrompng');
       
  1008 			case 'image/gif':
       
  1009 				return function_exists('imagecreatefromgif');
       
  1010 		}
       
  1011 	}
       
  1012 	return false;
       
  1013 }
   915 }
  1014 
   916 
  1015 /**
   917 /**
  1016  * Create new GD image resource with transparency support
   918  * Create new GD image resource with transparency support
       
   919  * @TODO: Deprecate if possible.
  1017  *
   920  *
  1018  * @since 2.9.0
   921  * @since 2.9.0
  1019  *
   922  *
  1020  * @param int $width Image width
   923  * @param int $width Image width
  1021  * @param int $height Image height
   924  * @param int $height Image height
  1029 	}
   932 	}
  1030 	return $img;
   933 	return $img;
  1031 }
   934 }
  1032 
   935 
  1033 /**
   936 /**
  1034  * API for easily embedding rich media such as videos and images into content.
       
  1035  *
       
  1036  * @package WordPress
       
  1037  * @subpackage Embed
       
  1038  * @since 2.9.0
       
  1039  */
       
  1040 class WP_Embed {
       
  1041 	var $handlers = array();
       
  1042 	var $post_ID;
       
  1043 	var $usecache = true;
       
  1044 	var $linkifunknown = true;
       
  1045 
       
  1046 	/**
       
  1047 	 * Constructor
       
  1048 	 */
       
  1049 	function __construct() {
       
  1050 		// Hack to get the [embed] shortcode to run before wpautop()
       
  1051 		add_filter( 'the_content', array(&$this, 'run_shortcode'), 8 );
       
  1052 
       
  1053 		// Shortcode placeholder for strip_shortcodes()
       
  1054 		add_shortcode( 'embed', '__return_false' );
       
  1055 
       
  1056 		// Attempts to embed all URLs in a post
       
  1057 		if ( get_option('embed_autourls') )
       
  1058 			add_filter( 'the_content', array(&$this, 'autoembed'), 8 );
       
  1059 
       
  1060 		// After a post is saved, invalidate the oEmbed cache
       
  1061 		add_action( 'save_post', array(&$this, 'delete_oembed_caches') );
       
  1062 
       
  1063 		// After a post is saved, cache oEmbed items via AJAX
       
  1064 		add_action( 'edit_form_advanced', array(&$this, 'maybe_run_ajax_cache') );
       
  1065 	}
       
  1066 
       
  1067 	/**
       
  1068 	 * Process the [embed] shortcode.
       
  1069 	 *
       
  1070 	 * Since the [embed] shortcode needs to be run earlier than other shortcodes,
       
  1071 	 * this function removes all existing shortcodes, registers the [embed] shortcode,
       
  1072 	 * calls {@link do_shortcode()}, and then re-registers the old shortcodes.
       
  1073 	 *
       
  1074 	 * @uses $shortcode_tags
       
  1075 	 * @uses remove_all_shortcodes()
       
  1076 	 * @uses add_shortcode()
       
  1077 	 * @uses do_shortcode()
       
  1078 	 *
       
  1079 	 * @param string $content Content to parse
       
  1080 	 * @return string Content with shortcode parsed
       
  1081 	 */
       
  1082 	function run_shortcode( $content ) {
       
  1083 		global $shortcode_tags;
       
  1084 
       
  1085 		// Back up current registered shortcodes and clear them all out
       
  1086 		$orig_shortcode_tags = $shortcode_tags;
       
  1087 		remove_all_shortcodes();
       
  1088 
       
  1089 		add_shortcode( 'embed', array(&$this, 'shortcode') );
       
  1090 
       
  1091 		// Do the shortcode (only the [embed] one is registered)
       
  1092 		$content = do_shortcode( $content );
       
  1093 
       
  1094 		// Put the original shortcodes back
       
  1095 		$shortcode_tags = $orig_shortcode_tags;
       
  1096 
       
  1097 		return $content;
       
  1098 	}
       
  1099 
       
  1100 	/**
       
  1101 	 * If a post/page was saved, then output JavaScript to make
       
  1102 	 * an AJAX request that will call WP_Embed::cache_oembed().
       
  1103 	 */
       
  1104 	function maybe_run_ajax_cache() {
       
  1105 		global $post_ID;
       
  1106 
       
  1107 		if ( empty($post_ID) || empty($_GET['message']) || 1 != $_GET['message'] )
       
  1108 			return;
       
  1109 
       
  1110 ?>
       
  1111 <script type="text/javascript">
       
  1112 /* <![CDATA[ */
       
  1113 	jQuery(document).ready(function($){
       
  1114 		$.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post_ID, 'relative' ); ?>");
       
  1115 	});
       
  1116 /* ]]> */
       
  1117 </script>
       
  1118 <?php
       
  1119 	}
       
  1120 
       
  1121 	/**
       
  1122 	 * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead.
       
  1123 	 * This function should probably also only be used for sites that do not support oEmbed.
       
  1124 	 *
       
  1125 	 * @param string $id An internal ID/name for the handler. Needs to be unique.
       
  1126 	 * @param string $regex The regex that will be used to see if this handler should be used for a URL.
       
  1127 	 * @param callback $callback The callback function that will be called if the regex is matched.
       
  1128 	 * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
       
  1129 	 */
       
  1130 	function register_handler( $id, $regex, $callback, $priority = 10 ) {
       
  1131 		$this->handlers[$priority][$id] = array(
       
  1132 			'regex'    => $regex,
       
  1133 			'callback' => $callback,
       
  1134 		);
       
  1135 	}
       
  1136 
       
  1137 	/**
       
  1138 	 * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead.
       
  1139 	 *
       
  1140 	 * @param string $id The handler ID that should be removed.
       
  1141 	 * @param int $priority Optional. The priority of the handler to be removed (default: 10).
       
  1142 	 */
       
  1143 	function unregister_handler( $id, $priority = 10 ) {
       
  1144 		if ( isset($this->handlers[$priority][$id]) )
       
  1145 			unset($this->handlers[$priority][$id]);
       
  1146 	}
       
  1147 
       
  1148 	/**
       
  1149 	 * The {@link do_shortcode()} callback function.
       
  1150 	 *
       
  1151 	 * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers.
       
  1152 	 * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class.
       
  1153 	 *
       
  1154 	 * @uses wp_oembed_get()
       
  1155 	 * @uses wp_parse_args()
       
  1156 	 * @uses wp_embed_defaults()
       
  1157 	 * @uses WP_Embed::maybe_make_link()
       
  1158 	 * @uses get_option()
       
  1159 	 * @uses current_user_can()
       
  1160 	 * @uses wp_cache_get()
       
  1161 	 * @uses wp_cache_set()
       
  1162 	 * @uses get_post_meta()
       
  1163 	 * @uses update_post_meta()
       
  1164 	 *
       
  1165 	 * @param array $attr Shortcode attributes.
       
  1166 	 * @param string $url The URL attempting to be embedded.
       
  1167 	 * @return string The embed HTML on success, otherwise the original URL.
       
  1168 	 */
       
  1169 	function shortcode( $attr, $url = '' ) {
       
  1170 		global $post;
       
  1171 
       
  1172 		if ( empty($url) )
       
  1173 			return '';
       
  1174 
       
  1175 		$rawattr = $attr;
       
  1176 		$attr = wp_parse_args( $attr, wp_embed_defaults() );
       
  1177 
       
  1178 		// kses converts & into &amp; and we need to undo this
       
  1179 		// See http://core.trac.wordpress.org/ticket/11311
       
  1180 		$url = str_replace( '&amp;', '&', $url );
       
  1181 
       
  1182 		// Look for known internal handlers
       
  1183 		ksort( $this->handlers );
       
  1184 		foreach ( $this->handlers as $priority => $handlers ) {
       
  1185 			foreach ( $handlers as $id => $handler ) {
       
  1186 				if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
       
  1187 					if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
       
  1188 						return apply_filters( 'embed_handler_html', $return, $url, $attr );
       
  1189 				}
       
  1190 			}
       
  1191 		}
       
  1192 
       
  1193 		$post_ID = ( !empty($post->ID) ) ? $post->ID : null;
       
  1194 		if ( !empty($this->post_ID) ) // Potentially set by WP_Embed::cache_oembed()
       
  1195 			$post_ID = $this->post_ID;
       
  1196 
       
  1197 		// Unknown URL format. Let oEmbed have a go.
       
  1198 		if ( $post_ID ) {
       
  1199 
       
  1200 			// Check for a cached result (stored in the post meta)
       
  1201 			$cachekey = '_oembed_' . md5( $url . serialize( $attr ) );
       
  1202 			if ( $this->usecache ) {
       
  1203 				$cache = get_post_meta( $post_ID, $cachekey, true );
       
  1204 
       
  1205 				// Failures are cached
       
  1206 				if ( '{{unknown}}' === $cache )
       
  1207 					return $this->maybe_make_link( $url );
       
  1208 
       
  1209 				if ( !empty($cache) )
       
  1210 					return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
       
  1211 			}
       
  1212 
       
  1213 			// Use oEmbed to get the HTML
       
  1214 			$attr['discover'] = ( apply_filters('embed_oembed_discover', false) && author_can( $post_ID, 'unfiltered_html' ) );
       
  1215 			$html = wp_oembed_get( $url, $attr );
       
  1216 
       
  1217 			// Cache the result
       
  1218 			$cache = ( $html ) ? $html : '{{unknown}}';
       
  1219 			update_post_meta( $post_ID, $cachekey, $cache );
       
  1220 
       
  1221 			// If there was a result, return it
       
  1222 			if ( $html )
       
  1223 				return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
       
  1224 		}
       
  1225 
       
  1226 		// Still unknown
       
  1227 		return $this->maybe_make_link( $url );
       
  1228 	}
       
  1229 
       
  1230 	/**
       
  1231 	 * Delete all oEmbed caches.
       
  1232 	 *
       
  1233 	 * @param int $post_ID Post ID to delete the caches for.
       
  1234 	 */
       
  1235 	function delete_oembed_caches( $post_ID ) {
       
  1236 		$post_metas = get_post_custom_keys( $post_ID );
       
  1237 		if ( empty($post_metas) )
       
  1238 			return;
       
  1239 
       
  1240 		foreach( $post_metas as $post_meta_key ) {
       
  1241 			if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
       
  1242 				delete_post_meta( $post_ID, $post_meta_key );
       
  1243 		}
       
  1244 	}
       
  1245 
       
  1246 	/**
       
  1247 	 * Triggers a caching of all oEmbed results.
       
  1248 	 *
       
  1249 	 * @param int $post_ID Post ID to do the caching for.
       
  1250 	 */
       
  1251 	function cache_oembed( $post_ID ) {
       
  1252 		$post = get_post( $post_ID );
       
  1253 
       
  1254 		if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', array( 'post', 'page' ) ) ) )
       
  1255 			return;
       
  1256 
       
  1257 		// Trigger a caching
       
  1258 		if ( !empty($post->post_content) ) {
       
  1259 			$this->post_ID = $post->ID;
       
  1260 			$this->usecache = false;
       
  1261 
       
  1262 			$content = $this->run_shortcode( $post->post_content );
       
  1263 			if ( get_option('embed_autourls') )
       
  1264 				$this->autoembed( $content );
       
  1265 
       
  1266 			$this->usecache = true;
       
  1267 		}
       
  1268 	}
       
  1269 
       
  1270 	/**
       
  1271 	 * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding.
       
  1272 	 *
       
  1273 	 * @uses WP_Embed::autoembed_callback()
       
  1274 	 *
       
  1275 	 * @param string $content The content to be searched.
       
  1276 	 * @return string Potentially modified $content.
       
  1277 	 */
       
  1278 	function autoembed( $content ) {
       
  1279 		return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array(&$this, 'autoembed_callback'), $content );
       
  1280 	}
       
  1281 
       
  1282 	/**
       
  1283 	 * Callback function for {@link WP_Embed::autoembed()}.
       
  1284 	 *
       
  1285 	 * @uses WP_Embed::shortcode()
       
  1286 	 *
       
  1287 	 * @param array $match A regex match array.
       
  1288 	 * @return string The embed HTML on success, otherwise the original URL.
       
  1289 	 */
       
  1290 	function autoembed_callback( $match ) {
       
  1291 		$oldval = $this->linkifunknown;
       
  1292 		$this->linkifunknown = false;
       
  1293 		$return = $this->shortcode( array(), $match[1] );
       
  1294 		$this->linkifunknown = $oldval;
       
  1295 
       
  1296 		return "\n$return\n";
       
  1297 	}
       
  1298 
       
  1299 	/**
       
  1300 	 * Conditionally makes a hyperlink based on an internal class variable.
       
  1301 	 *
       
  1302 	 * @param string $url URL to potentially be linked.
       
  1303 	 * @return string Linked URL or the original URL.
       
  1304 	 */
       
  1305 	function maybe_make_link( $url ) {
       
  1306 		$output = ( $this->linkifunknown ) ? '<a href="' . esc_attr($url) . '">' . esc_html($url) . '</a>' : $url;
       
  1307 		return apply_filters( 'embed_maybe_make_link', $output, $url );
       
  1308 	}
       
  1309 }
       
  1310 $GLOBALS['wp_embed'] = new WP_Embed();
       
  1311 
       
  1312 /**
       
  1313  * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
   937  * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1314  *
   938  *
  1315  * @since 2.9.0
   939  * @since 2.9.0
  1316  * @see WP_Embed::register_handler()
   940  * @see WP_Embed::register_handler()
  1317  */
   941  */
  1332 }
   956 }
  1333 
   957 
  1334 /**
   958 /**
  1335  * Create default array of embed parameters.
   959  * Create default array of embed parameters.
  1336  *
   960  *
       
   961  * The width defaults to the content width as specified by the theme. If the
       
   962  * theme does not specify a content width, then 500px is used.
       
   963  *
       
   964  * The default height is 1.5 times the width, or 1000px, whichever is smaller.
       
   965  *
       
   966  * The 'embed_defaults' filter can be used to adjust either of these values.
       
   967  *
  1337  * @since 2.9.0
   968  * @since 2.9.0
  1338  *
   969  *
  1339  * @return array Default embed parameters.
   970  * @return array Default embed parameters.
  1340  */
   971  */
  1341 function wp_embed_defaults() {
   972 function wp_embed_defaults() {
  1342 	if ( !empty($GLOBALS['content_width']) )
   973 	if ( ! empty( $GLOBALS['content_width'] ) )
  1343 		$theme_width = (int) $GLOBALS['content_width'];
   974 		$width = (int) $GLOBALS['content_width'];
  1344 
   975 
  1345 	$width = get_option('embed_size_w');
   976 	if ( empty( $width ) )
  1346 
       
  1347 	if ( empty($width) && !empty($theme_width) )
       
  1348 		$width = $theme_width;
       
  1349 
       
  1350 	if ( empty($width) )
       
  1351 		$width = 500;
   977 		$width = 500;
  1352 
   978 
  1353 	$height = get_option('embed_size_h');
   979 	$height = min( ceil( $width * 1.5 ), 1000 );
  1354 
   980 
  1355 	if ( empty($height) )
   981 	return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  1356 		$height = 700;
       
  1357 
       
  1358 	return apply_filters( 'embed_defaults', array(
       
  1359 		'width'  => $width,
       
  1360 		'height' => $height,
       
  1361 	) );
       
  1362 }
   982 }
  1363 
   983 
  1364 /**
   984 /**
  1365  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
   985  * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1366  *
   986  *
  1415  */
  1035  */
  1416 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1036 function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1417 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1037 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1418 	$oembed = _wp_oembed_get_object();
  1038 	$oembed = _wp_oembed_get_object();
  1419 	$oembed->providers[$format] = array( $provider, $regex );
  1039 	$oembed->providers[$format] = array( $provider, $regex );
       
  1040 }
       
  1041 
       
  1042 /**
       
  1043  * Removes an oEmbed provider.
       
  1044  *
       
  1045  * @since 3.5
       
  1046  * @see WP_oEmbed
       
  1047  *
       
  1048  * @uses _wp_oembed_get_object()
       
  1049  *
       
  1050  * @param string $format The URL format for the oEmbed provider to remove.
       
  1051  */
       
  1052 function wp_oembed_remove_provider( $format ) {
       
  1053 	require_once( ABSPATH . WPINC . '/class-oembed.php' );
       
  1054 
       
  1055 	$oembed = _wp_oembed_get_object();
       
  1056 
       
  1057 	if ( isset( $oembed->providers[ $format ] ) ) {
       
  1058 		unset( $oembed->providers[ $format ] );
       
  1059 		return true;
       
  1060 	}
       
  1061 
       
  1062 	return false;
  1420 }
  1063 }
  1421 
  1064 
  1422 /**
  1065 /**
  1423  * Determines if default embed handlers should be loaded.
  1066  * Determines if default embed handlers should be loaded.
  1424  *
  1067  *
  1456 
  1099 
  1457 	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 );
  1100 	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 );
  1458 }
  1101 }
  1459 
  1102 
  1460 /**
  1103 /**
       
  1104  * {@internal Missing Short Description}}
       
  1105  *
       
  1106  * @since 2.3.0
       
  1107  *
       
  1108  * @param unknown_type $size
       
  1109  * @return unknown
       
  1110  */
       
  1111 function wp_convert_hr_to_bytes( $size ) {
       
  1112 	$size  = strtolower( $size );
       
  1113 	$bytes = (int) $size;
       
  1114 	if ( strpos( $size, 'k' ) !== false )
       
  1115 		$bytes = intval( $size ) * 1024;
       
  1116 	elseif ( strpos( $size, 'm' ) !== false )
       
  1117 		$bytes = intval($size) * 1024 * 1024;
       
  1118 	elseif ( strpos( $size, 'g' ) !== false )
       
  1119 		$bytes = intval( $size ) * 1024 * 1024 * 1024;
       
  1120 	return $bytes;
       
  1121 }
       
  1122 
       
  1123 /**
       
  1124  * {@internal Missing Short Description}}
       
  1125  *
       
  1126  * @since 2.3.0
       
  1127  *
       
  1128  * @param unknown_type $bytes
       
  1129  * @return unknown
       
  1130  */
       
  1131 function wp_convert_bytes_to_hr( $bytes ) {
       
  1132 	$units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' );
       
  1133 	$log   = log( $bytes, 1024 );
       
  1134 	$power = (int) $log;
       
  1135 	$size  = pow( 1024, $log - $power );
       
  1136 	return $size . $units[$power];
       
  1137 }
       
  1138 
       
  1139 /**
       
  1140  * {@internal Missing Short Description}}
       
  1141  *
       
  1142  * @since 2.5.0
       
  1143  *
       
  1144  * @return unknown
       
  1145  */
       
  1146 function wp_max_upload_size() {
       
  1147 	$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
       
  1148 	$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
       
  1149 	$bytes   = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
       
  1150 	return $bytes;
       
  1151 }
       
  1152 
       
  1153 /**
       
  1154  * Returns a WP_Image_Editor instance and loads file into it.
       
  1155  *
       
  1156  * @since 3.5.0
       
  1157  * @access public
       
  1158  *
       
  1159  * @param string $path Path to file to load
       
  1160  * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
       
  1161  * @return WP_Image_Editor|WP_Error
       
  1162  */
       
  1163 function wp_get_image_editor( $path, $args = array() ) {
       
  1164 	$args['path'] = $path;
       
  1165 
       
  1166 	if ( ! isset( $args['mime_type'] ) ) {
       
  1167 		$file_info  = wp_check_filetype( $args['path'] );
       
  1168 
       
  1169 		// If $file_info['type'] is false, then we let the editor attempt to
       
  1170 		// figure out the file type, rather than forcing a failure based on extension.
       
  1171 		if ( isset( $file_info ) && $file_info['type'] )
       
  1172 			$args['mime_type'] = $file_info['type'];
       
  1173 	}
       
  1174 
       
  1175 	$implementation = _wp_image_editor_choose( $args );
       
  1176 
       
  1177 	if ( $implementation ) {
       
  1178 		$editor = new $implementation( $path );
       
  1179 		$loaded = $editor->load();
       
  1180 
       
  1181 		if ( is_wp_error( $loaded ) )
       
  1182 			return $loaded;
       
  1183 
       
  1184 		return $editor;
       
  1185 	}
       
  1186 
       
  1187 	return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
       
  1188 }
       
  1189 
       
  1190 /**
       
  1191  * Tests whether there is an editor that supports a given mime type or methods.
       
  1192  *
       
  1193  * @since 3.5.0
       
  1194  * @access public
       
  1195  *
       
  1196  * @param string|array $args Array of requirements.  Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
       
  1197  * @return boolean true if an eligible editor is found; false otherwise
       
  1198  */
       
  1199 function wp_image_editor_supports( $args = array() ) {
       
  1200 	return (bool) _wp_image_editor_choose( $args );
       
  1201 }
       
  1202 
       
  1203 /**
       
  1204  * Tests which editors are capable of supporting the request.
       
  1205  *
       
  1206  * @since 3.5.0
       
  1207  * @access private
       
  1208  *
       
  1209  * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
       
  1210  * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
       
  1211  */
       
  1212 function _wp_image_editor_choose( $args = array() ) {
       
  1213 	require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
       
  1214 	require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
       
  1215 	require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
       
  1216 
       
  1217 	$implementations = apply_filters( 'wp_image_editors',
       
  1218 		array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
       
  1219 
       
  1220 	foreach ( $implementations as $implementation ) {
       
  1221 		if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
       
  1222 			continue;
       
  1223 
       
  1224 		if ( isset( $args['mime_type'] ) &&
       
  1225 			! call_user_func(
       
  1226 				array( $implementation, 'supports_mime_type' ),
       
  1227 				$args['mime_type'] ) ) {
       
  1228 			continue;
       
  1229 		}
       
  1230 
       
  1231 		if ( isset( $args['methods'] ) &&
       
  1232 			 array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
       
  1233 			continue;
       
  1234 		}
       
  1235 
       
  1236 		return $implementation;
       
  1237 	}
       
  1238 
       
  1239 	return false;
       
  1240 }
       
  1241 
       
  1242 /**
  1461  * Prints default plupload arguments.
  1243  * Prints default plupload arguments.
  1462  *
  1244  *
  1463  * @since 3.4.0
  1245  * @since 3.4.0
  1464  */
  1246  */
  1465 function wp_plupload_default_settings() {
  1247 function wp_plupload_default_settings() {
  1466 	global $wp_scripts;
  1248 	global $wp_scripts;
       
  1249 
       
  1250 	$data = $wp_scripts->get_data( 'wp-plupload', 'data' );
       
  1251 	if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
       
  1252 		return;
  1467 
  1253 
  1468 	$max_upload_size = wp_max_upload_size();
  1254 	$max_upload_size = wp_max_upload_size();
  1469 
  1255 
  1470 	$defaults = array(
  1256 	$defaults = array(
  1471 		'runtimes'            => 'html5,silverlight,flash,html4',
  1257 		'runtimes'            => 'html5,silverlight,flash,html4',
  1472 		'file_data_name'      => 'async-upload', // key passed to $_FILE.
  1258 		'file_data_name'      => 'async-upload', // key passed to $_FILE.
  1473 		'multiple_queues'     => true,
  1259 		'multiple_queues'     => true,
  1474 		'max_file_size'       => $max_upload_size . 'b',
  1260 		'max_file_size'       => $max_upload_size . 'b',
  1475 		'url'                 => admin_url( 'admin-ajax.php', 'relative' ),
  1261 		'url'                 => admin_url( 'async-upload.php', 'relative' ),
  1476 		'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
  1262 		'flash_swf_url'       => includes_url( 'js/plupload/plupload.flash.swf' ),
  1477 		'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1263 		'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1478 		'filters'             => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  1264 		'filters'             => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  1479 		'multipart'           => true,
  1265 		'multipart'           => true,
  1480 		'urlstream_upload'    => true,
  1266 		'urlstream_upload'    => true,
  1481 	);
  1267 	);
  1482 
  1268 
       
  1269 	// Multi-file uploading doesn't currently work in iOS Safari,
       
  1270 	// single-file allows the built-in camera to be used as source for images
       
  1271 	if ( wp_is_mobile() )
       
  1272 		$defaults['multi_selection'] = false;
       
  1273 
  1483 	$defaults = apply_filters( 'plupload_default_settings', $defaults );
  1274 	$defaults = apply_filters( 'plupload_default_settings', $defaults );
  1484 
  1275 
  1485 	$params = array(
  1276 	$params = array(
  1486 		'action' => 'upload-attachment',
  1277 		'action' => 'upload-attachment',
  1487 	);
  1278 	);
  1494 		'defaults' => $defaults,
  1285 		'defaults' => $defaults,
  1495 		'browser'  => array(
  1286 		'browser'  => array(
  1496 			'mobile'    => wp_is_mobile(),
  1287 			'mobile'    => wp_is_mobile(),
  1497 			'supported' => _device_can_upload(),
  1288 			'supported' => _device_can_upload(),
  1498 		),
  1289 		),
       
  1290 		'limitExceeded' => is_multisite() && ! is_upload_space_available()
  1499 	);
  1291 	);
  1500 
  1292 
  1501 	$script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  1293 	$script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  1502 
  1294 
  1503 	$data = $wp_scripts->get_data( 'wp-plupload', 'data' );
       
  1504 	if ( $data )
  1295 	if ( $data )
  1505 		$script = "$data\n$script";
  1296 		$script = "$data\n$script";
  1506 
  1297 
  1507 	$wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1298 	$wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1508 }
  1299 }
  1509 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  1300 add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
       
  1301 
       
  1302 /**
       
  1303  * Prepares an attachment post object for JS, where it is expected
       
  1304  * to be JSON-encoded and fit into an Attachment model.
       
  1305  *
       
  1306  * @since 3.5.0
       
  1307  *
       
  1308  * @param mixed $attachment Attachment ID or object.
       
  1309  * @return array Array of attachment details.
       
  1310  */
       
  1311 function wp_prepare_attachment_for_js( $attachment ) {
       
  1312 	if ( ! $attachment = get_post( $attachment ) )
       
  1313 		return;
       
  1314 
       
  1315 	if ( 'attachment' != $attachment->post_type )
       
  1316 		return;
       
  1317 
       
  1318 	$meta = wp_get_attachment_metadata( $attachment->ID );
       
  1319 	if ( false !== strpos( $attachment->post_mime_type, '/' ) )
       
  1320 		list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
       
  1321 	else
       
  1322 		list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
       
  1323 
       
  1324 	$attachment_url = wp_get_attachment_url( $attachment->ID );
       
  1325 
       
  1326 	$response = array(
       
  1327 		'id'          => $attachment->ID,
       
  1328 		'title'       => $attachment->post_title,
       
  1329 		'filename'    => basename( $attachment->guid ),
       
  1330 		'url'         => $attachment_url,
       
  1331 		'link'        => get_attachment_link( $attachment->ID ),
       
  1332 		'alt'         => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
       
  1333 		'author'      => $attachment->post_author,
       
  1334 		'description' => $attachment->post_content,
       
  1335 		'caption'     => $attachment->post_excerpt,
       
  1336 		'name'        => $attachment->post_name,
       
  1337 		'status'      => $attachment->post_status,
       
  1338 		'uploadedTo'  => $attachment->post_parent,
       
  1339 		'date'        => strtotime( $attachment->post_date_gmt ) * 1000,
       
  1340 		'modified'    => strtotime( $attachment->post_modified_gmt ) * 1000,
       
  1341 		'menuOrder'   => $attachment->menu_order,
       
  1342 		'mime'        => $attachment->post_mime_type,
       
  1343 		'type'        => $type,
       
  1344 		'subtype'     => $subtype,
       
  1345 		'icon'        => wp_mime_type_icon( $attachment->ID ),
       
  1346 		'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
       
  1347 		'nonces'      => array(
       
  1348 			'update' => false,
       
  1349 			'delete' => false,
       
  1350 		),
       
  1351 		'editLink'   => false,
       
  1352 	);
       
  1353 
       
  1354 	if ( current_user_can( 'edit_post', $attachment->ID ) ) {
       
  1355 		$response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
       
  1356 		$response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
       
  1357 	}
       
  1358 
       
  1359 	if ( current_user_can( 'delete_post', $attachment->ID ) )
       
  1360 		$response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
       
  1361 
       
  1362 	if ( $meta && 'image' === $type ) {
       
  1363 		$sizes = array();
       
  1364 		$possible_sizes = apply_filters( 'image_size_names_choose', array(
       
  1365 			'thumbnail' => __('Thumbnail'),
       
  1366 			'medium'    => __('Medium'),
       
  1367 			'large'     => __('Large'),
       
  1368 			'full'      => __('Full Size'),
       
  1369 		) );
       
  1370 		unset( $possible_sizes['full'] );
       
  1371 
       
  1372 		// Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
       
  1373 		// First: run the image_downsize filter. If it returns something, we can use its data.
       
  1374 		// If the filter does not return something, then image_downsize() is just an expensive
       
  1375 		// way to check the image metadata, which we do second.
       
  1376 		foreach ( $possible_sizes as $size => $label ) {
       
  1377 			if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
       
  1378 				if ( ! $downsize[3] )
       
  1379 					continue;
       
  1380 				$sizes[ $size ] = array(
       
  1381 					'height'      => $downsize[2],
       
  1382 					'width'       => $downsize[1],
       
  1383 					'url'         => $downsize[0],
       
  1384 					'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
       
  1385 				);
       
  1386 			} elseif ( isset( $meta['sizes'][ $size ] ) ) {
       
  1387 				if ( ! isset( $base_url ) )
       
  1388 					$base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
       
  1389 
       
  1390 				// Nothing from the filter, so consult image metadata if we have it.
       
  1391 				$size_meta = $meta['sizes'][ $size ];
       
  1392 
       
  1393 				// We have the actual image size, but might need to further constrain it if content_width is narrower.
       
  1394 				// This is not necessary for thumbnails and medium size.
       
  1395 				if ( 'thumbnail' == $size || 'medium' == $size ) {
       
  1396 					$width = $size_meta['width'];
       
  1397 					$height = $size_meta['height'];
       
  1398 				} else {
       
  1399 					list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
       
  1400 				}
       
  1401 
       
  1402 				$sizes[ $size ] = array(
       
  1403 					'height'      => $height,
       
  1404 					'width'       => $width,
       
  1405 					'url'         => $base_url . $size_meta['file'],
       
  1406 					'orientation' => $height > $width ? 'portrait' : 'landscape',
       
  1407 				);
       
  1408 			}
       
  1409 		}
       
  1410 
       
  1411 		$sizes['full'] = array(
       
  1412 			'height'      => $meta['height'],
       
  1413 			'width'       => $meta['width'],
       
  1414 			'url'         => $attachment_url,
       
  1415 			'orientation' => $meta['height'] > $meta['width'] ? 'portrait' : 'landscape',
       
  1416 		);
       
  1417 
       
  1418 		$response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
       
  1419 	}
       
  1420 
       
  1421 	if ( function_exists('get_compat_media_markup') )
       
  1422 		$response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
       
  1423 
       
  1424 	return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
       
  1425 }
       
  1426 
       
  1427 /**
       
  1428  * Enqueues all scripts, styles, settings, and templates necessary to use
       
  1429  * all media JS APIs.
       
  1430  *
       
  1431  * @since 3.5.0
       
  1432  */
       
  1433 function wp_enqueue_media( $args = array() ) {
       
  1434 	$defaults = array(
       
  1435 		'post' => null,
       
  1436 	);
       
  1437 	$args = wp_parse_args( $args, $defaults );
       
  1438 
       
  1439 	// We're going to pass the old thickbox media tabs to `media_upload_tabs`
       
  1440 	// to ensure plugins will work. We will then unset those tabs.
       
  1441 	$tabs = array(
       
  1442 		// handler action suffix => tab label
       
  1443 		'type'     => '',
       
  1444 		'type_url' => '',
       
  1445 		'gallery'  => '',
       
  1446 		'library'  => '',
       
  1447 	);
       
  1448 
       
  1449 	$tabs = apply_filters( 'media_upload_tabs', $tabs );
       
  1450 	unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
       
  1451 
       
  1452 	$settings = array(
       
  1453 		'tabs'      => $tabs,
       
  1454 		'tabUrl'    => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
       
  1455 		'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
       
  1456 		'captions'  => ! apply_filters( 'disable_captions', '' ),
       
  1457 		'nonce'     => array(
       
  1458 			'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
       
  1459 		),
       
  1460 		'post'    => array(
       
  1461 			'id' => 0,
       
  1462 		),
       
  1463 	);
       
  1464 
       
  1465 	$post = null;
       
  1466 	if ( isset( $args['post'] ) ) {
       
  1467 		$post = get_post( $args['post'] );
       
  1468 		$settings['post'] = array(
       
  1469 			'id' => $post->ID,
       
  1470 			'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
       
  1471 		);
       
  1472 
       
  1473 		if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) {
       
  1474 			$featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
       
  1475 			$settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
       
  1476 		}
       
  1477 	}
       
  1478 
       
  1479 	$hier = $post && is_post_type_hierarchical( $post->post_type );
       
  1480 
       
  1481 	$strings = array(
       
  1482 		// Generic
       
  1483 		'url'         => __( 'URL' ),
       
  1484 		'addMedia'    => __( 'Add Media' ),
       
  1485 		'search'      => __( 'Search' ),
       
  1486 		'select'      => __( 'Select' ),
       
  1487 		'cancel'      => __( 'Cancel' ),
       
  1488 		/* translators: This is a would-be plural string used in the media manager.
       
  1489 		   If there is not a word you can use in your language to avoid issues with the
       
  1490 		   lack of plural support here, turn it into "selected: %d" then translate it.
       
  1491 		 */
       
  1492 		'selected'    => __( '%d selected' ),
       
  1493 		'dragInfo'    => __( 'Drag and drop to reorder images.' ),
       
  1494 
       
  1495 		// Upload
       
  1496 		'uploadFilesTitle'  => __( 'Upload Files' ),
       
  1497 		'uploadImagesTitle' => __( 'Upload Images' ),
       
  1498 
       
  1499 		// Library
       
  1500 		'mediaLibraryTitle'  => __( 'Media Library' ),
       
  1501 		'insertMediaTitle'   => __( 'Insert Media' ),
       
  1502 		'createNewGallery'   => __( 'Create a new gallery' ),
       
  1503 		'returnToLibrary'    => __( '&#8592; Return to library' ),
       
  1504 		'allMediaItems'      => __( 'All media items' ),
       
  1505 		'noItemsFound'       => __( 'No items found.' ),
       
  1506 		'insertIntoPost'     => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
       
  1507 		'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
       
  1508 		'warnDelete' =>      __( "You are about to permanently delete this item.\n  'Cancel' to stop, 'OK' to delete." ),
       
  1509 
       
  1510 		// From URL
       
  1511 		'insertFromUrlTitle' => __( 'Insert from URL' ),
       
  1512 
       
  1513 		// Featured Images
       
  1514 		'setFeaturedImageTitle' => __( 'Set Featured Image' ),
       
  1515 		'setFeaturedImage'    => __( 'Set featured image' ),
       
  1516 
       
  1517 		// Gallery
       
  1518 		'createGalleryTitle' => __( 'Create Gallery' ),
       
  1519 		'editGalleryTitle'   => __( 'Edit Gallery' ),
       
  1520 		'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
       
  1521 		'insertGallery'      => __( 'Insert gallery' ),
       
  1522 		'updateGallery'      => __( 'Update gallery' ),
       
  1523 		'addToGallery'       => __( 'Add to gallery' ),
       
  1524 		'addToGalleryTitle'  => __( 'Add to Gallery' ),
       
  1525 		'reverseOrder'       => __( 'Reverse order' ),
       
  1526 	);
       
  1527 
       
  1528 	$settings = apply_filters( 'media_view_settings', $settings, $post );
       
  1529 	$strings  = apply_filters( 'media_view_strings',  $strings,  $post );
       
  1530 
       
  1531 	$strings['settings'] = $settings;
       
  1532 
       
  1533 	wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
       
  1534 
       
  1535 	wp_enqueue_script( 'media-editor' );
       
  1536 	wp_enqueue_style( 'media-views' );
       
  1537 	wp_plupload_default_settings();
       
  1538 
       
  1539 	require_once ABSPATH . WPINC . '/media-template.php';
       
  1540 	add_action( 'admin_footer', 'wp_print_media_templates' );
       
  1541 	add_action( 'wp_footer', 'wp_print_media_templates' );
       
  1542 
       
  1543 	do_action( 'wp_enqueue_media' );
       
  1544 }