imagefile.php 24 KB

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