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