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();
34 * A wrapper on uploaded images
36 * Makes it slightly easier to accept an image file from upload.
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/
45 class ImageFile extends MediaFile
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
54 public function __construct($id, string $filepath)
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);
61 $info = @getimagesize($this->filepath);
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);
73 $this->width = $info[0];
74 $this->height = $info[1];
75 $this->type = $info[2];
76 $this->mimetype = $info['mime'];
81 null /* filehash, MediaFile will calculate it */,
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'])) {
93 case 3: // top is bottom
96 case 6: // top is right
99 case 8: // top is left
103 // If we ever write this back, Orientation should be set to '1'
105 } elseif ($this->type === IMAGETYPE_GIF) {
106 $this->animated = $this->isAnimatedGif();
109 Event::handle('FillImageFileMetadata', array($this));
112 public static function fromFileObject(File $file)
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.'));
121 // First some mimetype specific exceptions
122 switch ($file->mimetype) {
123 case 'image/svg+xml':
124 throw new UseFileAsThumbnailException($file);
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();
135 if (!file_exists($imgPath)) {
136 throw new FileNotFoundException($imgPath);
140 $image = new ImageFile($file->getID(), $imgPath);
141 } catch (Exception $e) {
142 // Avoid deleting the original
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));
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
154 common_debug(sprintf(
155 'Exception %s caught when creating ImageFile for File id==%s ' .
156 'and imgPath==%s: %s',
160 _ve($e->getMessage())
167 public function getPath()
169 if (!file_exists($this->filepath)) {
170 throw new FileNotFoundException($this->filepath);
173 return $this->filepath;
177 * Process a file upload
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
191 public static function fromUpload(string $param='upload', Profile $scoped = null)
193 return parent::fromUpload($param, $scoped);
197 * Several obscure file types should be normalized to PNG on resize.
199 * Keeps only PNG, JPEG and GIF
203 public function preferredType()
205 // Keep only JPEG and GIF in their orignal format
206 if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
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;
216 * Copy the image file to the given destination.
218 * This function may modify the resulting file. Please use the
219 * returned ImageFile object to read metadata (width, height etc.)
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
229 public function copyTo($outpath)
231 return new ImageFile(null, $this->resizeTo($outpath));
235 * Create and save a thumbnail image.
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
243 public function resizeTo($outpath, array $box=array())
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;
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.'));
257 // Don't rotate/crop/scale if it isn't necessary
258 if ($box['width'] === $this->width
259 && $box['height'] === $this->height
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;
272 $box['x'] = $box['y'];
275 $box['w'] = $box['h'];
280 if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
281 $outpath = $this->resizeToFile($outpath, $box);
284 if (!file_exists($outpath)) {
285 if ($this->fileRecord instanceof File) {
286 throw new UseFileAsThumbnailException($this->fileRecord);
288 throw new UnsupportedMediaException('No local File object exists for ImageFile.');
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
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
307 protected function resizeToFile(string $outpath, array $box) : string
309 $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
311 switch ($this->type) {
313 $image_src = imagecreatefromgif($this->filepath);
316 $image_src = imagecreatefromjpeg($this->filepath);
319 $image_src = imagecreatefrompng($this->filepath);
322 $image_src = imagecreatefrombmp($this->filepath);
325 $image_src = imagecreatefromwbmp($this->filepath);
328 $image_src = imagecreatefromxbm($this->filepath);
331 // TRANS: Exception thrown when trying to resize an unknown file type.
332 throw new Exception(_m('Unknown file type'));
335 if ($this->rotate != 0) {
336 $image_src = imagerotate($image_src, $this->rotate, 0);
339 $image_dest = imagecreatetruecolor($box['width'], $box['height']);
341 if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
342 $transparent_idx = imagecolortransparent($image_src);
344 if ($transparent_idx >= 0 && $transparent_idx < 255) {
345 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
346 $transparent_idx = imagecolorallocate(
348 $transparent_color['red'],
349 $transparent_color['green'],
350 $transparent_color['blue']
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);
375 $type = $this->preferredType();
379 imagegif($image_dest, $outpath);
382 imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
385 imagepng($image_dest, $outpath);
388 // TRANS: Exception thrown when trying resize an unknown file type.
389 throw new Exception(_m('Unknown file type'));
392 imagedestroy($image_src);
393 imagedestroy($image_dest);
394 ini_set('memory_limit', $old_limit); // Restore the old memory limit
399 public function unlink()
401 @unlink($this->filepath);
404 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
406 return self::getScalingValues(
417 * Gets scaling values for images of various types. Cropping can be enabled.
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.
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)
429 * @throws ServerException
431 public static function getScalingValues(
439 $maxW = $maxW ?: common_config('thumbnail', 'width');
440 $maxH = $maxH ?: common_config('thumbnail', 'height');
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
450 // Because GD doesn't understand EXIF orientation etc.
451 if (abs($rotate) == 90) {
457 // Cropping data (for original image size). Default values, 0 and null,
458 // imply no cropping and with preserved aspect ratio (per axis).
461 $cw = null; // crop area width
462 $ch = null; // crop area height
465 $s_ar = $width / $height;
466 $t_ar = $maxW / $maxH;
471 // Source aspect ratio differs from target, recalculate crop points!
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);
481 $rh = ceil($height * $rw / $width);
483 // Scaling caused too large height, decrease to max accepted value
486 $rw = ceil($width * $rh / $height);
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));
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).
500 protected function isAnimatedGif()
502 if (!($fh = @fopen($this->filepath, 'rb'))) {
507 //an animated gif contains multiple "frames", with each frame having a
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.
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);
527 return $count >= 1; // number of animated frames apart from the original image
530 public function getFileThumbnail($width, $height, $crop, $upscale=false)
532 if (!$this->fileRecord instanceof File) {
533 throw new ServerException('No File object attached to this ImageFile object.');
536 // Throws FileNotFoundException or FileNotStoredLocallyException
537 $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
538 $filename = basename($this->filepath);
540 if ($width === null) {
541 $width = common_config('thumbnail', 'width');
542 $height = common_config('thumbnail', 'height');
543 $crop = common_config('thumbnail', 'crop');
547 if ($width > $this->width) {
548 $width = $this->width;
550 if (!is_null($height) && $height > $this->height) {
551 $height = $this->height;
555 if ($height === null) {
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);
566 $thumb = File_thumbnail::pkeyGet(array(
567 'file_id'=> $this->fileRecord->getID(),
571 if ($thumb instanceof File_thumbnail) {
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);
582 // The boundary box for our resizing
584 'width'=>$width, 'height'=>$height,
589 $outpath = File_thumbnail::path(
590 "thumb-{$this->fileRecord->id}-{$box['width']}x{$box['height']}-{$outfilename}");
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.');
602 common_debug(sprintf(
603 'Generating a thumbnail of File id=%u of size %ux%u',
604 $this->fileRecord->getID(),
609 // Perform resize and store into file
610 $outpath = $this->resizeTo($outpath, $box);
611 $outname = basename($outpath);
613 return File_thumbnail::saveThumbnail(
614 $this->fileRecord->getID(),
615 // no url since we generated it ourselves and can dynamically