Utils.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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\Avatar;
  24. use App\Entity\File;
  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 validateAndStoreFile(SymfonyFile $sfile,
  41. string $dest_dir,
  42. ?string $title = null,
  43. bool $is_local = true,
  44. ?int $actor_id = null): File
  45. {
  46. // The following properly gets the mimetype with `file` or other
  47. // available methods, so should be safe
  48. $hash = hash_file(File::FILEHASH_ALGO, $sfile->getPathname());
  49. $file = File::create([
  50. 'file_hash' => $hash,
  51. 'actor_id' => $actor_id,
  52. 'mimetype' => $sfile->getMimeType(),
  53. 'title' => $title ?: _m('Untitled attachment'),
  54. 'is_local' => $is_local,
  55. ]);
  56. $sfile->move($dest_dir, $hash);
  57. // TODO Normalize file types
  58. return $file;
  59. }
  60. /**
  61. * Include $filepath in the response, for viewing or downloading.
  62. *
  63. * @throws ServerException
  64. */
  65. public static function sendFile(string $filepath, string $mimetype, ?string $output_filename, string $disposition = 'inline'): Response
  66. {
  67. $response = new BinaryFileResponse(
  68. $filepath,
  69. Response::HTTP_OK,
  70. [
  71. 'Content-Description' => 'File Transfer',
  72. 'Content-Type' => $mimetype,
  73. 'Content-Disposition' => HeaderUtils::makeDisposition($disposition, $output_filename ?: _m('untitled')),
  74. 'Cache-Control' => 'public',
  75. ],
  76. $public = true,
  77. $disposition = null,
  78. $add_etag = true,
  79. $add_last_modified = true
  80. );
  81. if (Common::config('site', 'x_static_delivery')) {
  82. $response->trustXSendfileTypeHeader();
  83. }
  84. return $response;
  85. }
  86. /**
  87. * Throw a client exception if the cache key $id doesn't contain
  88. * exactly one entry
  89. *
  90. * @param mixed $except
  91. * @param mixed $id
  92. */
  93. private static function error($except, $id, array $res)
  94. {
  95. switch (count($res)) {
  96. case 0:
  97. throw new $except();
  98. case 1:
  99. return $res[0];
  100. default:
  101. Log::error('Media query returned more than one result for identifier: \"' . $id . '\"');
  102. throw new ClientException(_m('Internal server error'));
  103. }
  104. }
  105. /**
  106. * Get the file info by id
  107. *
  108. * Returns the file's hash, mimetype and title
  109. */
  110. public static function getFileInfo(int $id)
  111. {
  112. return self::error(NoSuchFileException::class,
  113. $id,
  114. Cache::get("file-info-{$id}",
  115. function () use ($id) {
  116. return DB::dql('select f.file_hash, f.mimetype, f.title ' .
  117. 'from App\\Entity\\File f ' .
  118. 'where f.id = :id',
  119. ['id' => $id]);
  120. }));
  121. }
  122. // ----- Attachment ------
  123. /**
  124. * Get the attachment file info by id
  125. *
  126. * Returns the attachment file's hash, mimetype, title and path
  127. */
  128. public static function getAttachmentFileInfo(int $id): array
  129. {
  130. $res = self::getFileInfo($id);
  131. $res['file_path'] = Common::config('attachments', 'dir') . $res['file_hash'];
  132. return $res;
  133. }
  134. // ----- Avatar ------
  135. /**
  136. * Get the avatar associated with the given nickname
  137. */
  138. public static function getAvatar(?string $nickname = null): Avatar
  139. {
  140. $nickname = $nickname ?: Common::userNickname();
  141. return self::error(NoAvatarException::class,
  142. $nickname,
  143. Cache::get("avatar-{$nickname}",
  144. function () use ($nickname) {
  145. return DB::dql('select a from App\\Entity\\Avatar a ' .
  146. 'join App\Entity\GSActor g with a.gsactor_id = g.id ' .
  147. 'where g.nickname = :nickname',
  148. ['nickname' => $nickname]);
  149. }));
  150. }
  151. /**
  152. * Get the cached avatar associated with the given nickname, or the current user if not given
  153. */
  154. public static function getAvatarUrl(?string $nickname = null): string
  155. {
  156. $nickname = $nickname ?: Common::userNickname();
  157. return Cache::get("avatar-url-{$nickname}", function () use ($nickname) {
  158. try {
  159. return self::getAvatar($nickname)->getUrl();
  160. } catch (NoAvatarException $e) {
  161. }
  162. $package = new Package(new EmptyVersionStrategy());
  163. return $package->getUrl(Common::config('avatar', 'default'));
  164. });
  165. }
  166. /**
  167. * Get the cached avatar file info associated with the given nickname
  168. *
  169. * Returns the avatar file's hash, mimetype, title and path.
  170. * Ensures exactly one cached value exists
  171. */
  172. public static function getAvatarFileInfo(string $nickname): array
  173. {
  174. try {
  175. $res = self::error(NoAvatarException::class,
  176. $nickname,
  177. Cache::get("avatar-file-info-{$nickname}",
  178. function () use ($nickname) {
  179. return DB::dql('select f.file_hash, f.mimetype, f.title ' .
  180. 'from App\\Entity\\File f ' .
  181. 'join App\\Entity\\Avatar a with f.id = a.file_id ' .
  182. 'join App\\Entity\\GSActor g with g.id = a.gsactor_id ' .
  183. 'where g.nickname = :nickname',
  184. ['nickname' => $nickname]);
  185. }));
  186. $res['file_path'] = Avatar::getFilePathStatic($res['file_hash']);
  187. return $res;
  188. } catch (Exception $e) {
  189. $filepath = INSTALLDIR . '/public/assets/default-avatar.svg';
  190. return ['file_path' => $filepath, 'mimetype' => 'image/svg+xml', 'title' => null];
  191. }
  192. }
  193. }