Bez popisu

image.php 38KB

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