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

/wp-admin/includes/image.php

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