]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
No need for ImageMagick to detected animated GIF
[quix0rs-gnu-social.git] / lib / imagefile.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstraction for an image file
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Image
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Zach Copley <zach@status.net>
26  * @copyright 2008-2009 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('GNUSOCIAL')) { exit(1); }
32
33 /**
34  * A wrapper on uploaded files
35  *
36  * Makes it slightly easier to accept an image file from upload.
37  *
38  * @category Image
39  * @package  StatusNet
40  * @author   Evan Prodromou <evan@status.net>
41  * @author   Zach Copley <zach@status.net>
42  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
43  * @link     http://status.net/
44  */
45
46 class ImageFile
47 {
48     var $id;
49     var $filepath;
50     var $filename;
51     var $type;
52     var $height;
53     var $width;
54     var $rotate=0;  // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
55     var $animated = null;  // Animated image? (has more than 1 frame). null means untested
56
57     function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
58     {
59         $this->id = $id;
60         $this->filepath = $filepath;
61         $this->filename = basename($filepath);
62
63         $info = @getimagesize($this->filepath);
64
65         if (!(
66             ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
67             ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
68             $info[2] == IMAGETYPE_BMP ||
69             ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
70             ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
71             ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
72
73             // TRANS: Exception thrown when trying to upload an unsupported image file format.
74             throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
75         }
76
77         $this->type = ($info) ? $info[2]:$type;
78         $this->width = ($info) ? $info[0]:$width;
79         $this->height = ($info) ? $info[1]:$height;
80
81         if ($this->type == IMAGETYPE_JPEG && function_exists('exif_read_data')) {
82             // Orientation value to rotate thumbnails properly
83             $exif = exif_read_data($this->filepath);
84             if (is_array($exif) && isset($exif['Orientation'])) {
85                 switch ((int)$exif['Orientation']) {
86                 case 1: // top is top
87                     $this->rotate = 0;
88                     break;
89                 case 3: // top is bottom
90                     $this->rotate = 180;
91                     break;
92                 case 6: // top is right
93                     $this->rotate = -90;
94                     break;
95                 case 8: // top is left
96                     $this->rotate = 90;
97                     break;
98                 }
99                 // If we ever write this back, Orientation should be set to '1'
100             }
101         } elseif ($this->type === IMAGETYPE_GIF) {
102             $this->animated = $this->isAnimatedGif();
103         }
104
105         Event::handle('FillImageFileMetadata', array($this));
106     }
107
108     public static function fromFileObject(File $file)
109     {
110         $imgPath = null;
111         $media = common_get_mime_media($file->mimetype);
112         if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
113             switch ($media) {
114             case 'image':
115                 $imgPath = $file->getPath();
116                 break;
117             default:
118                 throw new UnsupportedMediaException(_('Unsupported media format.'), $file->getPath());
119             }
120         }
121
122         if (!file_exists($imgPath)) {
123             throw new ServerException(sprintf('Image not available locally: %s', $imgPath));
124         }
125
126         try {
127             $image = new ImageFile($file->id, $imgPath);
128         } catch (UnsupportedMediaException $e) {
129             // Avoid deleting the original
130             if ($imgPath != $file->getPath()) {
131                 unlink($imgPath);
132             }
133             throw $e;
134         }
135         return $image;
136     }
137
138     public function getPath()
139     {
140         if (!file_exists($this->filepath)) {
141             throw new ServerException('No file in ImageFile filepath');
142         }
143
144         return $this->filepath;
145     }
146
147     static function fromUpload($param='upload')
148     {
149         switch ($_FILES[$param]['error']) {
150          case UPLOAD_ERR_OK: // success, jump out
151             break;
152
153          case UPLOAD_ERR_INI_SIZE:
154          case UPLOAD_ERR_FORM_SIZE:
155             // TRANS: Exception thrown when too large a file is uploaded.
156             // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
157             throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
158
159          case UPLOAD_ERR_PARTIAL:
160             @unlink($_FILES[$param]['tmp_name']);
161             // TRANS: Exception thrown when uploading an image and that action could not be completed.
162             throw new Exception(_('Partial upload.'));
163
164          case UPLOAD_ERR_NO_FILE:
165             // No file; probably just a non-AJAX submission.
166          default:
167             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
168             // TRANS: Exception thrown when uploading an image fails for an unknown reason.
169             throw new Exception(_('System error uploading file.'));
170         }
171
172         $info = @getimagesize($_FILES[$param]['tmp_name']);
173
174         if (!$info) {
175             @unlink($_FILES[$param]['tmp_name']);
176             // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
177             throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
178         }
179
180         return new ImageFile(null, $_FILES[$param]['tmp_name']);
181     }
182
183     /**
184      * Compat interface for old code generating avatar thumbnails...
185      * Saves the scaled file directly into the avatar area.
186      *
187      * @param int $size target width & height -- must be square
188      * @param int $x (default 0) upper-left corner to crop from
189      * @param int $y (default 0) upper-left corner to crop from
190      * @param int $w (default full) width of image area to crop
191      * @param int $h (default full) height of image area to crop
192      * @return string filename
193      */
194     function resize($size, $x = 0, $y = 0, $w = null, $h = null)
195     {
196         $targetType = $this->preferredType();
197         $outname = Avatar::filename($this->id,
198                                     image_type_to_extension($targetType),
199                                     $size,
200                                     common_timestamp());
201         $outpath = Avatar::path($outname);
202         $this->resizeTo($outpath, array('width'=>$size, 'height'=>$size,
203                                         'x'=>$x,        'y'=>$y,
204                                         'w'=>$w,        'h'=>$h));
205         return $outname;
206     }
207
208     /**
209      * Copy the image file to the given destination.
210      *
211      * This function may modify the resulting file. Please use the
212      * returned ImageFile object to read metadata (width, height etc.)
213      *
214      * @param string $outpath
215      * @return ImageFile the image stored at target path
216      */
217     function copyTo($outpath)
218     {
219         return new ImageFile(null, $this->resizeTo($outpath));
220     }
221
222     /**
223      * Create and save a thumbnail image.
224      *
225      * @param string $outpath
226      * @param array $box    width, height, boundary box (x,y,w,h) defaults to full image
227      * @return string full local filesystem filename
228      */
229     function resizeTo($outpath, array $box=array())
230     {
231         $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
232         $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
233         $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
234         $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
235         $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
236         $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
237
238         if (!file_exists($this->filepath)) {
239             // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
240             throw new Exception(_('Lost our file.'));
241         }
242
243         // Don't rotate/crop/scale if it isn't necessary
244         if ($box['width'] === $this->width
245                 && $box['height'] === $this->height
246                 && $box['x'] === 0
247                 && $box['y'] === 0
248                 && $box['w'] === $this->width
249                 && $box['h'] === $this->height
250                 && $this->type == $this->preferredType()) {
251             if ($this->rotate == 0) {
252                 // No rotational difference, just copy it as-is
253                 @copy($this->filepath, $outpath);
254                 return $outpath;
255             } elseif (abs($this->rotate) == 90) {
256                 // Box is rotated 90 degrees in either direction,
257                 // so we have to redefine x to y and vice versa.
258                 $tmp = $box['width'];
259                 $box['width'] = $box['height'];
260                 $box['height'] = $tmp;
261                 $tmp = $box['x'];
262                 $box['x'] = $box['y'];
263                 $box['y'] = $tmp;
264                 $tmp = $box['w'];
265                 $box['w'] = $box['h'];
266                 $box['h'] = $tmp;
267             }
268         }
269
270
271         if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
272             $this->resizeToFile($outpath, $box);
273         }
274
275         if (!file_exists($outpath)) {
276             throw new UseFileAsThumbnailException($this->id);
277         }
278
279         return $outpath;
280     }
281
282     protected function resizeToFile($outpath, array $box)
283     {
284         switch ($this->type) {
285         case IMAGETYPE_GIF:
286             $image_src = imagecreatefromgif($this->filepath);
287             break;
288         case IMAGETYPE_JPEG:
289             $image_src = imagecreatefromjpeg($this->filepath);
290             break;
291         case IMAGETYPE_PNG:
292             $image_src = imagecreatefrompng($this->filepath);
293             break;
294         case IMAGETYPE_BMP:
295             $image_src = imagecreatefrombmp($this->filepath);
296             break;
297         case IMAGETYPE_WBMP:
298             $image_src = imagecreatefromwbmp($this->filepath);
299             break;
300         case IMAGETYPE_XBM:
301             $image_src = imagecreatefromxbm($this->filepath);
302             break;
303         default:
304             // TRANS: Exception thrown when trying to resize an unknown file type.
305             throw new Exception(_('Unknown file type'));
306         }
307
308         if ($this->rotate != 0) {
309             $image_src = imagerotate($image_src, $this->rotate, 0);
310         }
311
312         $image_dest = imagecreatetruecolor($box['width'], $box['height']);
313
314         if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
315
316             $transparent_idx = imagecolortransparent($image_src);
317
318             if ($transparent_idx >= 0) {
319
320                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
321                 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
322                 imagefill($image_dest, 0, 0, $transparent_idx);
323                 imagecolortransparent($image_dest, $transparent_idx);
324
325             } elseif ($this->type == IMAGETYPE_PNG) {
326
327                 imagealphablending($image_dest, false);
328                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
329                 imagefill($image_dest, 0, 0, $transparent);
330                 imagesavealpha($image_dest, true);
331
332             }
333         }
334
335         imagecopyresampled($image_dest, $image_src, 0, 0, $box['x'], $box['y'], $box['width'], $box['height'], $box['w'], $box['h']);
336
337         switch ($this->preferredType()) {
338          case IMAGETYPE_GIF:
339             imagegif($image_dest, $outpath);
340             break;
341          case IMAGETYPE_JPEG:
342             imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
343             break;
344          case IMAGETYPE_PNG:
345             imagepng($image_dest, $outpath);
346             break;
347          default:
348             // TRANS: Exception thrown when trying resize an unknown file type.
349             throw new Exception(_('Unknown file type'));
350         }
351
352         imagedestroy($image_src);
353         imagedestroy($image_dest);
354     }
355
356
357     /**
358      * Several obscure file types should be normalized to PNG on resize.
359      *
360      * @fixme consider flattening anything not GIF or JPEG to PNG
361      * @return int
362      */
363     function preferredType()
364     {
365         if($this->type == IMAGETYPE_BMP) {
366             //we don't want to save BMP... it's an inefficient, rare, antiquated format
367             //save png instead
368             return IMAGETYPE_PNG;
369         } else if($this->type == IMAGETYPE_WBMP) {
370             //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
371             //save png instead
372             return IMAGETYPE_PNG;
373         } else if($this->type == IMAGETYPE_XBM) {
374             //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
375             //save png instead
376             return IMAGETYPE_PNG;
377         }
378         return $this->type;
379     }
380
381     function unlink()
382     {
383         @unlink($this->filepath);
384     }
385
386     static function maxFileSize()
387     {
388         $value = ImageFile::maxFileSizeInt();
389
390         if ($value > 1024 * 1024) {
391             $value = $value/(1024*1024);
392             // TRANS: Number of megabytes. %d is the number.
393             return sprintf(_m('%dMB','%dMB',$value),$value);
394         } else if ($value > 1024) {
395             $value = $value/1024;
396             // TRANS: Number of kilobytes. %d is the number.
397             return sprintf(_m('%dkB','%dkB',$value),$value);
398         } else {
399             // TRANS: Number of bytes. %d is the number.
400             return sprintf(_m('%dB','%dB',$value),$value);
401         }
402     }
403
404     static function maxFileSizeInt()
405     {
406         return min(ImageFile::strToInt(ini_get('post_max_size')),
407                    ImageFile::strToInt(ini_get('upload_max_filesize')),
408                    ImageFile::strToInt(ini_get('memory_limit')));
409     }
410
411     static function strToInt($str)
412     {
413         $unit = substr($str, -1);
414         $num = substr($str, 0, -1);
415
416         switch(strtoupper($unit)){
417          case 'G':
418             $num *= 1024;
419          case 'M':
420             $num *= 1024;
421          case 'K':
422             $num *= 1024;
423         }
424
425         return $num;
426     }
427
428     public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
429     {
430         return self::getScalingValues($this->width, $this->height,
431                                         $maxWidth, $maxHeight, $crop, $this->rotate);
432     }
433
434     /*
435      * Gets scaling values for images of various types. Cropping can be enabled.
436      *
437      * Values will scale _up_ to fit max values if cropping is enabled!
438      * With cropping disabled, the max value of each axis will be respected.
439      *
440      * @param $width    int Original width
441      * @param $height   int Original height
442      * @param $maxW     int Resulting max width
443      * @param $maxH     int Resulting max height
444      * @param $crop     int Crop to the size (not preserving aspect ratio)
445      */
446     public static function getScalingValues($width, $height,
447                                         $maxW=null, $maxH=null,
448                                         $crop=null, $rotate=0)
449     {
450         $maxW = $maxW ?: common_config('thumbnail', 'width');
451         $maxH = $maxH ?: common_config('thumbnail', 'height');
452   
453         if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
454             throw new ServerException('Bad parameters for ImageFile::getScalingValues');
455         } elseif ($maxH === null) {
456             // if maxH is null, we set maxH to equal maxW and enable crop
457             $maxH = $maxW;
458             $crop = true;
459         }
460
461         // Because GD doesn't understand EXIF orientation etc.
462         if (abs($rotate) == 90) {
463             $tmp = $width;
464             $width = $height;
465             $height = $tmp;
466         }
467   
468         // Cropping data (for original image size). Default values, 0 and null,
469         // imply no cropping and with preserved aspect ratio (per axis).
470         $cx = 0;    // crop x
471         $cy = 0;    // crop y
472         $cw = null; // crop area width
473         $ch = null; // crop area height
474   
475         if ($crop) {
476             $s_ar = $width / $height;
477             $t_ar = $maxW / $maxH;
478
479             $rw = $maxW;
480             $rh = $maxH;
481
482             // Source aspect ratio differs from target, recalculate crop points!
483             if ($s_ar > $t_ar) {
484                 $cx = floor($width / 2 - $height * $t_ar / 2);
485                 $cw = ceil($height * $t_ar);
486             } elseif ($s_ar < $t_ar) {
487                 $cy = floor($height / 2 - $width / $t_ar / 2);
488                 $ch = ceil($width / $t_ar);
489             }
490         } else {
491             $rw = $maxW;
492             $rh = ceil($height * $rw / $width);
493
494             // Scaling caused too large height, decrease to max accepted value
495             if ($rh > $maxH) {
496                 $rh = $maxH;
497                 $rw = ceil($width * $rh / $height);
498             }
499         }
500         return array(intval($rw), intval($rh),
501                     intval($cx), intval($cy),
502                     is_null($cw) ? $width : intval($cw),
503                     is_null($ch) ? $height : intval($ch));
504     }
505
506     /**
507      * Animated GIF test, courtesy of frank at huddler dot com et al:
508      * http://php.net/manual/en/function.imagecreatefromgif.php#104473
509      * Modified so avoid landing inside of a header (and thus not matching our regexp).
510      */
511     protected function isAnimatedGif()
512     {
513         if (!($fh = @fopen($this->filepath, 'rb'))) {
514             return false;
515         }
516
517         $count = 0;
518         //an animated gif contains multiple "frames", with each frame having a
519         //header made up of:
520         // * a static 4-byte sequence (\x00\x21\xF9\x04)
521         // * 4 variable bytes
522         // * a static 2-byte sequence (\x00\x2C)
523         // In total the header is maximum 10 bytes.
524
525         // We read through the file til we reach the end of the file, or we've found
526         // at least 2 frame headers
527         while(!feof($fh) && $count < 2) {
528             $chunk = fread($fh, 1024 * 100); //read 100kb at a time
529             $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
530             // rewind in case we ended up in the middle of the header, but avoid
531             // infinite loop (i.e. don't rewind if we're already in the end).
532             if (!feof($fh) && ftell($fh) >= 9) {
533                 fseek($fh, -9, SEEK_CUR);
534             }
535         }
536
537         fclose($fh);
538         return $count > 1;
539     }
540 }
541
542 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
543 if(!function_exists('imagecreatefrombmp')){
544     //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
545     function imagecreatefrombmp($p_sFile)
546     {
547         //    Load the image into a string
548         $file    =    fopen($p_sFile,"rb");
549         $read    =    fread($file,10);
550         while(!feof($file)&&($read<>""))
551             $read    .=    fread($file,1024);
552
553         $temp    =    unpack("H*",$read);
554         $hex    =    $temp[1];
555         $header    =    substr($hex,0,108);
556
557         //    Process the header
558         //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
559         if (substr($header,0,4)=="424d")
560         {
561             //    Cut it in parts of 2 bytes
562             $header_parts    =    str_split($header,2);
563
564             //    Get the width        4 bytes
565             $width            =    hexdec($header_parts[19].$header_parts[18]);
566
567             //    Get the height        4 bytes
568             $height            =    hexdec($header_parts[23].$header_parts[22]);
569
570             //    Unset the header params
571             unset($header_parts);
572         }
573
574         //    Define starting X and Y
575         $x                =    0;
576         $y                =    1;
577
578         //    Create newimage
579         $image            =    imagecreatetruecolor($width,$height);
580
581         //    Grab the body from the image
582         $body            =    substr($hex,108);
583
584         //    Calculate if padding at the end-line is needed
585         //    Divided by two to keep overview.
586         //    1 byte = 2 HEX-chars
587         $body_size        =    (strlen($body)/2);
588         $header_size    =    ($width*$height);
589
590         //    Use end-line padding? Only when needed
591         $usePadding        =    ($body_size>($header_size*3)+4);
592
593         //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
594         //    Calculate the next DWORD-position in the body
595         for ($i=0;$i<$body_size;$i+=3)
596         {
597             //    Calculate line-ending and padding
598             if ($x>=$width)
599             {
600                 //    If padding needed, ignore image-padding
601                 //    Shift i to the ending of the current 32-bit-block
602                 if ($usePadding)
603                     $i    +=    $width%4;
604
605                 //    Reset horizontal position
606                 $x    =    0;
607
608                 //    Raise the height-position (bottom-up)
609                 $y++;
610
611                 //    Reached the image-height? Break the for-loop
612                 if ($y>$height)
613                     break;
614             }
615
616             //    Calculation of the RGB-pixel (defined as BGR in image-data)
617             //    Define $i_pos as absolute position in the body
618             $i_pos    =    $i*2;
619             $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
620             $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
621             $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);
622
623             //    Calculate and draw the pixel
624             $color    =    imagecolorallocate($image,$r,$g,$b);
625             imagesetpixel($image,$x,$height-$y,$color);
626
627             //    Raise the horizontal position
628             $x++;
629         }
630
631         //    Unset the body / free the memory
632         unset($body);
633
634         //    Return image-object
635         return $image;
636     }
637 }   // if(!function_exists('imagecreatefrombmp'))