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
130 $imgPath = $file->getPath();
133 throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
137 if (!file_exists($imgPath)) {
138 throw new FileNotFoundException($imgPath);
142 $image = new ImageFile($file->getID(), $imgPath);
143 } catch (Exception $e) {
144 // Avoid deleting the original
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));
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
156 common_debug(sprintf(
157 'Exception %s caught when creating ImageFile for File id==%s ' .
158 'and imgPath==%s: %s',
162 _ve($e->getMessage())
169 public function getPath()
171 if (!file_exists($this->filepath)) {
172 throw new FileNotFoundException($this->filepath);
175 return $this->filepath;
179 * Process a file upload
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
193 public static function fromUpload(string $param='upload', Profile $scoped = null)
195 return parent::fromUpload($param, $scoped);
199 * Several obscure file types should be normalized to PNG on resize.
201 * Keeps only PNG, JPEG and GIF
205 public function preferredType()
207 // Keep only JPEG and GIF in their orignal format
208 if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
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;
218 * Copy the image file to the given destination.
220 * This function may modify the resulting file. Please use the
221 * returned ImageFile object to read metadata (width, height etc.)
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
231 public function copyTo($outpath)
233 return new ImageFile(null, $this->resizeTo($outpath));
237 * Create and save a thumbnail image.
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
245 public function resizeTo($outpath, array $box=array())
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;
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.'));
259 // Don't rotate/crop/scale if it isn't necessary
260 if ($box['width'] === $this->width
261 && $box['height'] === $this->height
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;
274 $box['x'] = $box['y'];
277 $box['w'] = $box['h'];
282 if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
283 $this->resizeToFile($outpath, $box);
286 if (!file_exists($outpath)) {
287 if ($this->fileRecord instanceof File) {
288 throw new UseFileAsThumbnailException($this->fileRecord);
290 throw new UnsupportedMediaException('No local File object exists for ImageFile.');
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
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
309 protected function resizeToFile($outpath, array $box)
311 $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
313 switch ($this->type) {
315 $image_src = imagecreatefromgif($this->filepath);
318 $image_src = imagecreatefromjpeg($this->filepath);
321 $image_src = imagecreatefrompng($this->filepath);
324 $image_src = imagecreatefrombmp($this->filepath);
327 $image_src = imagecreatefromwbmp($this->filepath);
330 $image_src = imagecreatefromxbm($this->filepath);
333 // TRANS: Exception thrown when trying to resize an unknown file type.
334 throw new Exception(_m('Unknown file type'));
337 if ($this->rotate != 0) {
338 $image_src = imagerotate($image_src, $this->rotate, 0);
341 $image_dest = imagecreatetruecolor($box['width'], $box['height']);
343 if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
344 $transparent_idx = imagecolortransparent($image_src);
346 if ($transparent_idx >= 0 && $transparent_idx < 255) {
347 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
348 $transparent_idx = imagecolorallocate(
350 $transparent_color['red'],
351 $transparent_color['green'],
352 $transparent_color['blue']
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);
377 $type = $this->preferredType();
378 $ext = image_type_to_extension($type, true);
379 $outpath = preg_replace("/\.[^\.]+$/", $ext, $outpath);
383 imagegif($image_dest, $outpath);
386 imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
389 imagepng($image_dest, $outpath);
392 // TRANS: Exception thrown when trying resize an unknown file type.
393 throw new Exception(_m('Unknown file type'));
396 imagedestroy($image_src);
397 imagedestroy($image_dest);
398 ini_set('memory_limit', $old_limit); // Restore the old memory limit
401 public function unlink()
403 @unlink($this->filepath);
406 public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
408 return self::getScalingValues(
419 * Gets scaling values for images of various types. Cropping can be enabled.
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.
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)
431 * @throws ServerException
433 public static function getScalingValues(
441 $maxW = $maxW ?: common_config('thumbnail', 'width');
442 $maxH = $maxH ?: common_config('thumbnail', 'height');
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
452 // Because GD doesn't understand EXIF orientation etc.
453 if (abs($rotate) == 90) {
459 // Cropping data (for original image size). Default values, 0 and null,
460 // imply no cropping and with preserved aspect ratio (per axis).
463 $cw = null; // crop area width
464 $ch = null; // crop area height
467 $s_ar = $width / $height;
468 $t_ar = $maxW / $maxH;
473 // Source aspect ratio differs from target, recalculate crop points!
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);
483 $rh = ceil($height * $rw / $width);
485 // Scaling caused too large height, decrease to max accepted value
488 $rw = ceil($width * $rh / $height);
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));
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).
502 protected function isAnimatedGif()
504 if (!($fh = @fopen($this->filepath, 'rb'))) {
509 //an animated gif contains multiple "frames", with each frame having a
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.
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);
529 return $count >= 1; // number of animated frames apart from the original image
532 public function getFileThumbnail($width, $height, $crop, $upscale=false)
534 if (!$this->fileRecord instanceof File) {
535 throw new ServerException('No File object attached to this ImageFile object.');
538 if ($width === null) {
539 $width = common_config('thumbnail', 'width');
540 $height = common_config('thumbnail', 'height');
541 $crop = common_config('thumbnail', 'crop');
545 if ($width > $this->width) {
546 $width = $this->width;
548 if (!is_null($height) && $height > $this->height) {
549 $height = $this->height;
553 if ($height === null) {
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);
564 $thumb = File_thumbnail::pkeyGet(array(
565 'file_id'=> $this->fileRecord->getID(),
569 if ($thumb instanceof File_thumbnail) {
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);
578 // The boundary box for our resizing
579 $box = array('width'=>$width, 'height'=>$height,
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.');
593 common_debug(sprintf(
594 'Generating a thumbnail of File id==%u of size %ux%u',
595 $this->fileRecord->getID(),
600 // Perform resize and store into file
601 $this->resizeTo($outpath, $box);
604 // Avoid deleting the original
605 if (!in_array($this->getPath(), [File::path($this->filename), File_thumbnail::path($this->filename)])) {
608 } catch (FileNotFoundException $e) {
609 // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
612 return File_thumbnail::saveThumbnail(
613 $this->fileRecord->getID(),
614 // no url since we generated it ourselves and can dynamically