PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/media.php

https://bitbucket.org/abnopanda/wordpress
PHP | 1890 lines | 1114 code | 229 blank | 547 comment | 188 complexity | a391921589c91498ea445b5d6e899896 MD5 | raw file

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

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

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