Utils.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. <?php
  2. // {{{ License
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. // }}}
  18. namespace Component\Media;
  19. use App\Core\Cache;
  20. use App\Core\DB\DB;
  21. use function App\Core\I18n\_m;
  22. use App\Core\Log;
  23. use App\Entity\Attachment;
  24. use App\Entity\Avatar;
  25. use App\Util\Common;
  26. use App\Util\Exception\ClientException;
  27. use Component\Media\Exception\NoAvatarException;
  28. use Exception;
  29. use Symfony\Component\Asset\Package;
  30. use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
  31. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  32. use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
  33. use Symfony\Component\HttpFoundation\HeaderUtils;
  34. use Symfony\Component\HttpFoundation\Response;
  35. abstract class Utils
  36. {
  37. /**
  38. * Perform file validation (checks and normalization) and store the given file
  39. */
  40. public static function validateAndStoreAttachment(SymfonyFile $sfile,
  41. string $dest_dir,
  42. ?string $title = null,
  43. bool $is_local = true,
  44. ?int $actor_id = null): Attachment
  45. {
  46. // The following properly gets the mimetype with `file` or other
  47. // available methods, so should be safe
  48. $hash = hash_file(Attachment::FILEHASH_ALGO, $sfile->getPathname());
  49. $file = Attachment::create([
  50. 'file_hash' => $hash,
  51. 'actor_id' => $actor_id,
  52. 'mimetype' => $sfile->getMimeType(),
  53. 'title' => $title ?: _m('Untitled attachment'),
  54. 'filename' => $hash,
  55. 'is_local' => $is_local,
  56. ]);
  57. $sfile->move($dest_dir, $hash);
  58. // TODO Normalize file types
  59. return $file;
  60. }
  61. /**
  62. * Include $filepath in the response, for viewing or downloading.
  63. *
  64. * @throws ServerException
  65. */
  66. public static function sendFile(string $filepath, string $mimetype, ?string $output_filename, string $disposition = 'inline'): Response
  67. {
  68. $response = new BinaryFileResponse(
  69. $filepath,
  70. Response::HTTP_OK,
  71. [
  72. 'Content-Description' => 'File Transfer',
  73. 'Content-Type' => $mimetype,
  74. 'Content-Disposition' => HeaderUtils::makeDisposition($disposition, $output_filename ?: _m('Untitled attachment')),
  75. 'Cache-Control' => 'public',
  76. ],
  77. $public = true,
  78. $disposition = null,
  79. $add_etag = true,
  80. $add_last_modified = true
  81. );
  82. if (Common::config('site', 'x_static_delivery')) {
  83. $response->trustXSendfileTypeHeader();
  84. }
  85. return $response;
  86. }
  87. /**
  88. * Throw a client exception if the cache key $id doesn't contain
  89. * exactly one entry
  90. *
  91. * @param mixed $except
  92. * @param mixed $id
  93. */
  94. private static function error($except, $id, array $res)
  95. {
  96. switch (count($res)) {
  97. case 0:
  98. throw new $except();
  99. case 1:
  100. return $res[0];
  101. default:
  102. Log::error('Media query returned more than one result for identifier: \"' . $id . '\"');
  103. throw new ClientException(_m('Internal server error'));
  104. }
  105. }
  106. /**
  107. * Get the file info by id
  108. *
  109. * Returns the file's hash, mimetype and title
  110. */
  111. public static function getFileInfo(int $id)
  112. {
  113. return self::error(NoSuchFileException::class,
  114. $id,
  115. Cache::get("file-info-{$id}",
  116. function () use ($id) {
  117. return DB::dql('select at.file_hash, at.mimetype, at.title ' .
  118. 'from App\\Entity\\Attachment at ' .
  119. 'where at.id = :id',
  120. ['id' => $id]);
  121. }));
  122. }
  123. // ----- Attachment ------
  124. /**
  125. * Get the attachment file info by id
  126. *
  127. * Returns the attachment file's hash, mimetype, title and path
  128. */
  129. public static function getAttachmentFileInfo(int $id): array
  130. {
  131. $res = self::getFileInfo($id);
  132. $res['file_path'] = Common::config('attachments', 'dir') . $res['file_hash'];
  133. return $res;
  134. }
  135. // ----- Avatar ------
  136. /**
  137. * Get the avatar associated with the given nickname
  138. */
  139. public static function getAvatar(?string $nickname = null): Avatar
  140. {
  141. $nickname = $nickname ?: Common::userNickname();
  142. return self::error(NoAvatarException::class,
  143. $nickname,
  144. Cache::get("avatar-{$nickname}",
  145. function () use ($nickname) {
  146. return DB::dql('select a from App\\Entity\\Avatar a ' .
  147. 'join App\Entity\GSActor g with a.gsactor_id = g.id ' .
  148. 'where g.nickname = :nickname',
  149. ['nickname' => $nickname]);
  150. }));
  151. }
  152. /**
  153. * Get the cached avatar associated with the given nickname, or the current user if not given
  154. */
  155. public static function getAvatarUrl(?string $nickname = null): string
  156. {
  157. $nickname = $nickname ?: Common::userNickname();
  158. return Cache::get("avatar-url-{$nickname}", function () use ($nickname) {
  159. try {
  160. return self::getAvatar($nickname)->getUrl();
  161. } catch (NoAvatarException $e) {
  162. }
  163. $package = new Package(new EmptyVersionStrategy());
  164. return $package->getUrl(Common::config('avatar', 'default'));
  165. });
  166. }
  167. /**
  168. * Get the cached avatar file info associated with the given nickname
  169. *
  170. * Returns the avatar file's hash, mimetype, title and path.
  171. * Ensures exactly one cached value exists
  172. */
  173. public static function getAvatarFileInfo(string $nickname): array
  174. {
  175. try {
  176. $res = self::error(NoAvatarException::class,
  177. $nickname,
  178. Cache::get("avatar-file-info-{$nickname}",
  179. function () use ($nickname) {
  180. return DB::dql('select f.file_hash, f.mimetype, f.title ' .
  181. 'from App\\Entity\\Attachment f ' .
  182. 'join App\\Entity\\Avatar a with f.id = a.file_id ' .
  183. 'join App\\Entity\\GSActor g with g.id = a.gsactor_id ' .
  184. 'where g.nickname = :nickname',
  185. ['nickname' => $nickname]);
  186. }));
  187. $res['file_path'] = Avatar::getFilePathStatic($res['file_hash']);
  188. return $res;
  189. } catch (Exception $e) {
  190. $filepath = INSTALLDIR . '/public/assets/default-avatar.svg';
  191. return ['file_path' => $filepath, 'mimetype' => 'image/svg+xml', 'title' => null];
  192. }
  193. }
  194. // ------------------------------
  195. /**
  196. * Get the minor part of a mimetype. image/webp -> image
  197. */
  198. public static function mimetypeMajor(string $mime)
  199. {
  200. return explode('/', self::mimeBare($mime))[0];
  201. }
  202. /**
  203. * Get the minor part of a mimetype. image/webp -> webp
  204. */
  205. public static function mimetypeMinor(string $mime)
  206. {
  207. return explode('/', self::mimeBare($mime))[1];
  208. }
  209. /**
  210. * Get only the mimetype and not additional info (separated from bare mime with semi-colon)
  211. */
  212. public static function mimeBare(string $mimetype)
  213. {
  214. $mimetype = mb_strtolower($mimetype);
  215. if (($semicolon = mb_strpos($mimetype, ';')) !== false) {
  216. $mimetype = mb_substr($mimetype, 0, $semicolon);
  217. }
  218. return trim($mimetype);
  219. }
  220. }