RepeatNote.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. namespace Plugin\RepeatNote;
  20. use App\Core\Cache;
  21. use App\Core\DB\DB;
  22. use App\Core\Event;
  23. use function App\Core\I18n\_m;
  24. use App\Core\Modules\NoteHandlerPlugin;
  25. use App\Core\Router\RouteLoader;
  26. use App\Core\Router\Router;
  27. use App\Entity\Activity;
  28. use App\Entity\Actor;
  29. use App\Entity\Note;
  30. use App\Util\Common;
  31. use App\Util\Exception\BugFoundException;
  32. use App\Util\Exception\ClientException;
  33. use App\Util\Exception\DuplicateFoundException;
  34. use App\Util\Exception\ServerException;
  35. use Component\Language\Entity\Language;
  36. use Component\Posting\Posting;
  37. use DateTime;
  38. use Plugin\RepeatNote\Entity\NoteRepeat as RepeatEntity;
  39. use const SORT_REGULAR;
  40. use Symfony\Component\HttpFoundation\Request;
  41. class RepeatNote extends NoteHandlerPlugin
  42. {
  43. /**
  44. * **Repeats a Note**
  45. *
  46. * This means the current Actor creates a new Note, cloning the contents of
  47. * the original Note provided as an argument.
  48. *
  49. * Bear in mind that, if it's a repeat, the **reply_to** should be to the
  50. * original, and **conversation** ought to be the same.
  51. *
  52. * In the end, the Activity is created, and a new notification for the
  53. * repeat Activity created
  54. *
  55. * @throws BugFoundException
  56. * @throws ClientException
  57. * @throws DuplicateFoundException
  58. * @throws ServerException
  59. */
  60. public static function repeatNote(Note $note, int $actor_id, string $source = 'web'): ?Activity
  61. {
  62. $note_repeat = RepeatEntity::getNoteActorRepeat($note, $actor_id);
  63. if (!\is_null($note_repeat)) {
  64. return null;
  65. }
  66. $original_note_id = $note->getId();
  67. // Create a new note with the same content as the original
  68. $repeat = Posting::storeLocalNote(
  69. actor: Actor::getById($actor_id),
  70. content: $note->getContent(),
  71. content_type: $note->getContentType(),
  72. locale: \is_null($lang_id = $note->getLanguageId()) ? null : Language::getById($lang_id)->getLocale(),
  73. // If it's a repeat, the reply_to should be to the original, conversation ought to be the same
  74. reply_to_id: $note->getReplyTo(),
  75. processed_attachments: $note->getAttachmentsWithTitle(),
  76. notify: false,
  77. rendered: $note->getRendered(),
  78. );
  79. DB::persist(RepeatEntity::create([
  80. 'note_id' => $repeat->getId(),
  81. 'actor_id' => $actor_id,
  82. 'repeat_of' => $original_note_id,
  83. ]));
  84. Cache::delete(RepeatEntity::cacheKeys($note->getId(), $actor_id)['actor_repeat']);
  85. Cache::delete(RepeatEntity::cacheKeys($note->getId())['repeats']);
  86. // Log an activity
  87. $repeat_activity = Activity::create([
  88. 'actor_id' => $actor_id,
  89. 'verb' => 'repeat',
  90. 'object_type' => 'note',
  91. 'object_id' => $note->getId(),
  92. 'source' => $source,
  93. ]);
  94. DB::persist($repeat_activity);
  95. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $repeat_activity, [], _m('{nickname} repeated note {note_id}.', ['{nickname}' => $actor->getNickname(), '{note_id}' => $repeat_activity->getObjectId()])]);
  96. return $repeat_activity;
  97. }
  98. /**
  99. * **Undoes a Repeat**
  100. *
  101. * Removes the Repeat from NoteRepeat table, and the deletes the Note
  102. * clone.
  103. *
  104. * Finally, creates a new Activity, undoing the repeat, and the respective
  105. * Notification is handled.
  106. *
  107. * @throws ServerException
  108. */
  109. public static function unrepeatNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  110. {
  111. $note_repeat = RepeatEntity::getNoteActorRepeat($note_id, $actor_id);
  112. if (!\is_null($note_repeat)) { // If it was repeated, then we can undo it
  113. // Find previous repeat activity
  114. $already_repeated_activity = DB::findOneBy(Activity::class, [
  115. 'actor_id' => $actor_id,
  116. 'verb' => 'repeat',
  117. 'object_type' => 'note',
  118. 'object_id' => $note_repeat->getRepeatOf(),
  119. ], return_null: true);
  120. // Remove the clone note
  121. DB::findOneBy(Note::class, ['id' => $note_repeat->getNoteId()])->delete(actor: Actor::getById($actor_id));
  122. // Remove from the note_repeat table
  123. DB::removeBy(RepeatEntity::class, ['note_id' => $note_repeat->getNoteId()]);
  124. Cache::delete(RepeatEntity::cacheKeys($note_id, $actor_id)['actor_repeat']);
  125. Cache::delete(RepeatEntity::cacheKeys($note_repeat->getNoteId())['repeats']);
  126. // Log an activity
  127. $undo_repeat_activity = Activity::create([
  128. 'actor_id' => $actor_id,
  129. 'verb' => 'undo',
  130. 'object_type' => 'activity',
  131. 'object_id' => $already_repeated_activity->getId(),
  132. 'source' => $source,
  133. ]);
  134. DB::persist($undo_repeat_activity);
  135. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $undo_repeat_activity, [], _m('{nickname} unrepeated note {note_id}.', ['{nickname}' => $actor->getNickname(), '{note_id}' => $note_id])]);
  136. return $undo_repeat_activity;
  137. } else {
  138. // Either was undoed already
  139. if (!\is_null($already_repeated_activity = DB::findOneBy('activity', [
  140. 'actor_id' => $actor_id,
  141. 'verb' => 'repeat',
  142. 'object_type' => 'note',
  143. 'object_id' => $note_id,
  144. ], return_null: true))) {
  145. return DB::findOneBy('activity', [
  146. 'actor_id' => $actor_id,
  147. 'verb' => 'undo',
  148. 'object_type' => 'activity',
  149. 'object_id' => $already_repeated_activity->getId(),
  150. ], return_null: true); // null if not undoed
  151. } else {
  152. // or it's an attempt to undo something that wasn't repeated in the first place,
  153. return null;
  154. }
  155. }
  156. }
  157. /**
  158. * Filters repeats out of Conversations, and replaces a repeat with the
  159. * original Note on Actor feed
  160. */
  161. public function onFilterNoteList(?Actor $actor, array &$notes, Request $request): bool
  162. {
  163. // Replaces repeat with original note on Actor feed
  164. // it's pretty cool
  165. if (str_starts_with($request->get('_route'), 'actor_view_')) {
  166. $notes = array_map(
  167. fn (Note $note) => RepeatEntity::isNoteRepeat($note)
  168. ? Note::getById(RepeatEntity::getByPK($note->getId())->getRepeatOf())
  169. : $note,
  170. $notes,
  171. );
  172. return Event::next;
  173. }
  174. // Filter out repeats altogether
  175. $notes = array_filter($notes, fn (Note $note) => !RepeatEntity::isNoteRepeat($note));
  176. return Event::next;
  177. }
  178. /**
  179. * HTML rendering event that adds the repeat form as a note
  180. * action, if a user is logged in
  181. *
  182. * @return bool Event hook
  183. */
  184. public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
  185. {
  186. // Only logged users can repeat notes
  187. if (\is_null($user = Common::user())) {
  188. return Event::next;
  189. }
  190. $note_repeat = RepeatEntity::getNoteActorRepeat($note, $user->getId());
  191. // If note is repeated, "is_repeated" is 1, 0 otherwise.
  192. $is_repeat = !\is_null($note_repeat);
  193. // Generating URL for repeat action route
  194. $args = ['note_id' => !$is_repeat ? $note->getId() : $note_repeat->getRepeatOf()];
  195. $type = Router::ABSOLUTE_PATH;
  196. $repeat_action_url = $is_repeat
  197. ? Router::url('repeat_remove', $args, $type)
  198. : Router::url('repeat_add', $args, $type);
  199. // Concatenating get parameter to redirect the user to where he came from
  200. $repeat_action_url .= '?from=' . urlencode($request->getRequestUri());
  201. $extra_classes = $is_repeat ? 'note-actions-set' : 'note-actions-unset';
  202. $repeat_action = [
  203. 'url' => $repeat_action_url,
  204. 'title' => $is_repeat ? 'Remove this repeat' : 'Repeat this note!',
  205. 'classes' => "button-container repeat-button-container {$extra_classes}",
  206. 'note_id' => 'repeat-button-container-' . $note->getId(),
  207. ];
  208. $actions[] = $repeat_action;
  209. return Event::next;
  210. }
  211. /**
  212. * Appends in Note information stating who and what user actions were
  213. * performed.
  214. *
  215. * @param array $vars Contains the Note currently being rendered
  216. * @param array $result Rendered String containing anchors for Actors that
  217. * repeated the Note
  218. *
  219. * @return bool
  220. */
  221. public function onAppendCardNote(array $vars, array &$result)
  222. {
  223. // If note is the original and user isn't the one who repeated, append on end "user repeated this"
  224. // If user is the one who repeated, append on end "you repeated this, remove repeat?"
  225. $check_user = !\is_null(Common::user());
  226. // The current Note being rendered
  227. $note = $vars['note'];
  228. // Will have actors array, and action string
  229. // Actors are the subjects, action is the verb (in the final phrase)
  230. $repeat_actors = [];
  231. $note_repeats = RepeatEntity::getNoteRepeats($note);
  232. // Get actors who repeated the note
  233. foreach ($note_repeats as $repeat) {
  234. $repeat_actors[] = Actor::getByPK($repeat->getActorId());
  235. }
  236. if (\count($repeat_actors) < 1) {
  237. return Event::next;
  238. }
  239. // Filter out multiple replies from the same actor
  240. $repeat_actors = array_unique($repeat_actors, SORT_REGULAR);
  241. $result[] = ['actors' => $repeat_actors, 'action' => 'repeated'];
  242. return Event::next;
  243. }
  244. /**
  245. * Deletes every repeat entity that is related to a deleted Note in its
  246. * respective table
  247. */
  248. public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
  249. {
  250. $note_repeats_list = RepeatEntity::getNoteRepeats($note);
  251. foreach ($note_repeats_list as $note_repeat) {
  252. DB::remove($note_repeat);
  253. }
  254. return Event::next;
  255. }
  256. /**
  257. * Connects the following Routes to their respective Controllers:
  258. *
  259. * - **repeat_add**
  260. * page containing the Note the user wishes to Repeat and a button to
  261. * confirm it wishes to perform the action
  262. *
  263. * - **repeat_remove**
  264. * same as above, except that it undoes the aforementioned action
  265. *
  266. * @return bool Event hook
  267. */
  268. public function onAddRoute(RouteLoader $r): bool
  269. {
  270. // Add/remove note to/from repeats
  271. $r->connect(id: 'repeat_add', uri_path: '/object/note/{note_id<\d+>}/repeat', target: [Controller\Repeat::class, 'repeatAddNote']);
  272. $r->connect(id: 'repeat_remove', uri_path: '/object/note/{note_id<\d+>}/unrepeat', target: [Controller\Repeat::class, 'repeatRemoveNote']);
  273. return Event::next;
  274. }
  275. // ActivityPub handling and processing for Repeats is below
  276. /**
  277. * ActivityPub Inbox handler for Announces and Undo Announce activities
  278. *
  279. * @param Actor $actor Actor who authored the activity
  280. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  281. * @param mixed $type_object Activity's Object
  282. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  283. *
  284. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  285. */
  286. private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  287. {
  288. if (!\in_array($type_activity->get('type'), ['Announce', 'Undo'])) {
  289. return Event::next;
  290. }
  291. if ($type_activity->get('type') === 'Announce') { // Repeat
  292. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  293. if ($type_object->get('type') === 'Note') {
  294. $note = \Plugin\ActivityPub\Util\Model\Note::fromJson($type_object);
  295. $note_id = $note->getId();
  296. } else {
  297. return Event::next;
  298. }
  299. } elseif ($type_object instanceof Note) {
  300. $note = $type_object;
  301. $note_id = $note->getId();
  302. } else {
  303. return Event::next;
  304. }
  305. } else { // Undo Repeat
  306. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  307. $ap_prev_repeat_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object);
  308. $prev_repeat_act = $ap_prev_repeat_act->getActivity();
  309. if ($prev_repeat_act->getVerb() === 'repeat' && $prev_repeat_act->getObjectType() === 'note') {
  310. $note_id = $prev_repeat_act->getObjectId();
  311. } else {
  312. return Event::next;
  313. }
  314. } elseif ($type_object instanceof Activity) {
  315. if ($type_object->getVerb() === 'repeat' && $type_object->getObjectType() === 'note') {
  316. $note_id = $type_object->getObjectId();
  317. } else {
  318. return Event::next;
  319. }
  320. } else {
  321. return Event::next;
  322. }
  323. }
  324. if ($type_activity->get('type') === 'Announce') {
  325. $activity = self::repeatNote($note ?? Note::getById($note_id), $actor->getId(), source: 'ActivityPub');
  326. } else {
  327. $activity = self::unrepeatNote($note_id, $actor->getId(), source: 'ActivityPub');
  328. }
  329. if (!\is_null($activity)) {
  330. // Store ActivityPub Activity
  331. $ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([
  332. 'activity_id' => $activity->getId(),
  333. 'activity_uri' => $type_activity->get('id'),
  334. 'created' => new DateTime($type_activity->get('published') ?? 'now'),
  335. 'modified' => new DateTime(),
  336. ]);
  337. DB::persist($ap_act);
  338. }
  339. return Event::stop;
  340. }
  341. /**
  342. * Convert an Activity Streams 2.0 Announce or Undo Announce into the appropriate Repeat and Undo Repeat entities
  343. *
  344. * @param Actor $actor Actor who authored the activity
  345. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  346. * @param \ActivityPhp\Type\AbstractObject $type_object Activity Streams 2.0 Object
  347. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  348. *
  349. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  350. */
  351. public function onNewActivityPubActivity(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, \ActivityPhp\Type\AbstractObject $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  352. {
  353. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  354. }
  355. /**
  356. * Convert an Activity Streams 2.0 formatted activity with a known object into Entities
  357. *
  358. * @param Actor $actor Actor who authored the activity
  359. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  360. * @param mixed $type_object Object
  361. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  362. *
  363. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  364. */
  365. public function onNewActivityPubActivityWithObject(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  366. {
  367. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  368. }
  369. /**
  370. * Translate GNU social internal verb 'repeat' to Activity Streams 2.0 'Announce'
  371. *
  372. * @param string $verb GNU social's internal verb
  373. * @param null|string $gs_verb_to_activity_stream_two_verb Resulting Activity Streams 2.0 verb
  374. *
  375. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  376. */
  377. public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool
  378. {
  379. if ($verb === 'repeat') {
  380. $gs_verb_to_activity_stream_two_verb = 'Announce';
  381. return Event::stop;
  382. }
  383. return Event::next;
  384. }
  385. }