123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 |
- <?php
- defined('GNUSOCIAL') || die();
- use Intervention\Image\ImageManagerStatic as Image;
- class ImageFile extends MediaFile
- {
- public $type;
- public $height;
- public $width;
- public $rotate = 0;
- public $animated;
- public $mimetype;
-
- public function __construct(?int $id = null, string $filepath, ?string $filehash = null, ?string $fileurl = null)
- {
- $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
-
-
- $this->filepath = $filepath;
- $this->filename = basename($filepath);
- $img = Image::make($this->filepath);
- $this->mimetype = $img->mime();
- $cmp = function ($obj, $type) {
- if ($obj->mimetype == image_type_to_mime_type($type)) {
- $obj->type = $type;
- return true;
- }
- return false;
- };
- if (!(($cmp($this, IMAGETYPE_GIF) && function_exists('imagecreatefromgif')) ||
- ($cmp($this, IMAGETYPE_JPEG) && function_exists('imagecreatefromjpeg')) ||
- ($cmp($this, IMAGETYPE_BMP) && function_exists('imagecreatefrombmp')) ||
- ($cmp($this, IMAGETYPE_WBMP) && function_exists('imagecreatefromwbmp')) ||
- ($cmp($this, IMAGETYPE_XBM) && function_exists('imagecreatefromxbm')) ||
- ($cmp($this, IMAGETYPE_PNG) && function_exists('imagecreatefrompng')) ||
- ($cmp($this, IMAGETYPE_WEBP) && function_exists('imagecreatefromwebp'))
- )
- ) {
- common_debug("Mimetype '{$this->mimetype}' was not recognized as a supported format");
-
- throw new UnsupportedMediaException(_m('Unsupported image format.'), $this->filepath);
- }
- $this->width = $img->width();
- $this->height = $img->height();
- parent::__construct(
- $filepath,
- $this->mimetype,
- $filehash,
- $id,
- $fileurl
- );
- if ($this->type === IMAGETYPE_JPEG) {
-
- $exif = @$img->exif();
- if (is_array($exif) && isset($exif['Orientation'])) {
- switch ((int)($exif['Orientation'])) {
- case 1:
- $this->rotate = 0;
- break;
- case 3:
- $this->rotate = 180;
- break;
- case 6:
- $this->rotate = -90;
- break;
- case 8:
- $this->rotate = 90;
- break;
- }
-
- }
- } elseif ($this->type === IMAGETYPE_GIF) {
- $this->animated = $this->isAnimatedGif();
- }
- Event::handle('FillImageFileMetadata', [$this]);
- $img->destroy();
- ini_set('memory_limit', $old_limit);
- }
-
- public static function fromFileObject(File $file)
- {
- $media = common_get_mime_media($file->mimetype);
-
- if ($media !== 'image') {
- throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
- }
- $filepath = $file->getPath();
- return new self($file->getID(), $filepath, $file->filehash);
- }
- public function getPath()
- {
- if (!file_exists($this->filepath)) {
- throw new FileNotFoundException($this->filepath);
- }
- return $this->filepath;
- }
-
- public static function fromUpload(string $param = 'upload', ?Profile $scoped = null): self
- {
- $mediafile = parent::fromUpload($param, $scoped);
- if ($mediafile instanceof self) {
- return $mediafile;
- } else {
- $mediafile->delete();
-
-
-
- $hint = sprintf(_m('"%s" is not a supported file type on this server. ' .
- 'Try using another image format.'), $mediafile->mimetype);
- throw new ClientException($hint);
- }
- }
-
- public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null): self
- {
- $mediafile = parent::fromUrl($url, $scoped, $name, $file_id);
- if ($mediafile instanceof self) {
- return $mediafile;
- } else {
- $mediafile->delete();
-
-
-
- $hint = sprintf(_m('"%s" is not a supported file type on this server. ' .
- 'Try using another image format.'), $mediafile->mimetype);
- throw new ClientException($hint);
- }
- }
-
- public function preferredType()
- {
- if ($this->type == IMAGETYPE_GIF && $this->animated) {
- return $this->type;
- }
- return IMAGETYPE_WEBP;
- }
-
- public function copyTo($outpath)
- {
- return new self(null, $this->resizeTo($outpath));
- }
-
- public function resizeTo($outpath, array $box = [])
- {
- $box['width'] = isset($box['width']) ? (int)($box['width']) : $this->width;
- $box['height'] = isset($box['height']) ? (int)($box['height']) : $this->height;
- $box['x'] = isset($box['x']) ? (int)($box['x']) : 0;
- $box['y'] = isset($box['y']) ? (int)($box['y']) : 0;
- $box['w'] = isset($box['w']) ? (int)($box['w']) : $this->width;
- $box['h'] = isset($box['h']) ? (int)($box['h']) : $this->height;
- if (!file_exists($this->filepath)) {
-
-
- throw new FileNotFoundException($this->filepath);
- }
-
- if ($box['width'] === $this->width
- && $box['height'] === $this->height
- && $box['x'] === 0
- && $box['y'] === 0
- && $box['w'] === $this->width
- && $box['h'] === $this->height
- && $this->type === $this->preferredType()) {
- if (abs($this->rotate) == 90) {
-
-
- $tmp = $box['width'];
- $box['width'] = $box['height'];
- $box['height'] = $tmp;
- $tmp = $box['x'];
- $box['x'] = $box['y'];
- $box['y'] = $tmp;
- $tmp = $box['w'];
- $box['w'] = $box['h'];
- $box['h'] = $tmp;
- }
- }
- $this->height = $box['h'];
- $this->width = $box['w'];
- if (Event::handle('StartResizeImageFile', [$this, $outpath, $box])) {
- $outpath = $this->resizeToFile($outpath, $box);
- }
- if (!file_exists($outpath)) {
- if ($this->fileRecord instanceof File) {
- throw new UseFileAsThumbnailException($this->fileRecord);
- } else {
- throw new UnsupportedMediaException('No local File object exists for ImageFile.');
- }
- }
- return $outpath;
- }
-
- protected function resizeToFile(string $outpath, array $box): string
- {
- $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
- try {
- $img = Image::make($this->filepath);
- } catch (Exception $e) {
- common_log(LOG_ERR, __METHOD__ . ' encountered exception: ' . print_r($e, true));
-
- throw new Exception(_m('Unknown file type'));
- }
- if ($this->filepath === $outpath) {
- @unlink($outpath);
- }
- if ($this->rotate != 0) {
- $img = $img->orientate();
- }
- $img->fit(
- $box['width'],
- $box['height'],
- function ($constraint) {
- if (common_config('attachments', 'upscale') !== true) {
- $constraint->upsize();
- }
- }
- );
-
- $type = $this->preferredType();
- switch ($type) {
- case IMAGETYPE_WEBP:
- $img->save($outpath, 100, 'webp');
- break;
- case IMAGETYPE_GIF:
- $img->save($outpath, 100, 'gif');
- break;
- default:
-
- throw new Exception(_m('Unknown file type'));
- }
- $img->destroy();
- ini_set('memory_limit', $old_limit);
- return $outpath;
- }
- public function scaleToFit($maxWidth = null, $maxHeight = null, $crop = null)
- {
- return self::getScalingValues(
- $this->width,
- $this->height,
- $maxWidth,
- $maxHeight,
- $crop,
- $this->rotate
- );
- }
-
- public static function getScalingValues(
- $width,
- $height,
- $maxW = null,
- $maxH = null,
- $crop = null,
- $rotate = 0
- ) {
- $maxW = $maxW ?: common_config('thumbnail', 'width');
- $maxH = $maxH ?: common_config('thumbnail', 'height');
- if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
- throw new ServerException('Bad parameters for ImageFile::getScalingValues');
- }
- if ($maxH === null) {
-
- $maxH = $maxW;
- $crop = true;
- }
-
- if (abs($rotate) == 90) {
- $tmp = $width;
- $width = $height;
- $height = $tmp;
- }
-
-
- $cx = 0;
- $cy = 0;
- $cw = null;
- $ch = null;
- if ($crop) {
- $s_ar = $width / $height;
- $t_ar = $maxW / $maxH;
- $rw = $maxW;
- $rh = $maxH;
-
- if ($s_ar > $t_ar) {
- $cx = floor($width / 2 - $height * $t_ar / 2);
- $cw = ceil($height * $t_ar);
- } elseif ($s_ar < $t_ar) {
- $cy = floor($height / 2 - $width / $t_ar / 2);
- $ch = ceil($width / $t_ar);
- }
- } else {
- $rw = $maxW;
- $rh = ceil($height * $rw / $width);
-
- if ($rh > $maxH) {
- $rh = $maxH;
- $rw = ceil($width * $rh / $height);
- }
- }
- return [(int)$rw, (int)$rh,
- (int)$cx, (int)$cy,
- is_null($cw) ? $width : (int)$cw,
- is_null($ch) ? $height : (int)$ch];
- }
-
- protected function isAnimatedGif()
- {
- if (!($fh = @fopen($this->filepath, 'rb'))) {
- return false;
- }
- $count = 0;
-
-
-
-
-
-
-
-
- while (!feof($fh) && $count < 2) {
- $chunk = fread($fh, 1024 * 100);
- $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
-
-
- if (!feof($fh) && ftell($fh) >= 9) {
- fseek($fh, -9, SEEK_CUR);
- }
- }
- fclose($fh);
- return $count >= 1;
- }
-
- public function getFileThumbnail($width = null, $height = null, $crop = null, $upscale = false)
- {
- if (!$this->fileRecord instanceof File) {
- throw new ServerException('No File object attached to this ImageFile object.');
- }
-
- $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
- $filename = basename($this->filepath);
- if ($width === null) {
- $width = common_config('thumbnail', 'width');
- $height = common_config('thumbnail', 'height');
- $crop = common_config('thumbnail', 'crop');
- }
- if (!$upscale) {
- if ($width > $this->width) {
- $width = $this->width;
- }
- if (!is_null($height) && $height > $this->height) {
- $height = $this->height;
- }
- }
- if ($height === null) {
- $height = $width;
- $crop = true;
- }
-
-
-
-
- list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
- $thumb = File_thumbnail::pkeyGet([
- 'file_id' => $this->fileRecord->getID(),
- 'width' => $width,
- 'height' => $height,
- ]);
- if ($thumb instanceof File_thumbnail) {
- $this->height = $height;
- $this->width = $width;
- return $thumb;
- }
- $type = $this->preferredType();
- $ext = image_type_to_extension($type, true);
-
- $filename = MediaFile::decodeFilename(basename($this->filepath));
-
- $outfilename = MediaFile::encodeFilename($filename, $this->filehash, $ext);
-
- $box = [
- 'width' => $width, 'height' => $height,
- 'x' => $x, 'y' => $y,
- 'w' => $w, 'h' => $h,
- ];
- $outpath = File_thumbnail::path(
- "thumb-{$this->fileRecord->id}-{$box['width']}x{$box['height']}-{$outfilename}"
- );
-
- if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
- || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
- || $box['w'] < 1 || $box['x'] >= $this->width
- || $box['h'] < 1 || $box['y'] >= $this->height) {
-
- common_debug("Boundary box parameters for resize of {$this->filepath} : " . var_export($box, true));
- throw new ServerException('Bad thumbnail size parameters.');
- }
- common_debug(sprintf(
- 'Generating a thumbnail of File id=%u of size %ux%u',
- $this->fileRecord->getID(),
- $width,
- $height
- ));
- $this->height = $box['height'];
- $this->width = $box['width'];
-
- $outpath = $this->resizeTo($outpath, $box);
- $outname = basename($outpath);
- return File_thumbnail::saveThumbnail(
- $this->fileRecord->getID(),
- $this->fileRecord->getUrl(false),
- $width,
- $height,
- $outname
- );
- }
- }
|