imagefile.php 24 KB

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