PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/media.php

https://github.com/younggive/WordPress
PHP | 1486 lines | 769 code | 177 blank | 540 comment | 197 complexity | 0f993710a955ddc0581e2cb233960527 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

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

  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. */
  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. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  211. $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
  212. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />';
  213. $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  214. return $html;
  215. }
  216. /**
  217. * Load an image from a string, if PHP supports it.
  218. *
  219. * @since 2.1.0
  220. *
  221. * @param string $file Filename of the image to load.
  222. * @return resource The resulting image resource on success, Error string on failure.
  223. */
  224. function wp_load_image( $file ) {
  225. if ( is_numeric( $file ) )
  226. $file = get_attached_file( $file );
  227. if ( ! file_exists( $file ) )
  228. return sprintf(__('File &#8220;%s&#8221; doesn&#8217;t exist?'), $file);
  229. if ( ! function_exists('imagecreatefromstring') )
  230. return __('The GD image library is not installed.');
  231. // Set artificially high because GD uses uncompressed images in memory
  232. @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
  233. $image = imagecreatefromstring( file_get_contents( $file ) );
  234. if ( !is_resource( $image ) )
  235. return sprintf(__('File &#8220;%s&#8221; is not an image.'), $file);
  236. return $image;
  237. }
  238. /**
  239. * Calculates the new dimensions for a downsampled image.
  240. *
  241. * If either width or height are empty, no constraint is applied on
  242. * that dimension.
  243. *
  244. * @since 2.5.0
  245. *
  246. * @param int $current_width Current width of the image.
  247. * @param int $current_height Current height of the image.
  248. * @param int $max_width Optional. Maximum wanted width.
  249. * @param int $max_height Optional. Maximum wanted height.
  250. * @return array First item is the width, the second item is the height.
  251. */
  252. function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
  253. if ( !$max_width and !$max_height )
  254. return array( $current_width, $current_height );
  255. $width_ratio = $height_ratio = 1.0;
  256. $did_width = $did_height = false;
  257. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  258. $width_ratio = $max_width / $current_width;
  259. $did_width = true;
  260. }
  261. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  262. $height_ratio = $max_height / $current_height;
  263. $did_height = true;
  264. }
  265. // Calculate the larger/smaller ratios
  266. $smaller_ratio = min( $width_ratio, $height_ratio );
  267. $larger_ratio = max( $width_ratio, $height_ratio );
  268. if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
  269. // The larger ratio is too big. It would result in an overflow.
  270. $ratio = $smaller_ratio;
  271. else
  272. // The larger ratio fits, and is likely to be a more "snug" fit.
  273. $ratio = $larger_ratio;
  274. $w = intval( $current_width * $ratio );
  275. $h = intval( $current_height * $ratio );
  276. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  277. // 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.
  278. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  279. if ( $did_width && $w == $max_width - 1 )
  280. $w = $max_width; // Round it up
  281. if ( $did_height && $h == $max_height - 1 )
  282. $h = $max_height; // Round it up
  283. return array( $w, $h );
  284. }
  285. /**
  286. * Retrieve calculated resized dimensions for use in imagecopyresampled().
  287. *
  288. * Calculate dimensions and coordinates for a resized image that fits within a
  289. * specified width and height. If $crop is true, the largest matching central
  290. * portion of the image will be cropped out and resized to the required size.
  291. *
  292. * @since 2.5.0
  293. * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and
  294. * $crop to provide custom resize dimensions.
  295. *
  296. * @param int $orig_w Original width.
  297. * @param int $orig_h Original height.
  298. * @param int $dest_w New width.
  299. * @param int $dest_h New height.
  300. * @param bool $crop Optional, default is false. Whether to crop image or resize.
  301. * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function.
  302. */
  303. function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
  304. if ($orig_w <= 0 || $orig_h <= 0)
  305. return false;
  306. // at least one of dest_w or dest_h must be specific
  307. if ($dest_w <= 0 && $dest_h <= 0)
  308. return false;
  309. // plugins can use this to provide custom resize dimensions
  310. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  311. if ( null !== $output )
  312. return $output;
  313. if ( $crop ) {
  314. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  315. $aspect_ratio = $orig_w / $orig_h;
  316. $new_w = min($dest_w, $orig_w);
  317. $new_h = min($dest_h, $orig_h);
  318. if ( !$new_w ) {
  319. $new_w = intval($new_h * $aspect_ratio);
  320. }
  321. if ( !$new_h ) {
  322. $new_h = intval($new_w / $aspect_ratio);
  323. }
  324. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  325. $crop_w = round($new_w / $size_ratio);
  326. $crop_h = round($new_h / $size_ratio);
  327. $s_x = floor( ($orig_w - $crop_w) / 2 );
  328. $s_y = floor( ($orig_h - $crop_h) / 2 );
  329. } else {
  330. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  331. $crop_w = $orig_w;
  332. $crop_h = $orig_h;
  333. $s_x = 0;
  334. $s_y = 0;
  335. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  336. }
  337. // if the resulting image would be the same size or larger we don't want to resize it
  338. if ( $new_w >= $orig_w && $new_h >= $orig_h )
  339. return false;
  340. // the return array matches the parameters to imagecopyresampled()
  341. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  342. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  343. }
  344. /**
  345. * Scale down an image to fit a particular size and save a new copy of the image.
  346. *
  347. * The PNG transparency will be preserved using the function, as well as the
  348. * image type. If the file going in is PNG, then the resized image is going to
  349. * be PNG. The only supported image types are PNG, GIF, and JPEG.
  350. *
  351. * Some functionality requires API to exist, so some PHP version may lose out
  352. * support. This is not the fault of WordPress (where functionality is
  353. * downgraded, not actual defects), but of your PHP version.
  354. *
  355. * @since 2.5.0
  356. *
  357. * @param string $file Image file path.
  358. * @param int $max_w Maximum width to resize to.
  359. * @param int $max_h Maximum height to resize to.
  360. * @param bool $crop Optional. Whether to crop image or resize.
  361. * @param string $suffix Optional. File suffix.
  362. * @param string $dest_path Optional. New image file path.
  363. * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
  364. * @return mixed WP_Error on failure. String with new destination path.
  365. */
  366. function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
  367. $image = wp_load_image( $file );
  368. if ( !is_resource( $image ) )
  369. return new WP_Error( 'error_loading_image', $image, $file );
  370. $size = @getimagesize( $file );
  371. if ( !$size )
  372. return new WP_Error('invalid_image', __('Could not read image size'), $file);
  373. list($orig_w, $orig_h, $orig_type) = $size;
  374. $dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
  375. if ( !$dims )
  376. return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
  377. list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
  378. $newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
  379. imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  380. // convert from full colors to index colors, like original PNG.
  381. if ( IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor( $image ) )
  382. imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
  383. // we don't need the original in memory anymore
  384. imagedestroy( $image );
  385. // $suffix will be appended to the destination filename, just before the extension
  386. if ( !$suffix )
  387. $suffix = "{$dst_w}x{$dst_h}";
  388. $info = pathinfo($file);
  389. $dir = $info['dirname'];
  390. $ext = $info['extension'];
  391. $name = wp_basename($file, ".$ext");
  392. if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
  393. $dir = $_dest_path;
  394. $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
  395. if ( IMAGETYPE_GIF == $orig_type ) {
  396. if ( !imagegif( $newimage, $destfilename ) )
  397. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  398. } elseif ( IMAGETYPE_PNG == $orig_type ) {
  399. if ( !imagepng( $newimage, $destfilename ) )
  400. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  401. } else {
  402. // all other formats are converted to jpg
  403. if ( 'jpg' != $ext && 'jpeg' != $ext )
  404. $destfilename = "{$dir}/{$name}-{$suffix}.jpg";
  405. if ( !imagejpeg( $newimage, $destfilename, apply_filters( 'jpeg_quality', $jpeg_quality, 'image_resize' ) ) )
  406. return new WP_Error('resize_path_invalid', __( 'Resize path invalid' ));
  407. }
  408. imagedestroy( $newimage );
  409. // Set correct file permissions
  410. $stat = stat( dirname( $destfilename ));
  411. $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
  412. @ chmod( $destfilename, $perms );
  413. return $destfilename;
  414. }
  415. /**
  416. * Resize an image to make a thumbnail or intermediate size.
  417. *
  418. * The returned array has the file size, the image width, and image height. The
  419. * filter 'image_make_intermediate_size' can be used to hook in and change the
  420. * values of the returned array. The only parameter is the resized file path.
  421. *
  422. * @since 2.5.0
  423. *
  424. * @param string $file File path.
  425. * @param int $width Image width.
  426. * @param int $height Image height.
  427. * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
  428. * @return bool|array False, if no image was created. Metadata array on success.
  429. */
  430. function image_make_intermediate_size($file, $width, $height, $crop=false) {
  431. if ( $width || $height ) {
  432. $resized_file = image_resize($file, $width, $height, $crop);
  433. if ( !is_wp_error($resized_file) && $resized_file && $info = getimagesize($resized_file) ) {
  434. $resized_file = apply_filters('image_make_intermediate_size', $resized_file);
  435. return array(
  436. 'file' => wp_basename( $resized_file ),
  437. 'width' => $info[0],
  438. 'height' => $info[1],
  439. );
  440. }
  441. }
  442. return false;
  443. }
  444. /**
  445. * Retrieve the image's intermediate size (resized) path, width, and height.
  446. *
  447. * The $size parameter can be an array with the width and height respectively.
  448. * If the size matches the 'sizes' metadata array for width and height, then it
  449. * will be used. If there is no direct match, then the nearest image size larger
  450. * than the specified size will be used. If nothing is found, then the function
  451. * will break out and return false.
  452. *
  453. * The metadata 'sizes' is used for compatible sizes that can be used for the
  454. * parameter $size value.
  455. *
  456. * The url path will be given, when the $size parameter is a string.
  457. *
  458. * If you are passing an array for the $size, you should consider using
  459. * add_image_size() so that a cropped version is generated. It's much more
  460. * efficient than having to find the closest-sized image and then having the
  461. * browser scale down the image.
  462. *
  463. * @since 2.5.0
  464. * @see add_image_size()
  465. *
  466. * @param int $post_id Attachment ID for image.
  467. * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
  468. * @return bool|array False on failure or array of file path, width, and height on success.
  469. */
  470. function image_get_intermediate_size($post_id, $size='thumbnail') {
  471. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
  472. return false;
  473. // get the best one for a specified set of dimensions
  474. if ( is_array($size) && !empty($imagedata['sizes']) ) {
  475. foreach ( $imagedata['sizes'] as $_size => $data ) {
  476. // already cropped to width or height; so use this size
  477. if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
  478. $file = $data['file'];
  479. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  480. return compact( 'file', 'width', 'height' );
  481. }
  482. // add to lookup table: area => size
  483. $areas[$data['width'] * $data['height']] = $_size;
  484. }
  485. if ( !$size || !empty($areas) ) {
  486. // find for the smallest image not smaller than the desired size
  487. ksort($areas);
  488. foreach ( $areas as $_size ) {
  489. $data = $imagedata['sizes'][$_size];
  490. if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
  491. // Skip images with unexpectedly divergent aspect ratios (crops)
  492. // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
  493. $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
  494. // 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
  495. 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'] ) ) )
  496. continue;
  497. // If we're still here, then we're going to use this size
  498. $file = $data['file'];
  499. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  500. return compact( 'file', 'width', 'height' );
  501. }
  502. }
  503. }
  504. }
  505. if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
  506. return false;
  507. $data = $imagedata['sizes'][$size];
  508. // include the full filesystem path of the intermediate file
  509. if ( empty($data['path']) && !empty($data['file']) ) {
  510. $file_url = wp_get_attachment_url($post_id);
  511. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  512. $data['url'] = path_join( dirname($file_url), $data['file'] );
  513. }
  514. return $data;
  515. }
  516. /**
  517. * Get the available image sizes
  518. * @since 3.0.0
  519. * @return array Returns a filtered array of image size strings
  520. */
  521. function get_intermediate_image_sizes() {
  522. global $_wp_additional_image_sizes;
  523. $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
  524. if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
  525. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  526. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  527. }
  528. /**
  529. * Retrieve an image to represent an attachment.
  530. *
  531. * A mime icon for files, thumbnail or intermediate size for images.
  532. *
  533. * @since 2.5.0
  534. *
  535. * @param int $attachment_id Image attachment ID.
  536. * @param string $size Optional, default is 'thumbnail'.
  537. * @param bool $icon Optional, default is false. Whether it is an icon.
  538. * @return bool|array Returns an array (url, width, height), or false, if no image is available.
  539. */
  540. function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
  541. // get a thumbnail or intermediate image if there is one
  542. if ( $image = image_downsize($attachment_id, $size) )
  543. return $image;
  544. $src = false;
  545. if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
  546. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  547. $src_file = $icon_dir . '/' . wp_basename($src);
  548. @list($width, $height) = getimagesize($src_file);
  549. }
  550. if ( $src && $width && $height )
  551. return array( $src, $width, $height );
  552. return false;
  553. }
  554. /**
  555. * Get an HTML img element representing an image attachment
  556. *
  557. * While $size will accept an array, it is better to register a size with
  558. * add_image_size() so that a cropped version is generated. It's much more
  559. * efficient than having to find the closest-sized image and then having the
  560. * browser scale down the image.
  561. *
  562. * @see add_image_size()
  563. * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
  564. * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
  565. * @since 2.5.0
  566. *
  567. * @param int $attachment_id Image attachment ID.
  568. * @param string $size Optional, default is 'thumbnail'.
  569. * @param bool $icon Optional, default is false. Whether it is an icon.
  570. * @return string HTML img element or empty string on failure.
  571. */
  572. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  573. $html = '';
  574. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  575. if ( $image ) {
  576. list($src, $width, $height) = $image;
  577. $hwstring = image_hwstring($width, $height);
  578. if ( is_array($size) )
  579. $size = join('x', $size);
  580. $attachment = get_post($attachment_id);
  581. $default_attr = array(
  582. 'src' => $src,
  583. 'class' => "attachment-$size",
  584. 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
  585. 'title' => trim(strip_tags( $attachment->post_title )),
  586. );
  587. if ( empty($default_attr['alt']) )
  588. $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
  589. if ( empty($default_attr['alt']) )
  590. $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
  591. $attr = wp_parse_args($attr, $default_attr);
  592. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
  593. $attr = array_map( 'esc_attr', $attr );
  594. $html = rtrim("<img $hwstring");
  595. foreach ( $attr as $name => $value ) {
  596. $html .= " $name=" . '"' . $value . '"';
  597. }
  598. $html .= ' />';
  599. }
  600. return $html;
  601. }
  602. /**
  603. * Adds a 'wp-post-image' class to post thumbnails
  604. * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
  605. * dynamically add/remove itself so as to only filter post thumbnails
  606. *
  607. * @since 2.9.0
  608. * @param array $attr Attributes including src, class, alt, title
  609. * @return array
  610. */
  611. function _wp_post_thumbnail_class_filter( $attr ) {
  612. $attr['class'] .= ' wp-post-image';
  613. return $attr;
  614. }
  615. /**
  616. * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
  617. *
  618. * @since 2.9.0
  619. */
  620. function _wp_post_thumbnail_class_filter_add( $attr ) {
  621. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  622. }
  623. /**
  624. * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
  625. *
  626. * @since 2.9.0
  627. */
  628. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  629. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  630. }
  631. add_shortcode('wp_caption', 'img_caption_shortcode');
  632. add_shortcode('caption', 'img_caption_shortcode');
  633. /**
  634. * The Caption shortcode.
  635. *
  636. * Allows a plugin to replace the content that would otherwise be returned. The
  637. * filter is 'img_caption_shortcode' and passes an empty string, the attr
  638. * parameter and the content parameter values.
  639. *
  640. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  641. * 'caption'.
  642. *
  643. * @since 2.6.0
  644. *
  645. * @param array $attr Attributes attributed to the shortcode.
  646. * @param string $content Optional. Shortcode content.
  647. * @return string
  648. */
  649. function img_caption_shortcode($attr, $content = null) {
  650. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  651. if ( ! isset( $attr['caption'] ) ) {
  652. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  653. $content = $matches[1];
  654. $attr['caption'] = trim( $matches[2] );
  655. }
  656. }
  657. // Allow plugins/themes to override the default caption template.
  658. $output = apply_filters('img_caption_shortcode', '', $attr, $content);
  659. if ( $output != '' )
  660. return $output;
  661. extract(shortcode_atts(array(
  662. 'id' => '',
  663. 'align' => 'alignnone',
  664. 'width' => '',
  665. 'caption' => ''
  666. ), $attr));
  667. if ( 1 > (int) $width || empty($caption) )
  668. return $content;
  669. if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
  670. return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
  671. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
  672. }
  673. add_shortcode('gallery', 'gallery_shortcode');
  674. /**
  675. * The Gallery shortcode.
  676. *
  677. * This implements the functionality of the Gallery Shortcode for displaying
  678. * WordPress images on a post.
  679. *
  680. * @since 2.5.0
  681. *
  682. * @param array $attr Attributes of the shortcode.
  683. * @return string HTML content to display gallery.
  684. */
  685. function gallery_shortcode($attr) {
  686. $post = get_post();
  687. static $instance = 0;
  688. $instance++;
  689. // Allow plugins/themes to override the default gallery template.
  690. $output = apply_filters('post_gallery', '', $attr);
  691. if ( $output != '' )
  692. return $output;
  693. // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
  694. if ( isset( $attr['orderby'] ) ) {
  695. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  696. if ( !$attr['orderby'] )
  697. unset( $attr['orderby'] );
  698. }
  699. extract(shortcode_atts(array(
  700. 'order' => 'ASC',
  701. 'orderby' => 'menu_order ID',
  702. 'id' => $post->ID,
  703. 'itemtag' => 'dl',
  704. 'icontag' => 'dt',
  705. 'captiontag' => 'dd',
  706. 'columns' => 3,
  707. 'size' => 'thumbnail',
  708. 'ids' => '',
  709. 'include' => '',
  710. 'exclude' => ''
  711. ), $attr));
  712. $id = intval($id);
  713. if ( 'RAND' == $order )
  714. $orderby = 'none';
  715. if ( !empty( $ids ) ) {
  716. // 'ids' is explicitly ordered
  717. $orderby = 'post__in';
  718. $include = $ids;
  719. }
  720. if ( !empty($include) ) {
  721. $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  722. $attachments = array();
  723. foreach ( $_attachments as $key => $val ) {
  724. $attachments[$val->ID] = $_attachments[$key];
  725. }
  726. } elseif ( !empty($exclude) ) {
  727. $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  728. } else {
  729. $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  730. }
  731. if ( empty($attachments) )
  732. return '';
  733. if ( is_feed() ) {
  734. $output = "\n";
  735. foreach ( $attachments as $att_id => $attachment )
  736. $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  737. return $output;
  738. }
  739. $itemtag = tag_escape($itemtag);
  740. $captiontag = tag_escape($captiontag);
  741. $columns = intval($columns);
  742. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  743. $float = is_rtl() ? 'right' : 'left';
  744. $selector = "gallery-{$instance}";
  745. $gallery_style = $gallery_div = '';
  746. if ( apply_filters( 'use_default_gallery_style', true ) )
  747. $gallery_style = "
  748. <style type='text/css'>
  749. #{$selector} {
  750. margin: auto;
  751. }
  752. #{$selector} .gallery-item {
  753. float: {$float};
  754. margin-top: 10px;
  755. text-align: center;
  756. width: {$itemwidth}%;
  757. }
  758. #{$selector} img {
  759. border: 2px solid #cfcfcf;
  760. }
  761. #{$selector} .gallery-caption {
  762. margin-left: 0;
  763. }
  764. </style>
  765. <!-- see gallery_shortcode() in wp-includes/media.php -->";
  766. $size_class = sanitize_html_class( $size );
  767. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  768. $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
  769. $i = 0;
  770. foreach ( $attachments as $id => $attachment ) {
  771. $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
  772. $output .= "<{$itemtag} class='gallery-item'>";
  773. $output .= "
  774. <{$icontag} class='gallery-icon'>
  775. $link
  776. </{$icontag}>";
  777. if ( $captiontag && trim($attachment->post_excerpt) ) {
  778. $output .= "
  779. <{$captiontag} class='wp-caption-text gallery-caption'>
  780. " . wptexturize($attachment->post_excerpt) . "
  781. </{$captiontag}>";
  782. }
  783. $output .= "</{$itemtag}>";
  784. if ( $columns > 0 && ++$i % $columns == 0 )
  785. $output .= '<br style="clear: both" />';
  786. }
  787. $output .= "
  788. <br style='clear: both;' />
  789. </div>\n";
  790. return $output;
  791. }
  792. /**
  793. * Display previous image link that has the same post parent.
  794. *
  795. * @since 2.5.0
  796. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  797. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  798. * @return string HTML content.
  799. */
  800. function previous_image_link($size = 'thumbnail', $text = false) {
  801. adjacent_image_link(true, $size, $text);
  802. }
  803. /**
  804. * Display next image link that has the same post parent.
  805. *
  806. * @since 2.5.0
  807. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  808. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  809. * @return string HTML content.
  810. */
  811. function next_image_link($size = 'thumbnail', $text = false) {
  812. adjacent_image_link(false, $size, $text);
  813. }
  814. /**
  815. * Display next or previous image link that has the same post parent.
  816. *
  817. * Retrieves the current attachment object from the $post global.
  818. *
  819. * @since 2.5.0
  820. *
  821. * @param bool $prev Optional. Default is true to display previous link, false for next.
  822. */
  823. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  824. $post = get_post();
  825. $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' ) ) );
  826. foreach ( $attachments as $k => $attachment )
  827. if ( $attachment->ID == $post->ID )
  828. break;
  829. $k = $prev ? $k - 1 : $k + 1;
  830. if ( isset($attachments[$k]) )
  831. echo wp_get_attachment_link($attachments[$k]->ID, $size, true, false, $text);
  832. }
  833. /**
  834. * Retrieve taxonomies attached to the attachment.
  835. *
  836. * @since 2.5.0
  837. *
  838. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  839. * @return array Empty array on failure. List of taxonomies on success.
  840. */
  841. function get_attachment_taxonomies($attachment) {
  842. if ( is_int( $attachment ) )
  843. $attachment = get_post($attachment);
  844. else if ( is_array($attachment) )
  845. $attachment = (object) $attachment;
  846. if ( ! is_object($attachment) )
  847. return array();
  848. $filename = basename($attachment->guid);
  849. $objects = array('attachment');
  850. if ( false !== strpos($filename, '.') )
  851. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  852. if ( !empty($attachment->post_mime_type) ) {
  853. $objects[] = 'attachment:' . $attachment->post_mime_type;
  854. if ( false !== strpos($attachment->post_mime_type, '/') )
  855. foreach ( explode('/', $attachment->post_mime_type) as $token )
  856. if ( !empty($token) )
  857. $objects[] = "attachment:$token";
  858. }
  859. $taxonomies = array();
  860. foreach ( $objects as $object )
  861. if ( $taxes = get_object_taxonomies($object) )
  862. $taxonomies = array_merge($taxonomies, $taxes);
  863. return array_unique($taxonomies);
  864. }
  865. /**
  866. * Return all of the taxonomy names that are registered for attachments.
  867. *
  868. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  869. *
  870. * @since 3.5.0
  871. * @see get_attachment_taxonomies()
  872. * @uses get_taxonomies()
  873. *
  874. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  875. * @return array The names of all taxonomy of $object_type.
  876. */
  877. function get_taxonomies_for_attachments( $output = 'names' ) {
  878. $taxonomies = array();
  879. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  880. foreach ( $taxonomy->object_type as $object_type ) {
  881. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  882. if ( 'names' == $output )
  883. $taxonomies[] = $taxonomy->name;
  884. else
  885. $taxonomies[ $taxonomy->name ] = $taxonomy;
  886. break;
  887. }
  888. }
  889. }
  890. return $taxonomies;
  891. }
  892. /**
  893. * Check if the installed version of GD supports particular image type
  894. *
  895. * @since 2.9.0
  896. *
  897. * @param string $mime_type
  898. * @return bool
  899. */
  900. function gd_edit_image_support($mime_type) {
  901. if ( function_exists('imagetypes') ) {
  902. switch( $mime_type ) {
  903. case 'image/jpeg':
  904. return (imagetypes() & IMG_JPG) != 0;
  905. case 'image/png':
  906. return (imagetypes() & IMG_PNG) != 0;
  907. case 'image/gif':
  908. return (imagetypes() & IMG_GIF) != 0;
  909. }
  910. } else {
  911. switch( $mime_type ) {
  912. case 'image/jpeg':
  913. return function_exists('imagecreatefromjpeg');
  914. case 'image/png':
  915. return function_exists('imagecreatefrompng');
  916. case 'image/gif':
  917. return function_exists('imagecreatefromgif');
  918. }
  919. }
  920. return false;
  921. }
  922. /**
  923. * Create new GD image resource with transparency support
  924. *
  925. * @since 2.9.0
  926. *
  927. * @param int $width Image width
  928. * @param int $height Image height
  929. * @return image resource
  930. */
  931. function wp_imagecreatetruecolor($width, $height) {
  932. $img = imagecreatetruecolor($width, $height);
  933. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  934. imagealphablending($img, false);
  935. imagesavealpha($img, true);
  936. }
  937. return $img;
  938. }
  939. /**
  940. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  941. *
  942. * @since 2.9.0
  943. * @see WP_Embed::register_handler()
  944. */
  945. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  946. global $wp_embed;
  947. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  948. }
  949. /**
  950. * Unregister a previously registered embed handler.
  951. *
  952. * @since 2.9.0
  953. * @see WP_Embed::unregister_handler()
  954. */
  955. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  956. global $wp_embed;
  957. $wp_embed->unregister_handler( $id, $priority );
  958. }
  959. /**
  960. * Create default array of embed parameters.
  961. *
  962. * The width defaults to the content width as specified by the theme. If the
  963. * theme does not specify a content width, then 500px is used.
  964. *
  965. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  966. *
  967. * The 'embed_defaults' filter can be used to adjust either of these values.
  968. *
  969. * @since 2.9.0
  970. *
  971. * @return array Default embed parameters.
  972. */
  973. function wp_embed_defaults() {
  974. if ( ! empty( $GLOBALS['content_width'] ) )
  975. $width = (int) $GLOBALS['content_width'];
  976. if ( empty( $width ) )
  977. $width = 500;
  978. $height = min( ceil( $width * 1.5 ), 1000 );
  979. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  980. }
  981. /**
  982. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  983. *
  984. * @since 2.9.0
  985. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  986. *
  987. * @param int $example_width The width of an example embed.
  988. * @param int $example_height The height of an example embed.
  989. * @param int $max_width The maximum allowed width.
  990. * @param int $max_height The maximum allowed height.
  991. * @return array The maximum possible width and height based on the example ratio.
  992. */
  993. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  994. $example_width = (int) $example_width;
  995. $example_height = (int) $example_height;
  996. $max_width = (int) $max_width;
  997. $max_height = (int) $max_height;
  998. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  999. }
  1000. /**
  1001. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1002. *
  1003. * @since 2.9.0
  1004. * @see WP_oEmbed
  1005. *
  1006. * @uses _wp_oembed_get_object()
  1007. * @uses WP_oEmbed::get_html()
  1008. *
  1009. * @param string $url The URL that should be embedded.
  1010. * @param array $args Additional arguments and parameters.
  1011. * @return bool|string False on failure or the embed HTML on success.
  1012. */
  1013. function wp_oembed_get( $url, $args = '' ) {
  1014. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1015. $oembed = _wp_oembed_get_object();
  1016. return $oembed->get_html( $url, $args );
  1017. }
  1018. /**
  1019. * Adds a URL format and oEmbed provider URL pair.
  1020. *
  1021. * @since 2.9.0
  1022. * @see WP_oEmbed
  1023. *
  1024. * @uses _wp_oembed_get_object()
  1025. *
  1026. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1027. * @param string $provider The URL to the oEmbed provider.
  1028. * @param boolean $regex Whether the $format parameter is in a regex format.
  1029. */
  1030. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1031. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1032. $oembed = _wp_oembed_get_object();
  1033. $oembed->providers[$format] = array( $provider, $regex );
  1034. }
  1035. /**
  1036. * Removes an oEmbed provider.
  1037. *
  1038. * @since 3.5
  1039. * @see WP_oEmbed
  1040. *
  1041. * @uses _wp_oembed_get_object()
  1042. *
  1043. * @param string $format The URL format for the oEmbed provider to remove.
  1044. */
  1045. function wp_oembed_remove_provider( $format ) {
  1046. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1047. $oembed = _wp_oembed_get_object();
  1048. if ( isset( $oembed->providers[ $format ] ) ) {
  1049. unset( $oembed->providers[ $format ] );
  1050. return true;
  1051. }
  1052. return false;
  1053. }
  1054. /**
  1055. * Determines if default embed handlers should be loaded.
  1056. *
  1057. * Checks to make sure that the embeds library hasn't already been loaded. If
  1058. * it hasn't, then it will load the embeds library.
  1059. *
  1060. * @since 2.9.0
  1061. */
  1062. function wp_maybe_load_embeds() {
  1063. if ( ! apply_filters( 'load_default_embeds', true ) )
  1064. return;
  1065. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  1066. }
  1067. /**
  1068. * The Google Video embed handler callback. Google Video does not support oEmbed.
  1069. *
  1070. * @see WP_Embed::register_handler()
  1071. * @see WP_Embed::shortcode()
  1072. *
  1073. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1074. * @param array $attr Embed attributes.
  1075. * @param string $url The original URL that was matched by the regex.
  1076. * @param array $rawattr The original unmodified attributes.
  1077. * @return string The embed HTML.
  1078. */
  1079. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1080. // If the user supplied a fixed width AND height, use it
  1081. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1082. $width = (int) $rawattr['width'];
  1083. $height = (int) $rawattr['height'];
  1084. } else {
  1085. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1086. }
  1087. 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 );
  1088. }
  1089. /**
  1090. * {@internal Missing Short Description}}
  1091. *
  1092. * @since 2.3.0
  1093. *
  1094. * @param unknown_type $size
  1095. * @return unknown
  1096. */
  1097. function wp_convert_hr_to_bytes( $size ) {
  1098. $size = strtolower( $size );
  1099. $bytes = (int) $size;
  1100. if ( strpos( $size, 'k' ) !== false )
  1101. $bytes = intval( $size ) * 1024;
  1102. elseif ( strpos( $size, 'm' ) !== false )
  1103. $bytes = intval($size) * 1024 * 1024;
  1104. elseif ( strpos( $size, 'g' ) !== false )
  1105. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  1106. return $bytes;
  1107. }
  1108. /**
  1109. * {@internal Missing Short Description}}
  1110. *
  1111. * @since 2.3.0
  1112. *
  1113. * @param unknown_type $bytes
  1114. * @return unknown
  1115. */
  1116. function wp_convert_bytes_to_hr( $bytes ) {
  1117. $units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' );
  1118. $log = log( $bytes, 1024 );
  1119. $power = (int) $log;
  1120. $size = pow( 1024, $log - $power );
  1121. return $size . $units[$power];
  1122. }
  1123. /**
  1124. * {@internal Missing Short Description}}
  1125. *
  1126. * @since 2.5.0
  1127. *
  1128. * @return unknown
  1129. */
  1130. function wp_max_upload_size() {
  1131. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1132. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1133. $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1134. return $bytes;
  1135. }
  1136. /**
  1137. * Prints default plupload arguments.
  1138. *
  1139. * @since 3.4.0
  1140. */
  1141. function wp_plupload_default_settings() {
  1142. global $wp_scripts;
  1143. $max_upload_size = wp_max_upload_size();
  1144. $defaults = array(
  1145. 'runtimes' => 'html5,silverlight,flash,html4',
  1146. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  1147. 'multiple_queues' => true,
  1148. 'max_file_size' => $max_upload_size . 'b',
  1149. 'url' => admin_url( 'admin-ajax.php', 'relative' ),
  1150. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  1151. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1152. 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  1153. 'multipart' => true,
  1154. 'urlstream_upload' => true,
  1155. );
  1156. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  1157. $params = array(
  1158. 'action' => 'upload-attachment',
  1159. );
  1160. $params = apply_filters( 'plupload_default_params', $params );
  1161. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  1162. $defaults['multipart_params'] = $params;
  1163. $settings = array(
  1164. 'defaults' => $defaults,
  1165. 'browser' => array(
  1166. 'mobile' => wp_is_mobile(),
  1167. 'supported' => _device_can_upload(),
  1168. ),
  1169. );
  1170. $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  1171. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  1172. if ( $data )
  1173. $script = "$data\n$script";
  1174. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1175. }
  1176. add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  1177. /**
  1178. * Prepares an attachment post object for JS, where it is expected
  1179. * to be JSON-encoded and fit into an Attachment model.
  1180. *
  1181. * @since 3.5.0
  1182. *
  1183. * @param mixed $attachment Attachment ID or object.
  1184. * @return array Array of attachment details.
  1185. */
  1186. function wp_prepare_attachment_for_js( $attachment ) {
  1187. if ( ! $attachment = get_post( $attachment ) )
  1188. return;
  1189. if ( 'attachment' != $attachment->post_type )
  1190. return;
  1191. $meta = wp_get_attachment_metadata( $attachment->ID );
  1192. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  1193. $attachment_url = wp_get_attachment_url( $attachment->ID );
  1194. $response = array(
  1195. 'id' => $attachment->ID,
  1196. 'title' => $attachment->post_title,
  1197. 'filename' => basename( $attachment->guid ),
  1198. 'url' => $attachment_url,
  1199. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  1200. 'author' => $attachment->post_author,
  1201. 'description' => $attachment->post_content,
  1202. 'caption' => $attachment->post_excerpt,
  1203. 'name' => $attachment->post_name,
  1204. 'status' => $attachment->post_status,
  1205. 'uploadedTo' => $attachment->post_parent,
  1206. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  1207. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  1208. 'mime' => $attachment->post_mime_type,
  1209. 'type' => $type,
  1210. 'subtype' => $subtype,
  1211. 'icon' => wp_mime_type_icon( $attachment->ID ),
  1212. );
  1213. if ( $meta && 'image' === $type ) {
  1214. $sizes = array();
  1215. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  1216. if ( isset( $meta['sizes'] ) ) {
  1217. foreach ( $meta['sizes'] as $slug => $size ) {
  1218. $sizes[ $slug ] = array(
  1219. 'height' => $size['height'],
  1220. 'width' => $size['width'],
  1221. 'url' => $base_url . $size['file'],
  1222. 'orientation' => $size['height'] > $size['width'] ? 'portrait' : 'landscape',
  1223. );
  1224. }
  1225. }
  1226. $response = array_merge( $response, array(
  1227. 'height' => $meta['height'],
  1228. 'width' => $meta['width'],
  1229. 'sizes' => $sizes,
  1230. 'orientation' => $meta['height'] > $meta['width'] ? 'portrait' : 'landscape',
  1231. ) );
  1232. }
  1233. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  1234. }
  1235. /**
  1236. * Prints the templates used in the media manager.
  1237. *
  1238. * @since 3.5.0
  1239. */
  1240. function wp_print_media_templates( $attachment ) {
  1241. ?>
  1242. <script type="text/html" id="tmpl-media-modal">
  1243. <div class="media-modal">
  1244. <div class="media-modal-header">
  1245. <h3><%- title %></h3>
  1246. <a class="media-modal-close" href="" title="<?php esc_attr_e('Close'); ?>"><?php echo 'Close'; ?></a>
  1247. </div>
  1248. <div class="media-modal-content"></div>
  1249. </div>
  1250. <div class="media-modal-backdrop"></div>
  1251. </script>
  1252. <script type="text/html" id="tmpl-media-workspace">
  1253. <div class="upload-attachments">
  1254. <% if ( selectOne ) { %>
  1255. <h3><?php _e( 'Drop a file here' ); ?></h3>
  1256. <span><?php _ex( 'or', 'Uploader: Drop a file here - or - Select a File' ); ?></span>
  1257. <a href="#" class="button-secondary"><?php _e( 'Select a File' ); ?></a>
  1258. <% } else { %>
  1259. <h3><?php _e( 'Drop files here' ); ?></h3>
  1260. <span><?php _ex( 'or', 'Uploader: Drop files here - or - Select Files' ); ?></span>
  1261. <a href="#" class="button-secondary"><?php _e( 'Select Files' ); ?></a>
  1262. <% } %>
  1263. <div class="media-progress-bar"><div></div></div>
  1264. </div>
  1265. </script>
  1266. <script type="text/html" id="tmpl-attachments">
  1267. <div class="attachments-header">
  1268. <h3><%- directions %></h3>

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