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