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