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