PageRenderTime 62ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/media.php

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