PageRenderTime 33ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/media.php

https://bitbucket.org/crypticrod/sr_wp_code
PHP | 1441 lines | 682 code | 181 blank | 578 comment | 193 complexity | 03139e5c9d39729f6eaf07bec3732f74 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1, GPL-3.0, LGPL-2.0, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file