imagefile.php 23 KB

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