Conversation.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. /**
  20. * @author Hugo Sales <hugo@hsal.es>
  21. * @author Eliseu Amaro <mail@eliseuama.ro>
  22. * @copyright 2021-2022 Free Software Foundation, Inc http://www.fsf.org
  23. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  24. */
  25. namespace Component\Conversation;
  26. use App\Core\Cache;
  27. use App\Core\DB;
  28. use App\Core\Event;
  29. use function App\Core\I18n\_m;
  30. use App\Core\Modules\Component;
  31. use App\Core\Router;
  32. use App\Entity\Activity;
  33. use App\Entity\Actor;
  34. use App\Entity\Note;
  35. use App\Util\Common;
  36. use App\Util\Formatting;
  37. use Component\Conversation\Entity\Conversation as ConversationEntity;
  38. use Component\Conversation\Entity\ConversationMute;
  39. use EventResult;
  40. use Functional as F;
  41. use Symfony\Component\HttpFoundation\Request;
  42. class Conversation extends Component
  43. {
  44. public function onAddRoute(Router $r): EventResult
  45. {
  46. $r->connect('conversation', '/conversation/{conversation_id<\d+>}', [Controller\Conversation::class, 'showConversation']);
  47. $r->connect('conversation_mute', '/conversation/{conversation_id<\d+>}/mute', [Controller\Conversation::class, 'muteConversation']);
  48. $r->connect('conversation_reply_to', '/conversation/reply', [Controller\Conversation::class, 'addReply']);
  49. return Event::next;
  50. }
  51. /**
  52. * **Assigns** the given local Note it's corresponding **Conversation**.
  53. *
  54. * **If a _$parent_id_ is not given**, then the Actor is not attempting a reply,
  55. * therefore, we can assume (for now) that we need to create a new Conversation and assign it
  56. * to the newly created Note (please look at Component\Posting::storeLocalNote, where this function is used)
  57. *
  58. * **On the other hand**, given a _$parent_id_, the Actor is attempting to post a reply. Meaning that,
  59. * this Note conversation_id should be same as the parent Note
  60. *
  61. * @param \App\Entity\Note $current_note Local Note currently being assigned a Conversation
  62. * @param null|int $parent_id If present, it's a reply
  63. */
  64. public static function assignLocalConversation(Note $current_note, ?int $parent_id): void
  65. {
  66. if (!$parent_id) {
  67. // If none found, we don't know yet if it is a reply or root
  68. // Let's assume for now that it's a new conversation and deal with stitching later
  69. $conversation = ConversationEntity::create(['initial_note_id' => $current_note->getId()]);
  70. // We need the Conversation id itself, so a persist is in order
  71. DB::persist($conversation);
  72. // Set current_note's own conversation_id
  73. $current_note->setConversationId($conversation->getId());
  74. } else {
  75. // It's a reply for sure
  76. // Set reply_to property in newly created Note to parent's id
  77. // Parent will have a conversation of its own, the reply should have the same one
  78. $parent_note = Note::getById($parent_id);
  79. $current_note->setConversationId($parent_note->getConversationId());
  80. }
  81. DB::persist($current_note);
  82. }
  83. /**
  84. * HTML rendering event that adds a reply link as a note
  85. * action, if a user is logged in.
  86. *
  87. * @param \App\Entity\Note $note The Note being rendered
  88. * @param array{url: string, title: string, classes: string, id: string} $actions
  89. * Contains keys 'url' (linking 'conversation_reply_to' route),
  90. * 'title' (used as title for aforementioned url), 'classes' (CSS styling
  91. * classes used to visually inform the user of action context), 'id' (HTML
  92. * markup id used to redirect user to this anchor upon performing the
  93. * action)
  94. *
  95. * @throws \App\Util\Exception\ServerException
  96. */
  97. public function onAddNoteActions(Request $request, Note $note, array &$actions): EventResult
  98. {
  99. if (\is_null(Common::user())) {
  100. return Event::next;
  101. }
  102. $from = $request->query->has('from')
  103. ? $request->query->get('from')
  104. : $request->getPathInfo();
  105. $reply_action_url = Router::url(
  106. 'conversation_reply_to',
  107. [
  108. 'reply_to_id' => $note->getId(),
  109. 'from' => $from,
  110. '_fragment' => 'note-anchor-' . $note->getId(),
  111. ],
  112. Router::ABSOLUTE_PATH,
  113. );
  114. $reply_action = [
  115. 'url' => $reply_action_url,
  116. 'title' => _m('Reply to this note!'),
  117. 'classes' => 'button-container reply-button-container note-actions-unset',
  118. 'id' => 'reply-button-container-' . $note->getId(),
  119. ];
  120. $actions[] = $reply_action;
  121. return Event::next;
  122. }
  123. /**
  124. * Append on note information about user actions.
  125. *
  126. * @param array<string, mixed> $vars Contains information related to Note currently being rendered
  127. * @param array{actors: Actor[], action: string} $result
  128. *cContains keys 'actors', and 'action'. Needed to construct a string,
  129. * stating who ($result['actors']), has already performed a reply
  130. * ($result['action']), in the given Note (vars['note'])
  131. */
  132. public function onAppendCardNote(array $vars, array &$result): EventResult
  133. {
  134. if (str_contains($vars['request']->getPathInfo(), 'conversation')) {
  135. return Event::next;
  136. }
  137. // The current Note being rendered
  138. $note = $vars['note'];
  139. // Will have actors array, and action string
  140. // Actors are the subjects, action is the verb (in the final phrase)
  141. $reply_actors = F\map(
  142. $note->getReplies(),
  143. fn (Note $reply) => Actor::getByPK($reply->getActorId()),
  144. );
  145. if (empty($reply_actors)) {
  146. return Event::next;
  147. }
  148. // Filter out multiple replies from the same actor
  149. $reply_actors = array_unique($reply_actors, \SORT_REGULAR);
  150. $result[] = ['actors' => $reply_actors, 'action' => 'replied to'];
  151. return Event::next;
  152. }
  153. private function getReplyToIdFromRequest(Request $request): ?int
  154. {
  155. if (!\is_array($request->get('post_note')) || !\array_key_exists('_next', $request->get('post_note'))) {
  156. return null;
  157. }
  158. $next = parse_url($request->get('post_note')['_next']);
  159. if (!\array_key_exists('query', $next)) {
  160. return null;
  161. }
  162. parse_str($next['query'], $query);
  163. if (!\array_key_exists('reply_to_id', $query)) {
  164. return null;
  165. }
  166. return (int) $query['reply_to_id'];
  167. }
  168. /**
  169. * Informs **\App\Component\Posting::onAppendRightPostingBlock**, of the **current page context** in which the given
  170. * Actor is in. This is valuable when posting within a group route, allowing \App\Component\Posting to create a
  171. * Note **targeting** that specific Group.
  172. *
  173. * @param \App\Entity\Actor $actor The Actor currently attempting to post a Note
  174. * @param null|\App\Entity\Actor $context_actor The 'owner' of the current route (e.g. Group or Actor), used to target it
  175. */
  176. public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor &$context_actor): EventResult
  177. {
  178. $to_note_id = $this->getReplyToIdFromRequest($request);
  179. if (!\is_null($to_note_id)) {
  180. // Getting the actor itself
  181. $context_actor = Actor::getById(Note::getById((int) $to_note_id)->getActorId());
  182. return Event::stop;
  183. }
  184. return Event::next;
  185. }
  186. /**
  187. * Posting event to add extra information to Component\Posting form data
  188. *
  189. * @param array{reply_to_id: int} $data Transport data to be filled with reply_to_id
  190. *
  191. * @throws \App\Util\Exception\ClientException
  192. * @throws \App\Util\Exception\NoSuchNoteException
  193. */
  194. public function onPostingModifyData(Request $request, Actor $actor, array &$data): EventResult
  195. {
  196. $to_note_id = $this->getReplyToIdFromRequest($request);
  197. if (!\is_null($to_note_id)) {
  198. Note::ensureCanInteract(Note::getById($to_note_id), $actor);
  199. $data['reply_to_id'] = $to_note_id;
  200. }
  201. return Event::next;
  202. }
  203. /**
  204. * Add minimal Note card to RightPanel template
  205. *
  206. * @param string[] $elements
  207. */
  208. public function onPrependPostingForm(Request $request, array &$elements): EventResult
  209. {
  210. $elements[] = Formatting::twigRenderFile('cards/blocks/note_compact_wrapper.html.twig', ['note' => Note::getById((int) $request->query->get('reply_to_id'))]);
  211. return Event::next;
  212. }
  213. /**
  214. * Event launched when deleting given Note, it's deletion implies further changes to object related to this Note.
  215. * Please note, **replies are NOT deleted**, their reply_to is only set to null since this Note no longer exists.
  216. *
  217. * @param \App\Entity\Note $note Note being deleted
  218. * @param \App\Entity\Actor $actor Actor that performed the delete action
  219. */
  220. public function onNoteDeleteRelated(Note &$note, Actor $actor): EventResult
  221. {
  222. // Ensure we have the most up to date replies
  223. Cache::delete(Note::cacheKeys($note->getId())['replies']);
  224. DB::wrapInTransaction(fn () => F\each($note->getReplies(), fn (Note $note) => $note->setReplyTo(null)));
  225. Cache::delete(Note::cacheKeys($note->getId())['replies']);
  226. return Event::next;
  227. }
  228. /**
  229. * Adds extra actions related to Conversation Component, that act upon/from the given Note.
  230. *
  231. * @param \App\Entity\Note $note Current Note being rendered
  232. * @param array{url: string, title: string, classes?: string} $actions Containing 'url' (Controller connected
  233. * route), 'title' (used in anchor link containing the url), ?'classes' (CSS classes required for styling, if
  234. * needed)
  235. *
  236. * @throws \App\Util\Exception\ServerException
  237. */
  238. public function onAddExtraNoteActions(Request $request, Note $note, array &$actions): EventResult
  239. {
  240. if (\is_null($user = Common::user())) {
  241. return Event::next;
  242. }
  243. $from = $request->query->has('from')
  244. ? $request->query->get('from')
  245. : $request->getPathInfo();
  246. $mute_extra_action_url = Router::url(
  247. 'conversation_mute',
  248. [
  249. 'conversation_id' => $note->getConversationId(),
  250. 'from' => $from,
  251. '_fragment' => 'note-anchor-' . $note->getId(),
  252. ],
  253. Router::ABSOLUTE_PATH,
  254. );
  255. $actions[] = [
  256. 'title' => ConversationMute::isMuted($note, $user) ? _m('Unmute conversation') : _m('Mute conversation'),
  257. 'classes' => '',
  258. 'url' => $mute_extra_action_url,
  259. ];
  260. return Event::next;
  261. }
  262. /**
  263. * Prevents new Notifications to appear for muted conversations
  264. *
  265. * @param Activity $activity Notification Activity
  266. */
  267. public function onNewNotificationShould(Activity $activity, Actor $actor): EventResult
  268. {
  269. if ($activity->getObjectType() === 'note' && ConversationMute::isMuted($activity, $actor)) {
  270. return Event::stop;
  271. }
  272. return Event::next;
  273. }
  274. }