Utils.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 Component\Media\Exception\NoAvatarException;
  27. use Exception;
  28. use Symfony\Component\Asset\Package;
  29. use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
  30. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  31. use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
  32. use Symfony\Component\HttpFoundation\HeaderUtils;
  33. use Symfony\Component\HttpFoundation\Response;
  34. abstract class Utils
  35. {
  36. public static function validateAndStoreFile(SymfonyFile $sfile,
  37. string $dest_dir,
  38. ?string $title = null,
  39. bool $is_local = true,
  40. ?int $actor_id = null): File
  41. {
  42. // The following properly gets the mimetype with `file` or other
  43. // available methods, so should be safe
  44. $hash = hash_file(File::FILEHASH_ALGO, $sfile->getPathname());
  45. $file = File::create([
  46. 'file_hash' => $hash,
  47. 'actor_id' => $actor_id,
  48. 'mimetype' => $sfile->getMimeType(),
  49. 'title' => $title ?: _m('Untitled attachment'),
  50. 'is_local' => $is_local,
  51. ]);
  52. $sfile->move($dest_dir, $hash);
  53. // TODO Normalize file types
  54. return $file;
  55. }
  56. /**
  57. * Include $filepath in the response, for viewing or downloading.
  58. *
  59. * @throws ServerException
  60. */
  61. public static function sendFile(string $filepath, string $mimetype, ?string $output_filename, string $disposition = 'inline'): Response
  62. {
  63. $response = new BinaryFileResponse(
  64. $filepath,
  65. Response::HTTP_OK,
  66. [
  67. 'Content-Description' => 'File Transfer',
  68. 'Content-Type' => $mimetype,
  69. 'Content-Disposition' => HeaderUtils::makeDisposition($disposition, $output_filename ?: _m('untitled')),
  70. 'Cache-Control' => 'public',
  71. ],
  72. $public = true,
  73. $disposition = null,
  74. $add_etag = true,
  75. $add_last_modified = true
  76. );
  77. if (Common::config('site', 'x_static_delivery')) {
  78. $response->trustXSendfileTypeHeader();
  79. }
  80. return $response;
  81. }
  82. public static function error($except, $id, array $res)
  83. {
  84. switch (count($res)) {
  85. case 0:
  86. throw new $except();
  87. case 1:
  88. return $res[0];
  89. default:
  90. Log::error('Media query returned more than one result for identifier: \"' . $id . '\"');
  91. throw new Exception(_m('Internal server error'));
  92. }
  93. }
  94. public static function getAvatar(string $nickname)
  95. {
  96. return self::error(NoAvatarException::class,
  97. $nickname,
  98. Cache::get("avatar-{$nickname}",
  99. function () use ($nickname) {
  100. return DB::dql('select a from App\\Entity\\Avatar a ' .
  101. 'join App\Entity\GSActor g with a.gsactor_id = g.id ' .
  102. 'where g.nickname = :nickname',
  103. ['nickname' => $nickname]);
  104. }));
  105. }
  106. public static function getFileInfo(int $id)
  107. {
  108. return self::error(NoSuchFileException::class,
  109. $id,
  110. Cache::get("file-info-{$id}",
  111. function () use ($id) {
  112. return DB::dql('select f.file_hash, f.mimetype, f.title ' .
  113. 'from App\\Entity\\File f ' .
  114. 'where f.id = :id',
  115. ['id' => $id]);
  116. }));
  117. }
  118. public static function getAttachmentFileInfo(int $id)
  119. {
  120. $res = self::getFileInfo($id);
  121. $res['file_path'] = Common::config('attachments', 'dir') . $res['file_hash'];
  122. return $res;
  123. }
  124. public static function getAvatarFileInfo(string $nickname)
  125. {
  126. try {
  127. $res = self::error(NoAvatarException::class,
  128. $nickname,
  129. Cache::get("avatar-file-info-{$nickname}",
  130. function () use ($nickname) {
  131. return DB::dql('select f.file_hash, f.mimetype, f.title ' .
  132. 'from App\\Entity\\File f ' .
  133. 'join App\\Entity\\Avatar a with f.id = a.file_id ' .
  134. 'join App\\Entity\\GSActor g with g.id = a.gsactor_id ' .
  135. 'where g.nickname = :nickname',
  136. ['nickname' => $nickname]);
  137. }));
  138. $res['file_path'] = Avatar::getFilePathStatic($res['file_hash']);
  139. return $res;
  140. } catch (Exception $e) {
  141. $filepath = INSTALLDIR . '/public/assets/default-avatar.svg';
  142. return ['file_path' => $filepath, 'mimetype' => 'image/svg+xml', 'title' => null];
  143. }
  144. }
  145. public static function getAvatarUrl(?string $nickname = null)
  146. {
  147. if ($nickname == null) {
  148. $user = Common::user();
  149. if ($user != null) {
  150. $nickname = $user->getNickname();
  151. } else {
  152. throw new Exception('No user is logged in and no avatar provided to `getAvatarUrl`');
  153. }
  154. }
  155. return Cache::get("avatar-url-{$nickname}", function () use ($nickname) {
  156. try {
  157. return self::getAvatar($nickname)->getUrl();
  158. } catch (NoAvatarException $e) {
  159. }
  160. $package = new Package(new EmptyVersionStrategy());
  161. return $package->getUrl(Common::config('avatar', 'default'));
  162. });
  163. }
  164. }