]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
Fix for ticket #3007: .bmp avatar uploads weren't being properly converted to PNG...
[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             // TRANS: Exception thrown when too large a file is uploaded.
89             // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
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     /**
119      * Compat interface for old code generating avatar thumbnails...
120      * Saves the scaled file directly into the avatar area.
121      *
122      * @param int $size target width & height -- must be square
123      * @param int $x (default 0) upper-left corner to crop from
124      * @param int $y (default 0) upper-left corner to crop from
125      * @param int $w (default full) width of image area to crop
126      * @param int $h (default full) height of image area to crop
127      * @return string filename
128      */
129     function resize($size, $x = 0, $y = 0, $w = null, $h = null)
130     {
131         $targetType = $this->preferredType();
132         $outname = Avatar::filename($this->id,
133                                     image_type_to_extension($targetType),
134                                     $size,
135                                     common_timestamp());
136         $outpath = Avatar::path($outname);
137         $this->resizeTo($outpath, $size, $size, $x, $y, $w, $h);
138         return $outname;
139     }
140
141     /**
142      * Copy the image file to the given destination.
143      * For obscure formats, this will automatically convert to PNG;
144      * otherwise the original file will be copied as-is.
145      *
146      * @param string $outpath
147      * @return string filename
148      */
149     function copyTo($outpath)
150     {
151         return $this->resizeTo($outpath, $this->width, $this->height);
152     }
153
154     /**
155      * Create and save a thumbnail image.
156      *
157      * @param string $outpath
158      * @param int $width target width
159      * @param int $height target height
160      * @param int $x (default 0) upper-left corner to crop from
161      * @param int $y (default 0) upper-left corner to crop from
162      * @param int $w (default full) width of image area to crop
163      * @param int $h (default full) height of image area to crop
164      * @return string full local filesystem filename
165      */
166     function resizeTo($outpath, $width, $height, $x=0, $y=0, $w=null, $h=null)
167     {
168         $w = ($w === null) ? $this->width:$w;
169         $h = ($h === null) ? $this->height:$h;
170         $targetType = $this->preferredType();
171
172         if (!file_exists($this->filepath)) {
173             throw new Exception(_('Lost our file.'));
174             return;
175         }
176
177         // Don't crop/scale if it isn't necessary
178         if ($width === $this->width
179             && $height === $this->height
180             && $x === 0
181             && $y === 0
182             && $w === $this->width
183             && $h === $this->height
184             && $this->type == $targetType) {
185
186             @copy($this->filepath, $outpath);
187             return $outpath;
188         }
189
190         switch ($this->type) {
191          case IMAGETYPE_GIF:
192             $image_src = imagecreatefromgif($this->filepath);
193             break;
194          case IMAGETYPE_JPEG:
195             $image_src = imagecreatefromjpeg($this->filepath);
196             break;
197          case IMAGETYPE_PNG:
198             $image_src = imagecreatefrompng($this->filepath);
199             break;
200          case IMAGETYPE_BMP:
201             $image_src = imagecreatefrombmp($this->filepath);
202             break;
203          case IMAGETYPE_WBMP:
204             $image_src = imagecreatefromwbmp($this->filepath);
205             break;
206          case IMAGETYPE_XBM:
207             $image_src = imagecreatefromxbm($this->filepath);
208             break;
209          default:
210             throw new Exception(_('Unknown file type'));
211             return;
212         }
213
214         $image_dest = imagecreatetruecolor($width, $height);
215
216         if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
217
218             $transparent_idx = imagecolortransparent($image_src);
219
220             if ($transparent_idx >= 0) {
221
222                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
223                 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
224                 imagefill($image_dest, 0, 0, $transparent_idx);
225                 imagecolortransparent($image_dest, $transparent_idx);
226
227             } elseif ($this->type == IMAGETYPE_PNG) {
228
229                 imagealphablending($image_dest, false);
230                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
231                 imagefill($image_dest, 0, 0, $transparent);
232                 imagesavealpha($image_dest, true);
233
234             }
235         }
236
237         imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $width, $height, $w, $h);
238
239         switch ($targetType) {
240          case IMAGETYPE_GIF:
241             imagegif($image_dest, $outpath);
242             break;
243          case IMAGETYPE_JPEG:
244             imagejpeg($image_dest, $outpath, 100);
245             break;
246          case IMAGETYPE_PNG:
247             imagepng($image_dest, $outpath);
248             break;
249          default:
250             throw new Exception(_('Unknown file type'));
251             return;
252         }
253
254         imagedestroy($image_src);
255         imagedestroy($image_dest);
256
257         return $outpath;
258     }
259
260     /**
261      * Several obscure file types should be normalized to PNG on resize.
262      *
263      * @fixme consider flattening anything not GIF or JPEG to PNG
264      * @return int
265      */
266     function preferredType()
267     {
268         if($this->type == IMAGETYPE_BMP) {
269             //we don't want to save BMP... it's an inefficient, rare, antiquated format
270             //save png instead
271             return IMAGETYPE_PNG;
272         } else if($this->type == IMAGETYPE_WBMP) {
273             //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
274             //save png instead
275             return IMAGETYPE_PNG;
276         } else if($this->type == IMAGETYPE_XBM) {
277             //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
278             //save png instead
279             return IMAGETYPE_PNG;
280         }
281         return $this->type;
282     }
283
284     function unlink()
285     {
286         @unlink($this->filename);
287     }
288
289     static function maxFileSize()
290     {
291         $value = ImageFile::maxFileSizeInt();
292
293         if ($value > 1024 * 1024) {
294             $value = $value/(1024*1024);
295             // TRANS: Number of megabytes. %d is the number.
296             return sprintf(_m('%dMB','%dMB',$value),$value);
297         } else if ($value > 1024) {
298             $value = $value/1024;
299             // TRANS: Number of kilobytes. %d is the number.
300             return sprintf(_m('%dkB','%dkB',$value),$value);
301         } else {
302             // TRANS: Number of bytes. %d is the number.
303             return sprintf(_m('%dB','%dB',$value),$value);
304         }
305     }
306
307     static function maxFileSizeInt()
308     {
309         return min(ImageFile::strToInt(ini_get('post_max_size')),
310                    ImageFile::strToInt(ini_get('upload_max_filesize')),
311                    ImageFile::strToInt(ini_get('memory_limit')));
312     }
313
314     static function strToInt($str)
315     {
316         $unit = substr($str, -1);
317         $num = substr($str, 0, -1);
318
319         switch(strtoupper($unit)){
320          case 'G':
321             $num *= 1024;
322          case 'M':
323             $num *= 1024;
324          case 'K':
325             $num *= 1024;
326         }
327
328         return $num;
329     }
330 }
331
332 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
333 if(!function_exists('imagecreatefrombmp')){
334     //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
335     function imagecreatefrombmp($p_sFile)
336     {
337         //    Load the image into a string
338         $file    =    fopen($p_sFile,"rb");
339         $read    =    fread($file,10);
340         while(!feof($file)&&($read<>""))
341             $read    .=    fread($file,1024);
342
343         $temp    =    unpack("H*",$read);
344         $hex    =    $temp[1];
345         $header    =    substr($hex,0,108);
346
347         //    Process the header
348         //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
349         if (substr($header,0,4)=="424d")
350         {
351             //    Cut it in parts of 2 bytes
352             $header_parts    =    str_split($header,2);
353
354             //    Get the width        4 bytes
355             $width            =    hexdec($header_parts[19].$header_parts[18]);
356
357             //    Get the height        4 bytes
358             $height            =    hexdec($header_parts[23].$header_parts[22]);
359
360             //    Unset the header params
361             unset($header_parts);
362         }
363
364         //    Define starting X and Y
365         $x                =    0;
366         $y                =    1;
367
368         //    Create newimage
369         $image            =    imagecreatetruecolor($width,$height);
370
371         //    Grab the body from the image
372         $body            =    substr($hex,108);
373
374         //    Calculate if padding at the end-line is needed
375         //    Divided by two to keep overview.
376         //    1 byte = 2 HEX-chars
377         $body_size        =    (strlen($body)/2);
378         $header_size    =    ($width*$height);
379
380         //    Use end-line padding? Only when needed
381         $usePadding        =    ($body_size>($header_size*3)+4);
382
383         //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
384         //    Calculate the next DWORD-position in the body
385         for ($i=0;$i<$body_size;$i+=3)
386         {
387             //    Calculate line-ending and padding
388             if ($x>=$width)
389             {
390                 //    If padding needed, ignore image-padding
391                 //    Shift i to the ending of the current 32-bit-block
392                 if ($usePadding)
393                     $i    +=    $width%4;
394
395                 //    Reset horizontal position
396                 $x    =    0;
397
398                 //    Raise the height-position (bottom-up)
399                 $y++;
400
401                 //    Reached the image-height? Break the for-loop
402                 if ($y>$height)
403                     break;
404             }
405
406             //    Calculation of the RGB-pixel (defined as BGR in image-data)
407             //    Define $i_pos as absolute position in the body
408             $i_pos    =    $i*2;
409             $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
410             $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
411             $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);
412
413             //    Calculate and draw the pixel
414             $color    =    imagecolorallocate($image,$r,$g,$b);
415             imagesetpixel($image,$x,$height-$y,$color);
416
417             //    Raise the horizontal position
418             $x++;
419         }
420
421         //    Unset the body / free the memory
422         unset($body);
423
424         //    Return image-object
425         return $image;
426     }
427 }