]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/image.php
WordPress 4.6.3
[autoinstalls/wordpress.git] / wp-admin / includes / image.php
1 <?php
2 /**
3  * File contains all the administration image manipulation functions.
4  *
5  * @package WordPress
6  * @subpackage Administration
7  */
8
9 /**
10  * Crop an Image to a given size.
11  *
12  * @since 2.1.0
13  *
14  * @param string|int $src The source file or Attachment ID.
15  * @param int $src_x The start x position to crop from.
16  * @param int $src_y The start y position to crop from.
17  * @param int $src_w The width to crop.
18  * @param int $src_h The height to crop.
19  * @param int $dst_w The destination width.
20  * @param int $dst_h The destination height.
21  * @param int $src_abs Optional. If the source crop points are absolute.
22  * @param string $dst_file Optional. The destination file to write to.
23  * @return string|WP_Error New filepath on success, WP_Error on failure.
24  */
25 function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
26         $src_file = $src;
27         if ( is_numeric( $src ) ) { // Handle int as attachment ID
28                 $src_file = get_attached_file( $src );
29
30                 if ( ! file_exists( $src_file ) ) {
31                         // If the file doesn't exist, attempt a URL fopen on the src link.
32                         // This can occur with certain file replication plugins.
33                         $src = _load_image_to_edit_path( $src, 'full' );
34                 } else {
35                         $src = $src_file;
36                 }
37         }
38
39         $editor = wp_get_image_editor( $src );
40         if ( is_wp_error( $editor ) )
41                 return $editor;
42
43         $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
44         if ( is_wp_error( $src ) )
45                 return $src;
46
47         if ( ! $dst_file )
48                 $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
49
50         /*
51          * The directory containing the original file may no longer exist when
52          * using a replication plugin.
53          */
54         wp_mkdir_p( dirname( $dst_file ) );
55
56         $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
57
58         $result = $editor->save( $dst_file );
59         if ( is_wp_error( $result ) )
60                 return $result;
61
62         return $dst_file;
63 }
64
65 /**
66  * Generate post thumbnail attachment meta data.
67  *
68  * @since 2.1.0
69  *
70  * @global array $_wp_additional_image_sizes
71  *
72  * @param int $attachment_id Attachment Id to process.
73  * @param string $file Filepath of the Attached image.
74  * @return mixed Metadata for attachment.
75  */
76 function wp_generate_attachment_metadata( $attachment_id, $file ) {
77         $attachment = get_post( $attachment_id );
78
79         $metadata = array();
80         $support = false;
81         if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
82                 $imagesize = getimagesize( $file );
83                 $metadata['width'] = $imagesize[0];
84                 $metadata['height'] = $imagesize[1];
85
86                 // Make the file path relative to the upload dir.
87                 $metadata['file'] = _wp_relative_upload_path($file);
88
89                 // Make thumbnails and other intermediate sizes.
90                 global $_wp_additional_image_sizes;
91
92                 $sizes = array();
93                 foreach ( get_intermediate_image_sizes() as $s ) {
94                         $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
95                         if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
96                                 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
97                         else
98                                 $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
99                         if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
100                                 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
101                         else
102                                 $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
103                         if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
104                                 $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop']; // For theme-added sizes
105                         else
106                                 $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
107                 }
108
109                 /**
110                  * Filters the image sizes automatically generated when uploading an image.
111                  *
112                  * @since 2.9.0
113                  * @since 4.4.0 Added the `$metadata` argument.
114                  *
115                  * @param array $sizes    An associative array of image sizes.
116                  * @param array $metadata An associative array of image metadata: width, height, file.
117                  */
118                 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata );
119
120                 if ( $sizes ) {
121                         $editor = wp_get_image_editor( $file );
122
123                         if ( ! is_wp_error( $editor ) )
124                                 $metadata['sizes'] = $editor->multi_resize( $sizes );
125                 } else {
126                         $metadata['sizes'] = array();
127                 }
128
129                 // Fetch additional metadata from EXIF/IPTC.
130                 $image_meta = wp_read_image_metadata( $file );
131                 if ( $image_meta )
132                         $metadata['image_meta'] = $image_meta;
133
134         } elseif ( wp_attachment_is( 'video', $attachment ) ) {
135                 $metadata = wp_read_video_metadata( $file );
136                 $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' );
137         } elseif ( wp_attachment_is( 'audio', $attachment ) ) {
138                 $metadata = wp_read_audio_metadata( $file );
139                 $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' );
140         }
141
142         if ( $support && ! empty( $metadata['image']['data'] ) ) {
143                 // Check for existing cover.
144                 $hash = md5( $metadata['image']['data'] );
145                 $posts = get_posts( array(
146                         'fields' => 'ids',
147                         'post_type' => 'attachment',
148                         'post_mime_type' => $metadata['image']['mime'],
149                         'post_status' => 'inherit',
150                         'posts_per_page' => 1,
151                         'meta_key' => '_cover_hash',
152                         'meta_value' => $hash
153                 ) );
154                 $exists = reset( $posts );
155
156                 if ( ! empty( $exists ) ) {
157                         update_post_meta( $attachment_id, '_thumbnail_id', $exists );
158                 } else {
159                         $ext = '.jpg';
160                         switch ( $metadata['image']['mime'] ) {
161                         case 'image/gif':
162                                 $ext = '.gif';
163                                 break;
164                         case 'image/png':
165                                 $ext = '.png';
166                                 break;
167                         }
168                         $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
169                         $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
170                         if ( false === $uploaded['error'] ) {
171                                 $image_attachment = array(
172                                         'post_mime_type' => $metadata['image']['mime'],
173                                         'post_type' => 'attachment',
174                                         'post_content' => '',
175                                 );
176                                 /**
177                                  * Filters the parameters for the attachment thumbnail creation.
178                                  *
179                                  * @since 3.9.0
180                                  *
181                                  * @param array $image_attachment An array of parameters to create the thumbnail.
182                                  * @param array $metadata         Current attachment metadata.
183                                  * @param array $uploaded         An array containing the thumbnail path and url.
184                                  */
185                                 $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
186
187                                 $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
188                                 add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
189                                 $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
190                                 wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
191                                 update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
192                         }
193                 }
194         }
195
196         // Remove the blob of binary data from the array.
197         if ( $metadata ) {
198                 unset( $metadata['image']['data'] );
199         }
200
201         /**
202          * Filters the generated attachment meta data.
203          *
204          * @since 2.1.0
205          *
206          * @param array $metadata      An array of attachment meta data.
207          * @param int   $attachment_id Current attachment ID.
208          */
209         return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
210 }
211
212 /**
213  * Convert a fraction string to a decimal.
214  *
215  * @since 2.5.0
216  *
217  * @param string $str
218  * @return int|float
219  */
220 function wp_exif_frac2dec($str) {
221         @list( $n, $d ) = explode( '/', $str );
222         if ( !empty($d) )
223                 return $n / $d;
224         return $str;
225 }
226
227 /**
228  * Convert the exif date format to a unix timestamp.
229  *
230  * @since 2.5.0
231  *
232  * @param string $str
233  * @return int
234  */
235 function wp_exif_date2ts($str) {
236         @list( $date, $time ) = explode( ' ', trim($str) );
237         @list( $y, $m, $d ) = explode( ':', $date );
238
239         return strtotime( "{$y}-{$m}-{$d} {$time}" );
240 }
241
242 /**
243  * Get extended image metadata, exif or iptc as available.
244  *
245  * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
246  * created_timestamp, focal_length, shutter_speed, and title.
247  *
248  * The IPTC metadata that is retrieved is APP13, credit, byline, created date
249  * and time, caption, copyright, and title. Also includes FNumber, Model,
250  * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
251  *
252  * @todo Try other exif libraries if available.
253  * @since 2.5.0
254  *
255  * @param string $file
256  * @return bool|array False on failure. Image metadata array on success.
257  */
258 function wp_read_image_metadata( $file ) {
259         if ( ! file_exists( $file ) )
260                 return false;
261
262         list( , , $sourceImageType ) = getimagesize( $file );
263
264         /*
265          * EXIF contains a bunch of data we'll probably never need formatted in ways
266          * that are difficult to use. We'll normalize it and just extract the fields
267          * that are likely to be useful. Fractions and numbers are converted to
268          * floats, dates to unix timestamps, and everything else to strings.
269          */
270         $meta = array(
271                 'aperture' => 0,
272                 'credit' => '',
273                 'camera' => '',
274                 'caption' => '',
275                 'created_timestamp' => 0,
276                 'copyright' => '',
277                 'focal_length' => 0,
278                 'iso' => 0,
279                 'shutter_speed' => 0,
280                 'title' => '',
281                 'orientation' => 0,
282                 'keywords' => array(),
283         );
284
285         $iptc = array();
286         /*
287          * Read IPTC first, since it might contain data not available in exif such
288          * as caption, description etc.
289          */
290         if ( is_callable( 'iptcparse' ) ) {
291                 getimagesize( $file, $info );
292
293                 if ( ! empty( $info['APP13'] ) ) {
294                         $iptc = iptcparse( $info['APP13'] );
295
296                         // Headline, "A brief synopsis of the caption."
297                         if ( ! empty( $iptc['2#105'][0] ) ) {
298                                 $meta['title'] = trim( $iptc['2#105'][0] );
299                         /*
300                          * Title, "Many use the Title field to store the filename of the image,
301                          * though the field may be used in many ways."
302                          */
303                         } elseif ( ! empty( $iptc['2#005'][0] ) ) {
304                                 $meta['title'] = trim( $iptc['2#005'][0] );
305                         }
306
307                         if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
308                                 $caption = trim( $iptc['2#120'][0] );
309
310                                 mbstring_binary_safe_encoding();
311                                 $caption_length = strlen( $caption );
312                                 reset_mbstring_encoding();
313
314                                 if ( empty( $meta['title'] ) && $caption_length < 80 ) {
315                                         // Assume the title is stored in 2:120 if it's short.
316                                         $meta['title'] = $caption;
317                                 }
318
319                                 $meta['caption'] = $caption;
320                         }
321
322                         if ( ! empty( $iptc['2#110'][0] ) ) // credit
323                                 $meta['credit'] = trim( $iptc['2#110'][0] );
324                         elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
325                                 $meta['credit'] = trim( $iptc['2#080'][0] );
326
327                         if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) // created date and time
328                                 $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
329
330                         if ( ! empty( $iptc['2#116'][0] ) ) // copyright
331                                 $meta['copyright'] = trim( $iptc['2#116'][0] );
332
333                         if ( ! empty( $iptc['2#025'][0] ) ) { // keywords array
334                                 $meta['keywords'] = array_values( $iptc['2#025'] );
335                         }
336                  }
337         }
338
339         /**
340          * Filters the image types to check for exif data.
341          *
342          * @since 2.5.0
343          *
344          * @param array $image_types Image types to check for exif data.
345          */
346         if ( is_callable( 'exif_read_data' ) && in_array( $sourceImageType, apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ) ) ) {
347                 $exif = @exif_read_data( $file );
348
349                 if ( ! empty( $exif['ImageDescription'] ) ) {
350                         mbstring_binary_safe_encoding();
351                         $description_length = strlen( $exif['ImageDescription'] );
352                         reset_mbstring_encoding();
353
354                         if ( empty( $meta['title'] ) && $description_length < 80 ) {
355                                 // Assume the title is stored in ImageDescription
356                                 $meta['title'] = trim( $exif['ImageDescription'] );
357                         }
358
359                         if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) {
360                                 $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
361                         }
362
363                         if ( empty( $meta['caption'] ) ) {
364                                 $meta['caption'] = trim( $exif['ImageDescription'] );
365                         }
366                 } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) {
367                         $meta['caption'] = trim( $exif['Comments'] );
368                 }
369
370                 if ( empty( $meta['credit'] ) ) {
371                         if ( ! empty( $exif['Artist'] ) ) {
372                                 $meta['credit'] = trim( $exif['Artist'] );
373                         } elseif ( ! empty($exif['Author'] ) ) {
374                                 $meta['credit'] = trim( $exif['Author'] );
375                         }
376                 }
377
378                 if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
379                         $meta['copyright'] = trim( $exif['Copyright'] );
380                 }
381                 if ( ! empty( $exif['FNumber'] ) ) {
382                         $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
383                 }
384                 if ( ! empty( $exif['Model'] ) ) {
385                         $meta['camera'] = trim( $exif['Model'] );
386                 }
387                 if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
388                         $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
389                 }
390                 if ( ! empty( $exif['FocalLength'] ) ) {
391                         $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
392                 }
393                 if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
394                         $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
395                         $meta['iso'] = trim( $meta['iso'] );
396                 }
397                 if ( ! empty( $exif['ExposureTime'] ) ) {
398                         $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
399                 }
400                 if ( ! empty( $exif['Orientation'] ) ) {
401                         $meta['orientation'] = $exif['Orientation'];
402                 }
403         }
404
405         foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
406                 if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) {
407                         $meta[ $key ] = utf8_encode( $meta[ $key ] );
408                 }
409         }
410
411         foreach ( $meta['keywords'] as $key => $keyword ) {
412                 if ( ! seems_utf8( $keyword ) ) {
413                         $meta['keywords'][ $key ] = utf8_encode( $keyword );
414                 }
415         }
416
417         $meta = wp_kses_post_deep( $meta );
418
419         /**
420          * Filters the array of meta data read from an image's exif data.
421          *
422          * @since 2.5.0
423          * @since 4.4.0 The `$iptc` parameter was added.
424          *
425          * @param array  $meta            Image meta data.
426          * @param string $file            Path to image file.
427          * @param int    $sourceImageType Type of image.
428          * @param array  $iptc            IPTC data.
429          */
430         return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType, $iptc );
431
432 }
433
434 /**
435  * Validate that file is an image.
436  *
437  * @since 2.5.0
438  *
439  * @param string $path File path to test if valid image.
440  * @return bool True if valid image, false if not valid image.
441  */
442 function file_is_valid_image($path) {
443         $size = @getimagesize($path);
444         return !empty($size);
445 }
446
447 /**
448  * Validate that file is suitable for displaying within a web page.
449  *
450  * @since 2.5.0
451  *
452  * @param string $path File path to test.
453  * @return bool True if suitable, false if not suitable.
454  */
455 function file_is_displayable_image($path) {
456         $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP );
457
458         $info = @getimagesize( $path );
459         if ( empty( $info ) ) {
460                 $result = false;
461         } elseif ( ! in_array( $info[2], $displayable_image_types ) ) {
462                 $result = false;
463         } else {
464                 $result = true;
465         }
466
467         /**
468          * Filters whether the current image is displayable in the browser.
469          *
470          * @since 2.5.0
471          *
472          * @param bool   $result Whether the image can be displayed. Default true.
473          * @param string $path   Path to the image.
474          */
475         return apply_filters( 'file_is_displayable_image', $result, $path );
476 }
477
478 /**
479  * Load an image resource for editing.
480  *
481  * @since 2.9.0
482  *
483  * @param string $attachment_id Attachment ID.
484  * @param string $mime_type Image mime type.
485  * @param string $size Optional. Image size, defaults to 'full'.
486  * @return resource|false The resulting image resource on success, false on failure.
487  */
488 function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
489         $filepath = _load_image_to_edit_path( $attachment_id, $size );
490         if ( empty( $filepath ) )
491                 return false;
492
493         switch ( $mime_type ) {
494                 case 'image/jpeg':
495                         $image = imagecreatefromjpeg($filepath);
496                         break;
497                 case 'image/png':
498                         $image = imagecreatefrompng($filepath);
499                         break;
500                 case 'image/gif':
501                         $image = imagecreatefromgif($filepath);
502                         break;
503                 default:
504                         $image = false;
505                         break;
506         }
507         if ( is_resource($image) ) {
508                 /**
509                  * Filters the current image being loaded for editing.
510                  *
511                  * @since 2.9.0
512                  *
513                  * @param resource $image         Current image.
514                  * @param string   $attachment_id Attachment ID.
515                  * @param string   $size          Image size.
516                  */
517                 $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size );
518                 if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
519                         imagealphablending($image, false);
520                         imagesavealpha($image, true);
521                 }
522         }
523         return $image;
524 }
525
526 /**
527  * Retrieve the path or url of an attachment's attached file.
528  *
529  * If the attached file is not present on the local filesystem (usually due to replication plugins),
530  * then the url of the file is returned if url fopen is supported.
531  *
532  * @since 3.4.0
533  * @access private
534  *
535  * @param string $attachment_id Attachment ID.
536  * @param string $size Optional. Image size, defaults to 'full'.
537  * @return string|false File path or url on success, false on failure.
538  */
539 function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
540         $filepath = get_attached_file( $attachment_id );
541
542         if ( $filepath && file_exists( $filepath ) ) {
543                 if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
544                         /**
545                          * Filters the path to the current image.
546                          *
547                          * The filter is evaluated for all image sizes except 'full'.
548                          *
549                          * @since 3.1.0
550                          *
551                          * @param string $path          Path to the current image.
552                          * @param string $attachment_id Attachment ID.
553                          * @param string $size          Size of the image.
554                          */
555                         $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
556                 }
557         } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
558                 /**
559                  * Filters the image URL if not in the local filesystem.
560                  *
561                  * The filter is only evaluated if fopen is enabled on the server.
562                  *
563                  * @since 3.1.0
564                  *
565                  * @param string $image_url     Current image URL.
566                  * @param string $attachment_id Attachment ID.
567                  * @param string $size          Size of the image.
568                  */
569                 $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
570         }
571
572         /**
573          * Filters the returned path or URL of the current image.
574          *
575          * @since 2.9.0
576          *
577          * @param string|bool $filepath      File path or URL to current image, or false.
578          * @param string      $attachment_id Attachment ID.
579          * @param string      $size          Size of the image.
580          */
581         return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
582 }
583
584 /**
585  * Copy an existing image file.
586  *
587  * @since 3.4.0
588  * @access private
589  *
590  * @param string $attachment_id Attachment ID.
591  * @return string|false New file path on success, false on failure.
592  */
593 function _copy_image_file( $attachment_id ) {
594         $dst_file = $src_file = get_attached_file( $attachment_id );
595         if ( ! file_exists( $src_file ) )
596                 $src_file = _load_image_to_edit_path( $attachment_id );
597
598         if ( $src_file ) {
599                 $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
600                 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
601
602                 /*
603                  * The directory containing the original file may no longer
604                  * exist when using a replication plugin.
605                  */
606                 wp_mkdir_p( dirname( $dst_file ) );
607
608                 if ( ! @copy( $src_file, $dst_file ) )
609                         $dst_file = false;
610         } else {
611                 $dst_file = false;
612         }
613
614         return $dst_file;
615 }