Favourite.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 Eliseu Amaro <mail@eliseuama.ro>
  21. * @author Diogo Peralta Cordeiro <@diogo.site>
  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 Plugin\Favourite;
  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\NoteHandlerPlugin;
  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\Feed;
  36. use App\Entity\LocalUser;
  37. use App\Entity\Note;
  38. use App\Util\Common;
  39. use App\Util\Nickname;
  40. use DateTime;
  41. use Plugin\Favourite\Entity\NoteFavourite;
  42. use Symfony\Component\HttpFoundation\Request;
  43. class Favourite extends NoteHandlerPlugin
  44. {
  45. /**
  46. * Creates a new Favourite Entity, upon the given Actor performs a Favourite
  47. * action on the given Note object
  48. *
  49. * @param int $note_id Note id being favoured
  50. * @param int $actor_id Actor performing favourite Activity
  51. *
  52. * @throws \App\Util\Exception\ServerException
  53. */
  54. public static function favourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  55. {
  56. $opts = ['note_id' => $note_id, 'actor_id' => $actor_id];
  57. $note_already_favoured = Cache::get(
  58. NoteFavourite::cacheKeys($note_id, $actor_id)['favourite'],
  59. fn () => DB::findOneBy(NoteFavourite::class, $opts, return_null: true),
  60. );
  61. $activity = null;
  62. if (\is_null($note_already_favoured)) {
  63. DB::persist(NoteFavourite::create($opts));
  64. Cache::delete(NoteFavourite::cacheKeys($note_id, $actor_id)['favourite']);
  65. $activity = Activity::create([
  66. 'actor_id' => $actor_id,
  67. 'verb' => 'favourite',
  68. 'object_type' => 'note',
  69. 'object_id' => $note_id,
  70. 'source' => $source,
  71. ]);
  72. DB::persist($activity);
  73. }
  74. return $activity;
  75. }
  76. /**
  77. * Removes the Favourite Entity created beforehand, by the same Actor, and on the same Note
  78. *
  79. * @param int $note_id Note id being unfavoured
  80. * @param int $actor_id Actor undoing favourite Activity
  81. *
  82. * @throws \App\Util\Exception\ServerException
  83. */
  84. public static function unfavourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  85. {
  86. $note_already_favoured = Cache::get(
  87. NoteFavourite::cacheKeys($note_id, $actor_id)['favourite'],
  88. static fn () => DB::findOneBy(NoteFavourite::class, ['note_id' => $note_id, 'actor_id' => $actor_id], return_null: true),
  89. );
  90. $activity = null;
  91. if (!\is_null($note_already_favoured)) {
  92. DB::removeBy(NoteFavourite::class, ['note_id' => $note_id, 'actor_id' => $actor_id]);
  93. Cache::delete(NoteFavourite::cacheKeys($note_id, $actor_id)['favourite']);
  94. $favourite_activity = DB::findBy(Activity::class, ['verb' => 'favourite', 'object_type' => 'note', 'actor_id' => $actor_id, 'object_id' => $note_id], order_by: ['created' => 'DESC'])[0];
  95. $activity = Activity::create([
  96. 'actor_id' => $actor_id,
  97. 'verb' => 'undo', // 'undo_favourite',
  98. 'object_type' => 'activity', // 'note',
  99. 'object_id' => $favourite_activity->getId(), // $note_id,
  100. 'source' => $source,
  101. ]);
  102. DB::persist($activity);
  103. }
  104. return $activity;
  105. }
  106. /**
  107. * HTML rendering event that adds the favourite form as a note
  108. * action, if a user is logged in
  109. *
  110. * @param Note $note Current Note being rendered
  111. * @param array $actions Array containing all Note actions to be rendered
  112. *
  113. * @return bool Event hook, Event::next (true) is returned to allow Event to be handled by other handlers
  114. */
  115. public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
  116. {
  117. if (\is_null($user = Common::user())) {
  118. return Event::next;
  119. }
  120. // If note is favourite, "is_favourite" is 1
  121. $opts = ['note_id' => $note->getId(), 'actor_id' => $user->getId()];
  122. $is_favourite = !\is_null(
  123. Cache::get(
  124. NoteFavourite::cacheKeys($note->getId(), $user->getId())['favourite'],
  125. static fn () => DB::findOneBy(NoteFavourite::class, $opts, return_null: true),
  126. ),
  127. );
  128. // Generating URL for favourite action route
  129. $args = ['id' => $note->getId()];
  130. $type = Router::ABSOLUTE_PATH;
  131. $favourite_action_url = $is_favourite
  132. ? Router::url('favourite_remove', $args, $type)
  133. : Router::url('favourite_add', $args, $type);
  134. $query_string = $request->getQueryString();
  135. // Concatenating get parameter to redirect the user to where he came from
  136. $favourite_action_url .= '?from=' . urlencode($request->getRequestUri());
  137. $extra_classes = $is_favourite ? 'note-actions-set' : 'note-actions-unset';
  138. $favourite_action = [
  139. 'url' => $favourite_action_url,
  140. 'title' => $is_favourite ? 'Remove this note from favourites' : 'Favourite this note!',
  141. 'classes' => "button-container favourite-button-container {$extra_classes}",
  142. 'id' => 'favourite-button-container-' . $note->getId(),
  143. ];
  144. $actions[] = $favourite_action;
  145. return Event::next;
  146. }
  147. /**
  148. * Appends on Note currently being rendered complementary information regarding whom (subject) performed which Activity (verb) on aforementioned Note (object)
  149. *
  150. * @param array $vars Array containing necessary info to process event. In this case, contains the current Note being rendered
  151. * @param array $result Contains a hashmap for each Activity performed on Note (object)
  152. *
  153. * @return bool Event hook, Event::next (true) is returned to allow Event to be handled by other handlers
  154. */
  155. public function onAppendCardNote(array $vars, array &$result): bool
  156. {
  157. // If note is the original and user isn't the one who repeated, append on end "user repeated this"
  158. // If user is the one who repeated, append on end "you repeated this, remove repeat?"
  159. $check_user = !\is_null(Common::user());
  160. // The current Note being rendered
  161. $note = $vars['note'];
  162. // Will have actors array, and action string
  163. // Actors are the subjects, action is the verb (in the final phrase)
  164. $favourite_actors = NoteFavourite::getNoteFavouriteActors($note);
  165. if (\count($favourite_actors) < 1) {
  166. return Event::next;
  167. }
  168. // Filter out multiple replies from the same actor
  169. $favourite_actors = array_unique($favourite_actors, \SORT_REGULAR);
  170. $result[] = ['actors' => $favourite_actors, 'action' => 'favourited'];
  171. return Event::next;
  172. }
  173. /**
  174. * Deletes every favourite entity in table related to a deleted Note
  175. */
  176. public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
  177. {
  178. $note_favourites_list = NoteFavourite::getNoteFavourites($note);
  179. foreach ($note_favourites_list as $favourite_entity) {
  180. DB::remove($favourite_entity);
  181. }
  182. return Event::next;
  183. }
  184. /**
  185. * Maps Routes to their respective Controllers
  186. */
  187. public function onAddRoute(RouteLoader $r): bool
  188. {
  189. // Add/remove note to/from favourites
  190. $r->connect(id: 'favourite_add', uri_path: '/object/note/{id<\d+>}/favour', target: [Controller\Favourite::class, 'favouriteAddNote']);
  191. $r->connect(id: 'favourite_remove', uri_path: '/object/note/{id<\d+>}/unfavour', target: [Controller\Favourite::class, 'favouriteRemoveNote']);
  192. // View all favourites by actor id
  193. $r->connect(id: 'favourites_view_by_actor_id', uri_path: '/actor/{id<\d+>}/favourites', target: [Controller\Favourite::class, 'favouritesViewByActorId']);
  194. $r->connect(id: 'favourites_reverse_view_by_actor_id', uri_path: '/actor/{id<\d+>}/reverse_favourites', target: [Controller\Favourite::class, 'favouritesReverseViewByActorId']);
  195. // View all favourites by nickname
  196. $r->connect(id: 'favourites_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/favourites', target: [Controller\Favourite::class, 'favouritesViewByActorNickname']);
  197. $r->connect(id: 'favourites_reverse_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/reverse_favourites', target: [Controller\Favourite::class, 'reverseFavouritesViewByActorNickname']);
  198. return Event::next;
  199. }
  200. /**
  201. * Creates two feeds, including reverse favourites or favourites performed by given Actor
  202. *
  203. * @param int $actor_id Whom the favourites belong to
  204. *
  205. * @throws \App\Util\Exception\ServerException
  206. */
  207. public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering): bool
  208. {
  209. DB::persist(Feed::create([
  210. 'actor_id' => $actor_id,
  211. 'url' => Router::url($route = 'favourites_view_by_nickname', ['nickname' => $user->getNickname()]),
  212. 'route' => $route,
  213. 'title' => _m('Favourites'),
  214. 'ordering' => $ordering++,
  215. ]));
  216. DB::persist(Feed::create([
  217. 'actor_id' => $actor_id,
  218. 'url' => Router::url($route = 'favourites_reverse_view_by_nickname', ['nickname' => $user->getNickname()]),
  219. 'route' => $route,
  220. 'title' => _m('Reverse favourites'),
  221. 'ordering' => $ordering++,
  222. ]));
  223. return Event::next;
  224. }
  225. // ActivityPub handling and processing for Favourites is below
  226. /**
  227. * ActivityPub Inbox handler for Like and Undo Like activities
  228. *
  229. * @param Actor $actor Actor who authored the activity
  230. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  231. * @param mixed $type_object Activity's Object
  232. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  233. *
  234. * @throws \App\Util\Exception\ClientException
  235. * @throws \App\Util\Exception\DuplicateFoundException
  236. * @throws \App\Util\Exception\NoSuchActorException
  237. * @throws \App\Util\Exception\ServerException
  238. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  239. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  240. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  241. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  242. *
  243. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  244. */
  245. private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  246. {
  247. if (!\in_array($type_activity->get('type'), ['Like', 'Undo'])) {
  248. return Event::next;
  249. }
  250. if ($type_activity->get('type') === 'Like') { // Favourite
  251. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  252. if ($type_object->get('type') === 'Note' || $type_object->get('type') === 'ChatMessage' || $type_object->get('type') === 'Page') {
  253. $note = \Plugin\ActivityPub\Util\Model\Note::fromJson($type_object);
  254. $note_id = $note->getId();
  255. } else {
  256. return Event::next;
  257. }
  258. } elseif ($type_object instanceof Note) {
  259. $note_id = $type_object->getId();
  260. } else {
  261. return Event::next;
  262. }
  263. $activity = self::favourNote($note_id, $actor->getId(), source: 'ActivityPub');
  264. } elseif ($type_activity->get('type') === 'Undo') {
  265. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  266. $ap_prev_favourite_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object);
  267. $prev_favourite_act = $ap_prev_favourite_act->getActivity();
  268. if ($prev_favourite_act->getVerb() === 'favourite' && $prev_favourite_act->getObjectType() === 'note') {
  269. $note_id = $prev_favourite_act->getObjectId();
  270. } else {
  271. return Event::next;
  272. }
  273. } elseif ($type_object instanceof Activity) {
  274. if ($type_object->getVerb() === 'favourite' && $type_object->getObjectType() === 'note') {
  275. $note_id = $type_object->getObjectId();
  276. } else {
  277. return Event::next;
  278. }
  279. } else {
  280. return Event::next;
  281. }
  282. $activity = self::unfavourNote($note_id, $actor->getId(), source: 'ActivityPub');
  283. } else {
  284. return Event::next;
  285. }
  286. if (!\is_null($activity)) {
  287. // Store ActivityPub Activity
  288. $ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([
  289. 'activity_id' => $activity->getId(),
  290. 'activity_uri' => $type_activity->get('id'),
  291. 'created' => new DateTime($type_activity->get('published') ?? 'now'),
  292. 'modified' => new DateTime(),
  293. ]);
  294. DB::persist($ap_act);
  295. }
  296. return Event::stop;
  297. }
  298. public function onActivityPubNewNotification(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
  299. {
  300. switch ($activity->getVerb()) {
  301. case 'favourite':
  302. Event::handle('NewNotification', [$sender, $activity, $targets, _m('{actor_id} favoured note {note_id}.', ['{nickname}' => $sender->getId(), '{note_id}' => $activity->getObjectId()])]);
  303. return Event::stop;
  304. case 'undo':
  305. if ($activity->getObjectType() === 'activity') {
  306. $undone_favourite = $activity->getObject();
  307. if ($undone_favourite->getVerb() === 'favourite') {
  308. Event::handle('NewNotification', [$sender, $activity, $targets, _m('{actor_id} unfavoured note {note_id}.', ['{nickname}' => $sender->getId(), '{note_id}' => $activity->getObjectId()])]);
  309. return Event::stop;
  310. }
  311. }
  312. }
  313. return Event::next;
  314. }
  315. /**
  316. * Convert an Activity Streams 2.0 Like or Undo Like into the appropriate Favourite and Undo Favourite entities
  317. *
  318. * @param Actor $actor Actor who authored the activity
  319. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  320. * @param \ActivityPhp\Type\AbstractObject $type_object Activity Streams 2.0 Object
  321. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  322. *
  323. * @throws \App\Util\Exception\ClientException
  324. * @throws \App\Util\Exception\DuplicateFoundException
  325. * @throws \App\Util\Exception\NoSuchActorException
  326. * @throws \App\Util\Exception\ServerException
  327. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  328. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  329. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  330. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  331. *
  332. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  333. */
  334. public function onNewActivityPubActivity(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, \ActivityPhp\Type\AbstractObject $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  335. {
  336. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  337. }
  338. /**
  339. * Convert an Activity Streams 2.0 formatted activity with a known object into Entities
  340. *
  341. * @param Actor $actor Actor who authored the activity
  342. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  343. * @param mixed $type_object Object
  344. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  345. *
  346. * @throws \App\Util\Exception\ClientException
  347. * @throws \App\Util\Exception\DuplicateFoundException
  348. * @throws \App\Util\Exception\NoSuchActorException
  349. * @throws \App\Util\Exception\ServerException
  350. * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
  351. * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
  352. * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
  353. * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
  354. *
  355. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  356. */
  357. public function onNewActivityPubActivityWithObject(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  358. {
  359. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  360. }
  361. /**
  362. * Translate GNU social internal verb 'favourite' to Activity Streams 2.0 'Like'
  363. *
  364. * @param string $verb GNU social's internal verb
  365. * @param null|string $gs_verb_to_activity_stream_two_verb Resulting Activity Streams 2.0 verb
  366. *
  367. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  368. */
  369. public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool
  370. {
  371. if ($verb === 'favourite') {
  372. $gs_verb_to_activity_stream_two_verb = 'Like';
  373. return Event::stop;
  374. }
  375. return Event::next;
  376. }
  377. }