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

/wp-includes/media.php

https://github.com/dipakdotyadav/WordPress
PHP | 1862 lines | 1002 code | 237 blank | 623 comment | 223 complexity | cb8587bd604a948b9ff5a1cf6660ba22 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

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. * @subpackage Media
  7. */
  8. /**
  9. * Scale down the default size of an image.
  10. *
  11. * This is so that the image is a better fit for the editor and theme.
  12. *
  13. * The $size parameter accepts either an array or a string. The supported string
  14. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  15. * 128 width and 96 height in pixels. Also supported for the string value is
  16. * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
  17. * than the supported will result in the content_width size or 500 if that is
  18. * not set.
  19. *
  20. * Finally, there is a filter named 'editor_max_image_size', that will be called
  21. * on the calculated array for width and height, respectively. The second
  22. * parameter will be the value that was in the $size parameter. The returned
  23. * type for the hook is an array with the width as the first element and the
  24. * height as the second element.
  25. *
  26. * @since 2.5.0
  27. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  28. *
  29. * @param int $width Width of the image
  30. * @param int $height Height of the image
  31. * @param string|array $size Size of what the result image should be.
  32. * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
  33. * @return array Width and height of what the result image should resize to.
  34. */
  35. function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
  36. global $content_width, $_wp_additional_image_sizes;
  37. if ( ! $context )
  38. $context = is_admin() ? 'edit' : 'display';
  39. if ( is_array($size) ) {
  40. $max_width = $size[0];
  41. $max_height = $size[1];
  42. }
  43. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  44. $max_width = intval(get_option('thumbnail_size_w'));
  45. $max_height = intval(get_option('thumbnail_size_h'));
  46. // last chance thumbnail size defaults
  47. if ( !$max_width && !$max_height ) {
  48. $max_width = 128;
  49. $max_height = 96;
  50. }
  51. }
  52. elseif ( $size == 'medium' ) {
  53. $max_width = intval(get_option('medium_size_w'));
  54. $max_height = intval(get_option('medium_size_h'));
  55. // if no width is set, default to the theme content width if available
  56. }
  57. elseif ( $size == 'large' ) {
  58. // We're inserting a large size image into the editor. If it's a really
  59. // big image we'll scale it down to fit reasonably within the editor
  60. // itself, and within the theme's content width if it's known. The user
  61. // can resize it in the editor if they wish.
  62. $max_width = intval(get_option('large_size_w'));
  63. $max_height = intval(get_option('large_size_h'));
  64. if ( intval($content_width) > 0 )
  65. $max_width = min( intval($content_width), $max_width );
  66. } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  67. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  68. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  69. if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
  70. $max_width = min( intval($content_width), $max_width );
  71. }
  72. // $size == 'full' has no constraint
  73. else {
  74. $max_width = $width;
  75. $max_height = $height;
  76. }
  77. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  78. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  79. }
  80. /**
  81. * Retrieve width and height attributes using given width and height values.
  82. *
  83. * Both attributes are required in the sense that both parameters must have a
  84. * value, but are optional in that if you set them to false or null, then they
  85. * will not be added to the returned string.
  86. *
  87. * You can set the value using a string, but it will only take numeric values.
  88. * If you wish to put 'px' after the numbers, then it will be stripped out of
  89. * the return.
  90. *
  91. * @since 2.5.0
  92. *
  93. * @param int|string $width Optional. Width attribute value.
  94. * @param int|string $height Optional. Height attribute value.
  95. * @return string HTML attributes for width and, or height.
  96. */
  97. function image_hwstring($width, $height) {
  98. $out = '';
  99. if ($width)
  100. $out .= 'width="'.intval($width).'" ';
  101. if ($height)
  102. $out .= 'height="'.intval($height).'" ';
  103. return $out;
  104. }
  105. /**
  106. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  107. *
  108. * Array with image url, width, height, and whether is intermediate size, in
  109. * that order is returned on success is returned. $is_intermediate is true if
  110. * $url is a resized image, false if it is the original.
  111. *
  112. * The URL might be the original image, or it might be a resized version. This
  113. * function won't create a new resized copy, it will just return an already
  114. * resized one if it exists.
  115. *
  116. * A plugin may use the 'image_downsize' filter to hook into and offer image
  117. * resizing services for images. The hook must return an array with the same
  118. * elements that are returned in the function. The first element being the URL
  119. * to the new image that was resized.
  120. *
  121. * @since 2.5.0
  122. * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide
  123. * resize services.
  124. *
  125. * @param int $id Attachment ID for image.
  126. * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
  127. * @return bool|array False on failure, array on success.
  128. */
  129. function image_downsize($id, $size = 'medium') {
  130. if ( !wp_attachment_is_image($id) )
  131. return false;
  132. // plugins can use this to provide resize services
  133. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) )
  134. return $out;
  135. $img_url = wp_get_attachment_url($id);
  136. $meta = wp_get_attachment_metadata($id);
  137. $width = $height = 0;
  138. $is_intermediate = false;
  139. $img_url_basename = wp_basename($img_url);
  140. // try for a new style intermediate size
  141. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  142. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  143. $width = $intermediate['width'];
  144. $height = $intermediate['height'];
  145. $is_intermediate = true;
  146. }
  147. elseif ( $size == 'thumbnail' ) {
  148. // fall back to the old thumbnail
  149. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  150. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  151. $width = $info[0];
  152. $height = $info[1];
  153. $is_intermediate = true;
  154. }
  155. }
  156. if ( !$width && !$height && isset($meta['width'], $meta['height']) ) {
  157. // any other type: use the real image
  158. $width = $meta['width'];
  159. $height = $meta['height'];
  160. }
  161. if ( $img_url) {
  162. // we have the actual image size, but might need to further constrain it if content_width is narrower
  163. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  164. return array( $img_url, $width, $height, $is_intermediate );
  165. }
  166. return false;
  167. }
  168. /**
  169. * Registers a new image size
  170. *
  171. * @since 2.9.0
  172. */
  173. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  174. global $_wp_additional_image_sizes;
  175. $_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
  176. }
  177. /**
  178. * Registers an image size for the post thumbnail
  179. *
  180. * @since 2.9.0
  181. */
  182. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  183. add_image_size( 'post-thumbnail', $width, $height, $crop );
  184. }
  185. /**
  186. * An <img src /> tag for an image attachment, scaling it down if requested.
  187. *
  188. * The filter 'get_image_tag_class' allows for changing the class name for the
  189. * image without having to use regular expressions on the HTML content. The
  190. * parameters are: what WordPress will use for the class, the Attachment ID,
  191. * image align value, and the size the image should be.
  192. *
  193. * The second filter 'get_image_tag' has the HTML content, which can then be
  194. * further manipulated by a plugin to change all attribute values and even HTML
  195. * content.
  196. *
  197. * @since 2.5.0
  198. *
  199. * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element
  200. * class attribute.
  201. * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with
  202. * all attributes.
  203. *
  204. * @param int $id Attachment ID.
  205. * @param string $alt Image Description for the alt attribute.
  206. * @param string $title Image Description for the title attribute.
  207. * @param string $align Part of the class name for aligning the image.
  208. * @param string $size Optional. Default is 'medium'.
  209. * @return string HTML IMG element for given image attachment
  210. */
  211. function get_image_tag($id, $alt, $title, $align, $size='medium') {
  212. list( $img_src, $width, $height ) = image_downsize($id, $size);
  213. $hwstring = image_hwstring($width, $height);
  214. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  215. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  216. $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
  217. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  218. $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  219. return $html;
  220. }
  221. /**
  222. * Calculates the new dimensions for a downsampled image.
  223. *
  224. * If either width or height are empty, no constraint is applied on
  225. * that dimension.
  226. *
  227. * @since 2.5.0
  228. *
  229. * @param int $current_width Current width of the image.
  230. * @param int $current_height Current height of the image.
  231. * @param int $max_width Optional. Maximum wanted width.
  232. * @param int $max_height Optional. Maximum wanted height.
  233. * @return array First item is the width, the second item is the height.
  234. */
  235. function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
  236. if ( !$max_width and !$max_height )
  237. return array( $current_width, $current_height );
  238. $width_ratio = $height_ratio = 1.0;
  239. $did_width = $did_height = false;
  240. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  241. $width_ratio = $max_width / $current_width;
  242. $did_width = true;
  243. }
  244. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  245. $height_ratio = $max_height / $current_height;
  246. $did_height = true;
  247. }
  248. // Calculate the larger/smaller ratios
  249. $smaller_ratio = min( $width_ratio, $height_ratio );
  250. $larger_ratio = max( $width_ratio, $height_ratio );
  251. if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
  252. // The larger ratio is too big. It would result in an overflow.
  253. $ratio = $smaller_ratio;
  254. else
  255. // The larger ratio fits, and is likely to be a more "snug" fit.
  256. $ratio = $larger_ratio;
  257. $w = intval( $current_width * $ratio );
  258. $h = intval( $current_height * $ratio );
  259. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  260. // 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.
  261. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  262. if ( $did_width && $w == $max_width - 1 )
  263. $w = $max_width; // Round it up
  264. if ( $did_height && $h == $max_height - 1 )
  265. $h = $max_height; // Round it up
  266. return array( $w, $h );
  267. }
  268. /**
  269. * Retrieve calculated resized dimensions for use in WP_Image_Editor.
  270. *
  271. * Calculate dimensions and coordinates for a resized image that fits within a
  272. * specified width and height. If $crop is true, the largest matching central
  273. * portion of the image will be cropped out and resized to the required size.
  274. *
  275. * @since 2.5.0
  276. * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and
  277. * $crop to provide custom resize dimensions.
  278. *
  279. * @param int $orig_w Original width.
  280. * @param int $orig_h Original height.
  281. * @param int $dest_w New width.
  282. * @param int $dest_h New height.
  283. * @param bool $crop Optional, default is false. Whether to crop image or resize.
  284. * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function.
  285. */
  286. function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
  287. if ($orig_w <= 0 || $orig_h <= 0)
  288. return false;
  289. // at least one of dest_w or dest_h must be specific
  290. if ($dest_w <= 0 && $dest_h <= 0)
  291. return false;
  292. // plugins can use this to provide custom resize dimensions
  293. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  294. if ( null !== $output )
  295. return $output;
  296. if ( $crop ) {
  297. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  298. $aspect_ratio = $orig_w / $orig_h;
  299. $new_w = min($dest_w, $orig_w);
  300. $new_h = min($dest_h, $orig_h);
  301. if ( !$new_w ) {
  302. $new_w = intval($new_h * $aspect_ratio);
  303. }
  304. if ( !$new_h ) {
  305. $new_h = intval($new_w / $aspect_ratio);
  306. }
  307. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  308. $crop_w = round($new_w / $size_ratio);
  309. $crop_h = round($new_h / $size_ratio);
  310. $s_x = floor( ($orig_w - $crop_w) / 2 );
  311. $s_y = floor( ($orig_h - $crop_h) / 2 );
  312. } else {
  313. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  314. $crop_w = $orig_w;
  315. $crop_h = $orig_h;
  316. $s_x = 0;
  317. $s_y = 0;
  318. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  319. }
  320. // if the resulting image would be the same size or larger we don't want to resize it
  321. if ( $new_w >= $orig_w && $new_h >= $orig_h )
  322. return false;
  323. // the return array matches the parameters to imagecopyresampled()
  324. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  325. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  326. }
  327. /**
  328. * Resize an image to make a thumbnail or intermediate size.
  329. *
  330. * The returned array has the file size, the image width, and image height. The
  331. * filter 'image_make_intermediate_size' can be used to hook in and change the
  332. * values of the returned array. The only parameter is the resized file path.
  333. *
  334. * @since 2.5.0
  335. *
  336. * @param string $file File path.
  337. * @param int $width Image width.
  338. * @param int $height Image height.
  339. * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
  340. * @return bool|array False, if no image was created. Metadata array on success.
  341. */
  342. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  343. if ( $width || $height ) {
  344. $editor = wp_get_image_editor( $file );
  345. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  346. return false;
  347. $resized_file = $editor->save();
  348. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  349. unset( $resized_file['path'] );
  350. return $resized_file;
  351. }
  352. }
  353. return false;
  354. }
  355. /**
  356. * Retrieve the image's intermediate size (resized) path, width, and height.
  357. *
  358. * The $size parameter can be an array with the width and height respectively.
  359. * If the size matches the 'sizes' metadata array for width and height, then it
  360. * will be used. If there is no direct match, then the nearest image size larger
  361. * than the specified size will be used. If nothing is found, then the function
  362. * will break out and return false.
  363. *
  364. * The metadata 'sizes' is used for compatible sizes that can be used for the
  365. * parameter $size value.
  366. *
  367. * The url path will be given, when the $size parameter is a string.
  368. *
  369. * If you are passing an array for the $size, you should consider using
  370. * add_image_size() so that a cropped version is generated. It's much more
  371. * efficient than having to find the closest-sized image and then having the
  372. * browser scale down the image.
  373. *
  374. * @since 2.5.0
  375. * @see add_image_size()
  376. *
  377. * @param int $post_id Attachment ID for image.
  378. * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
  379. * @return bool|array False on failure or array of file path, width, and height on success.
  380. */
  381. function image_get_intermediate_size($post_id, $size='thumbnail') {
  382. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
  383. return false;
  384. // get the best one for a specified set of dimensions
  385. if ( is_array($size) && !empty($imagedata['sizes']) ) {
  386. foreach ( $imagedata['sizes'] as $_size => $data ) {
  387. // already cropped to width or height; so use this size
  388. if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
  389. $file = $data['file'];
  390. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  391. return compact( 'file', 'width', 'height' );
  392. }
  393. // add to lookup table: area => size
  394. $areas[$data['width'] * $data['height']] = $_size;
  395. }
  396. if ( !$size || !empty($areas) ) {
  397. // find for the smallest image not smaller than the desired size
  398. ksort($areas);
  399. foreach ( $areas as $_size ) {
  400. $data = $imagedata['sizes'][$_size];
  401. if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
  402. // Skip images with unexpectedly divergent aspect ratios (crops)
  403. // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
  404. $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
  405. // 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
  406. 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'] ) ) )
  407. continue;
  408. // If we're still here, then we're going to use this size
  409. $file = $data['file'];
  410. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  411. return compact( 'file', 'width', 'height' );
  412. }
  413. }
  414. }
  415. }
  416. if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
  417. return false;
  418. $data = $imagedata['sizes'][$size];
  419. // include the full filesystem path of the intermediate file
  420. if ( empty($data['path']) && !empty($data['file']) ) {
  421. $file_url = wp_get_attachment_url($post_id);
  422. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  423. $data['url'] = path_join( dirname($file_url), $data['file'] );
  424. }
  425. return $data;
  426. }
  427. /**
  428. * Get the available image sizes
  429. * @since 3.0.0
  430. * @return array Returns a filtered array of image size strings
  431. */
  432. function get_intermediate_image_sizes() {
  433. global $_wp_additional_image_sizes;
  434. $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
  435. if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
  436. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  437. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  438. }
  439. /**
  440. * Retrieve an image to represent an attachment.
  441. *
  442. * A mime icon for files, thumbnail or intermediate size for images.
  443. *
  444. * @since 2.5.0
  445. *
  446. * @param int $attachment_id Image attachment ID.
  447. * @param string $size Optional, default is 'thumbnail'.
  448. * @param bool $icon Optional, default is false. Whether it is an icon.
  449. * @return bool|array Returns an array (url, width, height), or false, if no image is available.
  450. */
  451. function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
  452. // get a thumbnail or intermediate image if there is one
  453. if ( $image = image_downsize($attachment_id, $size) )
  454. return $image;
  455. $src = false;
  456. if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
  457. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  458. $src_file = $icon_dir . '/' . wp_basename($src);
  459. @list($width, $height) = getimagesize($src_file);
  460. }
  461. if ( $src && $width && $height )
  462. return array( $src, $width, $height );
  463. return false;
  464. }
  465. /**
  466. * Get an HTML img element representing an image attachment
  467. *
  468. * While $size will accept an array, it is better to register a size with
  469. * add_image_size() so that a cropped version is generated. It's much more
  470. * efficient than having to find the closest-sized image and then having the
  471. * browser scale down the image.
  472. *
  473. * @see add_image_size()
  474. * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
  475. * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
  476. * @since 2.5.0
  477. *
  478. * @param int $attachment_id Image attachment ID.
  479. * @param string $size Optional, default is 'thumbnail'.
  480. * @param bool $icon Optional, default is false. Whether it is an icon.
  481. * @param mixed $attr Optional, attributes for the image markup.
  482. * @return string HTML img element or empty string on failure.
  483. */
  484. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  485. $html = '';
  486. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  487. if ( $image ) {
  488. list($src, $width, $height) = $image;
  489. $hwstring = image_hwstring($width, $height);
  490. if ( is_array($size) )
  491. $size = join('x', $size);
  492. $attachment = get_post($attachment_id);
  493. $default_attr = array(
  494. 'src' => $src,
  495. 'class' => "attachment-$size",
  496. 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
  497. );
  498. if ( empty($default_attr['alt']) )
  499. $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
  500. if ( empty($default_attr['alt']) )
  501. $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
  502. $attr = wp_parse_args($attr, $default_attr);
  503. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
  504. $attr = array_map( 'esc_attr', $attr );
  505. $html = rtrim("<img $hwstring");
  506. foreach ( $attr as $name => $value ) {
  507. $html .= " $name=" . '"' . $value . '"';
  508. }
  509. $html .= ' />';
  510. }
  511. return $html;
  512. }
  513. /**
  514. * Adds a 'wp-post-image' class to post thumbnails
  515. * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
  516. * dynamically add/remove itself so as to only filter post thumbnails
  517. *
  518. * @since 2.9.0
  519. * @param array $attr Attributes including src, class, alt, title
  520. * @return array
  521. */
  522. function _wp_post_thumbnail_class_filter( $attr ) {
  523. $attr['class'] .= ' wp-post-image';
  524. return $attr;
  525. }
  526. /**
  527. * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
  528. *
  529. * @since 2.9.0
  530. */
  531. function _wp_post_thumbnail_class_filter_add( $attr ) {
  532. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  533. }
  534. /**
  535. * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
  536. *
  537. * @since 2.9.0
  538. */
  539. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  540. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  541. }
  542. add_shortcode('wp_caption', 'img_caption_shortcode');
  543. add_shortcode('caption', 'img_caption_shortcode');
  544. /**
  545. * The Caption shortcode.
  546. *
  547. * Allows a plugin to replace the content that would otherwise be returned. The
  548. * filter is 'img_caption_shortcode' and passes an empty string, the attr
  549. * parameter and the content parameter values.
  550. *
  551. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  552. * 'caption'.
  553. *
  554. * @since 2.6.0
  555. *
  556. * @param array $attr Attributes attributed to the shortcode.
  557. * @param string $content Optional. Shortcode content.
  558. * @return string
  559. */
  560. function img_caption_shortcode($attr, $content = null) {
  561. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  562. if ( ! isset( $attr['caption'] ) ) {
  563. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  564. $content = $matches[1];
  565. $attr['caption'] = trim( $matches[2] );
  566. }
  567. }
  568. // Allow plugins/themes to override the default caption template.
  569. $output = apply_filters('img_caption_shortcode', '', $attr, $content);
  570. if ( $output != '' )
  571. return $output;
  572. extract(shortcode_atts(array(
  573. 'id' => '',
  574. 'align' => 'alignnone',
  575. 'width' => '',
  576. 'caption' => ''
  577. ), $attr, 'caption'));
  578. if ( 1 > (int) $width || empty($caption) )
  579. return $content;
  580. if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
  581. return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
  582. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
  583. }
  584. add_shortcode('gallery', 'gallery_shortcode');
  585. /**
  586. * The Gallery shortcode.
  587. *
  588. * This implements the functionality of the Gallery Shortcode for displaying
  589. * WordPress images on a post.
  590. *
  591. * @since 2.5.0
  592. *
  593. * @param array $attr Attributes of the shortcode.
  594. * @return string HTML content to display gallery.
  595. */
  596. function gallery_shortcode($attr) {
  597. $post = get_post();
  598. static $instance = 0;
  599. $instance++;
  600. if ( ! empty( $attr['ids'] ) ) {
  601. // 'ids' is explicitly ordered, unless you specify otherwise.
  602. if ( empty( $attr['orderby'] ) )
  603. $attr['orderby'] = 'post__in';
  604. $attr['include'] = $attr['ids'];
  605. }
  606. // Allow plugins/themes to override the default gallery template.
  607. $output = apply_filters('post_gallery', '', $attr);
  608. if ( $output != '' )
  609. return $output;
  610. // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
  611. if ( isset( $attr['orderby'] ) ) {
  612. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  613. if ( !$attr['orderby'] )
  614. unset( $attr['orderby'] );
  615. }
  616. extract(shortcode_atts(array(
  617. 'order' => 'ASC',
  618. 'orderby' => 'menu_order ID',
  619. 'id' => $post->ID,
  620. 'itemtag' => 'dl',
  621. 'icontag' => 'dt',
  622. 'captiontag' => 'dd',
  623. 'columns' => 3,
  624. 'size' => 'thumbnail',
  625. 'include' => '',
  626. 'exclude' => ''
  627. ), $attr, 'gallery'));
  628. $id = intval($id);
  629. if ( 'RAND' == $order )
  630. $orderby = 'none';
  631. if ( !empty($include) ) {
  632. $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  633. $attachments = array();
  634. foreach ( $_attachments as $key => $val ) {
  635. $attachments[$val->ID] = $_attachments[$key];
  636. }
  637. } elseif ( !empty($exclude) ) {
  638. $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  639. } else {
  640. $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  641. }
  642. if ( empty($attachments) )
  643. return '';
  644. if ( is_feed() ) {
  645. $output = "\n";
  646. foreach ( $attachments as $att_id => $attachment )
  647. $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  648. return $output;
  649. }
  650. $itemtag = tag_escape($itemtag);
  651. $captiontag = tag_escape($captiontag);
  652. $icontag = tag_escape($icontag);
  653. $valid_tags = wp_kses_allowed_html( 'post' );
  654. if ( ! isset( $valid_tags[ $itemtag ] ) )
  655. $itemtag = 'dl';
  656. if ( ! isset( $valid_tags[ $captiontag ] ) )
  657. $captiontag = 'dd';
  658. if ( ! isset( $valid_tags[ $icontag ] ) )
  659. $icontag = 'dt';
  660. $columns = intval($columns);
  661. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  662. $float = is_rtl() ? 'right' : 'left';
  663. $selector = "gallery-{$instance}";
  664. $gallery_style = $gallery_div = '';
  665. if ( apply_filters( 'use_default_gallery_style', true ) )
  666. $gallery_style = "
  667. <style type='text/css'>
  668. #{$selector} {
  669. margin: auto;
  670. }
  671. #{$selector} .gallery-item {
  672. float: {$float};
  673. margin-top: 10px;
  674. text-align: center;
  675. width: {$itemwidth}%;
  676. }
  677. #{$selector} img {
  678. border: 2px solid #cfcfcf;
  679. }
  680. #{$selector} .gallery-caption {
  681. margin-left: 0;
  682. }
  683. </style>
  684. <!-- see gallery_shortcode() in wp-includes/media.php -->";
  685. $size_class = sanitize_html_class( $size );
  686. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  687. $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
  688. $i = 0;
  689. foreach ( $attachments as $id => $attachment ) {
  690. $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
  691. $image_meta = wp_get_attachment_metadata( $id );
  692. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  693. $output .= "<{$itemtag} class='gallery-item'>";
  694. $output .= "
  695. <{$icontag} class='gallery-icon {$orientation}'>
  696. $link
  697. </{$icontag}>";
  698. if ( $captiontag && trim($attachment->post_excerpt) ) {
  699. $output .= "
  700. <{$captiontag} class='wp-caption-text gallery-caption'>
  701. " . wptexturize($attachment->post_excerpt) . "
  702. </{$captiontag}>";
  703. }
  704. $output .= "</{$itemtag}>";
  705. if ( $columns > 0 && ++$i % $columns == 0 )
  706. $output .= '<br style="clear: both" />';
  707. }
  708. $output .= "
  709. <br style='clear: both;' />
  710. </div>\n";
  711. return $output;
  712. }
  713. /**
  714. * Provide a No-JS Flash fallback as a last resort for audio / video
  715. *
  716. * @since 3.6.0
  717. *
  718. * @param string $url
  719. * @return string Fallback HTML
  720. */
  721. function wp_mediaelement_fallback( $url ) {
  722. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  723. }
  724. /**
  725. * Return a filtered list of WP-supported audio formats
  726. *
  727. * @since 3.6.0
  728. * @return array
  729. */
  730. function wp_get_audio_extensions() {
  731. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
  732. }
  733. /**
  734. * The Audio shortcode.
  735. *
  736. * This implements the functionality of the Audio Shortcode for displaying
  737. * WordPress mp3s in a post.
  738. *
  739. * @since 3.6.0
  740. *
  741. * @param array $attr Attributes of the shortcode.
  742. * @return string HTML content to display audio.
  743. */
  744. function wp_audio_shortcode( $attr ) {
  745. $post_id = get_post() ? get_the_ID() : 0;
  746. static $instances = 0;
  747. $instances++;
  748. $audio = null;
  749. $default_types = wp_get_audio_extensions();
  750. $defaults_atts = array( 'src' => '' );
  751. foreach ( $default_types as $type )
  752. $defaults_atts[$type] = '';
  753. $atts = shortcode_atts( $defaults_atts, $attr );
  754. extract( $atts );
  755. $primary = false;
  756. if ( ! empty( $src ) ) {
  757. $type = wp_check_filetype( $src );
  758. if ( ! in_array( $type['ext'], $default_types ) ) {
  759. printf( '<a class="wp-post-format-link-audio" href="%1$s">%1$s</a>', $src );
  760. return;
  761. }
  762. $primary = true;
  763. array_unshift( $default_types, 'src' );
  764. } else {
  765. foreach ( $default_types as $ext ) {
  766. if ( ! empty( $$ext ) ) {
  767. $type = wp_check_filetype( $$ext );
  768. if ( $type['ext'] === $ext )
  769. $primary = true;
  770. }
  771. }
  772. }
  773. if ( ! $primary ) {
  774. $audios = get_post_audio( $post_id );
  775. if ( empty( $audios ) )
  776. return;
  777. $audio = reset( $audios );
  778. $src = wp_get_attachment_url( $audio->ID );
  779. if ( empty( $src ) )
  780. return;
  781. array_unshift( $default_types, 'src' );
  782. }
  783. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  784. if ( 'mediaelement' === $library ) {
  785. wp_enqueue_style( 'wp-mediaelement' );
  786. wp_enqueue_script( 'wp-mediaelement' );
  787. }
  788. $atts = array(
  789. sprintf( 'class="%s"', apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ) ),
  790. sprintf( 'id="audio-%d-%d"', $post_id, $instances ),
  791. );
  792. $html = sprintf( '<audio %s controls="controls" preload="none">', join( ' ', $atts ) );
  793. $fileurl = '';
  794. $source = '<source type="%s" src="%s" />';
  795. foreach ( $default_types as $fallback ) {
  796. if ( ! empty( $$fallback ) ) {
  797. if ( empty( $fileurl ) )
  798. $fileurl = $$fallback;
  799. $type = wp_check_filetype( $$fallback );
  800. $html .= sprintf( $source, $type['type'], $$fallback );
  801. }
  802. }
  803. if ( 'mediaelement' === $library )
  804. $html .= wp_mediaelement_fallback( $fileurl );
  805. $html .= '</audio>';
  806. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id );
  807. }
  808. add_shortcode( 'audio', apply_filters( 'wp_audio_shortcode_handler', 'wp_audio_shortcode' ) );
  809. /**
  810. * Return a filtered list of WP-supported video formats
  811. *
  812. * @since 3.6.0
  813. * @return array
  814. */
  815. function wp_get_video_extensions() {
  816. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  817. }
  818. /**
  819. * The Video shortcode.
  820. *
  821. * This implements the functionality of the Video Shortcode for displaying
  822. * WordPress mp4s in a post.
  823. *
  824. * @since 3.6.0
  825. *
  826. * @param array $attr Attributes of the shortcode.
  827. * @return string HTML content to display video.
  828. */
  829. function wp_video_shortcode( $attr ) {
  830. global $content_width;
  831. $post_id = get_post() ? get_the_ID() : 0;
  832. static $instances = 0;
  833. $instances++;
  834. $video = null;
  835. $default_types = wp_get_video_extensions();
  836. $defaults_atts = array(
  837. 'src' => '',
  838. 'poster' => '',
  839. 'height' => 360,
  840. 'width' => empty( $content_width ) ? 640 : $content_width,
  841. );
  842. foreach ( $default_types as $type )
  843. $defaults_atts[$type] = '';
  844. $atts = shortcode_atts( $defaults_atts, $attr );
  845. extract( $atts );
  846. $primary = false;
  847. if ( ! empty( $src ) ) {
  848. $type = wp_check_filetype( $src );
  849. if ( ! in_array( $type['ext'], $default_types ) ) {
  850. printf( '<a class="wp-post-format-link-video" href="%1$s">%1$s</a>', $src );
  851. return;
  852. }
  853. $primary = true;
  854. array_unshift( $default_types, 'src' );
  855. } else {
  856. foreach ( $default_types as $ext ) {
  857. if ( ! empty( $$ext ) ) {
  858. $type = wp_check_filetype( $$ext );
  859. if ( $type['ext'] === $ext )
  860. $primary = true;
  861. }
  862. }
  863. }
  864. if ( ! $primary ) {
  865. $videos = get_post_video( $post_id );
  866. if ( empty( $videos ) )
  867. return;
  868. $video = reset( $videos );
  869. $src = wp_get_attachment_url( $video->ID );
  870. if ( empty( $src ) )
  871. return;
  872. array_unshift( $default_types, 'src' );
  873. }
  874. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  875. if ( 'mediaelement' === $library ) {
  876. wp_enqueue_style( 'wp-mediaelement' );
  877. wp_enqueue_script( 'wp-mediaelement' );
  878. }
  879. $atts = array(
  880. sprintf( 'class="%s"', apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ) ),
  881. sprintf( 'id="video-%d-%d"', $post_id, $instances ),
  882. sprintf( 'width="%d"', $width ),
  883. sprintf( 'height="%d"', $height ),
  884. );
  885. if ( ! empty( $poster ) )
  886. $atts[] = sprintf( 'poster="%s"', esc_url( $poster ) );
  887. $html = sprintf( '<video %s controls="controls" preload="none">', join( ' ', $atts ) );
  888. $fileurl = '';
  889. $source = '<source type="%s" src="%s" />';
  890. foreach ( $default_types as $fallback ) {
  891. if ( ! empty( $$fallback ) ) {
  892. if ( empty( $fileurl ) )
  893. $fileurl = $$fallback;
  894. $type = wp_check_filetype( $$fallback );
  895. // m4v sometimes shows up as video/mpeg which collides with mp4
  896. if ( 'm4v' === $type['ext'] )
  897. $type['type'] = 'video/m4v';
  898. $html .= sprintf( $source, $type['type'], $$fallback );
  899. }
  900. }
  901. if ( 'mediaelement' === $library )
  902. $html .= wp_mediaelement_fallback( $fileurl, $width, $height );
  903. $html .= '</video>';
  904. return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id );
  905. }
  906. add_shortcode( 'video', apply_filters( 'wp_video_shortcode_handler', 'wp_video_shortcode' ) );
  907. /**
  908. * Display previous image link that has the same post parent.
  909. *
  910. * @since 2.5.0
  911. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  912. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  913. * @return string HTML content.
  914. */
  915. function previous_image_link($size = 'thumbnail', $text = false) {
  916. adjacent_image_link(true, $size, $text);
  917. }
  918. /**
  919. * Display next image link that has the same post parent.
  920. *
  921. * @since 2.5.0
  922. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  923. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  924. * @return string HTML content.
  925. */
  926. function next_image_link($size = 'thumbnail', $text = false) {
  927. adjacent_image_link(false, $size, $text);
  928. }
  929. /**
  930. * Display next or previous image link that has the same post parent.
  931. *
  932. * Retrieves the current attachment object from the $post global.
  933. *
  934. * @since 2.5.0
  935. *
  936. * @param bool $prev Optional. Default is true to display previous link, false for next.
  937. */
  938. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  939. $post = get_post();
  940. $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' ) ) );
  941. foreach ( $attachments as $k => $attachment )
  942. if ( $attachment->ID == $post->ID )
  943. break;
  944. $k = $prev ? $k - 1 : $k + 1;
  945. $output = $attachment_id = null;
  946. if ( isset( $attachments[ $k ] ) ) {
  947. $attachment_id = $attachments[ $k ]->ID;
  948. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  949. }
  950. $adjacent = $prev ? 'previous' : 'next';
  951. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  952. }
  953. /**
  954. * Retrieve taxonomies attached to the attachment.
  955. *
  956. * @since 2.5.0
  957. *
  958. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  959. * @return array Empty array on failure. List of taxonomies on success.
  960. */
  961. function get_attachment_taxonomies($attachment) {
  962. if ( is_int( $attachment ) )
  963. $attachment = get_post($attachment);
  964. else if ( is_array($attachment) )
  965. $attachment = (object) $attachment;
  966. if ( ! is_object($attachment) )
  967. return array();
  968. $filename = basename($attachment->guid);
  969. $objects = array('attachment');
  970. if ( false !== strpos($filename, '.') )
  971. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  972. if ( !empty($attachment->post_mime_type) ) {
  973. $objects[] = 'attachment:' . $attachment->post_mime_type;
  974. if ( false !== strpos($attachment->post_mime_type, '/') )
  975. foreach ( explode('/', $attachment->post_mime_type) as $token )
  976. if ( !empty($token) )
  977. $objects[] = "attachment:$token";
  978. }
  979. $taxonomies = array();
  980. foreach ( $objects as $object )
  981. if ( $taxes = get_object_taxonomies($object) )
  982. $taxonomies = array_merge($taxonomies, $taxes);
  983. return array_unique($taxonomies);
  984. }
  985. /**
  986. * Return all of the taxonomy names that are registered for attachments.
  987. *
  988. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  989. *
  990. * @since 3.5.0
  991. * @see get_attachment_taxonomies()
  992. * @uses get_taxonomies()
  993. *
  994. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  995. * @return array The names of all taxonomy of $object_type.
  996. */
  997. function get_taxonomies_for_attachments( $output = 'names' ) {
  998. $taxonomies = array();
  999. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1000. foreach ( $taxonomy->object_type as $object_type ) {
  1001. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  1002. if ( 'names' == $output )
  1003. $taxonomies[] = $taxonomy->name;
  1004. else
  1005. $taxonomies[ $taxonomy->name ] = $taxonomy;
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. return $taxonomies;
  1011. }
  1012. /**
  1013. * Create new GD image resource with transparency support
  1014. * @TODO: Deprecate if possible.
  1015. *
  1016. * @since 2.9.0
  1017. *
  1018. * @param int $width Image width
  1019. * @param int $height Image height
  1020. * @return image resource
  1021. */
  1022. function wp_imagecreatetruecolor($width, $height) {
  1023. $img = imagecreatetruecolor($width, $height);
  1024. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1025. imagealphablending($img, false);
  1026. imagesavealpha($img, true);
  1027. }
  1028. return $img;
  1029. }
  1030. /**
  1031. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1032. *
  1033. * @since 2.9.0
  1034. * @see WP_Embed::register_handler()
  1035. */
  1036. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1037. global $wp_embed;
  1038. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  1039. }
  1040. /**
  1041. * Unregister a previously registered embed handler.
  1042. *
  1043. * @since 2.9.0
  1044. * @see WP_Embed::unregister_handler()
  1045. */
  1046. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1047. global $wp_embed;
  1048. $wp_embed->unregister_handler( $id, $priority );
  1049. }
  1050. /**
  1051. * Create default array of embed parameters.
  1052. *
  1053. * The width defaults to the content width as specified by the theme. If the
  1054. * theme does not specify a content width, then 500px is used.
  1055. *
  1056. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  1057. *
  1058. * The 'embed_defaults' filter can be used to adjust either of these values.
  1059. *
  1060. * @since 2.9.0
  1061. *
  1062. * @return array Default embed parameters.
  1063. */
  1064. function wp_embed_defaults() {
  1065. if ( ! empty( $GLOBALS['content_width'] ) )
  1066. $width = (int) $GLOBALS['content_width'];
  1067. if ( empty( $width ) )
  1068. $width = 500;
  1069. $height = min( ceil( $width * 1.5 ), 1000 );
  1070. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  1071. }
  1072. /**
  1073. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1074. *
  1075. * @since 2.9.0
  1076. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  1077. *
  1078. * @param int $example_width The width of an example embed.
  1079. * @param int $example_height The height of an example embed.
  1080. * @param int $max_width The maximum allowed width.
  1081. * @param int $max_height The maximum allowed height.
  1082. * @return array The maximum possible width and height based on the example ratio.
  1083. */
  1084. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1085. $example_width = (int) $example_width;
  1086. $example_height = (int) $example_height;
  1087. $max_width = (int) $max_width;
  1088. $max_height = (int) $max_height;
  1089. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  1090. }
  1091. /**
  1092. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1093. *
  1094. * @since 2.9.0
  1095. * @see WP_oEmbed
  1096. *
  1097. * @uses _wp_oembed_get_object()
  1098. * @uses WP_oEmbed::get_html()
  1099. *
  1100. * @param string $url The URL that should be embedded.
  1101. * @param array $args Additional arguments and parameters.
  1102. * @return bool|string False on failure or the embed HTML on success.
  1103. */
  1104. function wp_oembed_get( $url, $args = '' ) {
  1105. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1106. $oembed = _wp_oembed_get_object();
  1107. return $oembed->get_html( $url, $args );
  1108. }
  1109. /**
  1110. * Adds a URL format and oEmbed provider URL pair.
  1111. *
  1112. * @since 2.9.0
  1113. * @see WP_oEmbed
  1114. *
  1115. * @uses _wp_oembed_get_object()
  1116. *
  1117. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1118. * @param string $provider The URL to the oEmbed provider.
  1119. * @param boolean $regex Whether the $format parameter is in a regex format.
  1120. */
  1121. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1122. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1123. $oembed = _wp_oembed_get_object();
  1124. $oembed->providers[$format] = array( $provider, $regex );
  1125. }
  1126. /**
  1127. * Removes an oEmbed provider.
  1128. *
  1129. * @since 3.5.0
  1130. * @see WP_oEmbed
  1131. *
  1132. * @uses _wp_oembed_get_object()
  1133. *
  1134. * @param string $format The URL format for the oEmbed provider to remove.
  1135. */
  1136. function wp_oembed_remove_provider( $format ) {
  1137. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1138. $oembed = _wp_oembed_get_object();
  1139. if ( isset( $oembed->providers[ $format ] ) ) {
  1140. unset( $oembed->providers[ $format ] );
  1141. return true;
  1142. }
  1143. return false;
  1144. }
  1145. /**
  1146. * Determines if default embed handlers should be loaded.
  1147. *
  1148. * Checks to make sure that the embeds library hasn't already been loaded. If
  1149. * it hasn't, then it will load the embeds library.
  1150. *
  1151. * @since 2.9.0
  1152. */
  1153. function wp_maybe_load_embeds() {
  1154. if ( ! apply_filters( 'load_default_embeds', true ) )
  1155. return;
  1156. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  1157. }
  1158. /**
  1159. * The Google Video embed handler callback. Google Video does not support oEmbed.
  1160. *
  1161. * @see WP_Embed::register_handler()
  1162. * @see WP_Embed::shortcode()
  1163. *
  1164. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1165. * @param array $attr Embed attributes.
  1166. * @param string $url The original URL that was matched by the regex.
  1167. * @param array $rawattr The original unmodified attributes.
  1168. * @return string The embed HTML.
  1169. */
  1170. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1171. // If the user supplied a fixed width AND height, use it
  1172. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1173. $width = (int) $rawattr['width'];
  1174. $height = (int) $rawattr['height'];
  1175. } else {
  1176. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1177. }
  1178. return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&amp;hl=en&amp;fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr );
  1179. }
  1180. /**
  1181. * Converts a shorthand byte value to an integer byte value.
  1182. *
  1183. * @since 2.3.0
  1184. *
  1185. * @param string $size A shorthand byte value.
  1186. * @return int An integer byte value.
  1187. */
  1188. function wp_convert_hr_to_bytes( $size ) {
  1189. $size = strtolower( $size );
  1190. $bytes = (int) $size;
  1191. if ( strpos( $size, 'k' ) !== false )
  1192. $bytes = intval( $size ) * 1024;
  1193. elseif ( strpos( $size, 'm' ) !== false )
  1194. $bytes = intval($size) * 1024 * 1024;
  1195. elseif ( strpos( $size, 'g' ) !== false )
  1196. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  1197. return $bytes;
  1198. }
  1199. /**
  1200. * Determine the maximum upload size allowed in php.ini.
  1201. *
  1202. * @since 2.5.0
  1203. *
  1204. * @return int Allowed upload size.
  1205. */
  1206. function wp_max_upload_size() {
  1207. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1208. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1209. $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1210. return $bytes;
  1211. }
  1212. /**
  1213. * Returns a WP_Image_Editor instance and loads file into it.
  1214. *
  1215. * @since 3.5.0
  1216. * @access public
  1217. *
  1218. * @param string $path Path to file to load
  1219. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1220. * @return WP_Image_Editor|WP_Error
  1221. */
  1222. function wp_get_image_editor( $path, $args = array() ) {
  1223. $args['path'] = $path;
  1224. if ( ! isset( $args['mime_type'] ) ) {
  1225. $file_info = wp_check_filetype( $args['path'] );
  1226. // If $file_info['type'] is false, then we let the editor attempt to
  1227. // figure out the file type, rather than forcing a failure based on extension.
  1228. if ( isset( $file_info ) && $file_info['type'] )
  1229. $args['mime_type'] = $file_info['type'];
  1230. }
  1231. $implementation = _wp_image_editor_choose( $args );
  1232. if ( $implementation ) {
  1233. $editor = new $implementation( $path );
  1234. $loaded = $editor->load();
  1235. if ( is_wp_error( $loaded ) )
  1236. return $loaded;
  1237. return $editor;
  1238. }
  1239. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  1240. }
  1241. /**
  1242. * Tests whether there is an editor that supports a given mime type or methods.
  1243. *
  1244. * @since 3.5.0
  1245. * @access public
  1246. *
  1247. * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1248. * @return boolean true if an eligible editor is found; false otherwise
  1249. */
  1250. function wp_image_editor_supports( $args = array() ) {
  1251. return (bool) _wp_image_editor_choose( $args );
  1252. }
  1253. /**
  1254. * Tests which editors are capable of supporting the request.
  1255. *
  1256. * @since 3.5.0
  1257. * @access private
  1258. *
  1259. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1260. * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  1261. */
  1262. function _wp_image_editor_choose( $args = array() ) {
  1263. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  1264. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  1265. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  1266. $implementations = apply_filters( 'wp_image_editors',
  1267. array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  1268. foreach ( $implementations as $implementation ) {
  1269. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  1270. continue;
  1271. if ( isset( $args['mime_type'] ) &&
  1272. ! call_user_func(
  1273. array( $implementation, 'supports_mime_type' ),
  1274. $args['mime_type'] ) ) {
  1275. continue;
  1276. }
  1277. if ( isset( $args['methods'] ) &&
  1278. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  1279. continue;
  1280. }
  1281. return $implementation;
  1282. }
  1283. return false;
  1284. }
  1285. /**
  1286. * Prints default plupload arguments.
  1287. *
  1288. * @since 3.4.0
  1289. */
  1290. function wp_plupload_default_settings() {
  1291. global $wp_scripts;
  1292. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  1293. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  1294. return;
  1295. $max_upload_size = wp_max_upload_size();
  1296. $defaults = array(
  1297. 'runtimes' => 'html5,silverlight,flash,html4',
  1298. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  1299. 'multiple_queues' => true,
  1300. 'max_file_size' => $max_upload_size . 'b',
  1301. 'url' => admin_url( 'async-upload.php', 'relative' ),
  1302. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  1303. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1304. 'filters' => array

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