PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

https://github.com/yanickouellet/WordPress
PHP | 2528 lines | 1344 code | 340 blank | 844 comment | 323 complexity | acae13dabe7b5169ca5b8a88946f9a6a 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 ? $post->ID : 0,
  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. /* see gallery_shortcode() in wp-includes/media.php */
  684. </style>";
  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 = '';
  693. if ( isset( $image_meta['height'], $image_meta['width'] ) )
  694. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  695. $output .= "<{$itemtag} class='gallery-item'>";
  696. $output .= "
  697. <{$icontag} class='gallery-icon {$orientation}'>
  698. $link
  699. </{$icontag}>";
  700. if ( $captiontag && trim($attachment->post_excerpt) ) {
  701. $output .= "
  702. <{$captiontag} class='wp-caption-text gallery-caption'>
  703. " . wptexturize($attachment->post_excerpt) . "
  704. </{$captiontag}>";
  705. }
  706. $output .= "</{$itemtag}>";
  707. if ( $columns > 0 && ++$i % $columns == 0 )
  708. $output .= '<br style="clear: both" />';
  709. }
  710. $output .= "
  711. <br style='clear: both;' />
  712. </div>\n";
  713. return $output;
  714. }
  715. /**
  716. * Provide a No-JS Flash fallback as a last resort for audio / video
  717. *
  718. * @since 3.6.0
  719. *
  720. * @param string $url
  721. * @return string Fallback HTML
  722. */
  723. function wp_mediaelement_fallback( $url ) {
  724. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  725. }
  726. /**
  727. * Return a filtered list of WP-supported audio formats
  728. *
  729. * @since 3.6.0
  730. * @return array
  731. */
  732. function wp_get_audio_extensions() {
  733. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
  734. }
  735. /**
  736. * The Audio shortcode.
  737. *
  738. * This implements the functionality of the Audio Shortcode for displaying
  739. * WordPress mp3s in a post.
  740. *
  741. * @since 3.6.0
  742. *
  743. * @param array $attr Attributes of the shortcode.
  744. * @return string HTML content to display audio.
  745. */
  746. function wp_audio_shortcode( $attr ) {
  747. $post_id = get_post() ? get_the_ID() : 0;
  748. static $instances = 0;
  749. $instances++;
  750. $audio = null;
  751. $default_types = wp_get_audio_extensions();
  752. $defaults_atts = array( 'src' => '' );
  753. foreach ( $default_types as $type )
  754. $defaults_atts[$type] = '';
  755. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  756. extract( $atts );
  757. $primary = false;
  758. if ( ! empty( $src ) ) {
  759. $type = wp_check_filetype( $src );
  760. if ( ! in_array( $type['ext'], $default_types ) )
  761. return sprintf( '<a class="wp-post-format-link-audio" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  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_attached_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 && did_action( 'init' ) ) {
  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'], esc_url( $$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, 'video' );
  845. extract( $atts );
  846. $w = $width;
  847. $h = $height;
  848. if ( is_admin() && $width > 600 )
  849. $w = 600;
  850. elseif ( ! is_admin() && $w > $defaults_atts['width'] )
  851. $w = $defaults_atts['width'];
  852. if ( $w < $width )
  853. $height = round( ( $h * $w ) / $width );
  854. $width = $w;
  855. $primary = false;
  856. if ( ! empty( $src ) ) {
  857. $type = wp_check_filetype( $src );
  858. if ( ! in_array( $type['ext'], $default_types ) )
  859. return sprintf( '<a class="wp-post-format-link-video" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  860. $primary = true;
  861. array_unshift( $default_types, 'src' );
  862. } else {
  863. foreach ( $default_types as $ext ) {
  864. if ( ! empty( $$ext ) ) {
  865. $type = wp_check_filetype( $$ext );
  866. if ( $type['ext'] === $ext )
  867. $primary = true;
  868. }
  869. }
  870. }
  871. if ( ! $primary ) {
  872. $videos = get_attached_video( $post_id );
  873. if ( empty( $videos ) )
  874. return;
  875. $video = reset( $videos );
  876. $src = wp_get_attachment_url( $video->ID );
  877. if ( empty( $src ) )
  878. return;
  879. array_unshift( $default_types, 'src' );
  880. }
  881. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  882. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  883. wp_enqueue_style( 'wp-mediaelement' );
  884. wp_enqueue_script( 'wp-mediaelement' );
  885. }
  886. $atts = array(
  887. sprintf( 'class="%s"', apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ) ),
  888. sprintf( 'id="video-%d-%d"', $post_id, $instances ),
  889. sprintf( 'width="%d"', $width ),
  890. sprintf( 'height="%d"', $height ),
  891. );
  892. if ( ! empty( $poster ) )
  893. $atts[] = sprintf( 'poster="%s"', esc_url( $poster ) );
  894. $html = sprintf( '<video %s controls="controls" preload="none">', join( ' ', $atts ) );
  895. $fileurl = '';
  896. $source = '<source type="%s" src="%s" />';
  897. foreach ( $default_types as $fallback ) {
  898. if ( ! empty( $$fallback ) ) {
  899. if ( empty( $fileurl ) )
  900. $fileurl = $$fallback;
  901. $type = wp_check_filetype( $$fallback );
  902. // m4v sometimes shows up as video/mpeg which collides with mp4
  903. if ( 'm4v' === $type['ext'] )
  904. $type['type'] = 'video/m4v';
  905. $html .= sprintf( $source, $type['type'], esc_url( $$fallback ) );
  906. }
  907. }
  908. if ( 'mediaelement' === $library )
  909. $html .= wp_mediaelement_fallback( $fileurl );
  910. $html .= '</video>';
  911. return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id );
  912. }
  913. add_shortcode( 'video', apply_filters( 'wp_video_shortcode_handler', 'wp_video_shortcode' ) );
  914. /**
  915. * Display previous image link that has the same post parent.
  916. *
  917. * @since 2.5.0
  918. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  919. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  920. * @return string HTML content.
  921. */
  922. function previous_image_link($size = 'thumbnail', $text = false) {
  923. adjacent_image_link(true, $size, $text);
  924. }
  925. /**
  926. * Display next image link that has the same post parent.
  927. *
  928. * @since 2.5.0
  929. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  930. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  931. * @return string HTML content.
  932. */
  933. function next_image_link($size = 'thumbnail', $text = false) {
  934. adjacent_image_link(false, $size, $text);
  935. }
  936. /**
  937. * Display next or previous image link that has the same post parent.
  938. *
  939. * Retrieves the current attachment object from the $post global.
  940. *
  941. * @since 2.5.0
  942. *
  943. * @param bool $prev Optional. Default is true to display previous link, false for next.
  944. */
  945. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  946. $post = get_post();
  947. $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' ) ) );
  948. foreach ( $attachments as $k => $attachment )
  949. if ( $attachment->ID == $post->ID )
  950. break;
  951. $k = $prev ? $k - 1 : $k + 1;
  952. $output = $attachment_id = null;
  953. if ( isset( $attachments[ $k ] ) ) {
  954. $attachment_id = $attachments[ $k ]->ID;
  955. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  956. }
  957. $adjacent = $prev ? 'previous' : 'next';
  958. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  959. }
  960. /**
  961. * Retrieve taxonomies attached to the attachment.
  962. *
  963. * @since 2.5.0
  964. *
  965. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  966. * @return array Empty array on failure. List of taxonomies on success.
  967. */
  968. function get_attachment_taxonomies($attachment) {
  969. if ( is_int( $attachment ) )
  970. $attachment = get_post($attachment);
  971. else if ( is_array($attachment) )
  972. $attachment = (object) $attachment;
  973. if ( ! is_object($attachment) )
  974. return array();
  975. $filename = basename($attachment->guid);
  976. $objects = array('attachment');
  977. if ( false !== strpos($filename, '.') )
  978. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  979. if ( !empty($attachment->post_mime_type) ) {
  980. $objects[] = 'attachment:' . $attachment->post_mime_type;
  981. if ( false !== strpos($attachment->post_mime_type, '/') )
  982. foreach ( explode('/', $attachment->post_mime_type) as $token )
  983. if ( !empty($token) )
  984. $objects[] = "attachment:$token";
  985. }
  986. $taxonomies = array();
  987. foreach ( $objects as $object )
  988. if ( $taxes = get_object_taxonomies($object) )
  989. $taxonomies = array_merge($taxonomies, $taxes);
  990. return array_unique($taxonomies);
  991. }
  992. /**
  993. * Return all of the taxonomy names that are registered for attachments.
  994. *
  995. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  996. *
  997. * @since 3.5.0
  998. * @see get_attachment_taxonomies()
  999. * @uses get_taxonomies()
  1000. *
  1001. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  1002. * @return array The names of all taxonomy of $object_type.
  1003. */
  1004. function get_taxonomies_for_attachments( $output = 'names' ) {
  1005. $taxonomies = array();
  1006. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1007. foreach ( $taxonomy->object_type as $object_type ) {
  1008. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  1009. if ( 'names' == $output )
  1010. $taxonomies[] = $taxonomy->name;
  1011. else
  1012. $taxonomies[ $taxonomy->name ] = $taxonomy;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. return $taxonomies;
  1018. }
  1019. /**
  1020. * Create new GD image resource with transparency support
  1021. * @TODO: Deprecate if possible.
  1022. *
  1023. * @since 2.9.0
  1024. *
  1025. * @param int $width Image width
  1026. * @param int $height Image height
  1027. * @return image resource
  1028. */
  1029. function wp_imagecreatetruecolor($width, $height) {
  1030. $img = imagecreatetruecolor($width, $height);
  1031. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1032. imagealphablending($img, false);
  1033. imagesavealpha($img, true);
  1034. }
  1035. return $img;
  1036. }
  1037. /**
  1038. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1039. *
  1040. * @since 2.9.0
  1041. * @see WP_Embed::register_handler()
  1042. */
  1043. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1044. global $wp_embed;
  1045. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  1046. }
  1047. /**
  1048. * Unregister a previously registered embed handler.
  1049. *
  1050. * @since 2.9.0
  1051. * @see WP_Embed::unregister_handler()
  1052. */
  1053. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1054. global $wp_embed;
  1055. $wp_embed->unregister_handler( $id, $priority );
  1056. }
  1057. /**
  1058. * Create default array of embed parameters.
  1059. *
  1060. * The width defaults to the content width as specified by the theme. If the
  1061. * theme does not specify a content width, then 500px is used.
  1062. *
  1063. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  1064. *
  1065. * The 'embed_defaults' filter can be used to adjust either of these values.
  1066. *
  1067. * @since 2.9.0
  1068. *
  1069. * @return array Default embed parameters.
  1070. */
  1071. function wp_embed_defaults() {
  1072. if ( ! empty( $GLOBALS['content_width'] ) )
  1073. $width = (int) $GLOBALS['content_width'];
  1074. if ( empty( $width ) )
  1075. $width = 500;
  1076. $height = min( ceil( $width * 1.5 ), 1000 );
  1077. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  1078. }
  1079. /**
  1080. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1081. *
  1082. * @since 2.9.0
  1083. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  1084. *
  1085. * @param int $example_width The width of an example embed.
  1086. * @param int $example_height The height of an example embed.
  1087. * @param int $max_width The maximum allowed width.
  1088. * @param int $max_height The maximum allowed height.
  1089. * @return array The maximum possible width and height based on the example ratio.
  1090. */
  1091. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1092. $example_width = (int) $example_width;
  1093. $example_height = (int) $example_height;
  1094. $max_width = (int) $max_width;
  1095. $max_height = (int) $max_height;
  1096. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  1097. }
  1098. /**
  1099. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1100. *
  1101. * @since 2.9.0
  1102. * @see WP_oEmbed
  1103. *
  1104. * @uses _wp_oembed_get_object()
  1105. * @uses WP_oEmbed::get_html()
  1106. *
  1107. * @param string $url The URL that should be embedded.
  1108. * @param array $args Additional arguments and parameters.
  1109. * @return bool|string False on failure or the embed HTML on success.
  1110. */
  1111. function wp_oembed_get( $url, $args = '' ) {
  1112. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1113. $oembed = _wp_oembed_get_object();
  1114. return $oembed->get_html( $url, $args );
  1115. }
  1116. /**
  1117. * Adds a URL format and oEmbed provider URL pair.
  1118. *
  1119. * @since 2.9.0
  1120. * @see WP_oEmbed
  1121. *
  1122. * @uses _wp_oembed_get_object()
  1123. *
  1124. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1125. * @param string $provider The URL to the oEmbed provider.
  1126. * @param boolean $regex Whether the $format parameter is in a regex format.
  1127. */
  1128. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1129. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1130. $oembed = _wp_oembed_get_object();
  1131. $oembed->providers[$format] = array( $provider, $regex );
  1132. }
  1133. /**
  1134. * Removes an oEmbed provider.
  1135. *
  1136. * @since 3.5.0
  1137. * @see WP_oEmbed
  1138. *
  1139. * @uses _wp_oembed_get_object()
  1140. *
  1141. * @param string $format The URL format for the oEmbed provider to remove.
  1142. */
  1143. function wp_oembed_remove_provider( $format ) {
  1144. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1145. $oembed = _wp_oembed_get_object();
  1146. if ( isset( $oembed->providers[ $format ] ) ) {
  1147. unset( $oembed->providers[ $format ] );
  1148. return true;
  1149. }
  1150. return false;
  1151. }
  1152. /**
  1153. * Determines if default embed handlers should be loaded.
  1154. *
  1155. * Checks to make sure that the embeds library hasn't already been loaded. If
  1156. * it hasn't, then it will load the embeds library.
  1157. *
  1158. * @since 2.9.0
  1159. */
  1160. function wp_maybe_load_embeds() {
  1161. if ( ! apply_filters( 'load_default_embeds', true ) )
  1162. return;
  1163. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  1164. wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
  1165. wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  1166. }
  1167. /**
  1168. * The Google Video embed handler callback. Google Video does not support oEmbed.
  1169. *
  1170. * @see WP_Embed::register_handler()
  1171. * @see WP_Embed::shortcode()
  1172. *
  1173. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1174. * @param array $attr Embed attributes.
  1175. * @param string $url The original URL that was matched by the regex.
  1176. * @param array $rawattr The original unmodified attributes.
  1177. * @return string The embed HTML.
  1178. */
  1179. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1180. // If the user supplied a fixed width AND height, use it
  1181. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1182. $width = (int) $rawattr['width'];
  1183. $height = (int) $rawattr['height'];
  1184. } else {
  1185. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1186. }
  1187. 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 );
  1188. }
  1189. /**
  1190. * Audio embed handler callback.
  1191. *
  1192. * @since 3.6.0
  1193. *
  1194. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1195. * @param array $attr Embed attributes.
  1196. * @param string $url The original URL that was matched by the regex.
  1197. * @param array $rawattr The original unmodified attributes.
  1198. * @return string The embed HTML.
  1199. */
  1200. function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  1201. $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
  1202. return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  1203. }
  1204. /**
  1205. * Video embed handler callback.
  1206. *
  1207. * @since 3.6.0
  1208. *
  1209. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1210. * @param array $attr Embed attributes.
  1211. * @param string $url The original URL that was matched by the regex.
  1212. * @param array $rawattr The original unmodified attributes.
  1213. * @return string The embed HTML.
  1214. */
  1215. function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  1216. $dimensions = '';
  1217. if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  1218. $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  1219. $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  1220. } elseif ( strstr( $url, home_url() ) ) {
  1221. $id = attachment_url_to_postid( $url );
  1222. if ( ! empty( $id ) ) {
  1223. $meta = wp_get_attachment_metadata( $id );
  1224. if ( ! empty( $meta['width'] ) )
  1225. $dimensions .= sprintf( 'width="%d" ', (int) $meta['width'] );
  1226. if ( ! empty( $meta['height'] ) )
  1227. $dimensions .= sprintf( 'height="%d" ', (int) $meta['height'] );
  1228. }
  1229. }
  1230. $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
  1231. return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  1232. }
  1233. /**
  1234. * Converts a shorthand byte value to an integer byte value.
  1235. *
  1236. * @since 2.3.0
  1237. *
  1238. * @param string $size A shorthand byte value.
  1239. * @return int An integer byte value.
  1240. */
  1241. function wp_convert_hr_to_bytes( $size ) {
  1242. $size = strtolower( $size );
  1243. $bytes = (int) $size;
  1244. if ( strpos( $size, 'k' ) !== false )
  1245. $bytes = intval( $size ) * 1024;
  1246. elseif ( strpos( $size, 'm' ) !== false )
  1247. $bytes = intval($size) * 1024 * 1024;
  1248. elseif ( strpos( $size, 'g' ) !== false )
  1249. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  1250. return $bytes;
  1251. }
  1252. /**
  1253. * Determine the maximum upload size allowed in php.ini.
  1254. *
  1255. * @since 2.5.0
  1256. *
  1257. * @return int Allowed upload size.
  1258. */
  1259. function wp_max_upload_size() {
  1260. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1261. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1262. $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1263. return $bytes;
  1264. }
  1265. /**
  1266. * Returns a WP_Image_Editor instance and loads file into it.
  1267. *
  1268. * @since 3.5.0
  1269. * @access public
  1270. *
  1271. * @param string $path Path to file to load
  1272. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1273. * @return WP_Image_Editor|WP_Error
  1274. */
  1275. function wp_get_image_editor( $path, $args = array() ) {
  1276. $args['path'] = $path;
  1277. if ( ! isset( $args['mime_type'] ) ) {
  1278. $file_info = wp_check_filetype( $args['path'] );
  1279. // If $file_info['type'] is false, then we let the editor attempt to
  1280. // figure out the file type, rather than forcing a failure based on extension.
  1281. if ( isset( $file_info ) && $file_info['type'] )
  1282. $args['mime_type'] = $file_info['type'];
  1283. }
  1284. $implementation = _wp_image_editor_choose( $args );
  1285. if ( $implementation ) {
  1286. $editor = n

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