]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
[CORE] Bump Database requirement to MariaDB 10.3+
[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             if($media !== 'image') {
129                 throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
130             } else if (!empty($file->filename)) {
131                 $imgPath = $file->getPath();
132             }
133         }
134
135         if (!file_exists($imgPath)) {
136             throw new FileNotFoundException($imgPath);
137         }
138
139         try {
140             $image = new ImageFile($file->getID(), $imgPath);
141         } catch (Exception $e) {
142             // Avoid deleting the original
143             try {
144                 if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
145                     common_debug(__METHOD__.': Deleting temporary file that was created as image file' .
146                                  'thumbnail source: '._ve($imgPath));
147                     @unlink($imgPath);
148                 }
149             } catch (FileNotFoundException $e) {
150                 // File reported (via getPath) that the original file
151                 // doesn't exist anyway, so it's safe to delete $imgPath
152                 @unlink($imgPath);
153             }
154             common_debug(sprintf(
155                 'Exception %s caught when creating ImageFile for File id==%s ' .
156                                  'and imgPath==%s: %s',
157                 get_class($e),
158                 _ve($file->id),
159                 _ve($imgPath),
160                 _ve($e->getMessage())
161             ));
162             throw $e;
163         }
164         return $image;
165     }
166
167     public function getPath()
168     {
169         if (!file_exists($this->filepath)) {
170             throw new FileNotFoundException($this->filepath);
171         }
172
173         return $this->filepath;
174     }
175
176     /**
177      * Process a file upload
178      *
179      * Uses MediaFile's `fromUpload` to do the majority of the work and reencodes the image,
180      * to mitigate injection attacks.
181      * @param string $param
182      * @param Profile|null $scoped
183      * @return ImageFile|MediaFile
184      * @throws ClientException
185      * @throws NoResultException
186      * @throws NoUploadedMediaException
187      * @throws ServerException
188      * @throws UnsupportedMediaException
189      * @throws UseFileAsThumbnailException
190      */
191     public static function fromUpload(string $param='upload', Profile $scoped = null)
192     {
193         return parent::fromUpload($param, $scoped);
194     }
195
196     /**
197      * Several obscure file types should be normalized to PNG on resize.
198      *
199      * Keeps only PNG, JPEG and GIF
200      *
201      * @return int
202      */
203     public function preferredType()
204     {
205         // Keep only JPEG and GIF in their orignal format
206         if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
207             return $this->type;
208         }
209         // We don't want to save some formats as they are rare, inefficient and antiquated
210         // thus we can't guarantee clients will support
211         // So just save it as PNG
212         return IMAGETYPE_PNG;
213     }
214
215     /**
216      * Copy the image file to the given destination.
217      *
218      * This function may modify the resulting file. Please use the
219      * returned ImageFile object to read metadata (width, height etc.)
220      *
221      * @param string $outpath
222      * @return ImageFile the image stored at target path
223      * @throws ClientException
224      * @throws NoResultException
225      * @throws ServerException
226      * @throws UnsupportedMediaException
227      * @throws UseFileAsThumbnailException
228      */
229     public function copyTo($outpath)
230     {
231         return new ImageFile(null, $this->resizeTo($outpath));
232     }
233
234     /**
235      * Create and save a thumbnail image.
236      *
237      * @param string $outpath
238      * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
239      * @return string full local filesystem filename
240      * @throws UnsupportedMediaException
241      * @throws UseFileAsThumbnailException
242      */
243     public function resizeTo($outpath, array $box=array())
244     {
245         $box['width']  = isset($box['width'])  ? intval($box['width'])  : $this->width;
246         $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
247         $box['x']      = isset($box['x'])      ? intval($box['x'])      : 0;
248         $box['y']      = isset($box['y'])      ? intval($box['y'])      : 0;
249         $box['w']      = isset($box['w'])      ? intval($box['w'])      : $this->width;
250         $box['h']      = isset($box['h'])      ? intval($box['h'])      : $this->height;
251
252         if (!file_exists($this->filepath)) {
253             // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
254             throw new Exception(_m('Lost our file.'));
255         }
256
257         // Don't rotate/crop/scale if it isn't necessary
258         if ($box['width']     === $this->width
259             && $box['height'] === $this->height
260             && $box['x']      === 0
261             && $box['y']      === 0
262             && $box['w']      === $this->width
263             && $box['h']      === $this->height
264             && $this->type    === $this->preferredType()) {
265             if (abs($this->rotate) == 90) {
266                 // Box is rotated 90 degrees in either direction,
267                 // so we have to redefine x to y and vice versa.
268                 $tmp = $box['width'];
269                 $box['width'] = $box['height'];
270                 $box['height'] = $tmp;
271                 $tmp = $box['x'];
272                 $box['x'] = $box['y'];
273                 $box['y'] = $tmp;
274                 $tmp = $box['w'];
275                 $box['w'] = $box['h'];
276                 $box['h'] = $tmp;
277             }
278         }
279
280         if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
281             $outpath = $this->resizeToFile($outpath, $box);
282         }
283
284         if (!file_exists($outpath)) {
285             if ($this->fileRecord instanceof File) {
286                 throw new UseFileAsThumbnailException($this->fileRecord);
287             } else {
288                 throw new UnsupportedMediaException('No local File object exists for ImageFile.');
289             }
290         }
291
292         return $outpath;
293     }
294
295     /**
296      * Resizes a file. If $box is omitted, the size is not changed, but this is still useful,
297      * because it will reencode the image in the `self::prefferedType()` format. This only
298      * applies henceforward, not retroactively
299      *
300      * Increases the 'memory_limit' to the one in the 'attachments' section in the config, to
301      * enable the handling of bigger images, which can cause a peak of memory consumption, while
302      * encoding
303      * @param $outpath
304      * @param array $box
305      * @throws Exception
306      */
307     protected function resizeToFile(string $outpath, array $box) : string
308     {
309         $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
310         $image_src = null;
311         switch ($this->type) {
312         case IMAGETYPE_GIF:
313             $image_src = imagecreatefromgif($this->filepath);
314             break;
315         case IMAGETYPE_JPEG:
316             $image_src = imagecreatefromjpeg($this->filepath);
317             break;
318         case IMAGETYPE_PNG:
319             $image_src = imagecreatefrompng($this->filepath);
320             break;
321         case IMAGETYPE_BMP:
322             $image_src = imagecreatefrombmp($this->filepath);
323             break;
324         case IMAGETYPE_WBMP:
325             $image_src = imagecreatefromwbmp($this->filepath);
326             break;
327         case IMAGETYPE_XBM:
328             $image_src = imagecreatefromxbm($this->filepath);
329             break;
330         default:
331             // TRANS: Exception thrown when trying to resize an unknown file type.
332             throw new Exception(_m('Unknown file type'));
333         }
334
335         if ($this->rotate != 0) {
336             $image_src = imagerotate($image_src, $this->rotate, 0);
337         }
338
339         $image_dest = imagecreatetruecolor($box['width'], $box['height']);
340
341         if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
342             $transparent_idx = imagecolortransparent($image_src);
343
344             if ($transparent_idx >= 0 && $transparent_idx < 255) {
345                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
346                 $transparent_idx = imagecolorallocate(
347                     $image_dest,
348                     $transparent_color['red'],
349                     $transparent_color['green'],
350                     $transparent_color['blue']
351                 );
352                 imagefill($image_dest, 0, 0, $transparent_idx);
353                 imagecolortransparent($image_dest, $transparent_idx);
354             } elseif ($this->type == IMAGETYPE_PNG) {
355                 imagealphablending($image_dest, false);
356                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
357                 imagefill($image_dest, 0, 0, $transparent);
358                 imagesavealpha($image_dest, true);
359             }
360         }
361
362         imagecopyresampled(
363             $image_dest,
364             $image_src,
365             0,
366             0,
367             $box['x'],
368             $box['y'],
369             $box['width'],
370             $box['height'],
371             $box['w'],
372             $box['h']
373         );
374
375         $type = $this->preferredType();
376
377         switch ($type) {
378          case IMAGETYPE_GIF:
379             imagegif($image_dest, $outpath);
380             break;
381          case IMAGETYPE_JPEG:
382             imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
383             break;
384          case IMAGETYPE_PNG:
385             imagepng($image_dest, $outpath);
386             break;
387          default:
388             // TRANS: Exception thrown when trying resize an unknown file type.
389             throw new Exception(_m('Unknown file type'));
390         }
391
392         imagedestroy($image_src);
393         imagedestroy($image_dest);
394         ini_set('memory_limit', $old_limit); // Restore the old memory limit
395
396         return $outpath;
397     }
398
399     public function unlink()
400     {
401         @unlink($this->filepath);
402     }
403
404     public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
405     {
406         return self::getScalingValues(
407             $this->width,
408             $this->height,
409             $maxWidth,
410             $maxHeight,
411             $crop,
412             $this->rotate
413         );
414     }
415
416     /**
417      * Gets scaling values for images of various types. Cropping can be enabled.
418      *
419      * Values will scale _up_ to fit max values if cropping is enabled!
420      * With cropping disabled, the max value of each axis will be respected.
421      *
422      * @param $width    int Original width
423      * @param $height   int Original height
424      * @param $maxW     int Resulting max width
425      * @param $maxH     int Resulting max height
426      * @param $crop     int Crop to the size (not preserving aspect ratio)
427      * @param int $rotate
428      * @return array
429      * @throws ServerException
430      */
431     public static function getScalingValues(
432         $width,
433         $height,
434         $maxW=null,
435         $maxH=null,
436         $crop=null,
437         $rotate=0
438     ) {
439         $maxW = $maxW ?: common_config('thumbnail', 'width');
440         $maxH = $maxH ?: common_config('thumbnail', 'height');
441
442         if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
443             throw new ServerException('Bad parameters for ImageFile::getScalingValues');
444         } elseif ($maxH === null) {
445             // if maxH is null, we set maxH to equal maxW and enable crop
446             $maxH = $maxW;
447             $crop = true;
448         }
449
450         // Because GD doesn't understand EXIF orientation etc.
451         if (abs($rotate) == 90) {
452             $tmp = $width;
453             $width = $height;
454             $height = $tmp;
455         }
456
457         // Cropping data (for original image size). Default values, 0 and null,
458         // imply no cropping and with preserved aspect ratio (per axis).
459         $cx = 0;    // crop x
460         $cy = 0;    // crop y
461         $cw = null; // crop area width
462         $ch = null; // crop area height
463
464         if ($crop) {
465             $s_ar = $width / $height;
466             $t_ar = $maxW / $maxH;
467
468             $rw = $maxW;
469             $rh = $maxH;
470
471             // Source aspect ratio differs from target, recalculate crop points!
472             if ($s_ar > $t_ar) {
473                 $cx = floor($width / 2 - $height * $t_ar / 2);
474                 $cw = ceil($height * $t_ar);
475             } elseif ($s_ar < $t_ar) {
476                 $cy = floor($height / 2 - $width / $t_ar / 2);
477                 $ch = ceil($width / $t_ar);
478             }
479         } else {
480             $rw = $maxW;
481             $rh = ceil($height * $rw / $width);
482
483             // Scaling caused too large height, decrease to max accepted value
484             if ($rh > $maxH) {
485                 $rh = $maxH;
486                 $rw = ceil($width * $rh / $height);
487             }
488         }
489         return array(intval($rw), intval($rh),
490                      intval($cx), intval($cy),
491                      is_null($cw) ? $width : intval($cw),
492                      is_null($ch) ? $height : intval($ch));
493     }
494
495     /**
496      * Animated GIF test, courtesy of frank at huddler dot com et al:
497      * http://php.net/manual/en/function.imagecreatefromgif.php#104473
498      * Modified so avoid landing inside of a header (and thus not matching our regexp).
499      */
500     protected function isAnimatedGif()
501     {
502         if (!($fh = @fopen($this->filepath, 'rb'))) {
503             return false;
504         }
505
506         $count = 0;
507         //an animated gif contains multiple "frames", with each frame having a
508         //header made up of:
509         // * a static 4-byte sequence (\x00\x21\xF9\x04)
510         // * 4 variable bytes
511         // * a static 2-byte sequence (\x00\x2C)
512         // In total the header is maximum 10 bytes.
513
514         // We read through the file til we reach the end of the file, or we've found
515         // at least 2 frame headers
516         while (!feof($fh) && $count < 2) {
517             $chunk = fread($fh, 1024 * 100); //read 100kb at a time
518             $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
519             // rewind in case we ended up in the middle of the header, but avoid
520             // infinite loop (i.e. don't rewind if we're already in the end).
521             if (!feof($fh) && ftell($fh) >= 9) {
522                 fseek($fh, -9, SEEK_CUR);
523             }
524         }
525
526         fclose($fh);
527         return $count >= 1; // number of animated frames apart from the original image
528     }
529
530     public function getFileThumbnail($width, $height, $crop, $upscale=false)
531     {
532         if (!$this->fileRecord instanceof File) {
533             throw new ServerException('No File object attached to this ImageFile object.');
534         }
535
536         // Throws FileNotFoundException or FileNotStoredLocallyException
537         $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
538         $filename = basename($this->filepath);
539
540         if ($width === null) {
541             $width  = common_config('thumbnail', 'width');
542             $height = common_config('thumbnail', 'height');
543             $crop   = common_config('thumbnail', 'crop');
544         }
545
546         if (!$upscale) {
547             if ($width > $this->width) {
548                 $width = $this->width;
549             }
550             if (!is_null($height) && $height > $this->height) {
551                 $height = $this->height;
552             }
553         }
554
555         if ($height === null) {
556             $height = $width;
557             $crop = true;
558         }
559
560         // Get proper aspect ratio width and height before lookup
561         // We have to do it through an ImageFile object because of orientation etc.
562         // Only other solution would've been to rotate + rewrite uploaded files
563         // which we don't want to do because we like original, untouched data!
564         list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
565
566         $thumb = File_thumbnail::pkeyGet(array(
567                                             'file_id'=> $this->fileRecord->getID(),
568                                             'width'  => $width,
569                                             'height' => $height,
570                                          ));
571         if ($thumb instanceof File_thumbnail) {
572             return $thumb;
573         }
574
575         $type = $this->preferredType();
576         $ext = image_type_to_extension($type, true);
577         // Decoding returns null if the file is in the old format
578         $filename = MediaFile::decodeFilename(basename($this->filepath));
579         // Encoding null makes the file use 'untitled', and also replaces the extension
580         $outfilename = MediaFile::encodeFilename($filename, $this->filehash, $ext);
581
582         // The boundary box for our resizing
583         $box = [
584             'width'=>$width, 'height'=>$height,
585             'x'=>$x,         'y'=>$y,
586             'w'=>$w,         'h'=>$h
587         ];
588
589         $outpath = File_thumbnail::path(
590             "thumb-{$this->fileRecord->id}-{$box['width']}x{$box['height']}-{$outfilename}");
591
592         // Doublecheck that parameters are sane and integers.
593         if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
594                 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
595                 || $box['w'] < 1 || $box['x'] >= $this->width
596                 || $box['h'] < 1 || $box['y'] >= $this->height) {
597             // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
598             common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box, true));
599             throw new ServerException('Bad thumbnail size parameters.');
600         }
601
602         common_debug(sprintf(
603             'Generating a thumbnail of File id=%u of size %ux%u',
604             $this->fileRecord->getID(),
605             $width,
606             $height
607         ));
608
609         // Perform resize and store into file
610         $outpath = $this->resizeTo($outpath, $box);
611         $outname = basename($outpath);
612
613         return File_thumbnail::saveThumbnail(
614             $this->fileRecord->getID(),
615             // no url since we generated it ourselves and can dynamically
616             // generate the url
617             null,
618             $width,
619             $height,
620             $outname
621         );
622     }
623 }