image.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. }
  40. $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
  41. if ( is_wp_error( $src ) ) {
  42. return $src;
  43. }
  44. if ( ! $dst_file ) {
  45. $dst_file = str_replace( wp_basename( $src_file ), 'cropped-' . wp_basename( $src_file ), $src_file );
  46. }
  47. /*
  48. * The directory containing the original file may no longer exist when
  49. * using a replication plugin.
  50. */
  51. wp_mkdir_p( dirname( $dst_file ) );
  52. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
  53. $result = $editor->save( $dst_file );
  54. if ( is_wp_error( $result ) ) {
  55. return $result;
  56. }
  57. return $dst_file;
  58. }
  59. /**
  60. * Compare the existing image sub-sizes (as saved in the attachment meta)
  61. * to the currently registered image sub-sizes, and return the difference.
  62. *
  63. * Registered sub-sizes that are larger than the image are skipped.
  64. *
  65. * @since 5.3.0
  66. *
  67. * @param int $attachment_id The image attachment post ID.
  68. * @return array An array of the image sub-sizes that are currently defined but don't exist for this image.
  69. */
  70. function wp_get_missing_image_subsizes( $attachment_id ) {
  71. if ( ! wp_attachment_is_image( $attachment_id ) ) {
  72. return array();
  73. }
  74. $registered_sizes = wp_get_registered_image_subsizes();
  75. $image_meta = wp_get_attachment_metadata( $attachment_id );
  76. // Meta error?
  77. if ( empty( $image_meta ) ) {
  78. return $registered_sizes;
  79. }
  80. // Use the originally uploaded image dimensions as full_width and full_height.
  81. if ( ! empty( $image_meta['original_image'] ) ) {
  82. $image_file = wp_get_original_image_path( $attachment_id );
  83. $imagesize = @getimagesize( $image_file );
  84. }
  85. if ( ! empty( $imagesize ) ) {
  86. $full_width = $imagesize[0];
  87. $full_height = $imagesize[1];
  88. } else {
  89. $full_width = (int) $image_meta['width'];
  90. $full_height = (int) $image_meta['height'];
  91. }
  92. $possible_sizes = array();
  93. // Skip registered sizes that are too large for the uploaded image.
  94. foreach ( $registered_sizes as $size_name => $size_data ) {
  95. if ( image_resize_dimensions( $full_width, $full_height, $size_data['width'], $size_data['height'], $size_data['crop'] ) ) {
  96. $possible_sizes[ $size_name ] = $size_data;
  97. }
  98. }
  99. if ( empty( $image_meta['sizes'] ) ) {
  100. $image_meta['sizes'] = array();
  101. }
  102. // Remove sizes that already exist. Only checks for matching "size names".
  103. // It is possible that the dimensions for a particular size name have changed.
  104. // For example the user has changed the values on the Settings -> Media screen.
  105. // However we keep the old sub-sizes with the previous dimensions
  106. // as the image may have been used in an older post.
  107. $missing_sizes = array_diff_key( $possible_sizes, $image_meta['sizes'] );
  108. /**
  109. * Filters the array of missing image sub-sizes for an uploaded image.
  110. *
  111. * @since 5.3.0
  112. *
  113. * @param array $missing_sizes Array with the missing image sub-sizes.
  114. * @param array $image_meta The image meta data.
  115. * @param int $attachment_id The image attachment post ID.
  116. */
  117. return apply_filters( 'wp_get_missing_image_subsizes', $missing_sizes, $image_meta, $attachment_id );
  118. }
  119. /**
  120. * If any of the currently registered image sub-sizes are missing,
  121. * create them and update the image meta data.
  122. *
  123. * @since 5.3.0
  124. *
  125. * @param int $attachment_id The image attachment post ID.
  126. * @return array|WP_Error The updated image meta data array or WP_Error object
  127. * if both the image meta and the attached file are missing.
  128. */
  129. function wp_update_image_subsizes( $attachment_id ) {
  130. $image_meta = wp_get_attachment_metadata( $attachment_id );
  131. $image_file = wp_get_original_image_path( $attachment_id );
  132. if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
  133. // Previously failed upload?
  134. // If there is an uploaded file, make all sub-sizes and generate all of the attachment meta.
  135. if ( ! empty( $image_file ) ) {
  136. $image_meta = wp_create_image_subsizes( $image_file, $attachment_id );
  137. } else {
  138. return new WP_Error( 'invalid_attachment', __( 'The attached file cannot be found.' ) );
  139. }
  140. } else {
  141. $missing_sizes = wp_get_missing_image_subsizes( $attachment_id );
  142. if ( empty( $missing_sizes ) ) {
  143. return $image_meta;
  144. }
  145. // This also updates the image meta.
  146. $image_meta = _wp_make_subsizes( $missing_sizes, $image_file, $image_meta, $attachment_id );
  147. }
  148. /** This filter is documented in wp-admin/includes/image.php */
  149. $image_meta = apply_filters( 'wp_generate_attachment_metadata', $image_meta, $attachment_id, 'update' );
  150. // Save the updated metadata.
  151. wp_update_attachment_metadata( $attachment_id, $image_meta );
  152. return $image_meta;
  153. }
  154. /**
  155. * Updates the attached file and image meta data when the original image was edited.
  156. *
  157. * @since 5.3.0
  158. * @access private
  159. *
  160. * @param array $saved_data The data returned from WP_Image_Editor after successfully saving an image.
  161. * @param string $original_file Path to the original file.
  162. * @param array $image_meta The image meta data.
  163. * @param int $attachment_id The attachment post ID.
  164. * @return array The updated image meta data.
  165. */
  166. function _wp_image_meta_replace_original( $saved_data, $original_file, $image_meta, $attachment_id ) {
  167. $new_file = $saved_data['path'];
  168. // Update the attached file meta.
  169. update_attached_file( $attachment_id, $new_file );
  170. // Width and height of the new image.
  171. $image_meta['width'] = $saved_data['width'];
  172. $image_meta['height'] = $saved_data['height'];
  173. // Make the file path relative to the upload dir.
  174. $image_meta['file'] = _wp_relative_upload_path( $new_file );
  175. // Store the original image file name in image_meta.
  176. $image_meta['original_image'] = wp_basename( $original_file );
  177. return $image_meta;
  178. }
  179. /**
  180. * Creates image sub-sizes, adds the new data to the image meta `sizes` array, and updates the image metadata.
  181. *
  182. * Intended for use after an image is uploaded. Saves/updates the image metadata after each
  183. * sub-size is created. If there was an error, it is added to the returned image metadata array.
  184. *
  185. * @since 5.3.0
  186. *
  187. * @param string $file Full path to the image file.
  188. * @param int $attachment_id Attachment Id to process.
  189. * @return array The image attachment meta data.
  190. */
  191. function wp_create_image_subsizes( $file, $attachment_id ) {
  192. $imagesize = @getimagesize( $file );
  193. if ( empty( $imagesize ) ) {
  194. // File is not an image.
  195. return array();
  196. }
  197. // Default image meta
  198. $image_meta = array(
  199. 'width' => $imagesize[0],
  200. 'height' => $imagesize[1],
  201. 'file' => _wp_relative_upload_path( $file ),
  202. 'sizes' => array(),
  203. );
  204. // Fetch additional metadata from EXIF/IPTC.
  205. $exif_meta = wp_read_image_metadata( $file );
  206. if ( $exif_meta ) {
  207. $image_meta['image_meta'] = $exif_meta;
  208. }
  209. /**
  210. * Filters the "BIG image" threshold value.
  211. *
  212. * If the original image width or height is above the threshold, it will be scaled down. The threshold is
  213. * used as max width and max height. The scaled down image will be used as the largest available size, including
  214. * the `_wp_attached_file` post meta value.
  215. *
  216. * Returning `false` from the filter callback will disable the scaling.
  217. *
  218. * @since 5.3.0
  219. *
  220. * @param int $threshold The threshold value in pixels. Default 2560.
  221. * @param array $imagesize Indexed array of the image width and height (in that order).
  222. * @param string $file Full path to the uploaded image file.
  223. * @param int $attachment_id Attachment post ID.
  224. */
  225. $threshold = (int) apply_filters( 'big_image_size_threshold', 2560, $imagesize, $file, $attachment_id );
  226. // If the original image's dimensions are over the threshold, scale the image
  227. // and use it as the "full" size.
  228. if ( $threshold && ( $image_meta['width'] > $threshold || $image_meta['height'] > $threshold ) ) {
  229. $editor = wp_get_image_editor( $file );
  230. if ( is_wp_error( $editor ) ) {
  231. // This image cannot be edited.
  232. return $image_meta;
  233. }
  234. // Resize the image
  235. $resized = $editor->resize( $threshold, $threshold );
  236. $rotated = null;
  237. // If there is EXIF data, rotate according to EXIF Orientation.
  238. if ( ! is_wp_error( $resized ) && is_array( $exif_meta ) ) {
  239. $resized = $editor->maybe_exif_rotate();
  240. $rotated = $resized;
  241. }
  242. if ( ! is_wp_error( $resized ) ) {
  243. // Append "-scaled" to the image file name. It will look like "my_image-scaled.jpg".
  244. // This doesn't affect the sub-sizes names as they are generated from the original image (for best quality).
  245. $saved = $editor->save( $editor->generate_filename( 'scaled' ) );
  246. if ( ! is_wp_error( $saved ) ) {
  247. $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
  248. // If the image was rotated update the stored EXIF data.
  249. if ( true === $rotated && ! empty( $image_meta['image_meta']['orientation'] ) ) {
  250. $image_meta['image_meta']['orientation'] = 1;
  251. }
  252. } else {
  253. // TODO: log errors.
  254. }
  255. } else {
  256. // TODO: log errors.
  257. }
  258. } elseif ( ! empty( $exif_meta['orientation'] ) && (int) $exif_meta['orientation'] !== 1 ) {
  259. // Rotate the whole original image if there is EXIF data and "orientation" is not 1.
  260. $editor = wp_get_image_editor( $file );
  261. if ( is_wp_error( $editor ) ) {
  262. // This image cannot be edited.
  263. return $image_meta;
  264. }
  265. // Rotate the image
  266. $rotated = $editor->maybe_exif_rotate();
  267. if ( true === $rotated ) {
  268. // Append `-rotated` to the image file name.
  269. $saved = $editor->save( $editor->generate_filename( 'rotated' ) );
  270. if ( ! is_wp_error( $saved ) ) {
  271. $image_meta = _wp_image_meta_replace_original( $saved, $file, $image_meta, $attachment_id );
  272. // Update the stored EXIF data.
  273. if ( ! empty( $image_meta['image_meta']['orientation'] ) ) {
  274. $image_meta['image_meta']['orientation'] = 1;
  275. }
  276. } else {
  277. // TODO: log errors.
  278. }
  279. }
  280. }
  281. // Initial save of the new metadata.
  282. // At this point the file was uploaded and moved to the uploads directory
  283. // but the image sub-sizes haven't been created yet and the `sizes` array is empty.
  284. wp_update_attachment_metadata( $attachment_id, $image_meta );
  285. $new_sizes = wp_get_registered_image_subsizes();
  286. /**
  287. * Filters the image sizes automatically generated when uploading an image.
  288. *
  289. * @since 2.9.0
  290. * @since 4.4.0 Added the `$image_meta` argument.
  291. * @since 5.3.0 Added the `$attachment_id` argument.
  292. *
  293. * @param array $new_sizes Associative array of image sizes to be created.
  294. * @param array $image_meta The image meta data: width, height, file, sizes, etc.
  295. * @param int $attachment_id The attachment post ID for the image.
  296. */
  297. $new_sizes = apply_filters( 'intermediate_image_sizes_advanced', $new_sizes, $image_meta, $attachment_id );
  298. return _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id );
  299. }
  300. /**
  301. * Low-level function to create image sub-sizes.
  302. *
  303. * Updates the image meta after each sub-size is created.
  304. * Errors are stored in the returned image metadata array.
  305. *
  306. * @since 5.3.0
  307. * @access private
  308. *
  309. * @param array $new_sizes Array defining what sizes to create.
  310. * @param string $file Full path to the image file.
  311. * @param array $image_meta The attachment meta data array.
  312. * @param int $attachment_id Attachment Id to process.
  313. * @return array The attachment meta data with updated `sizes` array. Includes an array of errors encountered while resizing.
  314. */
  315. function _wp_make_subsizes( $new_sizes, $file, $image_meta, $attachment_id ) {
  316. if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
  317. // Not an image attachment.
  318. return array();
  319. }
  320. // Check if any of the new sizes already exist.
  321. if ( isset( $image_meta['sizes'] ) && is_array( $image_meta['sizes'] ) ) {
  322. foreach ( $image_meta['sizes'] as $size_name => $size_meta ) {
  323. // Only checks "size name" so we don't override existing images even if the dimensions
  324. // don't match the currently defined size with the same name.
  325. // To change the behavior, unset changed/mismatched sizes in the `sizes` array in image meta.
  326. if ( array_key_exists( $size_name, $new_sizes ) ) {
  327. unset( $new_sizes[ $size_name ] );
  328. }
  329. }
  330. } else {
  331. $image_meta['sizes'] = array();
  332. }
  333. if ( empty( $new_sizes ) ) {
  334. // Nothing to do...
  335. return $image_meta;
  336. }
  337. // Sort the image sub-sizes in order of priority when creating them.
  338. // This ensures there is an appropriate sub-size the user can access immediately
  339. // even when there was an error and not all sub-sizes were created.
  340. $priority = array(
  341. 'medium' => null,
  342. 'large' => null,
  343. 'thumbnail' => null,
  344. 'medium_large' => null,
  345. );
  346. $new_sizes = array_filter( array_merge( $priority, $new_sizes ) );
  347. $editor = wp_get_image_editor( $file );
  348. if ( is_wp_error( $editor ) ) {
  349. // The image cannot be edited.
  350. return $image_meta;
  351. }
  352. // If stored EXIF data exists, rotate the source image before creating sub-sizes.
  353. if ( ! empty( $image_meta['image_meta'] ) ) {
  354. $rotated = $editor->maybe_exif_rotate();
  355. if ( is_wp_error( $rotated ) ) {
  356. // TODO: log errors.
  357. }
  358. }
  359. if ( method_exists( $editor, 'make_subsize' ) ) {
  360. foreach ( $new_sizes as $new_size_name => $new_size_data ) {
  361. $new_size_meta = $editor->make_subsize( $new_size_data );
  362. if ( is_wp_error( $new_size_meta ) ) {
  363. // TODO: log errors.
  364. } else {
  365. // Save the size meta value.
  366. $image_meta['sizes'][ $new_size_name ] = $new_size_meta;
  367. wp_update_attachment_metadata( $attachment_id, $image_meta );
  368. }
  369. }
  370. } else {
  371. // Fall back to `$editor->multi_resize()`.
  372. $created_sizes = $editor->multi_resize( $new_sizes );
  373. if ( ! empty( $created_sizes ) ) {
  374. $image_meta['sizes'] = array_merge( $image_meta['sizes'], $created_sizes );
  375. wp_update_attachment_metadata( $attachment_id, $image_meta );
  376. }
  377. }
  378. return $image_meta;
  379. }
  380. /**
  381. * Generate attachment meta data and create image sub-sizes for images.
  382. *
  383. * @since 2.1.0
  384. *
  385. * @param int $attachment_id Attachment Id to process.
  386. * @param string $file Filepath of the Attached image.
  387. * @return mixed Metadata for attachment.
  388. */
  389. function wp_generate_attachment_metadata( $attachment_id, $file ) {
  390. $attachment = get_post( $attachment_id );
  391. $metadata = array();
  392. $support = false;
  393. $mime_type = get_post_mime_type( $attachment );
  394. if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) {
  395. // Make thumbnails and other intermediate sizes.
  396. $metadata = wp_create_image_subsizes( $file, $attachment_id );
  397. } elseif ( wp_attachment_is( 'video', $attachment ) ) {
  398. $metadata = wp_read_video_metadata( $file );
  399. $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' );
  400. } elseif ( wp_attachment_is( 'audio', $attachment ) ) {
  401. $metadata = wp_read_audio_metadata( $file );
  402. $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' );
  403. }
  404. if ( $support && ! empty( $metadata['image']['data'] ) ) {
  405. // Check for existing cover.
  406. $hash = md5( $metadata['image']['data'] );
  407. $posts = get_posts(
  408. array(
  409. 'fields' => 'ids',
  410. 'post_type' => 'attachment',
  411. 'post_mime_type' => $metadata['image']['mime'],
  412. 'post_status' => 'inherit',
  413. 'posts_per_page' => 1,
  414. 'meta_key' => '_cover_hash',
  415. 'meta_value' => $hash,
  416. )
  417. );
  418. $exists = reset( $posts );
  419. if ( ! empty( $exists ) ) {
  420. update_post_meta( $attachment_id, '_thumbnail_id', $exists );
  421. } else {
  422. $ext = '.jpg';
  423. switch ( $metadata['image']['mime'] ) {
  424. case 'image/gif':
  425. $ext = '.gif';
  426. break;
  427. case 'image/png':
  428. $ext = '.png';
  429. break;
  430. }
  431. $basename = str_replace( '.', '-', wp_basename( $file ) ) . '-image' . $ext;
  432. $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
  433. if ( false === $uploaded['error'] ) {
  434. $image_attachment = array(
  435. 'post_mime_type' => $metadata['image']['mime'],
  436. 'post_type' => 'attachment',
  437. 'post_content' => '',
  438. );
  439. /**
  440. * Filters the parameters for the attachment thumbnail creation.
  441. *
  442. * @since 3.9.0
  443. *
  444. * @param array $image_attachment An array of parameters to create the thumbnail.
  445. * @param array $metadata Current attachment metadata.
  446. * @param array $uploaded An array containing the thumbnail path and url.
  447. */
  448. $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
  449. $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
  450. add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
  451. $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
  452. wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
  453. update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
  454. }
  455. }
  456. } elseif ( 'application/pdf' === $mime_type ) {
  457. // Try to create image thumbnails for PDFs.
  458. $fallback_sizes = array(
  459. 'thumbnail',
  460. 'medium',
  461. 'large',
  462. );
  463. /**
  464. * Filters the image sizes generated for non-image mime types.
  465. *
  466. * @since 4.7.0
  467. *
  468. * @param array $fallback_sizes An array of image size names.
  469. * @param array $metadata Current attachment metadata.
  470. */
  471. $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
  472. $registered_sizes = wp_get_registered_image_subsizes();
  473. $merged_sizes = array_intersect_key( $registered_sizes, array_flip( $fallback_sizes ) );
  474. // Force thumbnails to be soft crops.
  475. if ( isset( $merged_sizes['thumbnail'] ) && is_array( $merged_sizes['thumbnail'] ) ) {
  476. $merged_sizes['thumbnail']['crop'] = false;
  477. }
  478. // Only load PDFs in an image editor if we're processing sizes.
  479. if ( ! empty( $merged_sizes ) ) {
  480. $editor = wp_get_image_editor( $file );
  481. if ( ! is_wp_error( $editor ) ) { // No support for this type of file
  482. /*
  483. * PDFs may have the same file filename as JPEGs.
  484. * Ensure the PDF preview image does not overwrite any JPEG images that already exist.
  485. */
  486. $dirname = dirname( $file ) . '/';
  487. $ext = '.' . pathinfo( $file, PATHINFO_EXTENSION );
  488. $preview_file = $dirname . wp_unique_filename( $dirname, wp_basename( $file, $ext ) . '-pdf.jpg' );
  489. $uploaded = $editor->save( $preview_file, 'image/jpeg' );
  490. unset( $editor );
  491. // Resize based on the full size image, rather than the source.
  492. if ( ! is_wp_error( $uploaded ) ) {
  493. $image_file = $uploaded['path'];
  494. unset( $uploaded['path'] );
  495. $metadata['sizes'] = array(
  496. 'full' => $uploaded,
  497. );
  498. // Save the meta data before any image post-processing errors could happen.
  499. wp_update_attachment_metadata( $attachment_id, $metadata );
  500. // Create sub-sizes saving the image meta after each.
  501. $metadata = _wp_make_subsizes( $merged_sizes, $image_file, $metadata, $attachment_id );
  502. }
  503. }
  504. }
  505. }
  506. // Remove the blob of binary data from the array.
  507. if ( $metadata ) {
  508. unset( $metadata['image']['data'] );
  509. }
  510. /**
  511. * Filters the generated attachment meta data.
  512. *
  513. * @since 2.1.0
  514. * @since 5.3.0 The `$context` parameter was added.
  515. *
  516. * @param array $metadata An array of attachment meta data.
  517. * @param int $attachment_id Current attachment ID.
  518. * @param string $context Additional context. Can be 'create' when metadata was initially created for new attachment
  519. * or 'update' when the metadata was updated.
  520. */
  521. return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id, 'create' );
  522. }
  523. /**
  524. * Convert a fraction string to a decimal.
  525. *
  526. * @since 2.5.0
  527. *
  528. * @param string $str
  529. * @return int|float
  530. */
  531. function wp_exif_frac2dec( $str ) {
  532. if ( false === strpos( $str, '/' ) ) {
  533. return $str;
  534. }
  535. list( $n, $d ) = explode( '/', $str );
  536. if ( ! empty( $d ) ) {
  537. return $n / $d;
  538. }
  539. return $str;
  540. }
  541. /**
  542. * Convert the exif date format to a unix timestamp.
  543. *
  544. * @since 2.5.0
  545. *
  546. * @param string $str
  547. * @return int
  548. */
  549. function wp_exif_date2ts( $str ) {
  550. list( $date, $time ) = explode( ' ', trim( $str ) );
  551. list( $y, $m, $d ) = explode( ':', $date );
  552. return strtotime( "{$y}-{$m}-{$d} {$time}" );
  553. }
  554. /**
  555. * Get extended image metadata, exif or iptc as available.
  556. *
  557. * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
  558. * created_timestamp, focal_length, shutter_speed, and title.
  559. *
  560. * The IPTC metadata that is retrieved is APP13, credit, byline, created date
  561. * and time, caption, copyright, and title. Also includes FNumber, Model,
  562. * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
  563. *
  564. * @todo Try other exif libraries if available.
  565. * @since 2.5.0
  566. *
  567. * @param string $file
  568. * @return bool|array False on failure. Image metadata array on success.
  569. */
  570. function wp_read_image_metadata( $file ) {
  571. if ( ! file_exists( $file ) ) {
  572. return false;
  573. }
  574. list( , , $image_type ) = @getimagesize( $file );
  575. /*
  576. * EXIF contains a bunch of data we'll probably never need formatted in ways
  577. * that are difficult to use. We'll normalize it and just extract the fields
  578. * that are likely to be useful. Fractions and numbers are converted to
  579. * floats, dates to unix timestamps, and everything else to strings.
  580. */
  581. $meta = array(
  582. 'aperture' => 0,
  583. 'credit' => '',
  584. 'camera' => '',
  585. 'caption' => '',
  586. 'created_timestamp' => 0,
  587. 'copyright' => '',
  588. 'focal_length' => 0,
  589. 'iso' => 0,
  590. 'shutter_speed' => 0,
  591. 'title' => '',
  592. 'orientation' => 0,
  593. 'keywords' => array(),
  594. );
  595. $iptc = array();
  596. /*
  597. * Read IPTC first, since it might contain data not available in exif such
  598. * as caption, description etc.
  599. */
  600. if ( is_callable( 'iptcparse' ) ) {
  601. @getimagesize( $file, $info );
  602. if ( ! empty( $info['APP13'] ) ) {
  603. $iptc = @iptcparse( $info['APP13'] );
  604. // Headline, "A brief synopsis of the caption."
  605. if ( ! empty( $iptc['2#105'][0] ) ) {
  606. $meta['title'] = trim( $iptc['2#105'][0] );
  607. /*
  608. * Title, "Many use the Title field to store the filename of the image,
  609. * though the field may be used in many ways."
  610. */
  611. } elseif ( ! empty( $iptc['2#005'][0] ) ) {
  612. $meta['title'] = trim( $iptc['2#005'][0] );
  613. }
  614. if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
  615. $caption = trim( $iptc['2#120'][0] );
  616. mbstring_binary_safe_encoding();
  617. $caption_length = strlen( $caption );
  618. reset_mbstring_encoding();
  619. if ( empty( $meta['title'] ) && $caption_length < 80 ) {
  620. // Assume the title is stored in 2:120 if it's short.
  621. $meta['title'] = $caption;
  622. }
  623. $meta['caption'] = $caption;
  624. }
  625. if ( ! empty( $iptc['2#110'][0] ) ) { // credit
  626. $meta['credit'] = trim( $iptc['2#110'][0] );
  627. } elseif ( ! empty( $iptc['2#080'][0] ) ) { // creator / legacy byline
  628. $meta['credit'] = trim( $iptc['2#080'][0] );
  629. }
  630. if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) { // created date and time
  631. $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
  632. }
  633. if ( ! empty( $iptc['2#116'][0] ) ) { // copyright
  634. $meta['copyright'] = trim( $iptc['2#116'][0] );
  635. }
  636. if ( ! empty( $iptc['2#025'][0] ) ) { // keywords array
  637. $meta['keywords'] = array_values( $iptc['2#025'] );
  638. }
  639. }
  640. }
  641. $exif = array();
  642. /**
  643. * Filters the image types to check for exif data.
  644. *
  645. * @since 2.5.0
  646. *
  647. * @param array $image_types Image types to check for exif data.
  648. */
  649. $exif_image_types = apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) );
  650. if ( is_callable( 'exif_read_data' ) && in_array( $image_type, $exif_image_types, true ) ) {
  651. $exif = @exif_read_data( $file );
  652. if ( ! empty( $exif['ImageDescription'] ) ) {
  653. mbstring_binary_safe_encoding();
  654. $description_length = strlen( $exif['ImageDescription'] );
  655. reset_mbstring_encoding();
  656. if ( empty( $meta['title'] ) && $description_length < 80 ) {
  657. // Assume the title is stored in ImageDescription
  658. $meta['title'] = trim( $exif['ImageDescription'] );
  659. }
  660. if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) {
  661. $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
  662. }
  663. if ( empty( $meta['caption'] ) ) {
  664. $meta['caption'] = trim( $exif['ImageDescription'] );
  665. }
  666. } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) {
  667. $meta['caption'] = trim( $exif['Comments'] );
  668. }
  669. if ( empty( $meta['credit'] ) ) {
  670. if ( ! empty( $exif['Artist'] ) ) {
  671. $meta['credit'] = trim( $exif['Artist'] );
  672. } elseif ( ! empty( $exif['Author'] ) ) {
  673. $meta['credit'] = trim( $exif['Author'] );
  674. }
  675. }
  676. if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
  677. $meta['copyright'] = trim( $exif['Copyright'] );
  678. }
  679. if ( ! empty( $exif['FNumber'] ) ) {
  680. $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
  681. }
  682. if ( ! empty( $exif['Model'] ) ) {
  683. $meta['camera'] = trim( $exif['Model'] );
  684. }
  685. if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
  686. $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
  687. }
  688. if ( ! empty( $exif['FocalLength'] ) ) {
  689. $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
  690. }
  691. if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
  692. $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
  693. $meta['iso'] = trim( $meta['iso'] );
  694. }
  695. if ( ! empty( $exif['ExposureTime'] ) ) {
  696. $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
  697. }
  698. if ( ! empty( $exif['Orientation'] ) ) {
  699. $meta['orientation'] = $exif['Orientation'];
  700. }
  701. }
  702. foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
  703. if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) {
  704. $meta[ $key ] = utf8_encode( $meta[ $key ] );
  705. }
  706. }
  707. foreach ( $meta['keywords'] as $key => $keyword ) {
  708. if ( ! seems_utf8( $keyword ) ) {
  709. $meta['keywords'][ $key ] = utf8_encode( $keyword );
  710. }
  711. }
  712. $meta = wp_kses_post_deep( $meta );
  713. /**
  714. * Filters the array of meta data read from an image's exif data.
  715. *
  716. * @since 2.5.0
  717. * @since 4.4.0 The `$iptc` parameter was added.
  718. * @since 5.0.0 The `$exif` parameter was added.
  719. *
  720. * @param array $meta Image meta data.
  721. * @param string $file Path to image file.
  722. * @param int $image_type Type of image, one of the `IMAGETYPE_XXX` constants.
  723. * @param array $iptc IPTC data.
  724. * @param array $exif EXIF data.
  725. */
  726. return apply_filters( 'wp_read_image_metadata', $meta, $file, $image_type, $iptc, $exif );
  727. }
  728. /**
  729. * Validate that file is an image.
  730. *
  731. * @since 2.5.0
  732. *
  733. * @param string $path File path to test if valid image.
  734. * @return bool True if valid image, false if not valid image.
  735. */
  736. function file_is_valid_image( $path ) {
  737. $size = @getimagesize( $path );
  738. return ! empty( $size );
  739. }
  740. /**
  741. * Validate that file is suitable for displaying within a web page.
  742. *
  743. * @since 2.5.0
  744. *
  745. * @param string $path File path to test.
  746. * @return bool True if suitable, false if not suitable.
  747. */
  748. function file_is_displayable_image( $path ) {
  749. $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO );
  750. $info = @getimagesize( $path );
  751. if ( empty( $info ) ) {
  752. $result = false;
  753. } elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
  754. $result = false;
  755. } else {
  756. $result = true;
  757. }
  758. /**
  759. * Filters whether the current image is displayable in the browser.
  760. *
  761. * @since 2.5.0
  762. *
  763. * @param bool $result Whether the image can be displayed. Default true.
  764. * @param string $path Path to the image.
  765. */
  766. return apply_filters( 'file_is_displayable_image', $result, $path );
  767. }
  768. /**
  769. * Load an image resource for editing.
  770. *
  771. * @since 2.9.0
  772. *
  773. * @param string $attachment_id Attachment ID.
  774. * @param string $mime_type Image mime type.
  775. * @param string $size Optional. Image size, defaults to 'full'.
  776. * @return resource|false The resulting image resource on success, false on failure.
  777. */
  778. function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
  779. $filepath = _load_image_to_edit_path( $attachment_id, $size );
  780. if ( empty( $filepath ) ) {
  781. return false;
  782. }
  783. switch ( $mime_type ) {
  784. case 'image/jpeg':
  785. $image = imagecreatefromjpeg( $filepath );
  786. break;
  787. case 'image/png':
  788. $image = imagecreatefrompng( $filepath );
  789. break;
  790. case 'image/gif':
  791. $image = imagecreatefromgif( $filepath );
  792. break;
  793. default:
  794. $image = false;
  795. break;
  796. }
  797. if ( is_resource( $image ) ) {
  798. /**
  799. * Filters the current image being loaded for editing.
  800. *
  801. * @since 2.9.0
  802. *
  803. * @param resource $image Current image.
  804. * @param string $attachment_id Attachment ID.
  805. * @param string $size Image size.
  806. */
  807. $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size );
  808. if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
  809. imagealphablending( $image, false );
  810. imagesavealpha( $image, true );
  811. }
  812. }
  813. return $image;
  814. }
  815. /**
  816. * Retrieve the path or url of an attachment's attached file.
  817. *
  818. * If the attached file is not present on the local filesystem (usually due to replication plugins),
  819. * then the url of the file is returned if url fopen is supported.
  820. *
  821. * @since 3.4.0
  822. * @access private
  823. *
  824. * @param string $attachment_id Attachment ID.
  825. * @param string $size Optional. Image size, defaults to 'full'.
  826. * @return string|false File path or url on success, false on failure.
  827. */
  828. function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
  829. $filepath = get_attached_file( $attachment_id );
  830. if ( $filepath && file_exists( $filepath ) ) {
  831. if ( 'full' !== $size ) {
  832. $data = image_get_intermediate_size( $attachment_id, $size );
  833. if ( $data ) {
  834. $filepath = path_join( dirname( $filepath ), $data['file'] );
  835. /**
  836. * Filters the path to the current image.
  837. *
  838. * The filter is evaluated for all image sizes except 'full'.
  839. *
  840. * @since 3.1.0
  841. *
  842. * @param string $path Path to the current image.
  843. * @param string $attachment_id Attachment ID.
  844. * @param string $size Size of the image.
  845. */
  846. $filepath = apply_filters( 'load_image_to_edit_filesystempath', $filepath, $attachment_id, $size );
  847. }
  848. }
  849. } elseif ( function_exists( 'fopen' ) && ini_get( 'allow_url_fopen' ) ) {
  850. /**
  851. * Filters the image URL if not in the local filesystem.
  852. *
  853. * The filter is only evaluated if fopen is enabled on the server.
  854. *
  855. * @since 3.1.0
  856. *
  857. * @param string $image_url Current image URL.
  858. * @param string $attachment_id Attachment ID.
  859. * @param string $size Size of the image.
  860. */
  861. $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
  862. }
  863. /**
  864. * Filters the returned path or URL of the current image.
  865. *
  866. * @since 2.9.0
  867. *
  868. * @param string|bool $filepath File path or URL to current image, or false.
  869. * @param string $attachment_id Attachment ID.
  870. * @param string $size Size of the image.
  871. */
  872. return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
  873. }
  874. /**
  875. * Copy an existing image file.
  876. *
  877. * @since 3.4.0
  878. * @access private
  879. *
  880. * @param string $attachment_id Attachment ID.
  881. * @return string|false New file path on success, false on failure.
  882. */
  883. function _copy_image_file( $attachment_id ) {
  884. $dst_file = get_attached_file( $attachment_id );
  885. $src_file = $dst_file;
  886. if ( ! file_exists( $src_file ) ) {
  887. $src_file = _load_image_to_edit_path( $attachment_id );
  888. }
  889. if ( $src_file ) {
  890. $dst_file = str_replace( wp_basename( $dst_file ), 'copy-' . wp_basename( $dst_file ), $dst_file );
  891. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );
  892. /*
  893. * The directory containing the original file may no longer
  894. * exist when using a replication plugin.
  895. */
  896. wp_mkdir_p( dirname( $dst_file ) );
  897. if ( ! copy( $src_file, $dst_file ) ) {
  898. $dst_file = false;
  899. }
  900. } else {
  901. $dst_file = false;
  902. }
  903. return $dst_file;
  904. }