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