Posting.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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\Posting;
  19. use App\Core\Cache;
  20. use App\Core\DB\DB;
  21. use App\Core\Event;
  22. use App\Core\Form;
  23. use App\Core\GSFile;
  24. use function App\Core\I18n\_m;
  25. use App\Core\Modules\Component;
  26. use App\Entity\Attachment;
  27. use App\Entity\AttachmentToNote;
  28. use App\Entity\GSActorToAttachment;
  29. use App\Entity\Link;
  30. use App\Entity\Note;
  31. use App\Entity\NoteToLink;
  32. use App\Util\Common;
  33. use App\Util\Exception\InvalidFormException;
  34. use App\Util\Exception\RedirectException;
  35. use InvalidArgumentException;
  36. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  37. use Symfony\Component\Form\Extension\Core\Type\FileType;
  38. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  39. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  40. class Posting extends Component
  41. {
  42. /**
  43. * "Perfect URL Regex", courtesy of https://urlregex.com/
  44. */
  45. const URL_REGEX = <<<END
  46. %(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@|\\d{1,3}(?:\\.\\d{1,3}){3}|(?:(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)(?:\\.(?:[a-z\\d\\x{00a1}-\\x{ffff}]+-?)*[a-z\\d\\x{00a1}-\\x{ffff}]+)*(?:\\.[a-z\\x{00a1}-\\x{ffff}]{2,6}))(?::\\d+)?(?:[^\\s]*)?%iu
  47. END;
  48. /**
  49. * HTML render event handler responsible for adding and handling
  50. * the result of adding the note submission form, only if a user is logged in
  51. */
  52. public function onStartTwigPopulateVars(array &$vars): bool
  53. {
  54. if (($user = Common::user()) == null) {
  55. return Event::next;
  56. }
  57. $actor_id = $user->getId();
  58. $to_tags = [];
  59. $tags = Cache::get("actor-tags-{$actor_id}", function () use ($actor_id) {
  60. return DB::dql('select c.tag from App\Entity\GSActorCircle c where c.tagger = :tagger', ['tagger' => $actor_id]);
  61. });
  62. foreach ($tags as $t) {
  63. $t = $t['tag'];
  64. $to_tags[$t] = $t;
  65. }
  66. $placeholder_string = ['How are you feeling?', 'Have something to share?', 'How was your day?'];
  67. Event::handle('PostingPlaceHolderString', [&$placeholder_string]);
  68. $rand_key = array_rand($placeholder_string);
  69. $request = $vars['request'];
  70. $form = Form::create([
  71. ['content', TextareaType::class, ['label' => ' ', 'data' => '', 'attr' => ['placeholder' => _m($placeholder_string[$rand_key])]]],
  72. ['attachments', FileType::class, ['label' => ' ', 'data' => null, 'multiple' => true, 'required' => false]],
  73. ['visibility', ChoiceType::class, ['label' => _m('Visibility:'), 'expanded' => true, 'data' => 'public', 'choices' => [_m('Public') => 'public', _m('Instance') => 'instance', _m('Private') => 'private']]],
  74. ['to', ChoiceType::class, ['label' => _m('To:'), 'multiple' => true, 'expanded' => true, 'choices' => $to_tags]],
  75. ['post_note', SubmitType::class, ['label' => _m('Post')]],
  76. ]);
  77. $form->handleRequest($request);
  78. if ($form->isSubmitted()) {
  79. $data = $form->getData();
  80. if ($form->isValid()) {
  81. self::storeNote($actor_id, $data['content'], $data['attachments'], $is_local = true);
  82. throw new RedirectException();
  83. } else {
  84. throw new InvalidFormException();
  85. }
  86. }
  87. $vars['post_form'] = $form->createView();
  88. return Event::next;
  89. }
  90. /**
  91. * Store the given note with $content and $attachments, created by
  92. * $actor_id, possibly as a reply to note $reply_to and with flag
  93. * $is_local. Sanitizes $content and $attachments
  94. */
  95. public static function storeNote(int $actor_id, ?string $content, array $attachments, bool $is_local, ?int $reply_to = null, ?int $repeat_of = null)
  96. {
  97. $note = Note::create([
  98. 'gsactor_id' => $actor_id,
  99. 'content' => $content,
  100. 'is_local' => $is_local,
  101. 'reply_to' => $reply_to,
  102. 'repeat_of' => $repeat_of,
  103. ]);
  104. $processed_attachments = [];
  105. foreach ($attachments as $f) { // where $f is a Symfony\Component\HttpFoundation\File\UploadedFile
  106. $filesize = $f->getSize();
  107. Event::handle('EnforceQuota', [$actor_id, $filesize]);
  108. $processed_attachments[] = [GSFile::sanitizeAndStoreFileAsAttachment($f), $f->getClientOriginalName()];
  109. }
  110. DB::persist($note);
  111. // Need file and note ids for the next step
  112. DB::flush();
  113. if ($processed_attachments != []) {
  114. foreach ($processed_attachments as [$a, $fname]) {
  115. if (empty(DB::findBy('gsactor_to_attachment', ['attachment_id' => $a->getId(), 'gsactor_id' => $actor_id]))) {
  116. DB::persist(GSActorToAttachment::create(['attachment_id' => $a->getId(), 'gsactor_id' => $actor_id]));
  117. }
  118. DB::persist(AttachmentToNote::create(['attachment_id' => $a->getId(), 'note_id' => $note->getId(), 'title' => $fname]));
  119. }
  120. DB::flush();
  121. }
  122. $matched_urls = [];
  123. $processed_urls = false;
  124. preg_match_all(self::URL_REGEX, $content, $matched_urls, PREG_SET_ORDER);
  125. foreach ($matched_urls as $match) {
  126. try {
  127. $link_id = Link::getOrCreate($match[0])->getId();
  128. DB::persist(NoteToLink::create(['link_id' => $link_id, 'note_id' => $note->getId()]));
  129. $processed_urls = true;
  130. } catch (InvalidArgumentException) {
  131. continue;
  132. }
  133. }
  134. if ($processed_urls) {
  135. DB::flush();
  136. }
  137. }
  138. /**
  139. * Get a unique representation of a file on disk
  140. *
  141. * This can be used in the future to deduplicate images by visual content
  142. */
  143. public function onHashFile(string $filename, ?string &$out_hash)
  144. {
  145. $out_hash = hash_file(Attachment::FILEHASH_ALGO, $filename);
  146. return Event::stop;
  147. }
  148. /**
  149. * Fill the list of allowed sizes for an attachment, to prevent potential DoS'ing by requesting thousands of different thumbnail sizes
  150. */
  151. public function onGetAllowedThumbnailSizes(?array &$sizes)
  152. {
  153. $sizes[] = ['width' => Common::config('thumbnail', 'width'), 'height' => Common::config('thumbnail', 'height')];
  154. return Event::next;
  155. }
  156. }