imagefile.php 22 KB

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