[ XREF Home ] [ Index ]

PHP Cross Reference of WordPress Trunk

Provided by Yoast

title

Body

[close]

/wp-includes/ -> media.php (source)

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


Generated: Wed Jun 1 08:30:02 2011 Cross-referenced by PHPXref 0.7
Provided by Yoast and awesome WordPress Hosting