]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
move image type checking to constructor, so checking will be done in all cases
[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('STATUSNET') && !defined('LACONICA')) {
32     exit(1);
33 }
34
35 /**
36  * A wrapper on uploaded files
37  *
38  * Makes it slightly easier to accept an image file from upload.
39  *
40  * @category Image
41  * @package  StatusNet
42  * @author   Evan Prodromou <evan@status.net>
43  * @author   Zach Copley <zach@status.net>
44  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45  * @link     http://status.net/
46  */
47
48 class ImageFile
49 {
50     var $id;
51     var $filepath;
52     var $barename;
53     var $type;
54     var $height;
55     var $width;
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_BMP ||
68             ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
69             ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
70             ($info[2] == IMAGETYPE_XPM && function_exists('imagecreatefromxpm')) ||
71             ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
72
73             @unlink($_FILES[$param]['tmp_name']);
74             throw new Exception(_('Unsupported image file format.'));
75             return;
76         }
77
78         $this->type = ($info) ? $info[2]:$type;
79         $this->width = ($info) ? $info[0]:$width;
80         $this->height = ($info) ? $info[1]:$height;
81     }
82
83     static function fromUpload($param='upload')
84     {
85         switch ($_FILES[$param]['error']) {
86          case UPLOAD_ERR_OK: // success, jump out
87             break;
88          case UPLOAD_ERR_INI_SIZE:
89          case UPLOAD_ERR_FORM_SIZE:
90             throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'),
91                 ImageFile::maxFileSize()));
92             return;
93          case UPLOAD_ERR_PARTIAL:
94             @unlink($_FILES[$param]['tmp_name']);
95             throw new Exception(_('Partial upload.'));
96             return;
97          case UPLOAD_ERR_NO_FILE:
98             // No file; probably just a non-AJAX submission.
99             return;
100          default:
101             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
102                 $_FILES[$param]['error']);
103             throw new Exception(_('System error uploading file.'));
104             return;
105         }
106
107         $info = @getimagesize($_FILES[$param]['tmp_name']);
108
109         if (!$info) {
110             @unlink($_FILES[$param]['tmp_name']);
111             throw new Exception(_('Not an image or corrupt file.'));
112             return;
113         }
114
115         return new ImageFile(null, $_FILES[$param]['tmp_name']);
116     }
117
118     function resize($size, $x = 0, $y = 0, $w = null, $h = null)
119     {
120         $w = ($w === null) ? $this->width:$w;
121         $h = ($h === null) ? $this->height:$h;
122
123         if (!file_exists($this->filepath)) {
124             throw new Exception(_('Lost our file.'));
125             return;
126         }
127
128         // Don't crop/scale if it isn't necessary
129         if ($size === $this->width
130             && $size === $this->height
131             && $x === 0
132             && $y === 0
133             && $w === $this->width
134             && $h === $this->height) {
135
136             $outname = Avatar::filename($this->id,
137                                         image_type_to_extension($this->type),
138                                         $size,
139                                         common_timestamp());
140             $outpath = Avatar::path($outname);
141             @copy($this->filepath, $outpath);
142             return $outname;
143         }
144
145         switch ($this->type) {
146          case IMAGETYPE_GIF:
147             $image_src = imagecreatefromgif($this->filepath);
148             break;
149          case IMAGETYPE_JPEG:
150             $image_src = imagecreatefromjpeg($this->filepath);
151             break;
152          case IMAGETYPE_PNG:
153             $image_src = imagecreatefrompng($this->filepath);
154             break;
155          case IMAGETYPE_BMP:
156             $image_src = imagecreatefrombmp($this->filepath);
157             break;
158          case IMAGETYPE_WBMP:
159             $image_src = imagecreatefromwbmp($this->filepath);
160             break;
161          case IMAGETYPE_XBM:
162             $image_src = imagecreatefromxbm($this->filepath);
163             break;
164          case IMAGETYPE_XPM:
165             $image_src = imagecreatefromxpm($this->filepath);
166             break;
167          default:
168             throw new Exception(_('Unknown file type'));
169             return;
170         }
171
172         $image_dest = imagecreatetruecolor($size, $size);
173
174         if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
175
176             $transparent_idx = imagecolortransparent($image_src);
177
178             if ($transparent_idx >= 0) {
179
180                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
181                 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
182                 imagefill($image_dest, 0, 0, $transparent_idx);
183                 imagecolortransparent($image_dest, $transparent_idx);
184
185             } elseif ($this->type == IMAGETYPE_PNG) {
186
187                 imagealphablending($image_dest, false);
188                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
189                 imagefill($image_dest, 0, 0, $transparent);
190                 imagesavealpha($image_dest, true);
191
192             }
193         }
194
195         imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $size, $size, $w, $h);
196
197         if($this->type == IMAGETYPE_BMP) {
198             //we don't want to save BMP... it's an inefficient, rare, antiquated format
199             //save png instead
200             $this->type = IMAGETYPE_PNG;
201         } else if($this->type == IMAGETYPE_WBMP) {
202             //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
203             //save png instead
204             $this->type = IMAGETYPE_PNG;
205         } else if($this->type == IMAGETYPE_XBM) {
206             //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
207             //save png instead
208             $this->type = IMAGETYPE_PNG;
209         } else if($this->type == IMAGETYPE_XPM) {
210             //we don't want to save XPM... it's a rare format that we can't guarantee clients will support
211             //save png instead
212             $this->type = IMAGETYPE_PNG;
213         }
214
215         $outname = Avatar::filename($this->id,
216                                     image_type_to_extension($this->type),
217                                     $size,
218                                     common_timestamp());
219
220         $outpath = Avatar::path($outname);
221
222         switch ($this->type) {
223          case IMAGETYPE_GIF:
224             imagegif($image_dest, $outpath);
225             break;
226          case IMAGETYPE_JPEG:
227             imagejpeg($image_dest, $outpath, 100);
228             break;
229          case IMAGETYPE_PNG:
230             imagepng($image_dest, $outpath);
231             break;
232          default:
233             throw new Exception(_('Unknown file type'));
234             return;
235         }
236
237         imagedestroy($image_src);
238         imagedestroy($image_dest);
239
240         return $outname;
241     }
242
243     function unlink()
244     {
245         @unlink($this->filename);
246     }
247
248     static function maxFileSize()
249     {
250         $value = ImageFile::maxFileSizeInt();
251
252         if ($value > 1024 * 1024) {
253             return ($value/(1024*1024)) . _('MB');
254         } else if ($value > 1024) {
255             return ($value/(1024)) . _('kB');
256         } else {
257             return $value;
258         }
259     }
260
261     static function maxFileSizeInt()
262     {
263         return min(ImageFile::strToInt(ini_get('post_max_size')),
264                    ImageFile::strToInt(ini_get('upload_max_filesize')),
265                    ImageFile::strToInt(ini_get('memory_limit')));
266     }
267
268     static function strToInt($str)
269     {
270         $unit = substr($str, -1);
271         $num = substr($str, 0, -1);
272
273         switch(strtoupper($unit)){
274          case 'G':
275             $num *= 1024;
276          case 'M':
277             $num *= 1024;
278          case 'K':
279             $num *= 1024;
280         }
281
282         return $num;
283     }
284 }
285
286 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
287 if(!function_exists('imagecreatefrombmp')){
288     //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
289     function imagecreatefrombmp($p_sFile)
290     {
291         //    Load the image into a string
292         $file    =    fopen($p_sFile,"rb");
293         $read    =    fread($file,10);
294         while(!feof($file)&&($read<>""))
295             $read    .=    fread($file,1024);
296
297         $temp    =    unpack("H*",$read);
298         $hex    =    $temp[1];
299         $header    =    substr($hex,0,108);
300
301         //    Process the header
302         //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
303         if (substr($header,0,4)=="424d")
304         {
305             //    Cut it in parts of 2 bytes
306             $header_parts    =    str_split($header,2);
307
308             //    Get the width        4 bytes
309             $width            =    hexdec($header_parts[19].$header_parts[18]);
310
311             //    Get the height        4 bytes
312             $height            =    hexdec($header_parts[23].$header_parts[22]);
313
314             //    Unset the header params
315             unset($header_parts);
316         }
317
318         //    Define starting X and Y
319         $x                =    0;
320         $y                =    1;
321
322         //    Create newimage
323         $image            =    imagecreatetruecolor($width,$height);
324
325         //    Grab the body from the image
326         $body            =    substr($hex,108);
327
328         //    Calculate if padding at the end-line is needed
329         //    Divided by two to keep overview.
330         //    1 byte = 2 HEX-chars
331         $body_size        =    (strlen($body)/2);
332         $header_size    =    ($width*$height);
333
334         //    Use end-line padding? Only when needed
335         $usePadding        =    ($body_size>($header_size*3)+4);
336
337         //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
338         //    Calculate the next DWORD-position in the body
339         for ($i=0;$i<$body_size;$i+=3)
340         {
341             //    Calculate line-ending and padding
342             if ($x>=$width)
343             {
344                 //    If padding needed, ignore image-padding
345                 //    Shift i to the ending of the current 32-bit-block
346                 if ($usePadding)
347                     $i    +=    $width%4;
348
349                 //    Reset horizontal position
350                 $x    =    0;
351
352                 //    Raise the height-position (bottom-up)
353                 $y++;
354
355                 //    Reached the image-height? Break the for-loop
356                 if ($y>$height)
357                     break;
358             }
359
360             //    Calculation of the RGB-pixel (defined as BGR in image-data)
361             //    Define $i_pos as absolute position in the body
362             $i_pos    =    $i*2;
363             $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
364             $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
365             $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);
366
367             //    Calculate and draw the pixel
368             $color    =    imagecolorallocate($image,$r,$g,$b);
369             imagesetpixel($image,$x,$height-$y,$color);
370
371             //    Raise the horizontal position
372             $x++;
373         }
374
375         //    Unset the body / free the memory
376         unset($body);
377
378         //    Return image-object
379         return $image;
380     }
381 }