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