Favourite.php 16 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\Favourite;
  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\Feed;
  30. use App\Entity\LocalUser;
  31. use App\Entity\Note;
  32. use App\Util\Common;
  33. use App\Util\Nickname;
  34. use DateTime;
  35. use Plugin\Favourite\Entity\NoteFavourite as FavouriteEntity;
  36. use Symfony\Component\HttpFoundation\Request;
  37. class Favourite extends NoteHandlerPlugin
  38. {
  39. /**
  40. * Creates a new Favourite Entity, upon the given Actor performs a Favourite
  41. * action on the given Note object
  42. *
  43. * A new notification is then handled, informing all interested Actors of this action
  44. *
  45. * @throws \App\Util\Exception\ServerException
  46. * @throws \Doctrine\ORM\OptimisticLockException
  47. * @throws \Doctrine\ORM\ORMException
  48. * @throws \Doctrine\ORM\TransactionRequiredException
  49. */
  50. public static function favourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  51. {
  52. $opts = ['note_id' => $note_id, 'actor_id' => $actor_id];
  53. $note_already_favoured = Cache::get(
  54. FavouriteEntity::cacheKeys($note_id, $actor_id)['favourite'],
  55. fn () => DB::findOneBy('note_favourite', $opts, return_null: true),
  56. );
  57. $activity = null;
  58. if (\is_null($note_already_favoured)) {
  59. DB::persist(FavouriteEntity::create($opts));
  60. Cache::delete(FavouriteEntity::cacheKeys($note_id, $actor_id)['favourite']);
  61. $activity = Activity::create([
  62. 'actor_id' => $actor_id,
  63. 'verb' => 'favourite',
  64. 'object_type' => 'note',
  65. 'object_id' => $note_id,
  66. 'source' => $source,
  67. ]);
  68. DB::persist($activity);
  69. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $activity, [], _m('{nickname} favoured note {note_id}.', ['{nickname}' => $actor->getNickname(), '{note_id}' => $activity->getObjectId()])]);
  70. }
  71. return $activity;
  72. }
  73. /**
  74. * Removes the Favourite Entity created beforehand, by the same Actor, and on the same Note
  75. *
  76. * Informs all interested Actors of this action, handling out the NewNotification event
  77. *
  78. * @throws \App\Util\Exception\ServerException
  79. * @throws \Doctrine\ORM\OptimisticLockException
  80. * @throws \Doctrine\ORM\ORMException
  81. * @throws \Doctrine\ORM\TransactionRequiredException
  82. */
  83. public static function unfavourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
  84. {
  85. $note_already_favoured = Cache::get(
  86. FavouriteEntity::cacheKeys($note_id, $actor_id)['favourite'],
  87. fn () => DB::findOneBy('note_favourite', ['note_id' => $note_id, 'actor_id' => $actor_id], return_null: true),
  88. );
  89. $activity = null;
  90. if (!\is_null($note_already_favoured)) {
  91. DB::remove($note_already_favoured);
  92. Cache::delete(FavouriteEntity::cacheKeys($note_id, $actor_id)['favourite']);
  93. $favourite_activity = DB::findBy('activity', ['verb' => 'favourite', 'object_type' => 'note', 'actor_id' => $actor_id, 'object_id' => $note_id], order_by: ['created' => 'DESC'])[0];
  94. $activity = Activity::create([
  95. 'actor_id' => $actor_id,
  96. 'verb' => 'undo', // 'undo_favourite',
  97. 'object_type' => 'activity', // 'note',
  98. 'object_id' => $favourite_activity->getId(), // $note_id,
  99. 'source' => $source,
  100. ]);
  101. DB::persist($activity);
  102. Event::handle('NewNotification', [$actor = Actor::getById($actor_id), $activity, [], _m('{nickname} unfavoured note {note_id}.', ['{nickname}' => $actor->getNickname(), '{note_id}' => $activity->getObjectId()])]);
  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. * @throws \Doctrine\ORM\OptimisticLockException
  111. * @throws \Doctrine\ORM\ORMException
  112. * @throws \Doctrine\ORM\TransactionRequiredException
  113. *
  114. * @return bool Event hook
  115. */
  116. public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
  117. {
  118. if (\is_null($user = Common::user())) {
  119. return Event::next;
  120. }
  121. // If note is favourite, "is_favourite" is 1
  122. $opts = ['note_id' => $note->getId(), 'actor_id' => $user->getId()];
  123. $is_favourite = !\is_null(
  124. Cache::get(
  125. FavouriteEntity::cacheKeys($note->getId(), $user->getId())['favourite'],
  126. fn () => DB::findOneBy('note_favourite', $opts, return_null: true),
  127. ),
  128. );
  129. // Generating URL for favourite action route
  130. $args = ['id' => $note->getId()];
  131. $type = Router::ABSOLUTE_PATH;
  132. $favourite_action_url = $is_favourite
  133. ? Router::url('favourite_remove', $args, $type)
  134. : Router::url('favourite_add', $args, $type);
  135. $query_string = $request->getQueryString();
  136. // Concatenating get parameter to redirect the user to where he came from
  137. $favourite_action_url .= '?from=' . urlencode($request->getRequestUri());
  138. $extra_classes = $is_favourite ? 'note-actions-set' : 'note-actions-unset';
  139. $favourite_action = [
  140. 'url' => $favourite_action_url,
  141. 'title' => $is_favourite ? 'Remove this note from favourites' : 'Favourite this note!',
  142. 'classes' => "button-container favourite-button-container {$extra_classes}",
  143. 'id' => 'favourite-button-container-' . $note->getId(),
  144. ];
  145. $actions[] = $favourite_action;
  146. return Event::next;
  147. }
  148. public function onAppendCardNote(array $vars, array &$result)
  149. {
  150. // If note is the original and user isn't the one who repeated, append on end "user repeated this"
  151. // If user is the one who repeated, append on end "you repeated this, remove repeat?"
  152. $check_user = !\is_null(Common::user());
  153. // The current Note being rendered
  154. $note = $vars['note'];
  155. // Will have actors array, and action string
  156. // Actors are the subjects, action is the verb (in the final phrase)
  157. $favourite_actors = FavouriteEntity::getNoteFavouriteActors($note);
  158. if (\count($favourite_actors) < 1) {
  159. return Event::next;
  160. }
  161. // Filter out multiple replies from the same actor
  162. $favourite_actors = array_unique($favourite_actors, \SORT_REGULAR);
  163. $result[] = ['actors' => $favourite_actors, 'action' => 'favourited'];
  164. return Event::next;
  165. }
  166. /**
  167. * Deletes every favourite entity in table related to a deleted Note
  168. */
  169. public function onNoteDeleteRelated(Note &$note, Actor $actor): bool
  170. {
  171. $note_favourites_list = FavouriteEntity::getNoteFavourites($note);
  172. foreach ($note_favourites_list as $favourite_entity) {
  173. DB::remove($favourite_entity);
  174. }
  175. return Event::next;
  176. }
  177. public function onAddRoute(RouteLoader $r): bool
  178. {
  179. // Add/remove note to/from favourites
  180. $r->connect(id: 'favourite_add', uri_path: '/object/note/{id<\d+>}/favour', target: [Controller\Favourite::class, 'favouriteAddNote']);
  181. $r->connect(id: 'favourite_remove', uri_path: '/object/note/{id<\d+>}/unfavour', target: [Controller\Favourite::class, 'favouriteRemoveNote']);
  182. // View all favourites by actor id
  183. $r->connect(id: 'favourites_view_by_actor_id', uri_path: '/actor/{id<\d+>}/favourites', target: [Controller\Favourite::class, 'favouritesViewByActorId']);
  184. $r->connect(id: 'favourites_reverse_view_by_actor_id', uri_path: '/actor/{id<\d+>}/reverse_favourites', target: [Controller\Favourite::class, 'favouritesReverseViewByActorId']);
  185. // View all favourites by nickname
  186. $r->connect(id: 'favourites_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/favourites', target: [Controller\Favourite::class, 'favouritesViewByActorNickname']);
  187. $r->connect(id: 'favourites_reverse_view_by_nickname', uri_path: '/@{nickname<' . Nickname::DISPLAY_FMT . '>}/reverse_favourites', target: [Controller\Favourite::class, 'reverseFavouritesViewByActorNickname']);
  188. return Event::next;
  189. }
  190. public function onCreateDefaultFeeds(int $actor_id, LocalUser $user, int &$ordering)
  191. {
  192. DB::persist(Feed::create([
  193. 'actor_id' => $actor_id,
  194. 'url' => Router::url($route = 'favourites_view_by_nickname', ['nickname' => $user->getNickname()]),
  195. 'route' => $route,
  196. 'title' => _m('Favourites'),
  197. 'ordering' => $ordering++,
  198. ]));
  199. DB::persist(Feed::create([
  200. 'actor_id' => $actor_id,
  201. 'url' => Router::url($route = 'favourites_reverse_view_by_nickname', ['nickname' => $user->getNickname()]),
  202. 'route' => $route,
  203. 'title' => _m('Reverse favourites'),
  204. 'ordering' => $ordering++,
  205. ]));
  206. return Event::next;
  207. }
  208. // ActivityPub handling and processing for Favourites is below
  209. /**
  210. * ActivityPub Inbox handler for Like and Undo Like activities
  211. *
  212. * @param Actor $actor Actor who authored the activity
  213. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  214. * @param mixed $type_object Activity's Object
  215. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  216. *
  217. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  218. */
  219. private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  220. {
  221. if (!\in_array($type_activity->get('type'), ['Like', 'Undo'])) {
  222. return Event::next;
  223. }
  224. if ($type_activity->get('type') === 'Like') { // Favourite
  225. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  226. if ($type_object->get('type') === 'Note') {
  227. $note_id = \Plugin\ActivityPub\Util\Model\Note::fromJson($type_object)->getId();
  228. } else {
  229. return Event::next;
  230. }
  231. } elseif ($type_object instanceof Note) {
  232. $note_id = $type_object->getId();
  233. } else {
  234. return Event::next;
  235. }
  236. } else { // Undo Favourite
  237. if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
  238. $ap_prev_favourite_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object);
  239. $prev_favourite_act = $ap_prev_favourite_act->getActivity();
  240. if ($prev_favourite_act->getVerb() === 'favourite' && $prev_favourite_act->getObjectType() === 'note') {
  241. $note_id = $prev_favourite_act->getObjectId();
  242. } else {
  243. return Event::next;
  244. }
  245. } elseif ($type_object instanceof Activity) {
  246. if ($type_object->getVerb() === 'favourite' && $type_object->getObjectType() === 'note') {
  247. $note_id = $type_object->getObjectId();
  248. } else {
  249. return Event::next;
  250. }
  251. } else {
  252. return Event::next;
  253. }
  254. }
  255. if ($type_activity->get('type') === 'Like') {
  256. $activity = self::favourNote($note_id, $actor->getId(), source: 'ActivityPub');
  257. } else {
  258. $activity = self::unfavourNote($note_id, $actor->getId(), source: 'ActivityPub');
  259. }
  260. if (!\is_null($activity)) {
  261. // Store ActivityPub Activity
  262. $ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([
  263. 'activity_id' => $activity->getId(),
  264. 'activity_uri' => $type_activity->get('id'),
  265. 'created' => new DateTime($type_activity->get('published') ?? 'now'),
  266. 'modified' => new DateTime(),
  267. ]);
  268. DB::persist($ap_act);
  269. }
  270. return Event::stop;
  271. }
  272. /**
  273. * Convert an Activity Streams 2.0 Like or Undo Like into the appropriate Favourite and Undo Favourite entities
  274. *
  275. * @param Actor $actor Actor who authored the activity
  276. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  277. * @param \ActivityPhp\Type\AbstractObject $type_object Activity Streams 2.0 Object
  278. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  279. *
  280. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  281. */
  282. public function onNewActivityPubActivity(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, \ActivityPhp\Type\AbstractObject $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  283. {
  284. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  285. }
  286. /**
  287. * Convert an Activity Streams 2.0 formatted activity with a known object into Entities
  288. *
  289. * @param Actor $actor Actor who authored the activity
  290. * @param \ActivityPhp\Type\AbstractObject $type_activity Activity Streams 2.0 Activity
  291. * @param mixed $type_object Object
  292. * @param null|\Plugin\ActivityPub\Entity\ActivitypubActivity $ap_act Resulting ActivitypubActivity
  293. *
  294. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  295. */
  296. public function onNewActivityPubActivityWithObject(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
  297. {
  298. return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
  299. }
  300. /**
  301. * Translate GNU social internal verb 'favourite' to Activity Streams 2.0 'Like'
  302. *
  303. * @param string $verb GNU social's internal verb
  304. * @param null|string $gs_verb_to_activity_stream_two_verb Resulting Activity Streams 2.0 verb
  305. *
  306. * @return bool Returns `Event::stop` if handled, `Event::next` otherwise
  307. */
  308. public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool
  309. {
  310. if ($verb === 'favourite') {
  311. $gs_verb_to_activity_stream_two_verb = 'Like';
  312. return Event::stop;
  313. }
  314. return Event::next;
  315. }
  316. }