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