AttachmentThumbnail.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. declare(strict_types = 1);
  3. // {{{ License
  4. // This file is part of GNU social - https://www.gnu.org/software/social
  5. //
  6. // GNU social is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // GNU social is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  18. // }}}
  19. namespace Component\Attachment\Entity;
  20. use App\Core\Cache;
  21. use App\Core\DB\DB;
  22. use App\Core\Entity;
  23. use App\Core\Event;
  24. use App\Core\GSFile;
  25. use App\Core\Log;
  26. use App\Core\Router\Router;
  27. use App\Util\Common;
  28. use App\Util\Exception\ClientException;
  29. use App\Util\Exception\NotFoundException;
  30. use App\Util\Exception\NotStoredLocallyException;
  31. use App\Util\Exception\ServerException;
  32. use App\Util\TemporaryFile;
  33. use DateTimeInterface;
  34. use Symfony\Component\Mime\MimeTypes;
  35. /**
  36. * Entity for Attachment thumbnails
  37. *
  38. * @category DB
  39. * @package GNUsocial
  40. *
  41. * @author Zach Copley <zach@status.net>
  42. * @copyright 2010 StatusNet Inc.
  43. * @author Mikael Nordfeldth <mmn@hethane.se>
  44. * @copyright 2009-2014 Free Software Foundation, Inc http://www.fsf.org
  45. * @author Hugo Sales <hugo@hsal.es>
  46. * @author Diogo Peralta Cordeiro <mail@diogo.site>
  47. * @author Eliseu Amaro <mail@eliseuama.ro>
  48. * @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
  49. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  50. */
  51. class AttachmentThumbnail extends Entity
  52. {
  53. public const SIZE_SMALL = 0;
  54. public const SIZE_MEDIUM = 1;
  55. public const SIZE_BIG = 2;
  56. public const SIZE_MAP = [
  57. 'small' => self::SIZE_SMALL,
  58. 'medium' => self::SIZE_MEDIUM,
  59. 'big' => self::SIZE_BIG,
  60. ];
  61. // {{{ Autocode
  62. // @codeCoverageIgnoreStart
  63. private int $attachment_id;
  64. private ?string $mimetype = null;
  65. private int $size = 0;
  66. private string $filename;
  67. private int $width;
  68. private int $height;
  69. private DateTimeInterface $modified;
  70. public function setAttachmentId(int $attachment_id): self
  71. {
  72. $this->attachment_id = $attachment_id;
  73. return $this;
  74. }
  75. public function getAttachmentId(): int
  76. {
  77. return $this->attachment_id;
  78. }
  79. public function setMimetype(?string $mimetype): self
  80. {
  81. $this->mimetype = \is_null($mimetype) ? null : mb_substr($mimetype, 0, 129);
  82. return $this;
  83. }
  84. public function getMimetype(): ?string
  85. {
  86. return $this->mimetype;
  87. }
  88. public function setSize(int $size): self
  89. {
  90. $this->size = $size;
  91. return $this;
  92. }
  93. public function getSize(): int
  94. {
  95. return $this->size;
  96. }
  97. public function setFilename(string $filename): self
  98. {
  99. $this->filename = mb_substr($filename, 0, 191);
  100. return $this;
  101. }
  102. public function getFilename(): string
  103. {
  104. return $this->filename;
  105. }
  106. public function setWidth(int $width): self
  107. {
  108. $this->width = $width;
  109. return $this;
  110. }
  111. public function getWidth(): int
  112. {
  113. return $this->width;
  114. }
  115. public function setHeight(int $height): self
  116. {
  117. $this->height = $height;
  118. return $this;
  119. }
  120. public function getHeight(): int
  121. {
  122. return $this->height;
  123. }
  124. public function setModified(DateTimeInterface $modified): self
  125. {
  126. $this->modified = $modified;
  127. return $this;
  128. }
  129. public function getModified(): DateTimeInterface
  130. {
  131. return $this->modified;
  132. }
  133. // @codeCoverageIgnoreEnd
  134. // }}} Autocode
  135. public static function sizeIntToStr(?int $size): string
  136. {
  137. $map = array_flip(self::SIZE_MAP);
  138. return $map[$size] ?? $map[self::SIZE_SMALL];
  139. }
  140. public static function sizeStrToInt(string $size)
  141. {
  142. return self::SIZE_MAP[$size] ?? self::SIZE_SMALL;
  143. }
  144. private ?Attachment $attachment = null;
  145. public function setAttachment(?Attachment $attachment)
  146. {
  147. $this->attachment = $attachment;
  148. }
  149. public function getAttachment()
  150. {
  151. if (isset($this->attachment) && !\is_null($this->attachment)) {
  152. return $this->attachment;
  153. } else {
  154. return $this->attachment = DB::findOneBy('attachment', ['id' => $this->attachment_id]);
  155. }
  156. }
  157. public static function getCacheKey(int $id, int $size)
  158. {
  159. return "thumb-{$id}-{$size}";
  160. }
  161. /**
  162. * @param ?string $size 'small'|'medium'|'big'
  163. *
  164. * @throws ClientException
  165. * @throws NotFoundException
  166. * @throws ServerException
  167. *
  168. * @return ?self
  169. */
  170. public static function getOrCreate(Attachment $attachment, ?string $size = null, bool $crop = false): ?self
  171. {
  172. $size ??= Common::config('thumbnail', 'default_size');
  173. $size_int = self::sizeStrToInt($size);
  174. try {
  175. return Cache::get(
  176. self::getCacheKey($attachment->getId(), $size_int),
  177. fn () => DB::findOneBy('attachment_thumbnail', ['attachment_id' => $attachment->getId(), 'size' => $size_int]),
  178. );
  179. } catch (NotFoundException) {
  180. if (\is_null($attachment->getWidth()) || \is_null($attachment->getHeight())) {
  181. return null;
  182. }
  183. [$predicted_width, $predicted_height] = self::predictScalingValues($attachment->getWidth(), $attachment->getHeight(), $size, $crop);
  184. if (\is_null($attachment->getPath()) || !file_exists($attachment->getPath())) {
  185. // Before we quit, check if there's any other thumb
  186. $alternative_thumbs = DB::findBy('attachment_thumbnail', ['attachment_id' => $attachment->getId()]);
  187. usort($alternative_thumbs, fn ($l, $r) => $r->getSize() <=> $l->getSize());
  188. if (empty($alternative_thumbs)) {
  189. throw new NotStoredLocallyException();
  190. } else {
  191. return $alternative_thumbs[0];
  192. }
  193. }
  194. $thumbnail = self::create(['attachment_id' => $attachment->getId()]);
  195. $mimetype = $attachment->getMimetype();
  196. $event_map[$mimetype] = [];
  197. $major_mime = GSFile::mimetypeMajor($mimetype);
  198. $event_map[$major_mime] = [];
  199. Event::handle('FileResizerAvailable', [&$event_map, $mimetype]);
  200. // Always prefer specific encoders
  201. /** @var callable[] function(string $source, ?TemporaryFile &$destination, int &$width, int &$height, bool $smart_crop, ?string &$mimetype): bool */
  202. $encoders = array_merge($event_map[$mimetype], $event_map[$major_mime]);
  203. foreach ($encoders as $encoder) {
  204. /** @var ?TemporaryFile */
  205. $temp = null; // Let the EncoderPlugin create a temporary file for us
  206. if ($encoder($attachment->getPath(), $temp, $predicted_width, $predicted_height, $crop, $mimetype)) {
  207. $thumbnail->setAttachment($attachment);
  208. $thumbnail->setSize($size_int);
  209. $mimetype = $temp->getMimeType();
  210. $ext = '.' . MimeTypes::getDefault()->getExtensions($mimetype)[0];
  211. $filename = "{$predicted_width}x{$predicted_height}{$ext}-" . $attachment->getFilehash();
  212. $thumbnail->setFilename($filename);
  213. $thumbnail->setMimetype($mimetype);
  214. $thumbnail->setWidth($predicted_width);
  215. $thumbnail->setHeight($predicted_height);
  216. DB::persist($thumbnail);
  217. DB::flush();
  218. $temp->move(Common::config('thumbnail', 'dir'), $filename);
  219. return $thumbnail;
  220. }
  221. }
  222. return null;
  223. }
  224. }
  225. public function getPath()
  226. {
  227. return Common::config('thumbnail', 'dir') . \DIRECTORY_SEPARATOR . $this->getFilename();
  228. }
  229. public function getUrl()
  230. {
  231. return Router::url('attachment_thumbnail', ['id' => $this->getAttachmentId(), 'size' => self::sizeIntToStr($this->getSize())]);
  232. }
  233. /**
  234. * Delete an attachment thumbnail
  235. */
  236. public function delete(bool $flush = true): void
  237. {
  238. $filepath = $this->getPath();
  239. if (file_exists($filepath)) {
  240. if (@unlink($filepath) === false) {
  241. // @codeCoverageIgnoreStart
  242. Log::warning("Failed deleting file for attachment thumbnail with id={$this->getAttachmentId()}, size={$this->getSize()} at {$filepath}");
  243. // @codeCoverageIgnoreEnd
  244. }
  245. }
  246. Cache::delete(self::getCacheKey($this->getAttachmentId(), $this->getSize()));
  247. DB::remove($this);
  248. if ($flush) {
  249. DB::flush();
  250. }
  251. }
  252. /**
  253. * Gets scaling values for images of various types. Cropping can be enabled.
  254. *
  255. * Values will scale _up_ to fit max values if cropping is enabled!
  256. * With cropping disabled, the max value of each axis will be respected.
  257. *
  258. * @param int $existing_width Original width
  259. * @param int $existing_height Original height
  260. *
  261. * @return array [predicted width, predicted height]
  262. */
  263. public static function predictScalingValues(
  264. int $existing_width,
  265. int $existing_height,
  266. string $requested_size,
  267. bool $crop,
  268. ): array {
  269. /**
  270. * 1:1 => Square
  271. * 4:3 => SD
  272. * 11:8 => Academy Ratio
  273. * 3:2 => Classic 35mm
  274. * 16:10 => Golden Ratio
  275. * 16:9 => Widescreen
  276. * 2.2:1 => Standard 70mm film
  277. */
  278. $allowed_aspect_ratios = [1, 1.3, 1.376, 1.5, 1.6, 1.7, 2.2]; // Ascending array
  279. $sizes = [
  280. 'small' => Common::config('thumbnail', 'small'),
  281. 'medium' => Common::config('thumbnail', 'medium'),
  282. 'big' => Common::config('thumbnail', 'big'),
  283. ];
  284. // We only scale if the image is larger than the minimum width and height for a thumbnail
  285. if ($existing_width < Common::config('thumbnail', 'minimum_width') && $existing_height < Common::config('thumbnail', 'minimum_height')) {
  286. return [$existing_width, $existing_height];
  287. }
  288. // We only scale if the total of pixels is greater than the maximum allowed for a thumbnail
  289. $total_of_pixels = $existing_width * $existing_height;
  290. if ($total_of_pixels < Common::config('thumbnail', 'maximum_pixels')) {
  291. return [$existing_width, $existing_height];
  292. }
  293. // Is this a portrait image?
  294. $flip = $existing_height > $existing_width;
  295. // Find the aspect ratio of the given image
  296. $existing_aspect_ratio = !$flip ? $existing_width / $existing_height : $existing_height / $existing_width;
  297. // Binary search the closer allowed aspect ratio
  298. $left = 0;
  299. $right = \count($allowed_aspect_ratios) - 1;
  300. while ($left < $right) {
  301. $mid = floor($left + ($right - $left) / 2);
  302. // Comparing absolute distances with middle value and right value
  303. if (abs($existing_aspect_ratio - $allowed_aspect_ratios[$mid]) < abs($existing_aspect_ratio - $allowed_aspect_ratios[$right])) {
  304. // search the left side of the array
  305. $right = $mid;
  306. } else {
  307. // search the right side of the array
  308. $left = $mid + 1;
  309. }
  310. }
  311. $closest_aspect_ratio = $allowed_aspect_ratios[$left];
  312. unset($mid, $left, $right);
  313. // TODO: For crop, we should test a threshold and understand if the image would better be cropped
  314. // Resulting width and height
  315. $rw = (int) ($sizes[$requested_size]);
  316. $rh = (int) ($rw / $closest_aspect_ratio);
  317. return !$flip ? [$rw, $rh] : [$rh, $rw];
  318. }
  319. public static function schemaDef(): array
  320. {
  321. return [
  322. 'name' => 'attachment_thumbnail',
  323. 'fields' => [
  324. 'attachment_id' => ['type' => 'int', 'foreign key' => true, 'target' => 'Attachment.id', 'multiplicity' => 'one to one', 'not null' => true, 'description' => 'thumbnail for what attachment'],
  325. 'mimetype' => ['type' => 'varchar', 'length' => 129, 'description' => 'resource mime type 64+1+64, images hardly will show up with long mimetypes, this is probably safe considering rfc6838#section-4.2'],
  326. 'size' => ['type' => 'int', 'not null' => true, 'default' => 0, 'description' => '0 = small; 1 = medium; 2 = big'],
  327. 'filename' => ['type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'thumbnail filename'],
  328. 'width' => ['type' => 'int', 'not null' => true, 'description' => 'width in pixels, if it can be described as such and data is available'],
  329. 'height' => ['type' => 'int', 'not null' => true, 'description' => 'height in pixels, if it can be described as such and data is available'],
  330. 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
  331. ],
  332. 'primary key' => ['attachment_id', 'size'],
  333. 'indexes' => [
  334. 'attachment_thumbnail_attachment_id_idx' => ['attachment_id'],
  335. ],
  336. ];
  337. }
  338. }