PageRenderTime 34ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/wordpress3.4.2/wp-admin/includes/image.php

https://bitbucket.org/ch3tag/mothers
PHP | 463 lines | 250 code | 57 blank | 156 comment | 71 complexity | 287986f147e36097cb6352cbbd7aa5ae MD5 | raw file
  1. <?php
  2. /**
  3. * File contains all the administration image manipulation functions.
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. */
  8. /**
  9. * Create a thumbnail from an Image given a maximum side size.
  10. *
  11. * This function can handle most image file formats which PHP supports. If PHP
  12. * does not have the functionality to save in a file of the same format, the
  13. * thumbnail will be created as a jpeg.
  14. *
  15. * @since 1.2.0
  16. *
  17. * @param mixed $file Filename of the original image, Or attachment id.
  18. * @param int $max_side Maximum length of a single side for the thumbnail.
  19. * @param mixed $deprecated Never used.
  20. * @return string Thumbnail path on success, Error string on failure.
  21. */
  22. function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) {
  23. if ( !empty( $deprecated ) )
  24. _deprecated_argument( __FUNCTION__, '1.2' );
  25. $thumbpath = image_resize( $file, $max_side, $max_side );
  26. return apply_filters( 'wp_create_thumbnail', $thumbpath );
  27. }
  28. /**
  29. * Crop an Image to a given size.
  30. *
  31. * @since 2.1.0
  32. *
  33. * @param string|int $src The source file or Attachment ID.
  34. * @param int $src_x The start x position to crop from.
  35. * @param int $src_y The start y position to crop from.
  36. * @param int $src_w The width to crop.
  37. * @param int $src_h The height to crop.
  38. * @param int $dst_w The destination width.
  39. * @param int $dst_h The destination height.
  40. * @param int $src_abs Optional. If the source crop points are absolute.
  41. * @param string $dst_file Optional. The destination file to write to.
  42. * @return string|WP_Error|false New filepath on success, WP_Error or false on failure.
  43. */
  44. function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
  45. if ( is_numeric( $src ) ) { // Handle int as attachment ID
  46. $src_file = get_attached_file( $src );
  47. if ( ! file_exists( $src_file ) ) {
  48. // If the file doesn't exist, attempt a url fopen on the src link.
  49. // This can occur with certain file replication plugins.
  50. $post = get_post( $src );
  51. $image_type = $post->post_mime_type;
  52. $src = load_image_to_edit( $src, $post->post_mime_type, 'full' );
  53. } else {
  54. $size = @getimagesize( $src_file );
  55. $image_type = ( $size ) ? $size['mime'] : '';
  56. $src = wp_load_image( $src_file );
  57. }
  58. } else {
  59. $size = @getimagesize( $src );
  60. $image_type = ( $size ) ? $size['mime'] : '';
  61. $src = wp_load_image( $src );
  62. }
  63. if ( ! is_resource( $src ) )
  64. return new WP_Error( 'error_loading_image', $src, $src_file );
  65. $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
  66. if ( $src_abs ) {
  67. $src_w -= $src_x;
  68. $src_h -= $src_y;
  69. }
  70. if ( function_exists( 'imageantialias' ) )
  71. imageantialias( $dst, true );
  72. imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  73. imagedestroy( $src ); // Free up memory
  74. if ( ! $dst_file )
  75. $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
  76. if ( 'image/png' != $image_type )
  77. $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
  78. // The directory containing the original file may no longer exist when
  79. // using a replication plugin.
  80. wp_mkdir_p( dirname( $dst_file ) );
  81. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
  82. if ( 'image/png' == $image_type && imagepng( $dst, $dst_file ) )
  83. return $dst_file;
  84. elseif ( imagejpeg( $dst, $dst_file, apply_filters( 'jpeg_quality', 90, 'wp_crop_image' ) ) )
  85. return $dst_file;
  86. else
  87. return false;
  88. }
  89. /**
  90. * Generate post thumbnail attachment meta data.
  91. *
  92. * @since 2.1.0
  93. *
  94. * @param int $attachment_id Attachment Id to process.
  95. * @param string $file Filepath of the Attached image.
  96. * @return mixed Metadata for attachment.
  97. */
  98. function wp_generate_attachment_metadata( $attachment_id, $file ) {
  99. $attachment = get_post( $attachment_id );
  100. $metadata = array();
  101. if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
  102. $imagesize = getimagesize( $file );
  103. $metadata['width'] = $imagesize[0];
  104. $metadata['height'] = $imagesize[1];
  105. list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
  106. $metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
  107. // Make the file path relative to the upload dir
  108. $metadata['file'] = _wp_relative_upload_path($file);
  109. // make thumbnails and other intermediate sizes
  110. global $_wp_additional_image_sizes;
  111. foreach ( get_intermediate_image_sizes() as $s ) {
  112. $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
  113. if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
  114. $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
  115. else
  116. $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
  117. if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
  118. $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
  119. else
  120. $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
  121. if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
  122. $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
  123. else
  124. $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
  125. }
  126. $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
  127. foreach ($sizes as $size => $size_data ) {
  128. $resized = image_make_intermediate_size( $file, $size_data['width'], $size_data['height'], $size_data['crop'] );
  129. if ( $resized )
  130. $metadata['sizes'][$size] = $resized;
  131. }
  132. // fetch additional metadata from exif/iptc
  133. $image_meta = wp_read_image_metadata( $file );
  134. if ( $image_meta )
  135. $metadata['image_meta'] = $image_meta;
  136. }
  137. return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
  138. }
  139. /**
  140. * Calculated the new dimensions for a downsampled image.
  141. *
  142. * @since 2.0.0
  143. * @see wp_constrain_dimensions()
  144. *
  145. * @param int $width Current width of the image
  146. * @param int $height Current height of the image
  147. * @return mixed Array(height,width) of shrunk dimensions.
  148. */
  149. function get_udims( $width, $height) {
  150. return wp_constrain_dimensions( $width, $height, 128, 96 );
  151. }
  152. /**
  153. * Convert a fraction string to a decimal.
  154. *
  155. * @since 2.5.0
  156. *
  157. * @param string $str
  158. * @return int|float
  159. */
  160. function wp_exif_frac2dec($str) {
  161. @list( $n, $d ) = explode( '/', $str );
  162. if ( !empty($d) )
  163. return $n / $d;
  164. return $str;
  165. }
  166. /**
  167. * Convert the exif date format to a unix timestamp.
  168. *
  169. * @since 2.5.0
  170. *
  171. * @param string $str
  172. * @return int
  173. */
  174. function wp_exif_date2ts($str) {
  175. @list( $date, $time ) = explode( ' ', trim($str) );
  176. @list( $y, $m, $d ) = explode( ':', $date );
  177. return strtotime( "{$y}-{$m}-{$d} {$time}" );
  178. }
  179. /**
  180. * Get extended image metadata, exif or iptc as available.
  181. *
  182. * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
  183. * created_timestamp, focal_length, shutter_speed, and title.
  184. *
  185. * The IPTC metadata that is retrieved is APP13, credit, byline, created date
  186. * and time, caption, copyright, and title. Also includes FNumber, Model,
  187. * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
  188. *
  189. * @todo Try other exif libraries if available.
  190. * @since 2.5.0
  191. *
  192. * @param string $file
  193. * @return bool|array False on failure. Image metadata array on success.
  194. */
  195. function wp_read_image_metadata( $file ) {
  196. if ( ! file_exists( $file ) )
  197. return false;
  198. list( , , $sourceImageType ) = getimagesize( $file );
  199. // exif contains a bunch of data we'll probably never need formatted in ways
  200. // that are difficult to use. We'll normalize it and just extract the fields
  201. // that are likely to be useful. Fractions and numbers are converted to
  202. // floats, dates to unix timestamps, and everything else to strings.
  203. $meta = array(
  204. 'aperture' => 0,
  205. 'credit' => '',
  206. 'camera' => '',
  207. 'caption' => '',
  208. 'created_timestamp' => 0,
  209. 'copyright' => '',
  210. 'focal_length' => 0,
  211. 'iso' => 0,
  212. 'shutter_speed' => 0,
  213. 'title' => '',
  214. );
  215. // read iptc first, since it might contain data not available in exif such
  216. // as caption, description etc
  217. if ( is_callable( 'iptcparse' ) ) {
  218. getimagesize( $file, $info );
  219. if ( ! empty( $info['APP13'] ) ) {
  220. $iptc = iptcparse( $info['APP13'] );
  221. // headline, "A brief synopsis of the caption."
  222. if ( ! empty( $iptc['2#105'][0] ) )
  223. $meta['title'] = utf8_encode( trim( $iptc['2#105'][0] ) );
  224. // title, "Many use the Title field to store the filename of the image, though the field may be used in many ways."
  225. elseif ( ! empty( $iptc['2#005'][0] ) )
  226. $meta['title'] = utf8_encode( trim( $iptc['2#005'][0] ) );
  227. if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
  228. $caption = utf8_encode( trim( $iptc['2#120'][0] ) );
  229. if ( empty( $meta['title'] ) ) {
  230. // Assume the title is stored in 2:120 if it's short.
  231. if ( strlen( $caption ) < 80 )
  232. $meta['title'] = $caption;
  233. else
  234. $meta['caption'] = $caption;
  235. } elseif ( $caption != $meta['title'] ) {
  236. $meta['caption'] = $caption;
  237. }
  238. }
  239. if ( ! empty( $iptc['2#110'][0] ) ) // credit
  240. $meta['credit'] = utf8_encode(trim($iptc['2#110'][0]));
  241. elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
  242. $meta['credit'] = utf8_encode(trim($iptc['2#080'][0]));
  243. if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time
  244. $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
  245. if ( ! empty( $iptc['2#116'][0] ) ) // copyright
  246. $meta['copyright'] = utf8_encode( trim( $iptc['2#116'][0] ) );
  247. }
  248. }
  249. // fetch additional info from exif if available
  250. if ( is_callable( 'exif_read_data' ) && in_array( $sourceImageType, apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ) ) ) {
  251. $exif = @exif_read_data( $file );
  252. if ( !empty( $exif['Title'] ) )
  253. $meta['title'] = utf8_encode( trim( $exif['Title'] ) );
  254. if ( ! empty( $exif['ImageDescription'] ) ) {
  255. if ( empty( $meta['title'] ) && strlen( $exif['ImageDescription'] ) < 80 ) {
  256. // Assume the title is stored in ImageDescription
  257. $meta['title'] = utf8_encode( trim( $exif['ImageDescription'] ) );
  258. if ( ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] )
  259. $meta['caption'] = utf8_encode( trim( $exif['COMPUTED']['UserComment'] ) );
  260. } elseif ( trim( $exif['ImageDescription'] ) != $meta['title'] ) {
  261. $meta['caption'] = utf8_encode( trim( $exif['ImageDescription'] ) );
  262. }
  263. } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
  264. $meta['caption'] = utf8_encode( trim( $exif['Comments'] ) );
  265. }
  266. if ( ! empty( $exif['Artist'] ) )
  267. $meta['credit'] = utf8_encode( trim( $exif['Artist'] ) );
  268. elseif ( ! empty($exif['Author'] ) )
  269. $meta['credit'] = utf8_encode( trim( $exif['Author'] ) );
  270. if ( ! empty( $exif['Copyright'] ) )
  271. $meta['copyright'] = utf8_encode( trim( $exif['Copyright'] ) );
  272. if ( ! empty($exif['FNumber'] ) )
  273. $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
  274. if ( ! empty($exif['Model'] ) )
  275. $meta['camera'] = utf8_encode( trim( $exif['Model'] ) );
  276. if ( ! empty($exif['DateTimeDigitized'] ) )
  277. $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized'] );
  278. if ( ! empty($exif['FocalLength'] ) )
  279. $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
  280. if ( ! empty($exif['ISOSpeedRatings'] ) ) {
  281. $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
  282. $meta['iso'] = utf8_encode( trim( $meta['iso'] ) );
  283. }
  284. if ( ! empty($exif['ExposureTime'] ) )
  285. $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
  286. }
  287. return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
  288. }
  289. /**
  290. * Validate that file is an image.
  291. *
  292. * @since 2.5.0
  293. *
  294. * @param string $path File path to test if valid image.
  295. * @return bool True if valid image, false if not valid image.
  296. */
  297. function file_is_valid_image($path) {
  298. $size = @getimagesize($path);
  299. return !empty($size);
  300. }
  301. /**
  302. * Validate that file is suitable for displaying within a web page.
  303. *
  304. * @since 2.5.0
  305. * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
  306. *
  307. * @param string $path File path to test.
  308. * @return bool True if suitable, false if not suitable.
  309. */
  310. function file_is_displayable_image($path) {
  311. $info = @getimagesize($path);
  312. if ( empty($info) )
  313. $result = false;
  314. elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed
  315. $result = false;
  316. else
  317. $result = true;
  318. return apply_filters('file_is_displayable_image', $result, $path);
  319. }
  320. /**
  321. * Load an image resource for editing.
  322. *
  323. * @since 2.9.0
  324. *
  325. * @param string $attachment_id Attachment ID.
  326. * @param string $mime_type Image mime type.
  327. * @param string $size Optional. Image size, defaults to 'full'.
  328. * @return resource|false The resulting image resource on success, false on failure.
  329. */
  330. function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
  331. $filepath = _load_image_to_edit_path( $attachment_id, $size );
  332. if ( empty( $filepath ) )
  333. return false;
  334. switch ( $mime_type ) {
  335. case 'image/jpeg':
  336. $image = imagecreatefromjpeg($filepath);
  337. break;
  338. case 'image/png':
  339. $image = imagecreatefrompng($filepath);
  340. break;
  341. case 'image/gif':
  342. $image = imagecreatefromgif($filepath);
  343. break;
  344. default:
  345. $image = false;
  346. break;
  347. }
  348. if ( is_resource($image) ) {
  349. $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size);
  350. if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  351. imagealphablending($image, false);
  352. imagesavealpha($image, true);
  353. }
  354. }
  355. return $image;
  356. }
  357. /**
  358. * Retrieve the path or url of an attachment's attached file.
  359. *
  360. * If the attached file is not present on the local filesystem (usually due to replication plugins),
  361. * then the url of the file is returned if url fopen is supported.
  362. *
  363. * @since 3.4.0
  364. * @access private
  365. *
  366. * @param string $attachment_id Attachment ID.
  367. * @param string $size Optional. Image size, defaults to 'full'.
  368. * @return string|false File path or url on success, false on failure.
  369. */
  370. function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
  371. $filepath = get_attached_file( $attachment_id );
  372. if ( $filepath && file_exists( $filepath ) ) {
  373. if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
  374. $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
  375. }
  376. } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
  377. $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
  378. }
  379. return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
  380. }
  381. /**
  382. * Copy an existing image file.
  383. *
  384. * @since 3.4.0
  385. * @access private
  386. *
  387. * @param string $attachment_id Attachment ID.
  388. * @return string|false New file path on success, false on failure.
  389. */
  390. function _copy_image_file( $attachment_id ) {
  391. $dst_file = $src_file = get_attached_file( $attachment_id );
  392. if ( ! file_exists( $src_file ) )
  393. $src_file = _load_image_to_edit_path( $attachment_id );
  394. if ( $src_file ) {
  395. $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
  396. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
  397. // The directory containing the original file may no longer exist when
  398. // using a replication plugin.
  399. wp_mkdir_p( dirname( $dst_file ) );
  400. if ( ! @copy( $src_file, $dst_file ) )
  401. $dst_file = false;
  402. } else {
  403. $dst_file = false;
  404. }
  405. return $dst_file;
  406. }