PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/msw/dev/wp-includes/media.php

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