]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
2138a03e60f8c1721309c1f5c3a30eae489c2ab5
[quix0rs-gnu-social.git] / lib / imagefile.php
1 <?php
2 /**
3  * GNU social - a federating social network
4  *
5  * Abstraction for an image file
6  *
7  * LICENCE: This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Image
21  * @package   GNUsocial
22  * @author    Evan Prodromou <evan@status.net>
23  * @author    Zach Copley <zach@status.net>
24  * @author    Mikael Nordfeldth <mmn@hethane.se>
25  * @author    Miguel Dantas <biodantasgs@gmail.com>
26  * @copyright 2008, 2019 Free Software Foundation http://fsf.org
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      https://www.gnu.org/software/social/
29  */
30
31 defined('GNUSOCIAL') || die();
32
33 /**
34  * A wrapper on uploaded images
35  *
36  * Makes it slightly easier to accept an image file from upload.
37  *
38  * @category Image
39  * @package  GNUsocial
40  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
41  * @author   Evan Prodromou <evan@status.net>
42  * @author   Zach Copley <zach@status.net>
43  * @link      https://www.gnu.org/software/social/
44  */
45 class ImageFile extends MediaFile
46 {
47     public $type;
48     public $height;
49     public $width;
50     public $rotate   = 0;    // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
51     public $animated = null; // Animated image? (has more than 1 frame). null means untested
52     public $mimetype = null; // The _ImageFile_ mimetype, _not_ the originating File object
53
54     public function __construct($id, string $filepath)
55     {
56         // These do not have to be the same as fileRecord->filename for example,
57         // since we may have generated an image source file from something else!
58         $this->filepath = $filepath;
59         $this->filename = basename($filepath);
60
61         $info = @getimagesize($this->filepath);
62
63         if (!(($info[2] == IMAGETYPE_GIF  && function_exists('imagecreatefromgif'))  ||
64               ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
65               ($info[2] == IMAGETYPE_BMP  && function_exists('imagecreatefrombmp')) ||
66               ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
67               ($info[2] == IMAGETYPE_XBM  && function_exists('imagecreatefromxbm'))  ||
68               ($info[2] == IMAGETYPE_PNG  && function_exists('imagecreatefrompng')))) {
69             // TRANS: Exception thrown when trying to upload an unsupported image file format.
70             throw new UnsupportedMediaException(_m('Unsupported image format.'), $this->filepath);
71         }
72
73         $this->width    = $info[0];
74         $this->height   = $info[1];
75         $this->type     = $info[2];
76         $this->mimetype = $info['mime'];
77
78         parent::__construct(
79             $filepath,
80             $this->mimetype,
81             null /* filehash, MediaFile will calculate it */,
82             $id
83         );
84
85         if ($this->type === IMAGETYPE_JPEG && function_exists('exif_read_data')) {
86             // Orientation value to rotate thumbnails properly
87             $exif = @exif_read_data($this->filepath);
88             if (is_array($exif) && isset($exif['Orientation'])) {
89                 switch (intval($exif['Orientation'])) {
90                 case 1: // top is top
91                     $this->rotate = 0;
92                     break;
93                 case 3: // top is bottom
94                     $this->rotate = 180;
95                     break;
96                 case 6: // top is right
97                     $this->rotate = -90;
98                     break;
99                 case 8: // top is left
100                     $this->rotate = 90;
101                     break;
102                 }
103                 // If we ever write this back, Orientation should be set to '1'
104             }
105         } elseif ($this->type === IMAGETYPE_GIF) {
106             $this->animated = $this->isAnimatedGif();
107         }
108
109         Event::handle('FillImageFileMetadata', array($this));
110     }
111
112     public static function fromFileObject(File $file)
113     {
114         $imgPath = null;
115         $media = common_get_mime_media($file->mimetype);
116         if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
117             if (empty($file->filename) && !file_exists($imgPath)) {
118                 throw new UnsupportedMediaException(_m('File without filename could not get a thumbnail source.'));
119             }
120
121             // First some mimetype specific exceptions
122             switch ($file->mimetype) {
123             case 'image/svg+xml':
124                 throw new UseFileAsThumbnailException($file);
125             }
126
127             // And we'll only consider it an image if it has such a media type
128             switch ($media) {
129             case 'image':
130                 $imgPath = $file->getPath();
131                 break;
132             default:
133                 throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
134             }
135         }
136
137         if (!file_exists($imgPath)) {
138             throw new FileNotFoundException($imgPath);
139         }
140
141         try {
142             $image = new ImageFile($file->getID(), $imgPath);
143         } catch (Exception $e) {
144             // Avoid deleting the original
145             try {
146                 if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
147                     common_debug(__METHOD__.': Deleting temporary file that was created as image file' .
148                                  'thumbnail source: '._ve($imgPath));
149                     @unlink($imgPath);
150                 }
151             } catch (FileNotFoundException $e) {
152                 // File reported (via getPath) that the original file
153                 // doesn't exist anyway, so it's safe to delete $imgPath
154                 @unlink($imgPath);
155             }
156             common_debug(sprintf(
157                 'Exception %s caught when creating ImageFile for File id==%s ' .
158                                  'and imgPath==%s: %s',
159                 get_class($e),
160                 _ve($file->id),
161                 _ve($imgPath),
162                 _ve($e->getMessage())
163             ));
164             throw $e;
165         }
166         return $image;
167     }
168
169     public function getPath()
170     {
171         if (!file_exists($this->filepath)) {
172             throw new FileNotFoundException($this->filepath);
173         }
174
175         return $this->filepath;
176     }
177
178     /**
179      * Process a file upload
180      *
181      * Uses MediaFile's `fromUpload` to do the majority of the work and reencodes the image,
182      * to mitigate injection attacks.
183      * @param string $param
184      * @param Profile|null $scoped
185      * @return ImageFile|MediaFile
186      * @throws ClientException
187      * @throws NoResultException
188      * @throws NoUploadedMediaException
189      * @throws ServerException
190      * @throws UnsupportedMediaException
191      * @throws UseFileAsThumbnailException
192      */
193     public static function fromUpload(string $param='upload', Profile $scoped = null)
194     {
195         return parent::fromUpload($param, $scoped);
196     }
197
198     /**
199      * Several obscure file types should be normalized to PNG on resize.
200      *
201      * Keeps only PNG, JPEG and GIF
202      *
203      * @return int
204      */
205     public function preferredType()
206     {
207         // Keep only JPEG and GIF in their orignal format
208         if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
209             return $this->type;
210         }
211         // We don't want to save some formats as they are rare, inefficient and antiquated
212         // thus we can't guarantee clients will support
213         // So just save it as PNG
214         return IMAGETYPE_PNG;
215     }
216
217     /**
218      * Copy the image file to the given destination.
219      *
220      * This function may modify the resulting file. Please use the
221      * returned ImageFile object to read metadata (width, height etc.)
222      *
223      * @param string $outpath
224      * @return ImageFile the image stored at target path
225      * @throws ClientException
226      * @throws NoResultException
227      * @throws ServerException
228      * @throws UnsupportedMediaException
229      * @throws UseFileAsThumbnailException
230      */
231     public function copyTo($outpath)
232     {
233         return new ImageFile(null, $this->resizeTo($outpath));
234     }
235
236     /**
237      * Create and save a thumbnail image.
238      *
239      * @param string $outpath
240      * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
241      * @return string full local filesystem filename
242      * @throws UnsupportedMediaException
243      * @throws UseFileAsThumbnailException
244      */
245     public function resizeTo($outpath, array $box=array())
246     {
247         $box['width']  = isset($box['width'])  ? intval($box['width'])  : $this->width;
248         $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
249         $box['x']      = isset($box['x'])      ? intval($box['x'])      : 0;
250         $box['y']      = isset($box['y'])      ? intval($box['y'])      : 0;
251         $box['w']      = isset($box['w'])      ? intval($box['w'])      : $this->width;
252         $box['h']      = isset($box['h'])      ? intval($box['h'])      : $this->height;
253
254         if (!file_exists($this->filepath)) {
255             // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
256             throw new Exception(_m('Lost our file.'));
257         }
258
259         // Don't rotate/crop/scale if it isn't necessary
260         if ($box['width']     === $this->width
261             && $box['height'] === $this->height
262             && $box['x']      === 0
263             && $box['y']      === 0
264             && $box['w']      === $this->width
265             && $box['h']      === $this->height
266             && $this->type    === $this->preferredType()) {
267             if (abs($this->rotate) == 90) {
268                 // Box is rotated 90 degrees in either direction,
269                 // so we have to redefine x to y and vice versa.
270                 $tmp = $box['width'];
271                 $box['width'] = $box['height'];
272                 $box['height'] = $tmp;
273                 $tmp = $box['x'];
274                 $box['x'] = $box['y'];
275                 $box['y'] = $tmp;
276                 $tmp = $box['w'];
277                 $box['w'] = $box['h'];
278                 $box['h'] = $tmp;
279             }
280         }
281
282         if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
283             $this->resizeToFile($outpath, $box);
284         }
285
286         if (!file_exists($outpath)) {
287             if ($this->fileRecord instanceof File) {
288                 throw new UseFileAsThumbnailException($this->fileRecord);
289             } else {
290                 throw new UnsupportedMediaException('No local File object exists for ImageFile.');
291             }
292         }
293
294         return $outpath;
295     }
296
297     /**
298      * Resizes a file. If $box is omitted, the size is not changed, but this is still useful,
299      * because it will reencode the image in the `self::prefferedType()` format. This only
300      * applies henceforward, not retroactively
301      *
302      * Increases the 'memory_limit' to the one in the 'attachments' section in the config, to
303      * enable the handling of bigger images, which can cause a peak of memory consumption, while
304      * encoding
305      * @param $outpath
306      * @param array $box
307      * @throws Exception
308      */
309     protected function resizeToFile($outpath, array $box)
310     {
311         $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
312         $image_src = null;
313         switch ($this->type) {
314         case IMAGETYPE_GIF:
315             $image_src = imagecreatefromgif($this->filepath);
316             break;
317         case IMAGETYPE_JPEG:
318             $image_src = imagecreatefromjpeg($this->filepath);
319             break;
320         case IMAGETYPE_PNG:
321             $image_src = imagecreatefrompng($this->filepath);
322             break;
323         case IMAGETYPE_BMP:
324             $image_src = imagecreatefrombmp($this->filepath);
325             break;
326         case IMAGETYPE_WBMP:
327             $image_src = imagecreatefromwbmp($this->filepath);
328             break;
329         case IMAGETYPE_XBM:
330             $image_src = imagecreatefromxbm($this->filepath);
331             break;
332         default:
333             // TRANS: Exception thrown when trying to resize an unknown file type.
334             throw new Exception(_m('Unknown file type'));
335         }
336
337         if ($this->rotate != 0) {
338             $image_src = imagerotate($image_src, $this->rotate, 0);
339         }
340
341         $image_dest = imagecreatetruecolor($box['width'], $box['height']);
342
343         if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
344             $transparent_idx = imagecolortransparent($image_src);
345
346             if ($transparent_idx >= 0 && $transparent_idx < 255) {
347                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
348                 $transparent_idx = imagecolorallocate(
349                     $image_dest,
350                     $transparent_color['red'],
351                     $transparent_color['green'],
352                     $transparent_color['blue']
353                 );
354                 imagefill($image_dest, 0, 0, $transparent_idx);
355                 imagecolortransparent($image_dest, $transparent_idx);
356             } elseif ($this->type == IMAGETYPE_PNG) {
357                 imagealphablending($image_dest, false);
358                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
359                 imagefill($image_dest, 0, 0, $transparent);
360                 imagesavealpha($image_dest, true);
361             }
362         }
363
364         imagecopyresampled(
365             $image_dest,
366             $image_src,
367             0,
368             0,
369             $box['x'],
370             $box['y'],
371             $box['width'],
372             $box['height'],
373             $box['w'],
374             $box['h']
375         );
376
377         $type = $this->preferredType();
378         $ext = image_type_to_extension($type, true);
379         $outpath = preg_replace("/\.[^\.]+$/", $ext, $outpath);
380
381         switch ($type) {
382          case IMAGETYPE_GIF:
383             imagegif($image_dest, $outpath);
384             break;
385          case IMAGETYPE_JPEG:
386             imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
387             break;
388          case IMAGETYPE_PNG:
389             imagepng($image_dest, $outpath);
390             break;
391          default:
392             // TRANS: Exception thrown when trying resize an unknown file type.
393             throw new Exception(_m('Unknown file type'));
394         }
395
396         imagedestroy($image_src);
397         imagedestroy($image_dest);
398         ini_set('memory_limit', $old_limit); // Restore the old memory limit
399     }
400
401     public function unlink()
402     {
403         @unlink($this->filepath);
404     }
405
406     public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
407     {
408         return self::getScalingValues(
409             $this->width,
410             $this->height,
411             $maxWidth,
412             $maxHeight,
413             $crop,
414             $this->rotate
415         );
416     }
417
418     /**
419      * Gets scaling values for images of various types. Cropping can be enabled.
420      *
421      * Values will scale _up_ to fit max values if cropping is enabled!
422      * With cropping disabled, the max value of each axis will be respected.
423      *
424      * @param $width    int Original width
425      * @param $height   int Original height
426      * @param $maxW     int Resulting max width
427      * @param $maxH     int Resulting max height
428      * @param $crop     int Crop to the size (not preserving aspect ratio)
429      * @param int $rotate
430      * @return array
431      * @throws ServerException
432      */
433     public static function getScalingValues(
434         $width,
435         $height,
436         $maxW=null,
437         $maxH=null,
438         $crop=null,
439         $rotate=0
440     ) {
441         $maxW = $maxW ?: common_config('thumbnail', 'width');
442         $maxH = $maxH ?: common_config('thumbnail', 'height');
443
444         if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
445             throw new ServerException('Bad parameters for ImageFile::getScalingValues');
446         } elseif ($maxH === null) {
447             // if maxH is null, we set maxH to equal maxW and enable crop
448             $maxH = $maxW;
449             $crop = true;
450         }
451
452         // Because GD doesn't understand EXIF orientation etc.
453         if (abs($rotate) == 90) {
454             $tmp = $width;
455             $width = $height;
456             $height = $tmp;
457         }
458
459         // Cropping data (for original image size). Default values, 0 and null,
460         // imply no cropping and with preserved aspect ratio (per axis).
461         $cx = 0;    // crop x
462         $cy = 0;    // crop y
463         $cw = null; // crop area width
464         $ch = null; // crop area height
465
466         if ($crop) {
467             $s_ar = $width / $height;
468             $t_ar = $maxW / $maxH;
469
470             $rw = $maxW;
471             $rh = $maxH;
472
473             // Source aspect ratio differs from target, recalculate crop points!
474             if ($s_ar > $t_ar) {
475                 $cx = floor($width / 2 - $height * $t_ar / 2);
476                 $cw = ceil($height * $t_ar);
477             } elseif ($s_ar < $t_ar) {
478                 $cy = floor($height / 2 - $width / $t_ar / 2);
479                 $ch = ceil($width / $t_ar);
480             }
481         } else {
482             $rw = $maxW;
483             $rh = ceil($height * $rw / $width);
484
485             // Scaling caused too large height, decrease to max accepted value
486             if ($rh > $maxH) {
487                 $rh = $maxH;
488                 $rw = ceil($width * $rh / $height);
489             }
490         }
491         return array(intval($rw), intval($rh),
492                      intval($cx), intval($cy),
493                      is_null($cw) ? $width : intval($cw),
494                      is_null($ch) ? $height : intval($ch));
495     }
496
497     /**
498      * Animated GIF test, courtesy of frank at huddler dot com et al:
499      * http://php.net/manual/en/function.imagecreatefromgif.php#104473
500      * Modified so avoid landing inside of a header (and thus not matching our regexp).
501      */
502     protected function isAnimatedGif()
503     {
504         if (!($fh = @fopen($this->filepath, 'rb'))) {
505             return false;
506         }
507
508         $count = 0;
509         //an animated gif contains multiple "frames", with each frame having a
510         //header made up of:
511         // * a static 4-byte sequence (\x00\x21\xF9\x04)
512         // * 4 variable bytes
513         // * a static 2-byte sequence (\x00\x2C)
514         // In total the header is maximum 10 bytes.
515
516         // We read through the file til we reach the end of the file, or we've found
517         // at least 2 frame headers
518         while (!feof($fh) && $count < 2) {
519             $chunk = fread($fh, 1024 * 100); //read 100kb at a time
520             $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
521             // rewind in case we ended up in the middle of the header, but avoid
522             // infinite loop (i.e. don't rewind if we're already in the end).
523             if (!feof($fh) && ftell($fh) >= 9) {
524                 fseek($fh, -9, SEEK_CUR);
525             }
526         }
527
528         fclose($fh);
529         return $count >= 1; // number of animated frames apart from the original image
530     }
531
532     public function getFileThumbnail($width, $height, $crop, $upscale=false)
533     {
534         if (!$this->fileRecord instanceof File) {
535             throw new ServerException('No File object attached to this ImageFile object.');
536         }
537
538         if ($width === null) {
539             $width  = common_config('thumbnail', 'width');
540             $height = common_config('thumbnail', 'height');
541             $crop   = common_config('thumbnail', 'crop');
542         }
543
544         if (!$upscale) {
545             if ($width > $this->width) {
546                 $width = $this->width;
547             }
548             if (!is_null($height) && $height > $this->height) {
549                 $height = $this->height;
550             }
551         }
552
553         if ($height === null) {
554             $height = $width;
555             $crop = true;
556         }
557
558         // Get proper aspect ratio width and height before lookup
559         // We have to do it through an ImageFile object because of orientation etc.
560         // Only other solution would've been to rotate + rewrite uploaded files
561         // which we don't want to do because we like original, untouched data!
562         list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
563
564         $thumb = File_thumbnail::pkeyGet(array(
565                                             'file_id'=> $this->fileRecord->getID(),
566                                             'width'  => $width,
567                                             'height' => $height,
568                                          ));
569         if ($thumb instanceof File_thumbnail) {
570             return $thumb;
571         }
572
573         $filename = $this->fileRecord->filehash ?: $this->filename;    // Remote files don't have $this->filehash
574         $extension = File::guessMimeExtension($this->mimetype);
575         $outname = "thumb-{$this->fileRecord->getID()}-{$width}x{$height}-{$filename}." . $extension;
576         $outpath = File_thumbnail::path($outname);
577
578         // The boundary box for our resizing
579         $box = array('width'=>$width, 'height'=>$height,
580                      'x'=>$x,         'y'=>$y,
581                      'w'=>$w,         'h'=>$h);
582
583         // Doublecheck that parameters are sane and integers.
584         if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
585                 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
586                 || $box['w'] < 1 || $box['x'] >= $this->width
587                 || $box['h'] < 1 || $box['y'] >= $this->height) {
588             // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
589             common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box, true));
590             throw new ServerException('Bad thumbnail size parameters.');
591         }
592
593         common_debug(sprintf(
594             'Generating a thumbnail of File id==%u of size %ux%u',
595             $this->fileRecord->getID(),
596             $width,
597             $height
598         ));
599
600         // Perform resize and store into file
601         $this->resizeTo($outpath, $box);
602
603         try {
604             // Avoid deleting the original
605             if (!in_array($this->getPath(), [File::path($this->filename), File_thumbnail::path($this->filename)])) {
606                 $this->unlink();
607             }
608         } catch (FileNotFoundException $e) {
609             // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
610         }
611
612         return File_thumbnail::saveThumbnail(
613             $this->fileRecord->getID(),
614             // no url since we generated it ourselves and can dynamically
615             // generate the url
616             null,
617             $width,
618             $height,
619             $outname
620         );
621     }
622 }