PageRenderTime 57ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/media.php

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