[PLUGIN][ActivityPub] Fix typo in getObjectByUri

This commit is contained in:
Diogo Peralta Cordeiro 2021-12-24 01:58:41 +00:00
parent 7407028891
commit e3efd25b43
Signed by: diogo
GPG Key ID: 18D2D35001FBFAB0
3 changed files with 97 additions and 138 deletions

View File

@ -1,6 +1,6 @@
<?php <?php
declare(strict_types=1); declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
@ -24,6 +24,7 @@ declare(strict_types=1);
* *
* @package GNUsocial * @package GNUsocial
* @category ActivityPub * @category ActivityPub
*
* @author Diogo Peralta Cordeiro <@diogo.site> * @author Diogo Peralta Cordeiro <@diogo.site>
* @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
@ -48,6 +49,8 @@ use App\Util\Nickname;
use Component\FreeNetwork\Entity\FreeNetworkActorProtocol; use Component\FreeNetwork\Entity\FreeNetworkActorProtocol;
use Component\FreeNetwork\Util\Discovery; use Component\FreeNetwork\Util\Discovery;
use Exception; use Exception;
use InvalidArgumentException;
use const PHP_URL_HOST;
use Plugin\ActivityPub\Controller\Inbox; use Plugin\ActivityPub\Controller\Inbox;
use Plugin\ActivityPub\Entity\ActivitypubActivity; use Plugin\ActivityPub\Entity\ActivitypubActivity;
use Plugin\ActivityPub\Entity\ActivitypubActor; use Plugin\ActivityPub\Entity\ActivitypubActor;
@ -59,6 +62,7 @@ use Plugin\ActivityPub\Util\Response\NoteResponse;
use Plugin\ActivityPub\Util\TypeResponse; use Plugin\ActivityPub\Util\TypeResponse;
use Plugin\ActivityPub\Util\Validator\contentLangModelValidator; use Plugin\ActivityPub\Util\Validator\contentLangModelValidator;
use Plugin\ActivityPub\Util\Validator\manuallyApprovesFollowersModelValidator; use Plugin\ActivityPub\Util\Validator\manuallyApprovesFollowersModelValidator;
use const PREG_SET_ORDER;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface; use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface; use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
@ -66,11 +70,6 @@ use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface; use Symfony\Contracts\HttpClient\ResponseInterface;
use XML_XRD; use XML_XRD;
use XML_XRD_Element_Link; use XML_XRD_Element_Link;
use function count;
use function is_null;
use const PHP_URL_HOST;
use const PREG_SET_ORDER;
use InvalidArgumentException;
/** /**
* Adds ActivityPub support to GNU social when enabled * Adds ActivityPub support to GNU social when enabled
@ -95,7 +94,7 @@ class ActivityPub extends Plugin
'as:Public', 'as:Public',
]; ];
public const HTTP_CLIENT_HEADERS = [ public const HTTP_CLIENT_HEADERS = [
'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent' => 'GNUsocialBot ' . GNUSOCIAL_VERSION . ' - ' . GNUSOCIAL_PROJECT_URL, 'User-Agent' => 'GNUsocialBot ' . GNUSOCIAL_VERSION . ' - ' . GNUSOCIAL_PROJECT_URL,
]; ];
@ -135,11 +134,6 @@ class ActivityPub extends Plugin
/** /**
* Fill Actor->getUrl() calls with correct URL coming from ActivityPub * Fill Actor->getUrl() calls with correct URL coming from ActivityPub
*
* @param Actor $actor
* @param int $type
* @param string|null $url
* @return bool
*/ */
public function onStartGetActorUri(Actor $actor, int $type, ?string &$url): bool public function onStartGetActorUri(Actor $actor, int $type, ?string &$url): bool
{ {
@ -147,7 +141,7 @@ class ActivityPub extends Plugin
// Is remote? // Is remote?
!$actor->getIsLocal() !$actor->getIsLocal()
// Is in ActivityPub? // Is in ActivityPub?
&& !is_null($ap_actor = ActivitypubActor::getByPK(['actor_id' => $actor->getId()])) && !\is_null($ap_actor = ActivitypubActor::getByPK(['actor_id' => $actor->getId()]))
// We can only provide a full URL (anything else wouldn't make sense) // We can only provide a full URL (anything else wouldn't make sense)
&& $type === Router::ABSOLUTE_URL && $type === Router::ABSOLUTE_URL
) { ) {
@ -165,7 +159,7 @@ class ActivityPub extends Plugin
*/ */
public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool
{ {
if (count(array_intersect(self::$accept_headers, $accept_header)) === 0) { if (\count(array_intersect(self::$accept_headers, $accept_header)) === 0) {
return Event::next; return Event::next;
} }
switch ($route) { switch ($route) {
@ -186,10 +180,6 @@ class ActivityPub extends Plugin
/** /**
* Add ActivityStreams 2 Extensions * Add ActivityStreams 2 Extensions
*
* @param string $type_name
* @param array $validators
* @return bool
*/ */
public function onActivityPubValidateActivityStreamsTwoData(string $type_name, array &$validators): bool public function onActivityPubValidateActivityStreamsTwoData(string $type_name, array &$validators): bool
{ {
@ -208,9 +198,6 @@ class ActivityPub extends Plugin
/** /**
* Let FreeNetwork Component know we exist and which class to use to call the freeNetworkDistribute method * Let FreeNetwork Component know we exist and which class to use to call the freeNetworkDistribute method
*
* @param array $protocols
* @return bool
*/ */
public function onAddFreeNetworkProtocol(array &$protocols): bool public function onAddFreeNetworkProtocol(array &$protocols): bool
{ {
@ -221,12 +208,6 @@ class ActivityPub extends Plugin
/** /**
* The FreeNetwork component will call this function to distribute this instance's activities * The FreeNetwork component will call this function to distribute this instance's activities
* *
* @param Actor $sender
* @param Activity $activity
* @param array $targets
* @param string|null $reason
* @param array $delivered
* @return bool
* @throws ClientExceptionInterface * @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface * @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface * @throws ServerExceptionInterface
@ -237,7 +218,7 @@ class ActivityPub extends Plugin
$to_addr = []; $to_addr = [];
foreach ($targets as $actor) { foreach ($targets as $actor) {
if (FreeNetworkActorProtocol::canIActor('activitypub', $actor->getId())) { if (FreeNetworkActorProtocol::canIActor('activitypub', $actor->getId())) {
if (is_null($ap_target = ActivitypubActor::getByPK(['actor_id' => $actor->getId()]))) { if (\is_null($ap_target = ActivitypubActor::getByPK(['actor_id' => $actor->getId()]))) {
continue; continue;
} }
$to_addr[$ap_target->getInboxSharedUri() ?? $ap_target->getInboxUri()][] = $actor; $to_addr[$ap_target->getInboxSharedUri() ?? $ap_target->getInboxUri()][] = $actor;
@ -257,7 +238,7 @@ class ActivityPub extends Plugin
if (!($status_code === 200 || $status_code === 202 || $status_code === 409)) { if (!($status_code === 200 || $status_code === 202 || $status_code === 409)) {
$res_body = json_decode($res->getContent(), true); $res_body = json_decode($res->getContent(), true);
$errors[] = $res_body['error'] ?? 'An unknown error occurred.'; $errors[] = $res_body['error'] ?? 'An unknown error occurred.';
//$to_failed[$inbox] = $activity; //$to_failed[$inbox] = $activity;
} else { } else {
array_push($delivered, ...$dummy); array_push($delivered, ...$dummy);
foreach ($dummy as $actor) { foreach ($dummy as $actor) {
@ -285,11 +266,6 @@ class ActivityPub extends Plugin
/** /**
* Internal tool to sign and send activities out * Internal tool to sign and send activities out
* *
* @param Actor $sender
* @param string $json_activity
* @param string $inbox
* @param string $method
* @return ResponseInterface
* @throws Exception * @throws Exception
*/ */
private static function postman(Actor $sender, string $json_activity, string $inbox, string $method = 'post'): ResponseInterface private static function postman(Actor $sender, string $json_activity, string $inbox, string $method = 'post'): ResponseInterface
@ -308,10 +284,6 @@ class ActivityPub extends Plugin
/** /**
* Add activity+json mimetype to WebFinger * Add activity+json mimetype to WebFinger
*
* @param XML_XRD $xrd
* @param Actor $object
* @return bool
*/ */
public function onEndWebFingerProfileLinks(XML_XRD $xrd, Actor $object): bool public function onEndWebFingerProfileLinks(XML_XRD $xrd, Actor $object): bool
{ {
@ -328,10 +300,6 @@ class ActivityPub extends Plugin
/** /**
* When FreeNetwork component asks us to help with identifying Actors from XRDs * When FreeNetwork component asks us to help with identifying Actors from XRDs
*
* @param XML_XRD $xrd
* @param Actor|null $actor
* @return bool
*/ */
public function onFreeNetworkFoundXrd(XML_XRD $xrd, ?Actor &$actor = null): bool public function onFreeNetworkFoundXrd(XML_XRD $xrd, ?Actor &$actor = null): bool
{ {
@ -341,7 +309,7 @@ class ActivityPub extends Plugin
$addr = Discovery::normalize($alias); $addr = Discovery::normalize($alias);
} }
} }
if (is_null($addr)) { if (\is_null($addr)) {
return Event::next; return Event::next;
} else { } else {
if (!FreeNetworkActorProtocol::canIAddr('activitypub', $addr)) { if (!FreeNetworkActorProtocol::canIAddr('activitypub', $addr)) {
@ -350,7 +318,7 @@ class ActivityPub extends Plugin
} }
try { try {
$ap_actor = ActivitypubActor::fromXrd($addr, $xrd); $ap_actor = ActivitypubActor::fromXrd($addr, $xrd);
$actor = Actor::getById($ap_actor->getActorId()); $actor = Actor::getById($ap_actor->getActorId());
FreeNetworkActorProtocol::protocolSucceeded('activitypub', $actor, $addr); FreeNetworkActorProtocol::protocolSucceeded('activitypub', $actor, $addr);
return Event::stop; return Event::stop;
} catch (Exception $e) { } catch (Exception $e) {
@ -363,17 +331,13 @@ class ActivityPub extends Plugin
/** /**
* When FreeNetwork component asks us to help with identifying Actors from URIs * When FreeNetwork component asks us to help with identifying Actors from URIs
*
* @param string $target
* @param Actor|null $actor
* @return bool
*/ */
public function onFreeNetworkFindMentions(string $target, ?Actor &$actor = null): bool public function onFreeNetworkFindMentions(string $target, ?Actor &$actor = null): bool
{ {
try { try {
if (FreeNetworkActorProtocol::canIAddr('activitypub', $addr = Discovery::normalize($target))) { if (FreeNetworkActorProtocol::canIAddr('activitypub', $addr = Discovery::normalize($target))) {
$ap_actor = ActivitypubActor::getByAddr($addr); $ap_actor = ActivitypubActor::getByAddr($addr);
$actor = Actor::getById($ap_actor->getActorId()); $actor = Actor::getById($ap_actor->getActorId());
FreeNetworkActorProtocol::protocolSucceeded('activitypub', $actor->getId(), $addr); FreeNetworkActorProtocol::protocolSucceeded('activitypub', $actor->getId(), $addr);
return Event::stop; return Event::stop;
} else { } else {
@ -386,13 +350,12 @@ class ActivityPub extends Plugin
} }
/** /**
* @param mixed $object
* @return string got from URI * @return string got from URI
*/ */
public static function getUriByObject(mixed $object): string public static function getUriByObject(mixed $object): string
{ {
if ($object instanceof Note) { if ($object instanceof Note) {
if($object->getIsLocal()) { if ($object->getIsLocal()) {
return $object->getUrl(); return $object->getUrl();
} else { } else {
// Try known remote objects // Try known remote objects
@ -401,29 +364,28 @@ class ActivityPub extends Plugin
return $known_object->getObjectUri(); return $known_object->getObjectUri();
} }
} }
} else if ($object instanceof Activity) { } elseif ($object instanceof Activity) {
// Try known remote activities // Try known remote activities
$known_activity = ActivitypubActivity::getByPK(['activity_id' => $object->getId()]); $known_activity = ActivitypubActivity::getByPK(['activity_id' => $object->getId()]);
if ($known_activity instanceof ActivitypubActivity) { if ($known_activity instanceof ActivitypubActivity) {
return $known_activity->getActivityUri(); return $known_activity->getActivityUri();
} else { } else {
return Router::url('activity_view', ['id' => $object->getId()], Router::ABSOLUTE_URL); return Router::url('activity_view', ['id' => $object->getId()], Router::ABSOLUTE_URL);
} }
} }
throw new InvalidArgumentException('ActivityPub::getUriByObject found a limitation with: '.var_export($object, true)); throw new InvalidArgumentException('ActivityPub::getUriByObject found a limitation with: ' . var_export($object, true));
} }
/** /**
* Get a Note from ActivityPub URI, if it doesn't exist, attempt to fetch it * Get a Note from ActivityPub URI, if it doesn't exist, attempt to fetch it
* This should only be necessary internally. * This should only be necessary internally.
* *
* @param string $resource
* @param bool $try_online
* @return null|Note|mixed got from URI
* @throws ClientExceptionInterface * @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface * @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface * @throws ServerExceptionInterface
* @throws TransportExceptionInterface * @throws TransportExceptionInterface
*
* @return null|mixed|Note got from URI
*/ */
public static function getObjectByUri(string $resource, bool $try_online = true) public static function getObjectByUri(string $resource, bool $try_online = true)
{ {
@ -445,7 +407,7 @@ class ActivityPub extends Plugin
$resource_parts = parse_url($resource); $resource_parts = parse_url($resource);
// TODO: Use URLMatcher // TODO: Use URLMatcher
if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) { if ($resource_parts['host'] === $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
$local_note = DB::find('note', ['url' => $resource]); $local_note = DB::findOneBy('note', ['url' => $resource]);
if ($local_note instanceof Note) { if ($local_note instanceof Note) {
return $local_note; return $local_note;
} }
@ -454,14 +416,14 @@ class ActivityPub extends Plugin
// Try remote // Try remote
if (!$try_online) { if (!$try_online) {
return null; return;
} }
$response = HTTPClient::get($resource, ['headers' => ActivityPub::HTTP_CLIENT_HEADERS]); $response = HTTPClient::get($resource, ['headers' => self::HTTP_CLIENT_HEADERS]);
// If it was deleted // If it was deleted
if ($response->getStatusCode() == 410) { if ($response->getStatusCode() == 410) {
//$obj = Type::create('Tombstone', ['id' => $resource]); //$obj = Type::create('Tombstone', ['id' => $resource]);
return null; return;
} elseif (!HTTPClient::statusCodeIsOkay($response)) { // If it is unavailable } elseif (!HTTPClient::statusCodeIsOkay($response)) { // If it is unavailable
throw new Exception('Non Ok Status Code for given Object id.'); throw new Exception('Non Ok Status Code for given Object id.');
} else { } else {
@ -473,9 +435,9 @@ class ActivityPub extends Plugin
* Get an Actor from ActivityPub URI, if it doesn't exist, attempt to fetch it * Get an Actor from ActivityPub URI, if it doesn't exist, attempt to fetch it
* This should only be necessary internally. * This should only be necessary internally.
* *
* @param string $resource
* @return Actor got from URI
* @throws NoSuchActorException * @throws NoSuchActorException
*
* @return Actor got from URI
*/ */
public static function getActorByUri(string $resource): Actor public static function getActorByUri(string $resource): Actor
{ {
@ -493,7 +455,7 @@ class ActivityPub extends Plugin
if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) { if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
return LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor(); return LocalUser::getByPK(['nickname' => $matches[0][1]])->getActor();
} elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) { } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
return Actor::getById((int)$matches[0][1]); return Actor::getById((int) $matches[0][1]);
} }
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
declare(strict_types=1); declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
@ -24,6 +24,7 @@ declare(strict_types=1);
* *
* @package GNUsocial * @package GNUsocial
* @category ActivityPub * @category ActivityPub
*
* @author Diogo Peralta Cordeiro <@diogo.site> * @author Diogo Peralta Cordeiro <@diogo.site>
* @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org * @copyright 2018-2019, 2021 Free Software Foundation, Inc http://www.fsf.org
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
@ -33,6 +34,7 @@ namespace Plugin\ActivityPub\Controller;
use App\Core\Controller; use App\Core\Controller;
use App\Core\DB\DB; use App\Core\DB\DB;
use function App\Core\I18n\_m;
use App\Core\Log; use App\Core\Log;
use App\Core\Router\Router; use App\Core\Router\Router;
use App\Entity\Actor; use App\Entity\Actor;
@ -40,15 +42,13 @@ use App\Util\Exception\ClientException;
use Component\FreeNetwork\Entity\FreeNetworkActorProtocol; use Component\FreeNetwork\Entity\FreeNetworkActorProtocol;
use Component\FreeNetwork\Util\Discovery; use Component\FreeNetwork\Util\Discovery;
use Exception; use Exception;
use const PHP_URL_HOST;
use Plugin\ActivityPub\Entity\ActivitypubActor; use Plugin\ActivityPub\Entity\ActivitypubActor;
use Plugin\ActivityPub\Entity\ActivitypubRsa; use Plugin\ActivityPub\Entity\ActivitypubRsa;
use Plugin\ActivityPub\Util\Explorer; use Plugin\ActivityPub\Util\Explorer;
use Plugin\ActivityPub\Util\HTTPSignature; use Plugin\ActivityPub\Util\HTTPSignature;
use Plugin\ActivityPub\Util\Model; use Plugin\ActivityPub\Util\Model;
use Plugin\ActivityPub\Util\TypeResponse; use Plugin\ActivityPub\Util\TypeResponse;
use function App\Core\I18n\_m;
use function is_null;
use const PHP_URL_HOST;
/** /**
* ActivityPub Inbox Handler * ActivityPub Inbox Handler
@ -69,7 +69,7 @@ class Inbox extends Controller
}; };
$path = Router::url('activitypub_inbox', type: Router::ABSOLUTE_PATH); $path = Router::url('activitypub_inbox', type: Router::ABSOLUTE_PATH);
if (!is_null($gsactor_id)) { if (!\is_null($gsactor_id)) {
try { try {
$user = DB::findOneBy('local_user', ['id' => $gsactor_id]); $user = DB::findOneBy('local_user', ['id' => $gsactor_id]);
$path = Router::url('activitypub_actor_inbox', ['gsactor_id' => $user->getId()], type: Router::ABSOLUTE_PATH); $path = Router::url('activitypub_actor_inbox', ['gsactor_id' => $user->getId()], type: Router::ABSOLUTE_PATH);
@ -79,8 +79,8 @@ class Inbox extends Controller
} }
Log::debug('ActivityPub Inbox: Received a POST request.'); Log::debug('ActivityPub Inbox: Received a POST request.');
$body = (string)$this->request->getContent(); $body = (string) $this->request->getContent();
Log::debug('ActivityPub Inbox: Request Body content: '.$body); Log::debug('ActivityPub Inbox: Request Body content: ' . $body);
$type = Model::jsonToType($body); $type = Model::jsonToType($body);
if ($type->has('actor') === false) { if ($type->has('actor') === false) {
@ -91,7 +91,7 @@ class Inbox extends Controller
$resource_parts = parse_url($type->get('actor')); $resource_parts = parse_url($type->get('actor'));
if ($resource_parts['host'] !== $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) { if ($resource_parts['host'] !== $_ENV['SOCIAL_DOMAIN']) { // XXX: Common::config('site', 'server')) {
$ap_actor = ActivitypubActor::fromUri($type->get('actor')); $ap_actor = ActivitypubActor::fromUri($type->get('actor'));
$actor = Actor::getById($ap_actor->getActorId()); $actor = Actor::getById($ap_actor->getActorId());
DB::flush(); DB::flush();
} else { } else {
throw new Exception('Only remote actors can use this endpoint.'); throw new Exception('Only remote actors can use this endpoint.');
@ -101,11 +101,11 @@ class Inbox extends Controller
return $error('Invalid actor.', $e); return $error('Invalid actor.', $e);
} }
$activitypub_rsa = ActivitypubRsa::getByActor($actor); $activitypub_rsa = ActivitypubRsa::getByActor($actor);
$actor_public_key = $activitypub_rsa->getPublicKey(); $actor_public_key = $activitypub_rsa->getPublicKey();
$headers = $this->request->headers->all(); $headers = $this->request->headers->all();
Log::debug('ActivityPub Inbox: Request Headers: '.var_export($headers, true)); Log::debug('ActivityPub Inbox: Request Headers: ' . var_export($headers, true));
// Flattify headers // Flattify headers
foreach ($headers as $key => $val) { foreach ($headers as $key => $val) {
$headers[$key] = $val[0]; $headers[$key] = $val[0];
@ -121,8 +121,8 @@ class Inbox extends Controller
$signatureData = HTTPSignature::parseSignatureHeader($headers['signature']); $signatureData = HTTPSignature::parseSignatureHeader($headers['signature']);
Log::debug('ActivityPub Inbox: HTTP Signature Data: ' . print_r($signatureData, true)); Log::debug('ActivityPub Inbox: HTTP Signature Data: ' . print_r($signatureData, true));
if (isset($signatureData['error'])) { if (isset($signatureData['error'])) {
Log::debug('ActivityPub Inbox: HTTP Signature: ' . json_encode($signatureData, JSON_PRETTY_PRINT)); Log::debug('ActivityPub Inbox: HTTP Signature: ' . json_encode($signatureData, \JSON_PRETTY_PRINT));
return $error(json_encode($signatureData, JSON_PRETTY_PRINT)); return $error(json_encode($signatureData, \JSON_PRETTY_PRINT));
} }
[$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body); [$verified, /*$headers*/] = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
@ -131,7 +131,7 @@ class Inbox extends Controller
if ($verified !== 1) { if ($verified !== 1) {
try { try {
$res = Explorer::get_remote_user_activity($ap_actor->getUri()); $res = Explorer::get_remote_user_activity($ap_actor->getUri());
if (is_null($res)) { if (\is_null($res)) {
return $error('Invalid remote actor (null response).'); return $error('Invalid remote actor (null response).');
} }
} catch (Exception $e) { } catch (Exception $e) {
@ -153,7 +153,7 @@ class Inbox extends Controller
} }
// HTTP signature checked out, make sure the "actor" of the activity matches that of the signature // HTTP signature checked out, make sure the "actor" of the activity matches that of the signature
Log::debug('ActivityPub Inbox: HTTP Signature: Authorized request. Will now start the inbox handler.'); Log::debug('ActivityPub Inbox: HTTP Signature: Authorised request. Will now start the inbox handler.');
// TODO: Check if Actor has authority over payload // TODO: Check if Actor has authority over payload
@ -162,7 +162,7 @@ class Inbox extends Controller
FreeNetworkActorProtocol::protocolSucceeded( FreeNetworkActorProtocol::protocolSucceeded(
'activitypub', 'activitypub',
$ap_actor->getActorId(), $ap_actor->getActorId(),
Discovery::normalize($actor->getNickname() . '@' . parse_url($ap_actor->getInboxUri(), PHP_URL_HOST)) Discovery::normalize($actor->getNickname() . '@' . parse_url($ap_actor->getInboxUri(), PHP_URL_HOST)),
); );
DB::flush(); DB::flush();
dd($ap_act, $act = $ap_act->getActivity(), $act->getActor(), $act->getObject()); dd($ap_act, $act = $ap_act->getActivity(), $act->getActor(), $act->getObject());

View File

@ -25,6 +25,7 @@ namespace Plugin\Favourite;
use App\Core\DB\DB; use App\Core\DB\DB;
use App\Core\Event; use App\Core\Event;
use function App\Core\I18n\_m;
use App\Core\Modules\NoteHandlerPlugin; use App\Core\Modules\NoteHandlerPlugin;
use App\Core\Router\RouteLoader; use App\Core\Router\RouteLoader;
use App\Core\Router\Router; use App\Core\Router\Router;
@ -34,28 +35,25 @@ use App\Entity\Feed;
use App\Entity\LocalUser; use App\Entity\LocalUser;
use App\Entity\Note; use App\Entity\Note;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\InvalidFormException;
use App\Util\Exception\NoSuchNoteException;
use App\Util\Exception\RedirectException;
use App\Util\Nickname; use App\Util\Nickname;
use DateTime;
use Plugin\Favourite\Entity\Favourite as FavouriteEntity; use Plugin\Favourite\Entity\Favourite as FavouriteEntity;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use function App\Core\I18n\_m;
class Favourite extends NoteHandlerPlugin class Favourite extends NoteHandlerPlugin
{ {
public static function favourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity public static function favourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
{ {
$opts = ['note_id' => $note_id, 'actor_id' => $actor_id]; $opts = ['note_id' => $note_id, 'actor_id' => $actor_id];
$note_already_favoured = DB::find('favourite', $opts); $note_already_favoured = DB::find('favourite', $opts);
if (is_null($note_already_favoured)) { if (\is_null($note_already_favoured)) {
DB::persist(FavouriteEntity::create($opts)); DB::persist(FavouriteEntity::create($opts));
$act = Activity::create([ $act = Activity::create([
'actor_id' => $actor_id, 'actor_id' => $actor_id,
'verb' => 'favourite', 'verb' => 'favourite',
'object_type' => 'note', 'object_type' => 'note',
'object_id' => $note_id, 'object_id' => $note_id,
'source' => $source, 'source' => $source,
]); ]);
DB::persist($act); DB::persist($act);
@ -67,15 +65,15 @@ class Favourite extends NoteHandlerPlugin
public static function unfavourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity public static function unfavourNote(int $note_id, int $actor_id, string $source = 'web'): ?Activity
{ {
$note_already_favoured = DB::find('favourite', ['note_id' => $note_id, 'actor_id' => $actor_id]); $note_already_favoured = DB::find('favourite', ['note_id' => $note_id, 'actor_id' => $actor_id]);
if (!is_null($note_already_favoured)) { if (!\is_null($note_already_favoured)) {
DB::remove($note_already_favoured); DB::remove($note_already_favoured);
$favourite_activity = DB::findBy('activity', ['verb' => 'favourite', 'object_type' => 'note', 'object_id' => $note_id], order_by: ['created' => 'DESC'])[0]; $favourite_activity = DB::findBy('activity', ['verb' => 'favourite', 'object_type' => 'note', 'object_id' => $note_id], order_by: ['created' => 'DESC'])[0];
$act = Activity::create([ $act = Activity::create([
'actor_id' => $actor_id, 'actor_id' => $actor_id,
'verb' => 'undo', // 'undo_favourite', 'verb' => 'undo', // 'undo_favourite',
'object_type' => 'activity', // 'note', 'object_type' => 'activity', // 'note',
'object_id' => $favourite_activity->getId(), // $note_id, 'object_id' => $favourite_activity->getId(), // $note_id,
'source' => $source, 'source' => $source,
]); ]);
DB::persist($act); DB::persist($act);
@ -88,38 +86,35 @@ class Favourite extends NoteHandlerPlugin
* HTML rendering event that adds the favourite form as a note * HTML rendering event that adds the favourite form as a note
* action, if a user is logged in * action, if a user is logged in
* *
* @param Request $request
* @param Note $note
* @param array $actions
* @return bool Event hook * @return bool Event hook
*/ */
public function onAddNoteActions(Request $request, Note $note, array &$actions): bool public function onAddNoteActions(Request $request, Note $note, array &$actions): bool
{ {
if (is_null($user = Common::user())) { if (\is_null($user = Common::user())) {
return Event::next; return Event::next;
} }
// If note is favourite, "is_favourite" is 1 // If note is favourite, "is_favourite" is 1
$opts = ['note_id' => $note->getId(), 'actor_id' => $user->getId()]; $opts = ['note_id' => $note->getId(), 'actor_id' => $user->getId()];
$is_favourite = DB::find('favourite', $opts) !== null; $is_favourite = DB::find('favourite', $opts) !== null;
// Generating URL for favourite action route // Generating URL for favourite action route
$args = ['id' => $note->getId()]; $args = ['id' => $note->getId()];
$type = Router::ABSOLUTE_PATH; $type = Router::ABSOLUTE_PATH;
$favourite_action_url = $is_favourite $favourite_action_url = $is_favourite
? Router::url('favourite_remove', $args, $type) ? Router::url('favourite_remove', $args, $type)
: Router::url('favourite_add', $args, $type); : Router::url('favourite_add', $args, $type);
$query_string = $request->getQueryString(); $query_string = $request->getQueryString();
// Concatenating get parameter to redirect the user to where he came from // Concatenating get parameter to redirect the user to where he came from
$favourite_action_url .= !is_null($query_string) ? '?from=' . mb_substr($query_string, 2) : ''; $favourite_action_url .= !\is_null($query_string) ? '?from=' . mb_substr($query_string, 2) : '';
$extra_classes = $is_favourite ? 'note-actions-set' : 'note-actions-unset'; $extra_classes = $is_favourite ? 'note-actions-set' : 'note-actions-unset';
$favourite_action = [ $favourite_action = [
'url' => $favourite_action_url, 'url' => $favourite_action_url,
'title' => $is_favourite ? 'Remove this note from favourites' : 'Favourite this note!', 'title' => $is_favourite ? 'Remove this note from favourites' : 'Favourite this note!',
'classes' => "button-container favourite-button-container {$extra_classes}", 'classes' => "button-container favourite-button-container {$extra_classes}",
'id' => 'favourite-button-container-' . $note->getId(), 'id' => 'favourite-button-container-' . $note->getId(),
]; ];
$actions[] = $favourite_action; $actions[] = $favourite_action;
@ -130,7 +125,7 @@ class Favourite extends NoteHandlerPlugin
{ {
// if note is the original, append on end "user favoured this" // if note is the original, append on end "user favoured this"
$actor = $vars['actor']; $actor = $vars['actor'];
$note = $vars['note']; $note = $vars['note'];
return Event::next; return Event::next;
} }
@ -155,16 +150,16 @@ class Favourite extends NoteHandlerPlugin
{ {
DB::persist(Feed::create([ DB::persist(Feed::create([
'actor_id' => $actor_id, 'actor_id' => $actor_id,
'url' => Router::url($route = 'favourites_view_by_nickname', ['nickname' => $user->getNickname()]), 'url' => Router::url($route = 'favourites_view_by_nickname', ['nickname' => $user->getNickname()]),
'route' => $route, 'route' => $route,
'title' => _m('Favourites'), 'title' => _m('Favourites'),
'ordering' => $ordering++, 'ordering' => $ordering++,
])); ]));
DB::persist(Feed::create([ DB::persist(Feed::create([
'actor_id' => $actor_id, 'actor_id' => $actor_id,
'url' => Router::url($route = 'favourites_reverse_view_by_nickname', ['nickname' => $user->getNickname()]), 'url' => Router::url($route = 'favourites_reverse_view_by_nickname', ['nickname' => $user->getNickname()]),
'route' => $route, 'route' => $route,
'title' => _m('Reverse favourites'), 'title' => _m('Reverse favourites'),
'ordering' => $ordering++, 'ordering' => $ordering++,
])); ]));
return Event::next; return Event::next;
@ -174,7 +169,7 @@ class Favourite extends NoteHandlerPlugin
private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool private function activitypub_handler(Actor $actor, \ActivityPhp\Type\AbstractObject $type_activity, mixed $type_object, ?\Plugin\ActivityPub\Entity\ActivitypubActivity &$ap_act): bool
{ {
if (!in_array($type_activity->get('type'), ['Like', 'Undo'])) { if (!\in_array($type_activity->get('type'), ['Like', 'Undo'])) {
return Event::next; return Event::next;
} }
if ($type_activity->get('type') === 'Like') { // Favourite if ($type_activity->get('type') === 'Like') { // Favourite
@ -184,7 +179,7 @@ class Favourite extends NoteHandlerPlugin
} else { } else {
return Event::next; return Event::next;
} }
} else if ($type_object instanceof Note) { } elseif ($type_object instanceof Note) {
$note_id = $type_object->getId(); $note_id = $type_object->getId();
} else { } else {
return Event::next; return Event::next;
@ -192,13 +187,13 @@ class Favourite extends NoteHandlerPlugin
} else { // Undo Favourite } else { // Undo Favourite
if ($type_object instanceof \ActivityPhp\Type\AbstractObject) { if ($type_object instanceof \ActivityPhp\Type\AbstractObject) {
$ap_prev_favourite_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object); $ap_prev_favourite_act = \Plugin\ActivityPub\Util\Model\Activity::fromJson($type_object);
$prev_favourite_act = $ap_prev_favourite_act->getActivity(); $prev_favourite_act = $ap_prev_favourite_act->getActivity();
if ($prev_favourite_act->getVerb() === 'favourite' && $prev_favourite_act->getObjectType() === 'note') { if ($prev_favourite_act->getVerb() === 'favourite' && $prev_favourite_act->getObjectType() === 'note') {
$note_id = $prev_favourite_act->getObjectId(); $note_id = $prev_favourite_act->getObjectId();
} else { } else {
return Event::next; return Event::next;
} }
} else if ($type_object instanceof Activity) { } elseif ($type_object instanceof Activity) {
if ($type_object->getVerb() === 'favourite' && $type_object->getObjectType() === 'note') { if ($type_object->getVerb() === 'favourite' && $type_object->getObjectType() === 'note') {
$note_id = $type_object->getObjectId(); $note_id = $type_object->getObjectId();
} else { } else {
@ -214,14 +209,16 @@ class Favourite extends NoteHandlerPlugin
} else { } else {
$act = self::unfavourNote($note_id, $actor->getId(), source: 'ActivityPub'); $act = self::unfavourNote($note_id, $actor->getId(), source: 'ActivityPub');
} }
// Store ActivityPub Activity if (!\is_null($act)) {
$ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([ // Store ActivityPub Activity
'activity_id' => $act->getId(), $ap_act = \Plugin\ActivityPub\Entity\ActivitypubActivity::create([
'activity_uri' => $type_activity->get('id'), 'activity_id' => $act->getId(),
'created' => new \DateTime($type_activity->get('published') ?? 'now'), 'activity_uri' => $type_activity->get('id'),
'modified' => new \DateTime(), 'created' => new DateTime($type_activity->get('published') ?? 'now'),
]); 'modified' => new DateTime(),
DB::persist($ap_act); ]);
DB::persist($ap_act);
}
return Event::stop; return Event::stop;
} }
@ -234,13 +231,13 @@ class Favourite extends NoteHandlerPlugin
{ {
return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act); return $this->activitypub_handler($actor, $type_activity, $type_object, $ap_act);
} }
public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool public function onGSVerbToActivityStreamsTwoActivityType(string $verb, ?string &$gs_verb_to_activity_stream_two_verb): bool
{ {
if ($verb === 'favourite') { if ($verb === 'favourite') {
$gs_verb_to_activity_stream_two_verb = 'Like'; $gs_verb_to_activity_stream_two_verb = 'Like';
return Event::stop; return Event::stop;
} }
return Event::next; return Event::next;
} }
} }