PageRenderTime 48ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/wp-includes/media.php

https://bitbucket.org/dkrzos/phc
PHP | 1560 lines | 810 code | 197 blank | 553 comment | 189 complexity | 3777f989f339b8960ce97909b9158bff MD5 | raw file
Possible License(s): GPL-2.0
  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. $img_url = wp_get_attachment_url($id);
  133. $meta = wp_get_attachment_metadata($id);
  134. $width = $height = 0;
  135. $is_intermediate = false;
  136. $img_url_basename = wp_basename($img_url);
  137. // plugins can use this to provide resize services
  138. if ( $out = apply_filters('image_downsize', false, $id, $size) )
  139. return $out;
  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. * @return string HTML img element or empty string on failure.
  482. */
  483. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  484. $html = '';
  485. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  486. if ( $image ) {
  487. list($src, $width, $height) = $image;
  488. $hwstring = image_hwstring($width, $height);
  489. if ( is_array($size) )
  490. $size = join('x', $size);
  491. $attachment = get_post($attachment_id);
  492. $default_attr = array(
  493. 'src' => $src,
  494. 'class' => "attachment-$size",
  495. 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
  496. );
  497. if ( empty($default_attr['alt']) )
  498. $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
  499. if ( empty($default_attr['alt']) )
  500. $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
  501. $attr = wp_parse_args($attr, $default_attr);
  502. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
  503. $attr = array_map( 'esc_attr', $attr );
  504. $html = rtrim("<img $hwstring");
  505. foreach ( $attr as $name => $value ) {
  506. $html .= " $name=" . '"' . $value . '"';
  507. }
  508. $html .= ' />';
  509. }
  510. return $html;
  511. }
  512. /**
  513. * Adds a 'wp-post-image' class to post thumbnails
  514. * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
  515. * dynamically add/remove itself so as to only filter post thumbnails
  516. *
  517. * @since 2.9.0
  518. * @param array $attr Attributes including src, class, alt, title
  519. * @return array
  520. */
  521. function _wp_post_thumbnail_class_filter( $attr ) {
  522. $attr['class'] .= ' wp-post-image';
  523. return $attr;
  524. }
  525. /**
  526. * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
  527. *
  528. * @since 2.9.0
  529. */
  530. function _wp_post_thumbnail_class_filter_add( $attr ) {
  531. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  532. }
  533. /**
  534. * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
  535. *
  536. * @since 2.9.0
  537. */
  538. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  539. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  540. }
  541. add_shortcode('wp_caption', 'img_caption_shortcode');
  542. add_shortcode('caption', 'img_caption_shortcode');
  543. /**
  544. * The Caption shortcode.
  545. *
  546. * Allows a plugin to replace the content that would otherwise be returned. The
  547. * filter is 'img_caption_shortcode' and passes an empty string, the attr
  548. * parameter and the content parameter values.
  549. *
  550. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  551. * 'caption'.
  552. *
  553. * @since 2.6.0
  554. *
  555. * @param array $attr Attributes attributed to the shortcode.
  556. * @param string $content Optional. Shortcode content.
  557. * @return string
  558. */
  559. function img_caption_shortcode($attr, $content = null) {
  560. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  561. if ( ! isset( $attr['caption'] ) ) {
  562. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  563. $content = $matches[1];
  564. $attr['caption'] = trim( $matches[2] );
  565. }
  566. }
  567. // Allow plugins/themes to override the default caption template.
  568. $output = apply_filters('img_caption_shortcode', '', $attr, $content);
  569. if ( $output != '' )
  570. return $output;
  571. extract(shortcode_atts(array(
  572. 'id' => '',
  573. 'align' => 'alignnone',
  574. 'width' => '',
  575. 'caption' => ''
  576. ), $attr));
  577. if ( 1 > (int) $width || empty($caption) )
  578. return $content;
  579. if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
  580. return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
  581. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
  582. }
  583. add_shortcode('gallery', 'gallery_shortcode');
  584. /**
  585. * The Gallery shortcode.
  586. *
  587. * This implements the functionality of the Gallery Shortcode for displaying
  588. * WordPress images on a post.
  589. *
  590. * @since 2.5.0
  591. *
  592. * @param array $attr Attributes of the shortcode.
  593. * @return string HTML content to display gallery.
  594. */
  595. function gallery_shortcode($attr) {
  596. $post = get_post();
  597. static $instance = 0;
  598. $instance++;
  599. if ( ! empty( $attr['ids'] ) ) {
  600. // 'ids' is explicitly ordered, unless you specify otherwise.
  601. if ( empty( $attr['orderby'] ) )
  602. $attr['orderby'] = 'post__in';
  603. $attr['include'] = $attr['ids'];
  604. }
  605. // Allow plugins/themes to override the default gallery template.
  606. $output = apply_filters('post_gallery', '', $attr);
  607. if ( $output != '' )
  608. return $output;
  609. // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
  610. if ( isset( $attr['orderby'] ) ) {
  611. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  612. if ( !$attr['orderby'] )
  613. unset( $attr['orderby'] );
  614. }
  615. extract(shortcode_atts(array(
  616. 'order' => 'ASC',
  617. 'orderby' => 'menu_order ID',
  618. 'id' => $post->ID,
  619. 'itemtag' => 'dl',
  620. 'icontag' => 'dt',
  621. 'captiontag' => 'dd',
  622. 'columns' => 3,
  623. 'size' => 'thumbnail',
  624. 'include' => '',
  625. 'exclude' => ''
  626. ), $attr));
  627. $id = intval($id);
  628. if ( 'RAND' == $order )
  629. $orderby = 'none';
  630. if ( !empty($include) ) {
  631. $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  632. $attachments = array();
  633. foreach ( $_attachments as $key => $val ) {
  634. $attachments[$val->ID] = $_attachments[$key];
  635. }
  636. } elseif ( !empty($exclude) ) {
  637. $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  638. } else {
  639. $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  640. }
  641. if ( empty($attachments) )
  642. return '';
  643. if ( is_feed() ) {
  644. $output = "\n";
  645. foreach ( $attachments as $att_id => $attachment )
  646. $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  647. return $output;
  648. }
  649. $itemtag = tag_escape($itemtag);
  650. $captiontag = tag_escape($captiontag);
  651. $icontag = tag_escape($icontag);
  652. $valid_tags = wp_kses_allowed_html( 'post' );
  653. if ( ! isset( $valid_tags[ $itemtag ] ) )
  654. $itemtag = 'dl';
  655. if ( ! isset( $valid_tags[ $captiontag ] ) )
  656. $captiontag = 'dd';
  657. if ( ! isset( $valid_tags[ $icontag ] ) )
  658. $icontag = 'dt';
  659. $columns = intval($columns);
  660. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  661. $float = is_rtl() ? 'right' : 'left';
  662. $selector = "gallery-{$instance}";
  663. $gallery_style = $gallery_div = '';
  664. if ( apply_filters( 'use_default_gallery_style', true ) )
  665. $gallery_style = "
  666. <style type='text/css'>
  667. #{$selector} {
  668. margin: auto;
  669. }
  670. #{$selector} .gallery-item {
  671. float: {$float};
  672. margin-top: 10px;
  673. text-align: center;
  674. width: {$itemwidth}%;
  675. }
  676. #{$selector} img {
  677. border: 2px solid #cfcfcf;
  678. }
  679. #{$selector} .gallery-caption {
  680. margin-left: 0;
  681. }
  682. </style>
  683. <!-- see gallery_shortcode() in wp-includes/media.php -->";
  684. $size_class = sanitize_html_class( $size );
  685. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  686. $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
  687. $i = 0;
  688. foreach ( $attachments as $id => $attachment ) {
  689. $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
  690. $output .= "<{$itemtag} class='gallery-item'>";
  691. $output .= "
  692. <{$icontag} class='gallery-icon'>
  693. $link
  694. </{$icontag}>";
  695. if ( $captiontag && trim($attachment->post_excerpt) ) {
  696. $output .= "
  697. <{$captiontag} class='wp-caption-text gallery-caption'>
  698. " . wptexturize($attachment->post_excerpt) . "
  699. </{$captiontag}>";
  700. }
  701. $output .= "</{$itemtag}>";
  702. if ( $columns > 0 && ++$i % $columns == 0 )
  703. $output .= '<br style="clear: both" />';
  704. }
  705. $output .= "
  706. <br style='clear: both;' />
  707. </div>\n";
  708. return $output;
  709. }
  710. /**
  711. * Display previous image link that has the same post parent.
  712. *
  713. * @since 2.5.0
  714. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  715. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  716. * @return string HTML content.
  717. */
  718. function previous_image_link($size = 'thumbnail', $text = false) {
  719. adjacent_image_link(true, $size, $text);
  720. }
  721. /**
  722. * Display next image link that has the same post parent.
  723. *
  724. * @since 2.5.0
  725. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  726. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  727. * @return string HTML content.
  728. */
  729. function next_image_link($size = 'thumbnail', $text = false) {
  730. adjacent_image_link(false, $size, $text);
  731. }
  732. /**
  733. * Display next or previous image link that has the same post parent.
  734. *
  735. * Retrieves the current attachment object from the $post global.
  736. *
  737. * @since 2.5.0
  738. *
  739. * @param bool $prev Optional. Default is true to display previous link, false for next.
  740. */
  741. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  742. $post = get_post();
  743. $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' ) ) );
  744. foreach ( $attachments as $k => $attachment )
  745. if ( $attachment->ID == $post->ID )
  746. break;
  747. $k = $prev ? $k - 1 : $k + 1;
  748. $output = $attachment_id = null;
  749. if ( isset( $attachments[ $k ] ) ) {
  750. $attachment_id = $attachments[ $k ]->ID;
  751. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  752. }
  753. $adjacent = $prev ? 'previous' : 'next';
  754. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  755. }
  756. /**
  757. * Retrieve taxonomies attached to the attachment.
  758. *
  759. * @since 2.5.0
  760. *
  761. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  762. * @return array Empty array on failure. List of taxonomies on success.
  763. */
  764. function get_attachment_taxonomies($attachment) {
  765. if ( is_int( $attachment ) )
  766. $attachment = get_post($attachment);
  767. else if ( is_array($attachment) )
  768. $attachment = (object) $attachment;
  769. if ( ! is_object($attachment) )
  770. return array();
  771. $filename = basename($attachment->guid);
  772. $objects = array('attachment');
  773. if ( false !== strpos($filename, '.') )
  774. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  775. if ( !empty($attachment->post_mime_type) ) {
  776. $objects[] = 'attachment:' . $attachment->post_mime_type;
  777. if ( false !== strpos($attachment->post_mime_type, '/') )
  778. foreach ( explode('/', $attachment->post_mime_type) as $token )
  779. if ( !empty($token) )
  780. $objects[] = "attachment:$token";
  781. }
  782. $taxonomies = array();
  783. foreach ( $objects as $object )
  784. if ( $taxes = get_object_taxonomies($object) )
  785. $taxonomies = array_merge($taxonomies, $taxes);
  786. return array_unique($taxonomies);
  787. }
  788. /**
  789. * Return all of the taxonomy names that are registered for attachments.
  790. *
  791. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  792. *
  793. * @since 3.5.0
  794. * @see get_attachment_taxonomies()
  795. * @uses get_taxonomies()
  796. *
  797. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  798. * @return array The names of all taxonomy of $object_type.
  799. */
  800. function get_taxonomies_for_attachments( $output = 'names' ) {
  801. $taxonomies = array();
  802. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  803. foreach ( $taxonomy->object_type as $object_type ) {
  804. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  805. if ( 'names' == $output )
  806. $taxonomies[] = $taxonomy->name;
  807. else
  808. $taxonomies[ $taxonomy->name ] = $taxonomy;
  809. break;
  810. }
  811. }
  812. }
  813. return $taxonomies;
  814. }
  815. /**
  816. * Create new GD image resource with transparency support
  817. * @TODO: Deprecate if possible.
  818. *
  819. * @since 2.9.0
  820. *
  821. * @param int $width Image width
  822. * @param int $height Image height
  823. * @return image resource
  824. */
  825. function wp_imagecreatetruecolor($width, $height) {
  826. $img = imagecreatetruecolor($width, $height);
  827. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  828. imagealphablending($img, false);
  829. imagesavealpha($img, true);
  830. }
  831. return $img;
  832. }
  833. /**
  834. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  835. *
  836. * @since 2.9.0
  837. * @see WP_Embed::register_handler()
  838. */
  839. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  840. global $wp_embed;
  841. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  842. }
  843. /**
  844. * Unregister a previously registered embed handler.
  845. *
  846. * @since 2.9.0
  847. * @see WP_Embed::unregister_handler()
  848. */
  849. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  850. global $wp_embed;
  851. $wp_embed->unregister_handler( $id, $priority );
  852. }
  853. /**
  854. * Create default array of embed parameters.
  855. *
  856. * The width defaults to the content width as specified by the theme. If the
  857. * theme does not specify a content width, then 500px is used.
  858. *
  859. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  860. *
  861. * The 'embed_defaults' filter can be used to adjust either of these values.
  862. *
  863. * @since 2.9.0
  864. *
  865. * @return array Default embed parameters.
  866. */
  867. function wp_embed_defaults() {
  868. if ( ! empty( $GLOBALS['content_width'] ) )
  869. $width = (int) $GLOBALS['content_width'];
  870. if ( empty( $width ) )
  871. $width = 500;
  872. $height = min( ceil( $width * 1.5 ), 1000 );
  873. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  874. }
  875. /**
  876. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  877. *
  878. * @since 2.9.0
  879. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  880. *
  881. * @param int $example_width The width of an example embed.
  882. * @param int $example_height The height of an example embed.
  883. * @param int $max_width The maximum allowed width.
  884. * @param int $max_height The maximum allowed height.
  885. * @return array The maximum possible width and height based on the example ratio.
  886. */
  887. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  888. $example_width = (int) $example_width;
  889. $example_height = (int) $example_height;
  890. $max_width = (int) $max_width;
  891. $max_height = (int) $max_height;
  892. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  893. }
  894. /**
  895. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  896. *
  897. * @since 2.9.0
  898. * @see WP_oEmbed
  899. *
  900. * @uses _wp_oembed_get_object()
  901. * @uses WP_oEmbed::get_html()
  902. *
  903. * @param string $url The URL that should be embedded.
  904. * @param array $args Additional arguments and parameters.
  905. * @return bool|string False on failure or the embed HTML on success.
  906. */
  907. function wp_oembed_get( $url, $args = '' ) {
  908. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  909. $oembed = _wp_oembed_get_object();
  910. return $oembed->get_html( $url, $args );
  911. }
  912. /**
  913. * Adds a URL format and oEmbed provider URL pair.
  914. *
  915. * @since 2.9.0
  916. * @see WP_oEmbed
  917. *
  918. * @uses _wp_oembed_get_object()
  919. *
  920. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  921. * @param string $provider The URL to the oEmbed provider.
  922. * @param boolean $regex Whether the $format parameter is in a regex format.
  923. */
  924. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  925. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  926. $oembed = _wp_oembed_get_object();
  927. $oembed->providers[$format] = array( $provider, $regex );
  928. }
  929. /**
  930. * Removes an oEmbed provider.
  931. *
  932. * @since 3.5
  933. * @see WP_oEmbed
  934. *
  935. * @uses _wp_oembed_get_object()
  936. *
  937. * @param string $format The URL format for the oEmbed provider to remove.
  938. */
  939. function wp_oembed_remove_provider( $format ) {
  940. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  941. $oembed = _wp_oembed_get_object();
  942. if ( isset( $oembed->providers[ $format ] ) ) {
  943. unset( $oembed->providers[ $format ] );
  944. return true;
  945. }
  946. return false;
  947. }
  948. /**
  949. * Determines if default embed handlers should be loaded.
  950. *
  951. * Checks to make sure that the embeds library hasn't already been loaded. If
  952. * it hasn't, then it will load the embeds library.
  953. *
  954. * @since 2.9.0
  955. */
  956. function wp_maybe_load_embeds() {
  957. if ( ! apply_filters( 'load_default_embeds', true ) )
  958. return;
  959. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  960. }
  961. /**
  962. * The Google Video embed handler callback. Google Video does not support oEmbed.
  963. *
  964. * @see WP_Embed::register_handler()
  965. * @see WP_Embed::shortcode()
  966. *
  967. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  968. * @param array $attr Embed attributes.
  969. * @param string $url The original URL that was matched by the regex.
  970. * @param array $rawattr The original unmodified attributes.
  971. * @return string The embed HTML.
  972. */
  973. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  974. // If the user supplied a fixed width AND height, use it
  975. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  976. $width = (int) $rawattr['width'];
  977. $height = (int) $rawattr['height'];
  978. } else {
  979. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  980. }
  981. 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 );
  982. }
  983. /**
  984. * {@internal Missing Short Description}}
  985. *
  986. * @since 2.3.0
  987. *
  988. * @param unknown_type $size
  989. * @return unknown
  990. */
  991. function wp_convert_hr_to_bytes( $size ) {
  992. $size = strtolower( $size );
  993. $bytes = (int) $size;
  994. if ( strpos( $size, 'k' ) !== false )
  995. $bytes = intval( $size ) * 1024;
  996. elseif ( strpos( $size, 'm' ) !== false )
  997. $bytes = intval($size) * 1024 * 1024;
  998. elseif ( strpos( $size, 'g' ) !== false )
  999. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  1000. return $bytes;
  1001. }
  1002. /**
  1003. * {@internal Missing Short Description}}
  1004. *
  1005. * @since 2.3.0
  1006. *
  1007. * @param unknown_type $bytes
  1008. * @return unknown
  1009. */
  1010. function wp_convert_bytes_to_hr( $bytes ) {
  1011. $units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' );
  1012. $log = log( $bytes, 1024 );
  1013. $power = (int) $log;
  1014. $size = pow( 1024, $log - $power );
  1015. return $size . $units[$power];
  1016. }
  1017. /**
  1018. * {@internal Missing Short Description}}
  1019. *
  1020. * @since 2.5.0
  1021. *
  1022. * @return unknown
  1023. */
  1024. function wp_max_upload_size() {
  1025. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1026. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1027. $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1028. return $bytes;
  1029. }
  1030. /**
  1031. * Returns a WP_Image_Editor instance and loads file into it.
  1032. *
  1033. * @since 3.5.0
  1034. * @access public
  1035. *
  1036. * @param string $path Path to file to load
  1037. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1038. * @return WP_Image_Editor|WP_Error
  1039. */
  1040. function wp_get_image_editor( $path, $args = array() ) {
  1041. $args['path'] = $path;
  1042. if ( ! isset( $args['mime_type'] ) ) {
  1043. $file_info = wp_check_filetype( $args['path'] );
  1044. // If $file_info['type'] is false, then we let the editor attempt to
  1045. // figure out the file type, rather than forcing a failure based on extension.
  1046. if ( isset( $file_info ) && $file_info['type'] )
  1047. $args['mime_type'] = $file_info['type'];
  1048. }
  1049. $implementation = _wp_image_editor_choose( $args );
  1050. if ( $implementation ) {
  1051. $editor = new $implementation( $path );
  1052. $loaded = $editor->load();
  1053. if ( is_wp_error( $loaded ) )
  1054. return $loaded;
  1055. return $editor;
  1056. }
  1057. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  1058. }
  1059. /**
  1060. * Tests whether there is an editor that supports a given mime type or methods.
  1061. *
  1062. * @since 3.5.0
  1063. * @access public
  1064. *
  1065. * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1066. * @return boolean true if an eligible editor is found; false otherwise
  1067. */
  1068. function wp_image_editor_supports( $args = array() ) {
  1069. return (bool) _wp_image_editor_choose( $args );
  1070. }
  1071. /**
  1072. * Tests which editors are capable of supporting the request.
  1073. *
  1074. * @since 3.5.0
  1075. * @access private
  1076. *
  1077. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1078. * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  1079. */
  1080. function _wp_image_editor_choose( $args = array() ) {
  1081. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  1082. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  1083. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  1084. $implementations = apply_filters( 'wp_image_editors',
  1085. array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  1086. foreach ( $implementations as $implementation ) {
  1087. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  1088. continue;
  1089. if ( isset( $args['mime_type'] ) &&
  1090. ! call_user_func(
  1091. array( $implementation, 'supports_mime_type' ),
  1092. $args['mime_type'] ) ) {
  1093. continue;
  1094. }
  1095. if ( isset( $args['methods'] ) &&
  1096. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  1097. continue;
  1098. }
  1099. return $implementation;
  1100. }
  1101. return false;
  1102. }
  1103. /**
  1104. * Prints default plupload arguments.
  1105. *
  1106. * @since 3.4.0
  1107. */
  1108. function wp_plupload_default_settings() {
  1109. global $wp_scripts;
  1110. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  1111. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  1112. return;
  1113. $max_upload_size = wp_max_upload_size();
  1114. $defaults = array(
  1115. 'runtimes' => 'html5,silverlight,flash,html4',
  1116. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  1117. 'multiple_queues' => true,
  1118. 'max_file_size' => $max_upload_size . 'b',
  1119. 'url' => admin_url( 'async-upload.php', 'relative' ),
  1120. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  1121. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1122. 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  1123. 'multipart' => true,
  1124. 'urlstream_upload' => true,
  1125. );
  1126. // Multi-file uploading doesn't currently work in iOS Safari,
  1127. // single-file allows the built-in camera to be used as source for images
  1128. if ( wp_is_mobile() )
  1129. $defaults['multi_selection'] = false;
  1130. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  1131. $params = array(
  1132. 'action' => 'upload-attachment',
  1133. );
  1134. $params = apply_filters( 'plupload_default_params', $params );
  1135. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  1136. $defaults['multipart_params'] = $params;
  1137. $settings = array(
  1138. 'defaults' => $defaults,
  1139. 'browser' => array(
  1140. 'mobile' => wp_is_mobile(),
  1141. 'supported' => _device_can_upload(),
  1142. ),
  1143. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  1144. );
  1145. $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  1146. if ( $data )
  1147. $script = "$data\n$script";
  1148. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1149. }
  1150. add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  1151. /**
  1152. * Prepares an attachment post object for JS, where it is expected
  1153. * to be JSON-encoded and fit into an Attachment model.
  1154. *
  1155. * @since 3.5.0
  1156. *
  1157. * @param mixed $attachment Attachment ID or object.
  1158. * @return array Array of attachment details.
  1159. */
  1160. function wp_prepare_attachment_for_js( $attachment ) {
  1161. if ( ! $attachment = get_post( $attachment ) )
  1162. return;
  1163. if ( 'attachment' != $attachment->post_type )
  1164. return;
  1165. $meta = wp_get_attachment_metadata( $attachment->ID );
  1166. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  1167. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  1168. else
  1169. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  1170. $attachment_url = wp_get_attachment_url( $attachment->ID );
  1171. $response = array(
  1172. 'id' => $attachment->ID,
  1173. 'title' => $attachment->post_title,
  1174. 'filename' => basename( $attachment->guid ),
  1175. 'url' => $attachment_url,
  1176. 'link' => get_attachment_link( $attachment->ID ),
  1177. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  1178. 'author' => $attachment->post_author,
  1179. 'description' => $attachment->post_content,
  1180. 'caption' => $attachment->post_excerpt,
  1181. 'name' => $attachment->post_name,
  1182. 'status' => $attachment->post_status,
  1183. 'uploadedTo' => $attachment->post_parent,
  1184. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  1185. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  1186. 'menuOrder' => $attachment->menu_order,
  1187. 'mime' => $attachment->post_mime_type,
  1188. 'type' => $type,
  1189. 'subtype' => $subtype,
  1190. 'icon' => wp_mime_type_icon( $attachment->ID ),
  1191. 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  1192. 'nonces' => array(
  1193. 'update' => false,
  1194. 'delete' => false,
  1195. ),
  1196. 'editLink' => false,
  1197. );
  1198. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  1199. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  1200. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  1201. }
  1202. if ( current_user_can( 'delete_post', $attachment->ID ) )
  1203. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  1204. if ( $meta && 'image' === $type ) {
  1205. $sizes = array();
  1206. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  1207. 'thumbnail' => __('Thumbnail'),
  1208. 'medium' => __('Medium'),
  1209. 'large' => __('Large'),
  1210. 'full' => __('Full Size'),
  1211. ) );
  1212. unset( $possible_sizes['full'] );
  1213. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  1214. // First: run the image_downsize filter. If it returns something, we can use its data.
  1215. // If the filter does not return something, then image_downsize() is just an expensive
  1216. // way to check the image metadata, which we do second.
  1217. foreach ( $possible_sizes as $size => $label ) {
  1218. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  1219. if ( ! $downsize[3] )
  1220. continue;
  1221. $sizes[ $size ] = array(
  1222. 'height' => $downsize[2],
  1223. 'width' => $downsize[1],
  1224. 'url' => $downsize[0],
  1225. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  1226. );
  1227. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  1228. if ( ! isset( $base_url ) )
  1229. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  1230. // Nothing from the filter, so consult image metadata if we have it.
  1231. $size_meta = $meta['sizes'][ $size ];
  1232. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  1233. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  1234. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  1235. $sizes[ $size ] = array(
  1236. 'height' => $height,
  1237. 'width' => $width,
  1238. 'url' => $base_url . $size_meta['file'],
  1239. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  1240. );
  1241. }
  1242. }
  1243. $sizes['full'] = array(
  1244. 'height' => $meta['height'],
  1245. 'width' => $meta['width'],
  1246. 'url' => $attachment_url,
  1247. 'orientation' => $meta['height'] > $meta['width'] ? 'portrait' : 'landscape',
  1248. );
  1249. $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
  1250. }
  1251. if ( function_exists('get_compat_media_markup') )
  1252. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  1253. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  1254. }
  1255. /**
  1256. * Enqueues all scripts, styles, settings, and templates necessary to use
  1257. * all media JS APIs.
  1258. *
  1259. * @since 3.5.0
  1260. */
  1261. function wp_enqueue_media( $args = array() ) {
  1262. // Enqueue me just once per page, please.
  1263. if ( did_action( 'wp_enqueue_media' ) )
  1264. return;
  1265. $defaults = array(
  1266. 'post' => null,
  1267. );
  1268. $args = wp_parse_args( $args, $defaults );
  1269. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  1270. // to ensure plugins will work. We will then unset those tabs.
  1271. $tabs = array(
  1272. // handler action suffix => tab label
  1273. 'type' => '',
  1274. 'type_url' => '',
  1275. 'gallery' => '',
  1276. 'library' => '',
  1277. );
  1278. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  1279. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  1280. $props = array(
  1281. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  1282. 'align' => get_option( 'image_default_align' ), // empty default
  1283. 'size' => get_option( 'image_default_size' ), // empty default
  1284. );
  1285. $settings = array(
  1286. 'tabs' => $tabs,
  1287. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  1288. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  1289. 'captions' => ! apply_filters( 'disable_captions', '' ),
  1290. 'nonce' => array(
  1291. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  1292. ),
  1293. 'post' => array(
  1294. 'id' => 0,
  1295. ),
  1296. 'defaultProps' => $props,
  1297. );
  1298. $post = null;
  1299. if ( isset( $args['post'] ) ) {
  1300. $post = get_post( $args['post'] );
  1301. $settings['post'] = array(
  1302. 'id' => $post->ID,
  1303. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  1304. );
  1305. if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) {
  1306. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  1307. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  1308. }
  1309. }
  1310. $hier = $post && is_post_type_hierarchical( $post->post_type );
  1311. $strings = array(
  1312. // Generic
  1313. 'url' => __( 'URL' ),
  1314. 'addMedia' => __( 'Add Media' ),
  1315. 'search' => __( 'Search' ),
  1316. 'select' => __( 'Select' ),
  1317. 'cancel' => __( 'Cancel' ),
  1318. /* translators: This is a would-be plural string used in the media manager.
  1319. If there is not a word you can use in your language to avoid issues with the
  1320. lack of plural support here, turn it into "selected: %d" then translate it.
  1321. */
  1322. 'selected' => __( '%d selected' ),
  1323. 'dragInfo' => __( 'Drag and drop to reorder images.' ),
  1324. // Upload
  1325. 'uploadFilesTitle' => __( 'Upload Files' ),
  1326. 'uploadImagesTitle' => __( 'Upload Images' ),
  1327. // Library
  1328. 'mediaLibraryTitle' => __( 'Media Library' ),
  1329. 'insertMediaTitle' => __( 'Insert Media' ),
  1330. 'createNewGallery' => __( 'Create a new gallery' ),
  1331. 'returnToLibrary' => __( '&#8592; Return to library' ),
  1332. 'allMediaItems' => __( 'All media items' ),
  1333. 'noItemsFound' => __( 'No items found.' ),
  1334. 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
  1335. 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
  1336. 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
  1337. // From URL
  1338. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  1339. // Featured Images
  1340. 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
  1341. 'setFeaturedImage' => __( 'Set featured image' ),
  1342. // Gallery
  1343. 'createGalleryTitle' => __( 'Create Gallery' ),
  1344. 'editGalleryTitle' => __( 'Edit Gallery' ),
  1345. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  1346. 'insertGallery' => __( 'Insert gallery' ),
  1347. 'updateGallery' => __( 'Update gallery' ),
  1348. 'addToGallery' => __( 'Add to gallery' ),
  1349. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  1350. 'reverseOrder' => __( 'Reverse order' ),
  1351. );
  1352. $settings = apply_filters( 'media_view_settings', $settings, $post );
  1353. $strings = apply_filters( 'media_view_strings', $strings, $post );
  1354. $strings['settings'] = $settings;
  1355. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  1356. wp_enqueue_script( 'media-editor' );
  1357. wp_enqueue_style( 'media-views' );
  1358. wp_plupload_default_settings();
  1359. require_once ABSPATH . WPINC . '/media-template.php';
  1360. add_action( 'admin_footer', 'wp_print_media_templates' );
  1361. add_action( 'wp_footer', 'wp_print_media_templates' );
  1362. do_action( 'wp_enqueue_media' );
  1363. }