123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605 |
- <?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 = null;
- public $mimetype = null;
- public function __construct($id, string $filepath)
- {
- $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;
- } else {
- 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')))) {
- 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,
- null ,
- $id
- );
- if ($this->type === IMAGETYPE_JPEG) {
-
- $exif = @$img->exif();
- if (is_array($exif) && isset($exif['Orientation'])) {
- switch (intval($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', array($this));
- $img->destroy();
- ini_set('memory_limit', $old_limit);
- }
-
- public static function fromFileObject(File $file)
- {
- $imgPath = null;
- $media = common_get_mime_media($file->mimetype);
- if (Event::handle('CreateFileImageThumbnailSource', array($file, &$imgPath, $media))) {
- if (empty($file->filename) && !file_exists($imgPath)) {
- throw new FileNotFoundException($imgPath);
- }
-
- switch ($file->mimetype) {
- case 'image/svg+xml':
- throw new UseFileAsThumbnailException($file);
- }
-
- if($media !== 'image') {
- throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
- } else if (!empty($file->filename)) {
- $imgPath = $file->getPath();
- }
- }
- if (!file_exists($imgPath)) {
- throw new FileNotFoundException($imgPath);
- }
- try {
- $image = new ImageFile($file->getID(), $imgPath);
- } catch (Exception $e) {
-
- try {
- if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
- common_debug(__METHOD__.': Deleting temporary file that was created as image file' .
- 'thumbnail source: '._ve($imgPath));
- @unlink($imgPath);
- }
- } catch (FileNotFoundException $e) {
-
-
- @unlink($imgPath);
- }
- common_debug(sprintf(
- 'Exception %s caught when creating ImageFile for File id==%s ' .
- 'and imgPath==%s: %s',
- get_class($e),
- _ve($file->id),
- _ve($imgPath),
- _ve($e->getMessage())
- ));
- throw $e;
- }
- return $image;
- }
- 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)
- {
- return parent::fromUpload($param, $scoped);
- }
-
- public function preferredType()
- {
-
- if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
- return $this->type;
- }
-
-
-
- return IMAGETYPE_PNG;
- }
-
- public function copyTo($outpath)
- {
- return new ImageFile(null, $this->resizeTo($outpath));
- }
-
- public function resizeTo($outpath, array $box=array())
- {
- $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
- $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
- $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
- $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
- $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
- $box['h'] = isset($box['h']) ? intval($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;
- }
- }
- if (Event::handle('StartResizeImageFile', array($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__ . ' ecountered 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_GIF:
- $img->save($outpath, 100, 'gif');
- break;
- case IMAGETYPE_PNG:
- $img->save($outpath, 100, 'png');
- break;
- case IMAGETYPE_JPEG:
- $img->save($outpath, common_config('image', 'jpegquality'), 'jpg');
- break;
- default:
-
- throw new Exception(_m('Unknown file type'));
- }
- $img->destroy();
- ini_set('memory_limit', $old_limit);
- return $outpath;
- }
- public function unlink()
- {
- @unlink($this->filepath);
- }
- 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');
- } elseif ($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 array(intval($rw), intval($rh),
- intval($cx), intval($cy),
- is_null($cw) ? $width : intval($cw),
- is_null($ch) ? $height : intval($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, $height, $crop, $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(array(
- 'file_id'=> $this->fileRecord->getID(),
- 'width' => $width,
- 'height' => $height,
- ));
- if ($thumb instanceof File_thumbnail) {
- 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
- ));
-
- $outpath = $this->resizeTo($outpath, $box);
- $outname = basename($outpath);
- return File_thumbnail::saveThumbnail(
- $this->fileRecord->getID(),
-
-
- null,
- $width,
- $height,
- $outname
- );
- }
- }
|