image.php 38 KB

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