imagefile.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 UnsupportedMediaException(_m('File without filename could not get a thumbnail source.'));
  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. switch ($media) {
  117. case 'image':
  118. $imgPath = $file->getPath();
  119. break;
  120. default:
  121. throw new UnsupportedMediaException(_m('Unsupported media format.'), $file->getPath());
  122. }
  123. }
  124. if (!file_exists($imgPath)) {
  125. throw new FileNotFoundException($imgPath);
  126. }
  127. try {
  128. $image = new ImageFile($file->getID(), $imgPath);
  129. } catch (Exception $e) {
  130. // Avoid deleting the original
  131. try {
  132. if (strlen($imgPath) > 0 && $imgPath !== $file->getPath()) {
  133. common_debug(__METHOD__.': Deleting temporary file that was created as image file' .
  134. 'thumbnail source: '._ve($imgPath));
  135. @unlink($imgPath);
  136. }
  137. } catch (FileNotFoundException $e) {
  138. // File reported (via getPath) that the original file
  139. // doesn't exist anyway, so it's safe to delete $imgPath
  140. @unlink($imgPath);
  141. }
  142. common_debug(sprintf(
  143. 'Exception %s caught when creating ImageFile for File id==%s ' .
  144. 'and imgPath==%s: %s',
  145. get_class($e),
  146. _ve($file->id),
  147. _ve($imgPath),
  148. _ve($e->getMessage())
  149. ));
  150. throw $e;
  151. }
  152. return $image;
  153. }
  154. public function getPath()
  155. {
  156. if (!file_exists($this->filepath)) {
  157. throw new FileNotFoundException($this->filepath);
  158. }
  159. return $this->filepath;
  160. }
  161. /**
  162. * Process a file upload
  163. *
  164. * Uses MediaFile's `fromUpload` to do the majority of the work and reencodes the image,
  165. * to mitigate injection attacks.
  166. * @param string $param
  167. * @param Profile|null $scoped
  168. * @return ImageFile|MediaFile
  169. * @throws ClientException
  170. * @throws NoResultException
  171. * @throws NoUploadedMediaException
  172. * @throws ServerException
  173. * @throws UnsupportedMediaException
  174. * @throws UseFileAsThumbnailException
  175. */
  176. public static function fromUpload(string $param='upload', Profile $scoped = null)
  177. {
  178. return parent::fromUpload($param, $scoped);
  179. }
  180. /**
  181. * Several obscure file types should be normalized to PNG on resize.
  182. *
  183. * Keeps only PNG, JPEG and GIF
  184. *
  185. * @return int
  186. */
  187. public function preferredType()
  188. {
  189. // Keep only JPEG and GIF in their orignal format
  190. if ($this->type === IMAGETYPE_JPEG || $this->type === IMAGETYPE_GIF) {
  191. return $this->type;
  192. }
  193. // We don't want to save some formats as they are rare, inefficient and antiquated
  194. // thus we can't guarantee clients will support
  195. // So just save it as PNG
  196. return IMAGETYPE_PNG;
  197. }
  198. /**
  199. * Copy the image file to the given destination.
  200. *
  201. * This function may modify the resulting file. Please use the
  202. * returned ImageFile object to read metadata (width, height etc.)
  203. *
  204. * @param string $outpath
  205. * @return ImageFile the image stored at target path
  206. * @throws ClientException
  207. * @throws NoResultException
  208. * @throws ServerException
  209. * @throws UnsupportedMediaException
  210. * @throws UseFileAsThumbnailException
  211. */
  212. public function copyTo($outpath)
  213. {
  214. return new ImageFile(null, $this->resizeTo($outpath));
  215. }
  216. /**
  217. * Create and save a thumbnail image.
  218. *
  219. * @param string $outpath
  220. * @param array $box width, height, boundary box (x,y,w,h) defaults to full image
  221. * @return string full local filesystem filename
  222. * @throws UnsupportedMediaException
  223. * @throws UseFileAsThumbnailException
  224. */
  225. public function resizeTo($outpath, array $box=array())
  226. {
  227. $box['width'] = isset($box['width']) ? intval($box['width']) : $this->width;
  228. $box['height'] = isset($box['height']) ? intval($box['height']) : $this->height;
  229. $box['x'] = isset($box['x']) ? intval($box['x']) : 0;
  230. $box['y'] = isset($box['y']) ? intval($box['y']) : 0;
  231. $box['w'] = isset($box['w']) ? intval($box['w']) : $this->width;
  232. $box['h'] = isset($box['h']) ? intval($box['h']) : $this->height;
  233. if (!file_exists($this->filepath)) {
  234. // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
  235. throw new Exception(_m('Lost our file.'));
  236. }
  237. // Don't rotate/crop/scale if it isn't necessary
  238. if ($box['width'] === $this->width
  239. && $box['height'] === $this->height
  240. && $box['x'] === 0
  241. && $box['y'] === 0
  242. && $box['w'] === $this->width
  243. && $box['h'] === $this->height
  244. && $this->type === $this->preferredType()) {
  245. if (abs($this->rotate) == 90) {
  246. // Box is rotated 90 degrees in either direction,
  247. // so we have to redefine x to y and vice versa.
  248. $tmp = $box['width'];
  249. $box['width'] = $box['height'];
  250. $box['height'] = $tmp;
  251. $tmp = $box['x'];
  252. $box['x'] = $box['y'];
  253. $box['y'] = $tmp;
  254. $tmp = $box['w'];
  255. $box['w'] = $box['h'];
  256. $box['h'] = $tmp;
  257. }
  258. }
  259. if (Event::handle('StartResizeImageFile', array($this, $outpath, $box))) {
  260. $this->resizeToFile($outpath, $box);
  261. }
  262. if (!file_exists($outpath)) {
  263. if ($this->fileRecord instanceof File) {
  264. throw new UseFileAsThumbnailException($this->fileRecord);
  265. } else {
  266. throw new UnsupportedMediaException('No local File object exists for ImageFile.');
  267. }
  268. }
  269. return $outpath;
  270. }
  271. /**
  272. * Resizes a file. If $box is omitted, the size is not changed, but this is still useful,
  273. * because it will reencode the image in the `self::prefferedType()` format. This only
  274. * applies henceforward, not retroactively
  275. *
  276. * Increases the 'memory_limit' to the one in the 'attachments' section in the config, to
  277. * enable the handling of bigger images, which can cause a peak of memory consumption, while
  278. * encoding
  279. * @param $outpath
  280. * @param array $box
  281. * @throws Exception
  282. */
  283. protected function resizeToFile($outpath, array $box)
  284. {
  285. $old_limit = ini_set('memory_limit', common_config('attachments', 'memory_limit'));
  286. $image_src = null;
  287. switch ($this->type) {
  288. case IMAGETYPE_GIF:
  289. $image_src = imagecreatefromgif($this->filepath);
  290. break;
  291. case IMAGETYPE_JPEG:
  292. $image_src = imagecreatefromjpeg($this->filepath);
  293. break;
  294. case IMAGETYPE_PNG:
  295. $image_src = imagecreatefrompng($this->filepath);
  296. break;
  297. case IMAGETYPE_BMP:
  298. $image_src = imagecreatefrombmp($this->filepath);
  299. break;
  300. case IMAGETYPE_WBMP:
  301. $image_src = imagecreatefromwbmp($this->filepath);
  302. break;
  303. case IMAGETYPE_XBM:
  304. $image_src = imagecreatefromxbm($this->filepath);
  305. break;
  306. default:
  307. // TRANS: Exception thrown when trying to resize an unknown file type.
  308. throw new Exception(_m('Unknown file type'));
  309. }
  310. if ($this->rotate != 0) {
  311. $image_src = imagerotate($image_src, $this->rotate, 0);
  312. }
  313. $image_dest = imagecreatetruecolor($box['width'], $box['height']);
  314. if ($this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
  315. $transparent_idx = imagecolortransparent($image_src);
  316. if ($transparent_idx >= 0 && $transparent_idx < 255) {
  317. $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
  318. $transparent_idx = imagecolorallocate(
  319. $image_dest,
  320. $transparent_color['red'],
  321. $transparent_color['green'],
  322. $transparent_color['blue']
  323. );
  324. imagefill($image_dest, 0, 0, $transparent_idx);
  325. imagecolortransparent($image_dest, $transparent_idx);
  326. } elseif ($this->type == IMAGETYPE_PNG) {
  327. imagealphablending($image_dest, false);
  328. $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
  329. imagefill($image_dest, 0, 0, $transparent);
  330. imagesavealpha($image_dest, true);
  331. }
  332. }
  333. imagecopyresampled(
  334. $image_dest,
  335. $image_src,
  336. 0,
  337. 0,
  338. $box['x'],
  339. $box['y'],
  340. $box['width'],
  341. $box['height'],
  342. $box['w'],
  343. $box['h']
  344. );
  345. $type = $this->preferredType();
  346. $ext = image_type_to_extension($type, true);
  347. $outpath = preg_replace("/\.[^\.]+$/", $ext, $outpath);
  348. switch ($type) {
  349. case IMAGETYPE_GIF:
  350. imagegif($image_dest, $outpath);
  351. break;
  352. case IMAGETYPE_JPEG:
  353. imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
  354. break;
  355. case IMAGETYPE_PNG:
  356. imagepng($image_dest, $outpath);
  357. break;
  358. default:
  359. // TRANS: Exception thrown when trying resize an unknown file type.
  360. throw new Exception(_m('Unknown file type'));
  361. }
  362. imagedestroy($image_src);
  363. imagedestroy($image_dest);
  364. ini_set('memory_limit', $old_limit); // Restore the old memory limit
  365. }
  366. public function unlink()
  367. {
  368. @unlink($this->filepath);
  369. }
  370. public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
  371. {
  372. return self::getScalingValues(
  373. $this->width,
  374. $this->height,
  375. $maxWidth,
  376. $maxHeight,
  377. $crop,
  378. $this->rotate
  379. );
  380. }
  381. /**
  382. * Gets scaling values for images of various types. Cropping can be enabled.
  383. *
  384. * Values will scale _up_ to fit max values if cropping is enabled!
  385. * With cropping disabled, the max value of each axis will be respected.
  386. *
  387. * @param $width int Original width
  388. * @param $height int Original height
  389. * @param $maxW int Resulting max width
  390. * @param $maxH int Resulting max height
  391. * @param $crop int Crop to the size (not preserving aspect ratio)
  392. * @param int $rotate
  393. * @return array
  394. * @throws ServerException
  395. */
  396. public static function getScalingValues(
  397. $width,
  398. $height,
  399. $maxW=null,
  400. $maxH=null,
  401. $crop=null,
  402. $rotate=0
  403. ) {
  404. $maxW = $maxW ?: common_config('thumbnail', 'width');
  405. $maxH = $maxH ?: common_config('thumbnail', 'height');
  406. if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
  407. throw new ServerException('Bad parameters for ImageFile::getScalingValues');
  408. } elseif ($maxH === null) {
  409. // if maxH is null, we set maxH to equal maxW and enable crop
  410. $maxH = $maxW;
  411. $crop = true;
  412. }
  413. // Because GD doesn't understand EXIF orientation etc.
  414. if (abs($rotate) == 90) {
  415. $tmp = $width;
  416. $width = $height;
  417. $height = $tmp;
  418. }
  419. // Cropping data (for original image size). Default values, 0 and null,
  420. // imply no cropping and with preserved aspect ratio (per axis).
  421. $cx = 0; // crop x
  422. $cy = 0; // crop y
  423. $cw = null; // crop area width
  424. $ch = null; // crop area height
  425. if ($crop) {
  426. $s_ar = $width / $height;
  427. $t_ar = $maxW / $maxH;
  428. $rw = $maxW;
  429. $rh = $maxH;
  430. // Source aspect ratio differs from target, recalculate crop points!
  431. if ($s_ar > $t_ar) {
  432. $cx = floor($width / 2 - $height * $t_ar / 2);
  433. $cw = ceil($height * $t_ar);
  434. } elseif ($s_ar < $t_ar) {
  435. $cy = floor($height / 2 - $width / $t_ar / 2);
  436. $ch = ceil($width / $t_ar);
  437. }
  438. } else {
  439. $rw = $maxW;
  440. $rh = ceil($height * $rw / $width);
  441. // Scaling caused too large height, decrease to max accepted value
  442. if ($rh > $maxH) {
  443. $rh = $maxH;
  444. $rw = ceil($width * $rh / $height);
  445. }
  446. }
  447. return array(intval($rw), intval($rh),
  448. intval($cx), intval($cy),
  449. is_null($cw) ? $width : intval($cw),
  450. is_null($ch) ? $height : intval($ch));
  451. }
  452. /**
  453. * Animated GIF test, courtesy of frank at huddler dot com et al:
  454. * http://php.net/manual/en/function.imagecreatefromgif.php#104473
  455. * Modified so avoid landing inside of a header (and thus not matching our regexp).
  456. */
  457. protected function isAnimatedGif()
  458. {
  459. if (!($fh = @fopen($this->filepath, 'rb'))) {
  460. return false;
  461. }
  462. $count = 0;
  463. //an animated gif contains multiple "frames", with each frame having a
  464. //header made up of:
  465. // * a static 4-byte sequence (\x00\x21\xF9\x04)
  466. // * 4 variable bytes
  467. // * a static 2-byte sequence (\x00\x2C)
  468. // In total the header is maximum 10 bytes.
  469. // We read through the file til we reach the end of the file, or we've found
  470. // at least 2 frame headers
  471. while (!feof($fh) && $count < 2) {
  472. $chunk = fread($fh, 1024 * 100); //read 100kb at a time
  473. $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
  474. // rewind in case we ended up in the middle of the header, but avoid
  475. // infinite loop (i.e. don't rewind if we're already in the end).
  476. if (!feof($fh) && ftell($fh) >= 9) {
  477. fseek($fh, -9, SEEK_CUR);
  478. }
  479. }
  480. fclose($fh);
  481. return $count >= 1; // number of animated frames apart from the original image
  482. }
  483. public function getFileThumbnail($width, $height, $crop, $upscale=false)
  484. {
  485. if (!$this->fileRecord instanceof File) {
  486. throw new ServerException('No File object attached to this ImageFile object.');
  487. }
  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. $filename = $this->fileRecord->filehash ?: $this->filename; // Remote files don't have $this->filehash
  519. $extension = File::guessMimeExtension($this->mimetype);
  520. $outname = "thumb-{$this->fileRecord->getID()}-{$width}x{$height}-{$filename}." . $extension;
  521. $outpath = File_thumbnail::path($outname);
  522. // The boundary box for our resizing
  523. $box = array('width'=>$width, 'height'=>$height,
  524. 'x'=>$x, 'y'=>$y,
  525. 'w'=>$w, 'h'=>$h);
  526. // Doublecheck that parameters are sane and integers.
  527. if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
  528. || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
  529. || $box['w'] < 1 || $box['x'] >= $this->width
  530. || $box['h'] < 1 || $box['y'] >= $this->height) {
  531. // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
  532. common_debug("Boundary box parameters for resize of {$this->filepath} : ".var_export($box, true));
  533. throw new ServerException('Bad thumbnail size parameters.');
  534. }
  535. common_debug(sprintf(
  536. 'Generating a thumbnail of File id==%u of size %ux%u',
  537. $this->fileRecord->getID(),
  538. $width,
  539. $height
  540. ));
  541. // Perform resize and store into file
  542. $this->resizeTo($outpath, $box);
  543. try {
  544. // Avoid deleting the original
  545. if (!in_array($this->getPath(), [File::path($this->filename), File_thumbnail::path($this->filename)])) {
  546. $this->unlink();
  547. }
  548. } catch (FileNotFoundException $e) {
  549. // $this->getPath() says the file doesn't exist anyway, so no point in trying to delete it!
  550. }
  551. return File_thumbnail::saveThumbnail(
  552. $this->fileRecord->getID(),
  553. // no url since we generated it ourselves and can dynamically
  554. // generate the url
  555. null,
  556. $width,
  557. $height,
  558. $outname
  559. );
  560. }
  561. }