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