[ Index ]

PHP Cross Reference of WordPress 3.0 beta 1

[ Index ]     [ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

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


Generated: Mon Apr 5 14:26:09 2010 Cross-referenced by PHPXref 0.7