PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wordpress3.4.2/wp-includes/media.php

https://bitbucket.org/ch3tag/mothers
PHP | 1509 lines | 727 code | 191 blank | 591 comment | 201 complexity | 7c742f5c461483987d133fc45bc25605 MD5 | raw file

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

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