Brak opisu

image.php 36KB

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