Conversation.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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\DB;
  28. use App\Core\Event;
  29. use function App\Core\I18n\_m;
  30. use App\Core\Modules\Component;
  31. use App\Core\Router\RouteLoader;
  32. use App\Core\Router\Router;
  33. use App\Entity\Activity;
  34. use App\Entity\Actor;
  35. use App\Entity\Note;
  36. use App\Util\Common;
  37. use App\Util\Formatting;
  38. use Component\Conversation\Entity\Conversation as ConversationEntity;
  39. use Component\Conversation\Entity\ConversationMute;
  40. use Functional as F;
  41. use Symfony\Component\HttpFoundation\Request;
  42. class Conversation extends Component
  43. {
  44. public function onAddRoute(RouteLoader $r): bool
  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 $actions Contains keys 'url' (linking 'conversation_reply_to'
  89. * route), 'title' (used as title for aforementioned url),
  90. * 'classes' (CSS styling classes used to visually inform the user of action context),
  91. * 'id' (HTML markup id used to redirect user to this anchor upon performing the action)
  92. *
  93. * @throws \App\Util\Exception\ServerException
  94. *
  95. * @return bool EventHook
  96. */
  97. public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
  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 $vars Contains information related to Note currently being rendered
  127. * @param array $result Contains keys 'actors', and 'action'. Needed to construct a string, stating who ($result['actors']), has already performed a reply ($result['action']), in the given Note (vars['note'])
  128. *
  129. * @return bool EventHook
  130. */
  131. public function onAppendCardNote(array $vars, array &$result): bool
  132. {
  133. if (str_contains($vars['request']->getPathInfo(), 'conversation')) {
  134. return Event::next;
  135. }
  136. // The current Note being rendered
  137. $note = $vars['note'];
  138. // Will have actors array, and action string
  139. // Actors are the subjects, action is the verb (in the final phrase)
  140. $reply_actors = F\map(
  141. $note->getReplies(),
  142. fn (Note $reply) => Actor::getByPK($reply->getActorId()),
  143. );
  144. if (empty($reply_actors)) {
  145. return Event::next;
  146. }
  147. // Filter out multiple replies from the same actor
  148. $reply_actors = array_unique($reply_actors, \SORT_REGULAR);
  149. $result[] = ['actors' => $reply_actors, 'action' => 'replied to'];
  150. return Event::next;
  151. }
  152. private function getReplyToIdFromRequest(Request $request): ?int
  153. {
  154. if (!\is_array($request->get('post_note')) || !\array_key_exists('_next', $request->get('post_note'))) {
  155. return null;
  156. }
  157. $next = parse_url($request->get('post_note')['_next']);
  158. if (!\array_key_exists('query', $next)) {
  159. return null;
  160. }
  161. parse_str($next['query'], $query);
  162. if (!\array_key_exists('reply_to_id', $query)) {
  163. return null;
  164. }
  165. return (int) $query['reply_to_id'];
  166. }
  167. /**
  168. * Informs **\App\Component\Posting::onAppendRightPostingBlock**, of the **current page context** in which the given
  169. * Actor is in. This is valuable when posting within a group route, allowing \App\Component\Posting to create a
  170. * Note **targeting** that specific Group.
  171. *
  172. * @param \App\Entity\Actor $actor The Actor currently attempting to post a Note
  173. * @param null|\App\Entity\Actor $context_actor The 'owner' of the current route (e.g. Group or Actor), used to target it
  174. *
  175. * @return bool EventHook
  176. */
  177. public function onPostingGetContextActor(Request $request, Actor $actor, ?Actor &$context_actor): bool
  178. {
  179. $to_note_id = $this->getReplyToIdFromRequest($request);
  180. if (!\is_null($to_note_id)) {
  181. // Getting the actor itself
  182. $context_actor = Actor::getById(Note::getById((int) $to_note_id)->getActorId());
  183. return Event::stop;
  184. }
  185. return Event::next;
  186. }
  187. /**
  188. * Posting event to add extra information to Component\Posting form data
  189. *
  190. * @param array $data Transport data to be filled with reply_to_id
  191. *
  192. * @throws \App\Util\Exception\ClientException
  193. * @throws \App\Util\Exception\NoSuchNoteException
  194. *
  195. * @return bool EventHook
  196. */
  197. public function onPostingModifyData(Request $request, Actor $actor, array &$data): bool
  198. {
  199. $to_note_id = $this->getReplyToIdFromRequest($request);
  200. if (!\is_null($to_note_id)) {
  201. Note::ensureCanInteract(Note::getById($to_note_id), $actor);
  202. $data['reply_to_id'] = $to_note_id;
  203. }
  204. return Event::next;
  205. }
  206. /**
  207. * Add minimal Note card to RightPanel template
  208. */
  209. public function onPrependPostingForm(Request $request, array &$elements): bool
  210. {
  211. $elements[] = Formatting::twigRenderFile('cards/blocks/note_compact_wrapper.html.twig', ['note' => Note::getById((int) $request->query->get('reply_to_id'))]);
  212. return Event::next;
  213. }
  214. /**
  215. * Event launched when deleting given Note, it's deletion implies further changes to object related to this Note.
  216. * Please note, **replies are NOT deleted**, their reply_to is only set to null since this Note no longer exists.
  217. *
  218. * @param \App\Entity\Note $note Note being deleted
  219. * @param \App\Entity\Actor $actor Actor that performed the delete action
  220. *
  221. * @return bool EventHook
  222. */
  223. public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
  224. {
  225. // Ensure we have the most up to date replies
  226. Cache::delete(Note::cacheKeys($note->getId())['replies']);
  227. DB::wrapInTransaction(fn () => F\each($note->getReplies(), fn (Note $note) => $note->setReplyTo(null)));
  228. Cache::delete(Note::cacheKeys($note->getId())['replies']);
  229. return Event::next;
  230. }
  231. /**
  232. * Adds extra actions related to Conversation Component, that act upon/from the given Note.
  233. *
  234. * @param \App\Entity\Note $note Current Note being rendered
  235. * @param array $actions Containing 'url' (Controller connected route), 'title' (used in anchor link containing the url), ?'classes' (CSS classes required for styling, if needed)
  236. *
  237. * @throws \App\Util\Exception\ServerException
  238. *
  239. * @return bool EventHook
  240. */
  241. public function onAddExtraNoteActions(Request $request, Note $note, array &$actions): bool
  242. {
  243. if (\is_null($user = Common::user())) {
  244. return Event::next;
  245. }
  246. $from = $request->query->has('from')
  247. ? $request->query->get('from')
  248. : $request->getPathInfo();
  249. $mute_extra_action_url = Router::url(
  250. 'conversation_mute',
  251. [
  252. 'conversation_id' => $note->getConversationId(),
  253. 'from' => $from,
  254. '_fragment' => 'note-anchor-' . $note->getId(),
  255. ],
  256. Router::ABSOLUTE_PATH,
  257. );
  258. $actions[] = [
  259. 'title' => ConversationMute::isMuted($note, $user) ? _m('Unmute conversation') : _m('Mute conversation'),
  260. 'classes' => '',
  261. 'url' => $mute_extra_action_url,
  262. ];
  263. return Event::next;
  264. }
  265. /**
  266. * Prevents new Notifications to appear for muted conversations
  267. *
  268. * @param Activity $activity Notification Activity
  269. *
  270. * @return bool EventHook
  271. */
  272. public function onNewNotificationShould(Activity $activity, Actor $actor): bool
  273. {
  274. if ($activity->getObjectType() === 'note' && ConversationMute::isMuted($activity, $actor)) {
  275. return Event::stop;
  276. }
  277. return Event::next;
  278. }
  279. }