3 * GNU social - a federating social network
5 * Abstraction for an image file
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.
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.
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/>.
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/
31 defined('GNUSOCIAL') || die();
33 use Intervention\Image\ImageManagerStatic as Image;
36 * A wrapper on uploaded images
38 * Makes it slightly easier to accept an image file from upload.
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/
47 class ImageFile extends MediaFile
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
56 public function __construct($id, string $filepath)
58 $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
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);
65 $img = Image::make($this->filepath);
66 $this->mimetype = $img->mime();
68 $cmp = function($obj, $type) {
69 if ($obj->mimetype == image_type_to_mime_type($type)) {
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);
87 $this->width = $img->width();
88 $this->height = $img->height();
93 null /* filehash, MediaFile will calculate it */,
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
105 case 3: // top is bottom
108 case 6: // top is right
111 case 8: // top is left
115 // If we ever write this back, Orientation should be set to '1'
117 } elseif ($this->type === IMAGETYPE_GIF) {
118 $this->animated = $this->isAnimatedGif();
121 Event::handle('FillImageFileMetadata', array($this));
124 ini_set('memory_limit', $old_limit); // Restore the old memory limit
128 * Create a thumbnail from a file object
132 public static function fromFileObject(File $file)
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);
141 // First some mimetype specific exceptions
142 switch ($file->mimetype) {
143 case 'image/svg+xml':
144 throw new UseFileAsThumbnailException($file);
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();
155 if (!file_exists($imgPath)) {
156 throw new FileNotFoundException($imgPath);
160 $image = new ImageFile($file->getID(), $imgPath);
161 } catch (Exception $e) {
162 // Avoid deleting the original
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));
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
174 common_debug(sprintf(
175 'Exception %s caught when creating ImageFile for File id==%s ' .
176 'and imgPath==%s: %s',
180 _ve($e->getMessage())
187 public function getPath()
189 if (!file_exists($this->filepath)) {
190 throw new FileNotFoundException($this->filepath);
193 return $this->filepath;
197 * Process a file upload
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
211 public static function fromUpload(string $param='upload', Profile $scoped = null)
213 return parent::fromUpload($param, $scoped);
217 * Several obscure file types should be normalized to PNG on resize.
219 * Keeps only PNG, JPEG and GIF
223 public function preferredType()
225 // Keep only JPEG and GIF in their orignal format
226 if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
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;
236 * Copy the image file to the given destination.
238 * This function may modify the resulting file. Please use the
239 * returned ImageFile object to read metadata (width, height etc.)
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
249 public function copyTo($outpath)
251 return new ImageFile(null, $this->resizeTo($outpath));
255 * Create and save a thumbnail image.
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
263 public function resizeTo($outpath, array $box=array())
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;
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);
278 // Don't rotate/crop/scale if it isn't necessary
279 if ($box['width'] === $this->width
280 && $box['height'] === $this->height
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;
293 $box['x'] = $box['y'];
296 $box['w'] = $box['h'];
301 if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
302 $outpath = $this->resizeToFile($outpath, $box);
305 if (!file_exists($outpath)) {
306 if ($this->fileRecord instanceof File) {
307 throw new UseFileAsThumbnailException($this->fileRecord);
309 throw new UnsupportedMediaException('No local File object exists for ImageFile.');
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
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
328 protected function resizeToFile(string $outpath, array $box) : string
330 $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
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'));
340 if ($this->filepath === $outpath) {
344 if ($this->rotate != 0) {
345 $img = $img->orientate();
348 $img->fit($box['width'], $box['height'],
349 function ($constraint) {
350 if (common_config('attachments', 'upscale') !== true) {
351 $constraint->upsize(); // Prevent upscaling
356 // Ensure we save in the correct format and allow customization based on type
357 $type = $this->preferredType();
360 $img->save($outpath, 100, 'gif');
363 $img->save($outpath, 100, 'png');
366 $img->save($outpath, common_config('image', 'jpegquality'), 'jpg');
369 // TRANS: Exception thrown when trying resize an unknown file type.
370 throw new Exception(_m('Unknown file type'));
375 ini_set('memory_limit', $old_limit); // Restore the old memory limit
380 public function unlink()
382 @unlink($this->filepath);
385 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
387 return self::getScalingValues(
398 * Gets scaling values for images of various types. Cropping can be enabled.
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.
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)
410 * @throws ServerException
412 public static function getScalingValues(
420 $maxW = $maxW ?: common_config('thumbnail', 'width');
421 $maxH = $maxH ?: common_config('thumbnail', 'height');
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
431 // Because GD doesn't understand EXIF orientation etc.
432 if (abs($rotate) == 90) {
438 // Cropping data (for original image size). Default values, 0 and null,
439 // imply no cropping and with preserved aspect ratio (per axis).
442 $cw = null; // crop area width
443 $ch = null; // crop area height
446 $s_ar = $width / $height;
447 $t_ar = $maxW / $maxH;
452 // Source aspect ratio differs from target, recalculate crop points!
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);
462 $rh = ceil($height * $rw / $width);
464 // Scaling caused too large height, decrease to max accepted value
467 $rw = ceil($width * $rh / $height);
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));
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).
481 protected function isAnimatedGif()
483 if (!($fh = @fopen($this->filepath, 'rb'))) {
488 //an animated gif contains multiple "frames", with each frame having a
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.
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);
508 return $count >= 1; // number of animated frames apart from the original image
511 public function getFileThumbnail($width, $height, $crop, $upscale=false)
513 if (!$this->fileRecord instanceof File) {
514 throw new ServerException('No File object attached to this ImageFile object.');
517 // Throws FileNotFoundException or FileNotStoredLocallyException
518 $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
519 $filename = basename($this->filepath);
521 if ($width === null) {
522 $width = common_config('thumbnail', 'width');
523 $height = common_config('thumbnail', 'height');
524 $crop = common_config('thumbnail', 'crop');
528 if ($width > $this->width) {
529 $width = $this->width;
531 if (!is_null($height) && $height > $this->height) {
532 $height = $this->height;
536 if ($height === null) {
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);
547 $thumb = File_thumbnail::pkeyGet(array(
548 'file_id'=> $this->fileRecord->getID(),
552 if ($thumb instanceof File_thumbnail) {
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);
563 // The boundary box for our resizing
565 'width'=>$width, 'height'=>$height,
570 $outpath = File_thumbnail::path(
571 "thumb-{$this->fileRecord->id}-{$box['width']}x{$box['height']}-{$outfilename}");
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.');
583 common_debug(sprintf(
584 'Generating a thumbnail of File id=%u of size %ux%u',
585 $this->fileRecord->getID(),
590 // Perform resize and store into file
591 $outpath = $this->resizeTo($outpath, $box);
592 $outname = basename($outpath);
594 return File_thumbnail::saveThumbnail(
595 $this->fileRecord->getID(),
596 // no url since we generated it ourselves and can dynamically