Attachment.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 function App\Core\I18n\_m;
  26. use App\Core\Log;
  27. use App\Core\Router\Router;
  28. use App\Entity\Note;
  29. use App\Util\Common;
  30. use App\Util\Exception\ClientException;
  31. use App\Util\Exception\DuplicateFoundException;
  32. use App\Util\Exception\NotFoundException;
  33. use App\Util\Exception\ServerException;
  34. use DateTimeInterface;
  35. /**
  36. * Entity for uploaded files
  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. * @copyright 2020-2021 Free Software Foundation, Inc http://www.fsf.org
  48. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  49. */
  50. class Attachment extends Entity
  51. {
  52. // {{{ Autocode
  53. // @codeCoverageIgnoreStart
  54. private int $id;
  55. private int $lives = 1;
  56. private ?string $filehash = null;
  57. private ?string $mimetype = null;
  58. private ?string $filename = null;
  59. private ?int $size = null;
  60. private ?int $width = null;
  61. private ?int $height = null;
  62. private DateTimeInterface $modified;
  63. public function setId(int $id): self
  64. {
  65. $this->id = $id;
  66. return $this;
  67. }
  68. public function getId(): int
  69. {
  70. return $this->id;
  71. }
  72. public function setLives(int $lives): self
  73. {
  74. $this->lives = $lives;
  75. return $this;
  76. }
  77. public function getLives(): int
  78. {
  79. return $this->lives;
  80. }
  81. public function setFilehash(?string $filehash): self
  82. {
  83. $this->filehash = \is_null($filehash) ? null : mb_substr($filehash, 0, 64);
  84. return $this;
  85. }
  86. public function getFilehash(): ?string
  87. {
  88. return $this->filehash;
  89. }
  90. public function setMimetype(?string $mimetype): self
  91. {
  92. $this->mimetype = \is_null($mimetype) ? null : mb_substr($mimetype, 0, 255);
  93. return $this;
  94. }
  95. public function getMimetype(): ?string
  96. {
  97. return $this->mimetype;
  98. }
  99. public function setFilename(?string $filename): self
  100. {
  101. $this->filename = \is_null($filename) ? null : mb_substr($filename, 0, 191);
  102. return $this;
  103. }
  104. public function getFilename(): ?string
  105. {
  106. return $this->filename;
  107. }
  108. public function setSize(?int $size): self
  109. {
  110. $this->size = $size;
  111. return $this;
  112. }
  113. public function getSize(): ?int
  114. {
  115. return $this->size;
  116. }
  117. public function setWidth(?int $width): self
  118. {
  119. $this->width = $width;
  120. return $this;
  121. }
  122. public function getWidth(): ?int
  123. {
  124. return $this->width;
  125. }
  126. public function setHeight(?int $height): self
  127. {
  128. $this->height = $height;
  129. return $this;
  130. }
  131. public function getHeight(): ?int
  132. {
  133. return $this->height;
  134. }
  135. public function setModified(DateTimeInterface $modified): self
  136. {
  137. $this->modified = $modified;
  138. return $this;
  139. }
  140. public function getModified(): DateTimeInterface
  141. {
  142. return $this->modified;
  143. }
  144. // @codeCoverageIgnoreEnd
  145. // }}} Autocode
  146. public function getMimetypeMajor(): ?string
  147. {
  148. $mime = $this->getMimetype();
  149. return \is_null($mime) ? $mime : GSFile::mimetypeMajor($mime);
  150. }
  151. public function getMimetypeMinor(): ?string
  152. {
  153. $mime = $this->getMimetype();
  154. return \is_null($mime) ? $mime : GSFile::mimetypeMinor($mime);
  155. }
  156. public function livesIncrementAndGet(): int
  157. {
  158. ++$this->lives;
  159. return $this->lives;
  160. }
  161. public function livesDecrementAndGet(): int
  162. {
  163. --$this->lives;
  164. return $this->lives;
  165. }
  166. public const FILEHASH_ALGO = 'sha256';
  167. /**
  168. * Delete a file if safe, removes dependencies, cleanups and flushes
  169. */
  170. public function kill(): bool
  171. {
  172. if ($this->livesDecrementAndGet() <= 0) {
  173. return DB::wrapInTransaction(fn () => $this->delete());
  174. }
  175. return true;
  176. }
  177. /**
  178. * Remove the respective file from disk
  179. */
  180. public function deleteStorage(): bool
  181. {
  182. if (!\is_null($filepath = $this->getPath())) {
  183. if (file_exists($filepath)) {
  184. if (@unlink($filepath) === false) {
  185. // @codeCoverageIgnoreStart
  186. Log::error("Failed deleting file for attachment with id={$this->getId()} at {$filepath}.");
  187. return false;
  188. // @codeCoverageIgnoreEnd
  189. } else {
  190. $this->setFilename(null);
  191. $this->setSize(null);
  192. // Important not to null neither width nor height
  193. DB::persist($this);
  194. DB::flush();
  195. }
  196. } else {
  197. // @codeCoverageIgnoreStart
  198. Log::warning("File for attachment with id={$this->getId()} at {$filepath} was already deleted when I was going to handle it.");
  199. // @codeCoverageIgnoreEnd
  200. }
  201. }
  202. return true;
  203. }
  204. /**
  205. * Attachment delete always removes dependencies, cleanups and flushes
  206. * WARNING: Wrap this function in a transaction!
  207. *
  208. * @see kill() It's more likely that you want to use that rather than call delete directly
  209. */
  210. protected function delete(): bool
  211. {
  212. // Friendly warning because the caller usually doesn't want to delete an attachment that is still referred elsewhere
  213. if ($this->getLives() > 0) {
  214. // @codeCoverageIgnoreStart
  215. Log::warning("Deleting file {$this->getId()} with {$this->getLives()} lives. Why are you killing it so old?");
  216. // @codeCoverageIgnoreEnd
  217. }
  218. // Collect files starting with the one associated with this attachment
  219. $files = [];
  220. if (!\is_null($filepath = $this->getPath())) {
  221. $files[] = $filepath;
  222. }
  223. // Collect thumbnail files and delete thumbnails
  224. foreach ($this->getThumbnails() as $at) {
  225. $files[] = $at->getPath();
  226. $at->delete(flush: false);
  227. }
  228. // Delete eventual remaining relations with Actors
  229. ActorToAttachment::removeWhereAttachmentId($this->getId());
  230. // Delete eventual remaining relations with Notes
  231. AttachmentToNote::removeWhereAttachmentId($this->getId());
  232. // Delete eventual remaining relations with Links
  233. AttachmentToLink::removeWhereAttachmentId($this->getId());
  234. // Remove this attachment
  235. DB::remove($this);
  236. // Delete the files from disk
  237. foreach ($files as $f) {
  238. if (file_exists($f)) {
  239. if (@unlink($f) === false) {
  240. // @codeCoverageIgnoreStart
  241. Log::error("Failed deleting file for attachment with id={$this->getId()} at {$f}.");
  242. // @codeCoverageIgnoreEnd
  243. }
  244. } else {
  245. // @codeCoverageIgnoreStart
  246. Log::warning("File for attachment with id={$this->getId()} at {$f} was already deleted when I was going to handle it.");
  247. // @codeCoverageIgnoreEnd
  248. }
  249. }
  250. // Flush these changes as we have deleted the files from disk
  251. DB::flush();
  252. return true;
  253. }
  254. /**
  255. * TODO: Maybe this isn't the best way of handling titles
  256. *
  257. * @throws DuplicateFoundException
  258. * @throws NotFoundException
  259. * @throws ServerException
  260. */
  261. public function getBestTitle(?Note $note = null): string
  262. {
  263. // If we have a note, then the best title is the title itself
  264. if (!\is_null(($note))) {
  265. $title = Cache::get('attachment-title-' . $this->getId() . '-' . $note->getId(), function () use ($note) {
  266. try {
  267. $attachment_to_note = DB::findOneBy('attachment_to_note', [
  268. 'attachment_id' => $this->getId(),
  269. 'note_id' => $note->getId(),
  270. ]);
  271. if (!\is_null($attachment_to_note->getTitle())) {
  272. return $attachment_to_note->getTitle();
  273. }
  274. } catch (NotFoundException) {
  275. $title = null;
  276. Event::handle('AttachmentGetBestTitle', [$this, $note, &$title]);
  277. return $title;
  278. }
  279. });
  280. if ($title != null) {
  281. return $title;
  282. }
  283. }
  284. // Else
  285. if (!\is_null($filename = $this->getFilename())) {
  286. // A filename would do just as well
  287. return $filename;
  288. } else {
  289. // Welp
  290. return _m('Untitled attachment');
  291. }
  292. }
  293. /**
  294. * Find all thumbnails associated with this attachment. Don't bother caching as this is not supposed to be a common operation
  295. */
  296. public function getThumbnails()
  297. {
  298. return DB::findBy('attachment_thumbnail', ['attachment_id' => $this->id]);
  299. }
  300. public function getPath()
  301. {
  302. $filename = $this->getFilename();
  303. return \is_null($filename) ? null : Common::config('attachments', 'dir') . \DIRECTORY_SEPARATOR . $filename;
  304. }
  305. public function getUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
  306. {
  307. return Router::url(id: 'note_attachment_view', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
  308. }
  309. public function getShowUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
  310. {
  311. return Router::url(id: 'note_attachment_show', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
  312. }
  313. public function getDownloadUrl(Note|int $note, int $type = Router::ABSOLUTE_URL): string
  314. {
  315. return Router::url(id: 'note_attachment_download', args: ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId()], type: $type);
  316. }
  317. /**
  318. * @throws ClientException
  319. * @throws NotFoundException
  320. * @throws ServerException
  321. *
  322. * @return AttachmentThumbnail
  323. */
  324. public function getThumbnail(?string $size = null, bool $crop = false): ?AttachmentThumbnail
  325. {
  326. return AttachmentThumbnail::getOrCreate(attachment: $this, size: $size, crop: $crop);
  327. }
  328. public function getThumbnailUrl(Note|int $note, ?string $size = null)
  329. {
  330. return Router::url('note_attachment_thumbnail', ['note_id' => \is_int($note) ? $note : $note->getId(), 'attachment_id' => $this->getId(), 'size' => $size ?? Common::config('thumbnail', 'default_size')]);
  331. }
  332. public static function schemaDef(): array
  333. {
  334. return [
  335. 'name' => 'attachment',
  336. 'fields' => [
  337. 'id' => ['type' => 'serial', 'not null' => true],
  338. 'lives' => ['type' => 'int', 'default' => 1, 'not null' => true, 'description' => 'RefCount, starts with 1'],
  339. 'filehash' => ['type' => 'varchar', 'length' => 64, 'description' => 'sha256 of the file contents, if the file is stored locally'],
  340. 'mimetype' => ['type' => 'varchar', 'length' => 255, 'description' => 'resource mime type 127+1+127 as per rfc6838#section-4.2'],
  341. 'filename' => ['type' => 'varchar', 'length' => 191, 'description' => 'file name of resource when available'],
  342. 'size' => ['type' => 'int', 'description' => 'size of resource when available'],
  343. 'width' => ['type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'],
  344. 'height' => ['type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'],
  345. 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'],
  346. ],
  347. 'primary key' => ['id'],
  348. 'unique keys' => [
  349. 'attachment_filehash_uniq' => ['filehash'],
  350. 'attachment_filename_uniq' => ['filename'],
  351. ],
  352. 'indexes' => [
  353. 'file_filehash_idx' => ['filehash'],
  354. ],
  355. ];
  356. }
  357. }