RepeatNote.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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\DB\DB;
  21. use App\Core\Event;
  22. use function App\Core\I18n\_m;
  23. use App\Core\Modules\NoteHandlerPlugin;
  24. use App\Core\Router\RouteLoader;
  25. use App\Core\Router\Router;
  26. use App\Entity\Activity;
  27. use App\Entity\Actor;
  28. use App\Entity\Language;
  29. use App\Entity\Note;
  30. use App\Util\Common;
  31. use App\Util\Exception\DuplicateFoundException;
  32. use App\Util\Exception\NotFoundException;
  33. use App\Util\Exception\ServerException;
  34. use App\Util\Formatting;
  35. use Component\Posting\Posting;
  36. use DateTime;
  37. use Plugin\RepeatNote\Entity\NoteRepeat;
  38. use const SORT_REGULAR;
  39. use Symfony\Component\HttpFoundation\Request;
  40. class RepeatNote extends NoteHandlerPlugin
  41. {
  42. public static function repeatNote(Note $note, int $actor_id, string $source = 'web'): Activity
  43. {
  44. $repeat_entity = DB::findBy('note_repeat', [
  45. 'actor_id' => $actor_id,
  46. 'note_id' => $note->getId(),
  47. ])[0] ?? null;
  48. if (!\is_null($repeat_entity)) {
  49. return DB::findBy('activity', [
  50. 'actor_id' => $actor_id,
  51. 'verb' => 'repeat',
  52. 'object_type' => 'note',
  53. 'object_id' => $note->getId()
  54. ], order_by: ['created' => 'DESC'])[0];
  55. }
  56. // Create a new note with the same content as the original
  57. $repeat = Posting::storeLocalNote(
  58. actor: Actor::getById($actor_id),
  59. content: $note->getContent(),
  60. content_type: $note->getContentType(),
  61. language: \is_null($lang_id = $note->getLanguageId()) ? null : Language::getById($lang_id)->getLocale(),
  62. processed_attachments: $note->getAttachmentsWithTitle(),
  63. );
  64. // Find the id of the note we just created
  65. $repeat_id = $repeat?->getId();
  66. $og_id = $note->getId();
  67. // Add it to note_repeat table
  68. if (!\is_null($repeat_id)) {
  69. DB::persist(NoteRepeat::create([
  70. 'note_id' => $repeat_id,
  71. 'actor_id' => $actor_id,
  72. 'repeat_of' => $og_id,
  73. ]));
  74. }
  75. // Log an activity
  76. $repeat_activity = Activity::create([
  77. 'actor_id' => $actor_id,
  78. 'verb' => 'repeat',
  79. 'object_type' => 'note',
  80. 'object_id' => $note->getId(),
  81. 'source' => $source,
  82. ]);
  83. DB::persist($repeat_activity);
  84. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $repeat_activity, [], "{$actor->getNickname()} repeated note {$note->getUrl()}"]);
  85. return $repeat_activity;
  86. }
  87. public static function unrepeatNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  88. {
  89. $already_repeated = DB::findBy('note_repeat', ['actor_id' => $actor_id, 'repeat_of' => $note_id])[0] ?? null;
  90. if (!\is_null($already_repeated)) { // If it was repeated, then we can undo it
  91. // Find previous repeat activity
  92. $already_repeated_activity = DB::findBy('activity', [
  93. 'actor_id' => $actor_id,
  94. 'verb' => 'repeat',
  95. 'object_type' => 'note',
  96. 'object_id' => $already_repeated->getRepeatOf(),
  97. ])[0] ?? null;
  98. // Remove the clone note
  99. DB::findBy('note', ['id' => $already_repeated->getNoteId()])[0]->delete();
  100. // Remove from the note_repeat table
  101. DB::remove(DB::findBy('note_repeat', ['note_id' => $already_repeated->getNoteId()])[0]);
  102. // Log an activity
  103. $undo_repeat_activity = Activity::create([
  104. 'actor_id' => $actor_id,
  105. 'verb' => 'undo',
  106. 'object_type' => 'activity',
  107. 'object_id' => $already_repeated_activity->getId(),
  108. 'source' => $source,
  109. ]);
  110. DB::persist($undo_repeat_activity);
  111. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $undo_repeat_activity, [], "{$actor->getNickname()} unrepeated note {$note_id}"]);
  112. return $undo_repeat_activity;
  113. } else {
  114. // Either was undoed already
  115. if (!\is_null($already_repeated_activity = DB::findBy('activity', [
  116. 'actor_id' => $actor_id,
  117. 'verb' => 'repeat',
  118. 'object_type' => 'note',
  119. 'object_id' => $note_id,
  120. ])[0] ?? null)) {
  121. return DB::findBy('activity', [
  122. 'actor_id' => $actor_id,
  123. 'verb' => 'undo',
  124. 'object_type' => 'activity',
  125. 'object_id' => $already_repeated_activity->getId(),
  126. ])[0] ?? null; // null if not undoed
  127. } else {
  128. // or it's an attempt to undo something that wasn't repeated in the first place,
  129. return null;
  130. }
  131. }
  132. }
  133. /**
  134. * HTML rendering event that adds the repeat form as a note
  135. * action, if a user is logged in
  136. *
  137. * @return bool Event hook
  138. */
  139. public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
  140. {
  141. // Only logged users can repeat notes
  142. if (\is_null($user = Common::user())) {
  143. return Event::next;
  144. }
  145. // If note is repeated, "is_repeated" is 1, 0 otherwise.
  146. $is_repeat = ($note_repeat = DB::findBy('note_repeat', [
  147. 'actor_id' => $user->getId(),
  148. 'note_id' => $note->getId(),
  149. ])) !== [] ? 1 : 0;
  150. // If note was already repeated, do not add the action
  151. try {
  152. if (DB::findOneBy('note_repeat', [
  153. 'repeat_of' => $note->getId(),
  154. 'actor_id' => $user->getId(),
  155. ])) {
  156. return Event::next;
  157. }
  158. } catch (DuplicateFoundException|NotFoundException) {
  159. // It's okay
  160. }
  161. // Generating URL for repeat action route
  162. $args = ['id' => $is_repeat === 0 ? $note->getId() : $note_repeat[0]->getRepeatOf()];
  163. $type = Router::ABSOLUTE_PATH;
  164. $repeat_action_url = $is_repeat
  165. ? Router::url('repeat_remove', $args, $type)
  166. : Router::url('repeat_add', $args, $type);
  167. // TODO clean this up
  168. // SECURITY: open redirect?
  169. $query_string = $request->getQueryString();
  170. // Concatenating get parameter to redirect the user to where he came from
  171. $repeat_action_url .= !\is_null($query_string) ? '?from=' . mb_substr($query_string, 2) : '';
  172. $extra_classes = $is_repeat ? 'note-actions-set' : 'note-actions-unset';
  173. $repeat_action = [
  174. 'url' => $repeat_action_url,
  175. 'title' => $is_repeat ? 'Remove this repeat' : 'Repeat this note!',
  176. 'classes' => "button-container repeat-button-container {$extra_classes}",
  177. 'id' => 'repeat-button-container-' . $note->getId(),
  178. ];
  179. $actions[] = $repeat_action;
  180. return Event::next;
  181. }
  182. /**
  183. * Append on note information about user actions.
  184. *
  185. * @return array|bool
  186. */
  187. public function onAppendCardNote(array $vars, array &$result)
  188. {
  189. // if note is the original and user isn't the one who repeated, append on end "user repeated this"
  190. // if user is the one who repeated, append on end "you repeated this, remove repeat?"
  191. $check_user = !\is_null(Common::user());
  192. $note = $vars['note'];
  193. $complementary_info = '';
  194. $repeat_actor = [];
  195. $note_repeats = NoteRepeat::getNoteRepeats($note);
  196. // Get actors who replied
  197. foreach ($note_repeats as $reply) {
  198. $repeat_actor[] = Actor::getByPK($reply->getActorId());
  199. }
  200. if (\count($repeat_actor) < 1) {
  201. return Event::next;
  202. }
  203. // Filter out multiple replies from the same actor
  204. $repeat_actor = array_unique($repeat_actor, SORT_REGULAR);
  205. // Add to complementary info
  206. foreach ($repeat_actor as $actor) {
  207. $repeat_actor_url = $actor->getUrl();
  208. $repeat_actor_nickname = $actor->getNickname();
  209. if ($check_user && $actor->getId() === (Common::actor())->getId()) {
  210. // If the repeat is yours
  211. try {
  212. $you_translation = _m('You');
  213. } catch (ServerException $e) {
  214. $you_translation = 'You';
  215. }
  216. $prepend = "<a href={$repeat_actor_url}>{$you_translation}</a>, " . ($prepend = &$complementary_info);
  217. $complementary_info = $prepend;
  218. } else {
  219. // If the repeat is from someone else
  220. $complementary_info .= "<a href={$repeat_actor_url}>{$repeat_actor_nickname}</a>, ";
  221. }
  222. }
  223. $complementary_info = rtrim(trim($complementary_info), ',');
  224. $complementary_info .= ' repeated this note.';
  225. $result[] = Formatting::twigRenderString($complementary_info, []);
  226. return $result;
  227. }
  228. public function onAddRoute(RouteLoader $r): bool
  229. {
  230. // Add/remove note to/from repeats
  231. $r->connect(id: 'repeat_add', uri_path: '/object/note/{id<\d+>}/repeat', target: [Controller\Repeat::class, 'repeatAddNote']);
  232. $r->connect(id: 'repeat_remove', uri_path: '/object/note/{id<\d+>}/unrepeat', target: [Controller\Repeat::class, 'repeatRemoveNote']);
  233. return Event::next;
  234. }
  235. // ActivityPub
  236. private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  237. {
  238. if (!\in_array($type_activity->get('type'), ['Announce', 'Undo'])) {
  239. return Event::next;
  240. }
  241. if ($type_activity->get('type') === 'Announce') { // Repeat
  242. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  243. if ($type_object->get('type') === 'Note') {
  244. $note = \Plugin\ActivityPub\Util\Model\Note::fromJson($type_object);
  245. $note_id = $note->getId();
  246. } else {
  247. return Event::next;
  248. }
  249. } elseif ($type_object instanceof Note) {
  250. $note = $type_object;
  251. $note_id = ${$note}->getId();
  252. } else {
  253. return Event::next;
  254. }
  255. } else { // Undo Repeat
  256. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  257. $ap_prev_repeat_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object);
  258. $prev_repeat_act = $ap_prev_repeat_act->getActivity();
  259. if ($prev_repeat_act->getVerb() === 'repeat' && $prev_repeat_act->getObjectType() === 'note') {
  260. $note_id = $prev_repeat_act->getObjectId();
  261. } else {
  262. return Event::next;
  263. }
  264. } elseif ($type_object instanceof Activity) {
  265. if ($type_object->getVerb() === 'repeat' && $type_object->getObjectType() === 'note') {
  266. $note_id = $type_object->getObjectId();
  267. } else {
  268. return Event::next;
  269. }
  270. } else {
  271. return Event::next;
  272. }
  273. }
  274. if ($type_activity->get('type') === 'Announce') {
  275. $act = self::repeatNote($note ?? Note::getById($note_id), $actor->getId(), source: 'ActivityPub');
  276. } else {
  277. $act = self::unrepeatNote($note_id, $actor->getId(), source: 'ActivityPub');
  278. }
  279. // Store ActivityPub Activity
  280. $ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([
  281. 'activity_id' => $act->getId(),
  282. 'activity_uri' => $type_activity->get('id'),
  283. 'created' => new DateTime($type_activity->get('published') ?? 'now'),
  284. 'modified' => new DateTime(),
  285. ]);
  286. DB::persist($ap_act);
  287. return Event::stop;
  288. }
  289. public function onNewActivityPubActivity(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, \ActivityPhp\Type\AbstractObject $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  290. {
  291. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  292. }
  293. public function onNewActivityPubActivityWithObject(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  294. {
  295. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  296. }
  297. public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool
  298. {
  299. if ($verb === 'repeat') {
  300. $gs_verb_to_activity_stream_two_verb = 'Announce';
  301. return Event::stop;
  302. }
  303. return Event::next;
  304. }
  305. }