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