imagefile.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Abstraction for an image file
  18. *
  19. * @category Image
  20. * @package GNUsocial
  21. *
  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. *
  29. * @see https://www.gnu.org/software/social/
  30. */
  31. defined('GNUSOCIAL') || die();
  32. use Intervention\Image\ImageManagerStatic as Image;
  33. /**
  34. * A wrapper on uploaded images
  35. *
  36. * Makes it slightly easier to accept an image file from upload.
  37. *
  38. * @category Image
  39. * @package GNUsocial
  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. *
  44. * @see https://www.gnu.org/software/social/
  45. */
  46. class ImageFile extends MediaFile
  47. {
  48. public $type;
  49. public $height;
  50. public $width;
  51. public $rotate = 0; // degrees to rotate for properly oriented image (extrapolated from EXIF etc.)
  52. public $animated = null; // Animated image? (has more than 1 frame). null means untested
  53. public $mimetype = null; // The _ImageFile_ mimetype, _not_ the originating File object
  54. public function __construct($id, string $filepath)
  55. {
  56. $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
  57. // These do not have to be the same as fileRecord->filename for example,
  58. // since we may have generated an image source file from something else!
  59. $this->filepath = $filepath;
  60. $this->filename = basename($filepath);
  61. $img = Image::make($this->filepath);
  62. $this->mimetype = $img->mime();
  63. $cmp = function ($obj, $type) {
  64. if ($obj->mimetype == image_type_to_mime_type($type)) {
  65. $obj->type = $type;
  66. return true;
  67. }
  68. return false;
  69. };
  70. if (!(($cmp($this, IMAGETYPE_GIF) && function_exists('imagecreatefromgif')) ||
  71. ($cmp($this, IMAGETYPE_JPEG) && function_exists('imagecreatefromjpeg')) ||
  72. ($cmp($this, IMAGETYPE_BMP) && function_exists('imagecreatefrombmp')) ||
  73. ($cmp($this, IMAGETYPE_WBMP) && function_exists('imagecreatefromwbmp')) ||
  74. ($cmp($this, IMAGETYPE_XBM) && function_exists('imagecreatefromxbm')) ||
  75. ($cmp($this, IMAGETYPE_PNG) && function_exists('imagecreatefrompng')))) {
  76. common_debug("Mimetype '{$this->mimetype}' was not recognized as a supported format");
  77. // TRANS: Exception thrown when trying to upload an unsupported image file format.
  78. throw new UnsupportedMediaException(_m('Unsupported image format.'), $this->filepath);
  79. }
  80. $this->width = $img->width();
  81. $this->height = $img->height();
  82. parent::__construct(
  83. $filepath,
  84. $this->mimetype,
  85. null /* filehash, MediaFile will calculate it */,
  86. $id
  87. );
  88. if ($this->type === IMAGETYPE_JPEG) {
  89. // Orientation value to rotate thumbnails properly
  90. $exif = @$img->exif();
  91. if (is_array($exif) && isset($exif['Orientation'])) {
  92. switch ((int) ($exif['Orientation'])) {
  93. case 1: // top is top
  94. $this->rotate = 0;
  95. break;
  96. case 3: // top is bottom
  97. $this->rotate = 180;
  98. break;
  99. case 6: // top is right
  100. $this->rotate = -90;
  101. break;
  102. case 8: // top is left
  103. $this->rotate = 90;
  104. break;
  105. }
  106. // If we ever write this back, Orientation should be set to '1'
  107. }
  108. } elseif ($this->type === IMAGETYPE_GIF) {
  109. $this->animated = $this->isAnimatedGif();
  110. }
  111. Event::handle('FillImageFileMetadata', [$this]);
  112. $img->destroy();
  113. ini_set('memory_limit', $old_limit); // Restore the old memory limit
  114. }
  115. /**
  116. * Create a thumbnail from a file object
  117. *
  118. * @return ImageFile
  119. */
  120. public static function fromFileObject(File $file)
  121. {
  122. $imgPath = null;
  123. $media = common_get_mime_media($file->mimetype);
  124. if (Event::handle('CreateFileImageThumbnailSource', [$file, &$imgPath, $media])) {
  125. if (empty($file->filename) && !file_exists($imgPath)) {
  126. throw new FileNotFoundException($imgPath);
  127. }
  128. // First some mimetype specific exceptions
  129. switch ($file->mimetype) {
  130. case 'image/svg+xml':
  131. throw new UseFileAsThumbnailException($file);
  132. }
  133. // And we'll only consider it an image if it has such a media type
  134. if ($media !== 'image') {
  135. throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
  136. }
  137. if (!empty($file->filename)) {
  138. $imgPath = $file->getPath();
  139. }
  140. }
  141. if (!file_exists($imgPath)) {
  142. throw new FileNotFoundException($imgPath);
  143. }
  144. try {
  145. $image = new self($file->getID(), $imgPath);
  146. } catch (Exception $e) {
  147. // Avoid deleting the original
  148. try {
  149. if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
  150. common_debug(__METHOD__ . ': Deleting temporary file that was created as image file' .
  151. 'thumbnail source: ' . _ve($imgPath));
  152. @unlink($imgPath);
  153. }
  154. } catch (FileNotFoundException $e) {
  155. // File reported (via getPath) that the original file
  156. // doesn't exist anyway, so it's safe to delete $imgPath
  157. @unlink($imgPath);
  158. }
  159. common_debug(sprintf(
  160. 'Exception %s caught when creating ImageFile for File id==%s ' .
  161. 'and imgPath==%s: %s',
  162. get_class($e),
  163. _ve($file->id),
  164. _ve($imgPath),
  165. _ve($e->getMessage())
  166. ));
  167. throw $e;
  168. }
  169. return $image;
  170. }
  171. public function getPath()
  172. {
  173. if (!file_exists($this->filepath)) {
  174. throw new FileNotFoundException($this->filepath);
  175. }
  176. return $this->filepath;
  177. }
  178. /**
  179. * Process a file upload
  180. *
  181. * Uses MediaFile's `fromUpload` to do the majority of the work and reencodes the image,
  182. * to mitigate injection attacks.
  183. *
  184. * @param string $param
  185. * @param null|Profile $scoped
  186. *
  187. * @throws ClientException
  188. * @throws NoResultException
  189. * @throws NoUploadedMediaException
  190. * @throws ServerException
  191. * @throws UnsupportedMediaException
  192. * @throws UseFileAsThumbnailException
  193. *
  194. * @return ImageFile|MediaFile
  195. */
  196. public static function fromUpload(string $param = 'upload', Profile $scoped = null)
  197. {
  198. return parent::fromUpload($param, $scoped);
  199. }
  200. /**
  201. * Several obscure file types should be normalized to PNG on resize.
  202. *
  203. * Keeps only PNG, JPEG and GIF
  204. *
  205. * @return int
  206. */
  207. public function preferredType()
  208. {
  209. // Keep only JPEG and GIF in their orignal format
  210. if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
  211. return $this->type;
  212. }
  213. // We don't want to save some formats as they are rare, inefficient and antiquated
  214. // thus we can't guarantee clients will support
  215. // So just save it as PNG
  216. return IMAGETYPE_PNG;
  217. }
  218. /**
  219. * Copy the image file to the given destination.
  220. *
  221. * This function may modify the resulting file. Please use the
  222. * returned ImageFile object to read metadata (width, height etc.)
  223. *
  224. * @param string $outpath
  225. *
  226. * @throws ClientException
  227. * @throws NoResultException
  228. * @throws ServerException
  229. * @throws UnsupportedMediaException
  230. * @throws UseFileAsThumbnailException
  231. *
  232. * @return ImageFile the image stored at target path
  233. */
  234. public function copyTo($outpath)
  235. {
  236. return new self(null, $this->resizeTo($outpath));
  237. }
  238. /**
  239. * Create and save a thumbnail image.
  240. *
  241. * @param string $outpath
  242. * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
  243. * @return string full local filesystem filename
  244. * @throws UnsupportedMediaException
  245. * @throws UseFileAsThumbnailException
  246. *
  247. * @return string full local filesystem filename
  248. */
  249. public function resizeTo($outpath, array $box = [])
  250. {
  251. $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
  252. $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
  253. $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
  254. $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
  255. $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
  256. $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
  257. if (!file_exists($this->filepath)) {
  258. // TRANS: Exception thrown during resize when image has been registered as present,
  259. // but is no longer there.
  260. throw new FileNotFoundException($this->filepath);
  261. }
  262. // Don't rotate/crop/scale if it isn't necessary
  263. if ($box['width'] === $this->width
  264. && $box['height'] === $this->height
  265. && $box['x'] === 0
  266. && $box['y'] === 0
  267. && $box['w'] === $this->width
  268. && $box['h'] === $this->height
  269. && $this->type === $this->preferredType()) {
  270. if (abs($this->rotate) == 90) {
  271. // Box is rotated 90 degrees in either direction,
  272. // so we have to redefine x to y and vice versa.
  273. $tmp = $box['width'];
  274. $box['width'] = $box['height'];
  275. $box['height'] = $tmp;
  276. $tmp = $box['x'];
  277. $box['x'] = $box['y'];
  278. $box['y'] = $tmp;
  279. $tmp = $box['w'];
  280. $box['w'] = $box['h'];
  281. $box['h'] = $tmp;
  282. }
  283. }
  284. $this->height = $box['h'];
  285. $this->width = $box['w'];
  286. if (Event::handle('StartResizeImageFile', [$this, $outpath, $box])) {
  287. $outpath = $this->resizeToFile($outpath, $box);
  288. }
  289. if (!file_exists($outpath)) {
  290. if ($this->fileRecord instanceof File) {
  291. throw new UseFileAsThumbnailException($this->fileRecord);
  292. } else {
  293. throw new UnsupportedMediaException('No local File object exists for ImageFile.');
  294. }
  295. }
  296. return $outpath;
  297. }
  298. /**
  299. * Resizes a file. If $box is omitted, the size is not changed, but this is still useful,
  300. * because it will reencode the image in the `self::prefferedType()` format. This only
  301. * applies henceforward, not retroactively
  302. *
  303. * Increases the 'memory_limit' to the one in the 'attachments' section in the config, to
  304. * enable the handling of bigger images, which can cause a peak of memory consumption, while
  305. * encoding
  306. *
  307. * @param $outpath
  308. * @param array $box
  309. *
  310. * @throws Exception
  311. */
  312. protected function resizeToFile(string $outpath, array $box): string
  313. {
  314. $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
  315. try {
  316. $img = Image::make($this->filepath);
  317. } catch (Exception $e) {
  318. common_log(LOG_ERR, __METHOD__ . ' ecountered exception: ' . print_r($e, true));
  319. // TRANS: Exception thrown when trying to resize an unknown file type.
  320. throw new Exception(_m('Unknown file type'));
  321. }
  322. if ($this->filepath === $outpath) {
  323. @unlink($outpath);
  324. }
  325. if ($this->rotate != 0) {
  326. $img = $img->orientate();
  327. }
  328. $img->fit($box['width'], $box['height'],
  329. function ($constraint) {
  330. if (common_config('attachments', 'upscale') !== true) {
  331. $constraint->upsize(); // Prevent upscaling
  332. }
  333. }
  334. );
  335. // Ensure we save in the correct format and allow customization based on type
  336. $type = $this->preferredType();
  337. switch ($type) {
  338. case IMAGETYPE_GIF:
  339. $img->save($outpath, 100, 'gif');
  340. break;
  341. case IMAGETYPE_PNG:
  342. $img->save($outpath, 100, 'png');
  343. break;
  344. case IMAGETYPE_JPEG:
  345. $img->save($outpath, common_config('image', 'jpegquality'), 'jpg');
  346. break;
  347. default:
  348. // TRANS: Exception thrown when trying resize an unknown file type.
  349. throw new Exception(_m('Unknown file type'));
  350. }
  351. $img->destroy();
  352. ini_set('memory_limit', $old_limit); // Restore the old memory limit
  353. return $outpath;
  354. }
  355. public function unlink()
  356. {
  357. @unlink($this->filepath);
  358. }
  359. public function scaleToFit($maxWidth = null, $maxHeight = null, $crop = null)
  360. {
  361. return self::getScalingValues(
  362. $this->width,
  363. $this->height,
  364. $maxWidth,
  365. $maxHeight,
  366. $crop,
  367. $this->rotate
  368. );
  369. }
  370. /**
  371. * Gets scaling values for images of various types. Cropping can be enabled.
  372. *
  373. * Values will scale _up_ to fit max values if cropping is enabled!
  374. * With cropping disabled, the max value of each axis will be respected.
  375. *
  376. * @param $width int Original width
  377. * @param $height int Original height
  378. * @param $maxW int Resulting max width
  379. * @param $maxH int Resulting max height
  380. * @param $crop int Crop to the size (not preserving aspect ratio)
  381. * @param int $rotate
  382. *
  383. * @throws ServerException
  384. *
  385. * @return array
  386. */
  387. public static function getScalingValues(
  388. $width,
  389. $height,
  390. $maxW = null,
  391. $maxH = null,
  392. $crop = null,
  393. $rotate = 0
  394. ) {
  395. $maxW = $maxW ?: common_config('thumbnail', 'width');
  396. $maxH = $maxH ?: common_config('thumbnail', 'height');
  397. if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
  398. throw new ServerException('Bad parameters for ImageFile::getScalingValues');
  399. }
  400. if ($maxH === null) {
  401. // if maxH is null, we set maxH to equal maxW and enable crop
  402. $maxH = $maxW;
  403. $crop = true;
  404. }
  405. // Because GD doesn't understand EXIF orientation etc.
  406. if (abs($rotate) == 90) {
  407. $tmp = $width;
  408. $width = $height;
  409. $height = $tmp;
  410. }
  411. // Cropping data (for original image size). Default values, 0 and null,
  412. // imply no cropping and with preserved aspect ratio (per axis).
  413. $cx = 0; // crop x
  414. $cy = 0; // crop y
  415. $cw = null; // crop area width
  416. $ch = null; // crop area height
  417. if ($crop) {
  418. $s_ar = $width / $height;
  419. $t_ar = $maxW / $maxH;
  420. $rw = $maxW;
  421. $rh = $maxH;
  422. // Source aspect ratio differs from target, recalculate crop points!
  423. if ($s_ar > $t_ar) {
  424. $cx = floor($width / 2 - $height * $t_ar / 2);
  425. $cw = ceil($height * $t_ar);
  426. } elseif ($s_ar < $t_ar) {
  427. $cy = floor($height / 2 - $width / $t_ar / 2);
  428. $ch = ceil($width / $t_ar);
  429. }
  430. } else {
  431. $rw = $maxW;
  432. $rh = ceil($height * $rw / $width);
  433. // Scaling caused too large height, decrease to max accepted value
  434. if ($rh > $maxH) {
  435. $rh = $maxH;
  436. $rw = ceil($width * $rh / $height);
  437. }
  438. }
  439. return array(intval($rw), intval($rh),
  440. intval($cx), intval($cy),
  441. is_null($cw) ? $width : intval($cw),
  442. is_null($ch) ? $height : intval($ch));
  443. }
  444. /**
  445. * Animated GIF test, courtesy of frank at huddler dot com et al:
  446. * http://php.net/manual/en/function.imagecreatefromgif.php#104473
  447. * Modified so avoid landing inside of a header (and thus not matching our regexp).
  448. */
  449. protected function isAnimatedGif()
  450. {
  451. if (!($fh = @fopen($this->filepath, 'rb'))) {
  452. return false;
  453. }
  454. $count = 0;
  455. //an animated gif contains multiple "frames", with each frame having a
  456. //header made up of:
  457. // * a static 4-byte sequence (\x00\x21\xF9\x04)
  458. // * 4 variable bytes
  459. // * a static 2-byte sequence (\x00\x2C)
  460. // In total the header is maximum 10 bytes.
  461. // We read through the file til we reach the end of the file, or we've found
  462. // at least 2 frame headers
  463. while (!feof($fh) && $count < 2) {
  464. $chunk = fread($fh, 1024 * 100); //read 100kb at a time
  465. $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
  466. // rewind in case we ended up in the middle of the header, but avoid
  467. // infinite loop (i.e. don't rewind if we're already in the end).
  468. if (!feof($fh) && ftell($fh) >= 9) {
  469. fseek($fh, -9, SEEK_CUR);
  470. }
  471. }
  472. fclose($fh);
  473. return $count >= 1; // number of animated frames apart from the original image
  474. }
  475. public function getFileThumbnail($width, $height, $crop, $upscale = false)
  476. {
  477. if (!$this->fileRecord instanceof File) {
  478. throw new ServerException('No File object attached to this ImageFile object.');
  479. }
  480. // Throws FileNotFoundException or FileNotStoredLocallyException
  481. $this->filepath = $this->fileRecord->getFileOrThumbnailPath();
  482. $filename = basename($this->filepath);
  483. if ($width === null) {
  484. $width = common_config('thumbnail', 'width');
  485. $height = common_config('thumbnail', 'height');
  486. $crop = common_config('thumbnail', 'crop');
  487. }
  488. if (!$upscale) {
  489. if ($width > $this->width) {
  490. $width = $this->width;
  491. }
  492. if (!is_null($height) && $height > $this->height) {
  493. $height = $this->height;
  494. }
  495. }
  496. if ($height === null) {
  497. $height = $width;
  498. $crop = true;
  499. }
  500. // Get proper aspect ratio width and height before lookup
  501. // We have to do it through an ImageFile object because of orientation etc.
  502. // Only other solution would've been to rotate + rewrite uploaded files
  503. // which we don't want to do because we like original, untouched data!
  504. list($width, $height, $x, $y, $w, $h) = $this->scaleToFit($width, $height, $crop);
  505. $thumb = File_thumbnail::pkeyGet([
  506. 'file_id' => $this->fileRecord->getID(),
  507. 'width' => $width,
  508. 'height' => $height,
  509. ]);
  510. if ($thumb instanceof File_thumbnail) {
  511. $this->height = $height;
  512. $this->width = $width;
  513. return $thumb;
  514. }
  515. $type = $this->preferredType();
  516. $ext = image_type_to_extension($type, true);
  517. // Decoding returns null if the file is in the old format
  518. $filename = MediaFile::decodeFilename(basename($this->filepath));
  519. // Encoding null makes the file use 'untitled', and also replaces the extension
  520. $outfilename = MediaFile::encodeFilename($filename, $this->filehash, $ext);
  521. // The boundary box for our resizing
  522. $box = [
  523. 'width' => $width, 'height' => $height,
  524. 'x' => $x, 'y' => $y,
  525. 'w' => $w, 'h' => $h,
  526. ];
  527. $outpath = File_thumbnail::path(
  528. "thumb-{$this->fileRecord->id}-{$box['width']}x{$box['height']}-{$outfilename}");
  529. // Doublecheck that parameters are sane and integers.
  530. if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
  531. || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
  532. || $box['w'] < 1 || $box['x'] >= $this->width
  533. || $box['h'] < 1 || $box['y'] >= $this->height) {
  534. // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
  535. common_debug("Boundary box parameters for resize of {$this->filepath} : " . var_export($box, true));
  536. throw new ServerException('Bad thumbnail size parameters.');
  537. }
  538. common_debug(sprintf(
  539. 'Generating a thumbnail of File id=%u of size %ux%u',
  540. $this->fileRecord->getID(),
  541. $width,
  542. $height
  543. ));
  544. $this->height = $box['height'];
  545. $this->width = $box['width'];
  546. // Perform resize and store into file
  547. $outpath = $this->resizeTo($outpath, $box);
  548. $outname = basename($outpath);
  549. return File_thumbnail::saveThumbnail(
  550. $this->fileRecord->getID(),
  551. // no url since we generated it ourselves and can dynamically
  552. // generate the url
  553. null,
  554. $width,
  555. $height,
  556. $outname
  557. );
  558. }
  559. }