PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-admin/includes/image.php

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