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