[ActivityPub] Initial cleanup, removing 'die' statements, and ignoring the subfolders

This commit is contained in:
Hugo Sales 2020-08-21 20:36:56 +00:00 committed by Hugo Sales
parent 38cfec8593
commit b624359b9a
Signed by: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0
2 changed files with 196 additions and 140 deletions

View File

@ -47,9 +47,10 @@ services:
Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider: ~ Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider: ~
Plugin\: Plugin\:
resource: '../plugins/*' resource: '../plugins/*/*.php'
exclude: '../plugins/*/{scripts,classes,lib,actions,locale,doc}'
tags: ['controller.service_arguments'] tags: ['controller.service_arguments']
Component\: Component\:
resource: '../components/*' resource: '../components/*/*.php'
tags: ['controller.service_arguments'] tags: ['controller.service_arguments']

View File

@ -1,4 +1,7 @@
<?php <?php
// {{{ 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
// //
// GNU social is free software: you can redistribute it and/or modify // GNU social is free software: you can redistribute it and/or modify
@ -14,48 +17,56 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
// }}}
/** /**
* ActivityPub implementation for GNU social * ActivityPub implementation for GNU social
* *
* @package GNUsocial * @package GNUsocial
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org * @author Hugo Sales <hugo@fc.up.pt>
* @copyright 2018-2020 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
* @link http://www.gnu.org/software/social/ *
* @see http://www.gnu.org/software/social/
*/ */
defined('GNUSOCIAL') || die(); namespace Plugin\ActivityPub;
// Import plugin libs use App\Core\Module;
foreach (glob(__DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . '*.php') as $filename) {
require_once $filename;
}
// Import plugin models
foreach (glob(__DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . '*.php') as $filename) {
require_once $filename;
}
// So that this isn't hardcoded everywhere // // Import plugin libs
const ACTIVITYPUB_PUBLIC_TO = ['https://www.w3.org/ns/activitystreams#Public', // foreach (glob(__DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . '*.php') as $filename) {
'Public', // require_once $filename;
'as:Public' // }
]; // // Import plugin models
const ACTIVITYPUB_HTTP_CLIENT_HEADERS = [ // foreach (glob(__DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . '*.php') as $filename) {
'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"', // require_once $filename;
'User-Agent: GNUsocialBot ' . GNUSOCIAL_VERSION . ' - https://gnusocial.rocks' // }
];
/** /**
* Adds ActivityPub support to GNU social when enabled * Adds ActivityPub support to GNU social when enabled
* *
* @category Plugin * @category Plugin
* @package GNUsocial * @package GNUsocial
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
* @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
*/ */
class ActivityPubPlugin extends Plugin class ActivityPub extends Module
{ {
const PLUGIN_VERSION = '0.4.0alpha0'; const PLUGIN_VERSION = '0.4.0alpha0';
// So that this isn't hardcoded everywhere
const ACTIVITYPUB_PUBLIC_TO = ['https://www.w3.org/ns/activitystreams#Public',
'Public',
'as:Public',
];
const ACTIVITYPUB_HTTP_CLIENT_HEADERS = [
'Accept: application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent: GNUsocialBot ' . GNUSOCIAL_VERSION . ' - https://gnusocial.network',
];
/** /**
* Returns a Actor's URI from its local $profile * Returns a Actor's URI from its local $profile
@ -65,7 +76,9 @@ class ActivityPubPlugin extends Plugin
* *
* @param Profile $profile Actor's local profile * @param Profile $profile Actor's local profile
* @param string &$uri I/O Actor's URI * @param string &$uri I/O Actor's URI
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*
* @return bool event hook * @return bool event hook
*/ */
public function onStartGetProfileUri(Profile $profile, &$uri): bool public function onStartGetProfileUri(Profile $profile, &$uri): bool
@ -83,13 +96,16 @@ class ActivityPubPlugin extends Plugin
* *
* @param string $url Notice's URL * @param string $url Notice's URL
* @param bool $grab_online whether to try online grabbing, defaults to true * @param bool $grab_online whether to try online grabbing, defaults to true
* @return Notice|null The Notice object *
* @throws Exception This function or provides a Notice, null, or fails with exception * @throws Exception This function or provides a Notice, null, or fails with exception
*
* @return null|Notice The Notice object
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public static function grab_notice_from_url(string $url, bool $grab_online = true): ?Notice public static function grab_notice_from_url(string $url, bool $grab_online = true): ?Notice
{ {
/* Offline Grabbing */ // Offline Grabbing
try { try {
// Look for a known remote notice // Look for a known remote notice
return Notice::getByUri($url); return Notice::getByUri($url);
@ -97,19 +113,19 @@ class ActivityPubPlugin extends Plugin
// Look for a local notice (unfortunately GNU social doesn't // Look for a local notice (unfortunately GNU social doesn't
// provide this functionality natively) // provide this functionality natively)
try { try {
$candidate = Notice::getByID((int)substr($url, (strlen(Activitypub_notice::note_uri(0))-1))); $candidate = Notice::getByID((int) substr($url, (strlen(common_local_url('apNotice', ['id' => 0])) - 1)));
if (Activitypub_notice::note_uri($candidate->getID()) === $url) { // Sanity check if (common_local_url('apNotice', ['id' => $candidate->getID()]) === $url) { // Sanity check
return $candidate; return $candidate;
} else { } else {
common_debug('ActivityPubPlugin Notice Grabber: '.$candidate->getUrl(). ' is different of '.$url); common_debug('ActivityPubPlugin Notice Grabber: ' . $candidate->getUrl() . ' is different of ' . $url);
} }
} catch (Exception $e) { } catch (Exception $e) {
common_debug('ActivityPubPlugin Notice Grabber: failed to find: '.$url.' offline.'); common_debug('ActivityPubPlugin Notice Grabber: failed to find: ' . $url . ' offline.');
} }
} }
if ($grab_online) { if ($grab_online) {
/* Online Grabbing */ // Online Grabbing
$client = new HTTPClient(); $client = new HTTPClient();
$response = $client->get($url, ACTIVITYPUB_HTTP_CLIENT_HEADERS); $response = $client->get($url, ACTIVITYPUB_HTTP_CLIENT_HEADERS);
$object = json_decode($response->getBody(), true); $object = json_decode($response->getBody(), true);
@ -132,11 +148,11 @@ class ActivityPubPlugin extends Plugin
throw new Exception("The acclaimed actor didn't create this note."); throw new Exception("The acclaimed actor didn't create this note.");
} }
} else { } else {
throw new Exception("Invalid Note Object. Maybe it's a Tombstone?"); throw new Exception('Valid ActivityPub Notice object but unsupported by GNU social.');
} }
} }
common_debug('ActivityPubPlugin Notice Grabber: failed to find: '.$url); common_debug('ActivityPubPlugin Notice Grabber: failed to find: ' . $url);
return null; return null;
} }
@ -144,8 +160,10 @@ class ActivityPubPlugin extends Plugin
* Route/Reroute urls * Route/Reroute urls
* *
* @param URLMapper $m * @param URLMapper $m
* @return void *
* @throws Exception * @throws Exception
*
* @return void
*/ */
public function onRouterInitialized(URLMapper $m) public function onRouterInitialized(URLMapper $m)
{ {
@ -153,7 +171,7 @@ class ActivityPubPlugin extends Plugin
'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' => 0, 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"' => 0,
'application/activity+json' => 1, 'application/activity+json' => 1,
'application/json' => 2, 'application/json' => 2,
'application/ld+json' => 3 'application/ld+json' => 3,
]; ];
$m->connect( $m->connect(
@ -242,6 +260,7 @@ class ActivityPubPlugin extends Plugin
* Plugin version information * Plugin version information
* *
* @param array $versions * @param array $versions
*
* @return bool hook true * @return bool hook true
*/ */
public function onPluginVersion(array &$versions): bool public function onPluginVersion(array &$versions): bool
@ -252,8 +271,8 @@ class ActivityPubPlugin extends Plugin
'author' => 'Diogo Cordeiro', 'author' => 'Diogo Cordeiro',
'homepage' => 'https://notabug.org/diogo/gnu-social/src/nightly/plugins/ActivityPub', 'homepage' => 'https://notabug.org/diogo/gnu-social/src/nightly/plugins/ActivityPub',
// TRANS: Plugin description. // TRANS: Plugin description.
'rawdescription' => _m('Follow people across social networks that implement '. 'rawdescription' => _m('Follow people across social networks that implement ' .
'<a href="https://activitypub.rocks/">ActivityPub</a>.') '<a href="https://activitypub.rocks/">ActivityPub</a>.'),
]; ];
return true; return true;
} }
@ -262,6 +281,7 @@ class ActivityPubPlugin extends Plugin
* Set up queue handlers for required interactions * Set up queue handlers for required interactions
* *
* @param QueueManager $qm * @param QueueManager $qm
*
* @return bool event hook return * @return bool event hook return
*/ */
public function onEndInitializeQueueManager(QueueManager $qm): bool public function onEndInitializeQueueManager(QueueManager $qm): bool
@ -277,7 +297,8 @@ class ActivityPubPlugin extends Plugin
* Enqueue saved notices for distribution * Enqueue saved notices for distribution
* *
* @param Notice $notice notice to be distributed * @param Notice $notice notice to be distributed
* @param Array &$transports list of transports to queue for * @param array &$transports list of transports to queue for
*
* @return bool event hook return * @return bool event hook return
*/ */
public function onStartEnqueueNotice(Notice $notice, array &$transports): bool public function onStartEnqueueNotice(Notice $notice, array &$transports): bool
@ -290,7 +311,7 @@ class ActivityPubPlugin extends Plugin
$this->log(LOG_INFO, "Notice:{$id} queued for distribution"); $this->log(LOG_INFO, "Notice:{$id} queued for distribution");
} }
} catch (Exception $e) { } catch (Exception $e) {
$this->log(LOG_ERR, "Invalid notice, not queueing for distribution"); $this->log(LOG_ERR, 'Invalid notice, not queueing for distribution');
} }
return true; return true;
@ -302,6 +323,7 @@ class ActivityPubPlugin extends Plugin
* notices away from the public timelines. * notices away from the public timelines.
* *
* @param Notice &$notice notice to be saved * @param Notice &$notice notice to be saved
*
* @return bool event hook return * @return bool event hook return
*/ */
public function onStartNoticeSave(Notice &$notice): bool public function onStartNoticeSave(Notice &$notice): bool
@ -309,14 +331,13 @@ class ActivityPubPlugin extends Plugin
if ($notice->reply_to) { if ($notice->reply_to) {
try { try {
$parent = $notice->getParent(); $parent = $notice->getParent();
$is_local = (int)$parent->is_local; $is_local = (int) $parent->is_local;
// if we're replying unlisted/followers-only notices received by AP // if we're replying unlisted/followers-only notices received by AP
// or replying to replies of such notices, then we make sure to set // or replying to replies of such notices, then we make sure to set
// the correct type flag. // the correct type flag.
if (($parent->source === 'ActivityPub' && $is_local === Notice::GATEWAY) || if (($parent->source === 'ActivityPub' && $is_local === Notice::GATEWAY) || ($parent->source === 'web' && $is_local === Notice::LOCAL_NONPUBLIC)) {
($parent->source === 'web' && $is_local === Notice::LOCAL_NONPUBLIC)) { $this->log(LOG_INFO, 'Enforcing type flag LOCAL_NONPUBLIC for new notice');
$this->log(LOG_INFO, "Enforcing type flag LOCAL_NONPUBLIC for new notice");
$notice->is_local = Notice::LOCAL_NONPUBLIC; $notice->is_local = Notice::LOCAL_NONPUBLIC;
} }
} catch (NoParentNoticeException $e) { } catch (NoParentNoticeException $e) {
@ -332,6 +353,7 @@ class ActivityPubPlugin extends Plugin
* *
* @param User $current current logged user * @param User $current current logged user
* @param array &$recipients * @param array &$recipients
*
* @return void * @return void
*/ */
public function onFillDirectMessageRecipients(User $current, array &$recipients): void public function onFillDirectMessageRecipients(User $current, array &$recipients): void
@ -341,10 +363,10 @@ class ActivityPubPlugin extends Plugin
foreach ($subs as $sub) { foreach ($subs as $sub) {
if (!$sub->isLocal()) { // AP plugin adds AP users if (!$sub->isLocal()) { // AP plugin adds AP users
try { try {
$value = 'profile:'.$sub->getID(); $value = 'profile:' . $sub->getID();
$recipients[$value] = substr($sub->getAcctUri(), 5) . " [{$sub->getBestName()}]"; $recipients[$value] = substr($sub->getAcctUri(), 5) . " [{$sub->getBestName()}]";
} catch (ProfileNoAcctUriException $e) { } catch (ProfileNoAcctUriException $e) {
$recipients[$value] = "[?@?] " . $e->profile->getBestName(); $recipients[$value] = '[?@?] ' . $e->profile->getBestName();
} }
} }
} }
@ -357,6 +379,7 @@ class ActivityPubPlugin extends Plugin
* Validate AP-recipients for profile page message action addition * Validate AP-recipients for profile page message action addition
* *
* @param Profile $recipient * @param Profile $recipient
*
* @return bool hook return value * @return bool hook return value
*/ */
public function onDirectMessageProfilePageActions(Profile $recipient): bool public function onDirectMessageProfilePageActions(Profile $recipient): bool
@ -374,6 +397,7 @@ class ActivityPubPlugin extends Plugin
* *
* @param Profile profile being deleted * @param Profile profile being deleted
* @param array &$related objects with same profile_id to be deleted * @param array &$related objects with same profile_id to be deleted
*
* @return void * @return void
*/ */
public function onProfileDeleteRelated(Profile $profile, array &$related): void public function onProfileDeleteRelated(Profile $profile, array &$related): void
@ -396,11 +420,12 @@ class ActivityPubPlugin extends Plugin
* Plugin Nodeinfo information * Plugin Nodeinfo information
* *
* @param array $protocols * @param array $protocols
*
* @return bool hook true * @return bool hook true
*/ */
public function onNodeInfoProtocols(array &$protocols) public function onNodeInfoProtocols(array &$protocols)
{ {
$protocols[] = "activitypub"; $protocols[] = 'activitypub';
return true; return true;
} }
@ -409,8 +434,11 @@ class ActivityPubPlugin extends Plugin
* *
* @param HTMLOutputter $out * @param HTMLOutputter $out
* @param Profile $profile * @param Profile $profile
* @return boolean hook return value *
* @throws Exception * @throws Exception
*
* @return bool hook return value
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public function onEndShowAccountProfileBlock(HTMLOutputter $out, Profile $profile) public function onEndShowAccountProfileBlock(HTMLOutputter $out, Profile $profile)
@ -444,7 +472,9 @@ class ActivityPubPlugin extends Plugin
* could do both search and grab. * could do both search and grab.
* *
* @param string $query search query * @param string $query search query
*
* @return bool hook * @return bool hook
*
* @author Bruno Casteleiro <up201505347@fc.up.pt> * @author Bruno Casteleiro <up201505347@fc.up.pt>
*/ */
public function onStartNoticeSearch(string $query): bool public function onStartNoticeSearch(string $query): bool
@ -463,7 +493,7 @@ class ActivityPubPlugin extends Plugin
return false; return false;
} }
} elseif (filter_var($query, FILTER_VALIDATE_URL)) { // URL found! } elseif (filter_var($query, FILTER_VALIDATE_URL)) { // URL found!
/* Is this an ActivityPub notice? */ // Is this an ActivityPub notice?
// If we already know it, just return // If we already know it, just return
try { try {
@ -486,7 +516,7 @@ class ActivityPubPlugin extends Plugin
// We will next check if this URL is an actor // We will next check if this URL is an actor
} }
/* Is this an ActivityPub actor? */ // Is this an ActivityPub actor?
// If we already know it, just return // If we already know it, just return
try { try {
@ -531,15 +561,15 @@ class ActivityPubPlugin extends Plugin
return true; return true;
} }
/******************************************************** // WebFinger Events
* WebFinger Events *
********************************************************/
/** /**
* Get remote user's ActivityPub_profile via a identifier * Get remote user's ActivityPub_profile via a identifier
* *
* @param string $arg A remote user identifier * @param string $arg A remote user identifier
* @return Activitypub_profile|null Valid profile in success | null otherwise *
* @return null|Activitypub_profile Valid profile in success | null otherwise
*
* @author GNU social * @author GNU social
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
@ -561,9 +591,9 @@ class ActivityPubPlugin extends Plugin
$urls[] = $arg; $urls[] = $arg;
} }
if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) { if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
$schemes = array('http', 'https'); $schemes = ['http', 'https'];
foreach ($schemes as $scheme) { foreach ($schemes as $scheme) {
$urls[] = "$scheme://$arg"; $urls[] = "{$scheme}://{$arg}";
} }
} }
@ -582,21 +612,23 @@ class ActivityPubPlugin extends Plugin
* Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
* *
* @author GNU social * @author GNU social
*
* @param string $text The text from which to extract webfinger IDs * @param string $text The text from which to extract webfinger IDs
* @param string $preMention Character(s) that signals a mention ('@', '!'...) * @param string $preMention Character(s) that signals a mention ('@', '!'...)
*
* @return array The matching IDs (without $preMention) and each respective position in the given string. * @return array The matching IDs (without $preMention) and each respective position in the given string.
*/ */
public static function extractWebfingerIds($text, $preMention='@') public static function extractWebfingerIds($text, $preMention = '@')
{ {
$wmatches = []; $wmatches = [];
$result = preg_match_all( $result = preg_match_all(
'/(?<!\S)'.preg_quote($preMention, '/').'('.Nickname::WEBFINGER_FMT.')/', '/(?<!\S)' . preg_quote($preMention, '/') . '(' . Nickname::WEBFINGER_FMT . ')/',
$text, $text,
$wmatches, $wmatches,
PREG_OFFSET_CAPTURE PREG_OFFSET_CAPTURE
); );
if ($result === false) { if ($result === false) {
common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').'); common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error==' . preg_last_error() . ').');
return []; return [];
} elseif (($n_matches = count($wmatches)) != 0) { } elseif (($n_matches = count($wmatches)) != 0) {
common_debug(sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, _ve($wmatches))); common_debug(sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, _ve($wmatches)));
@ -608,23 +640,25 @@ class ActivityPubPlugin extends Plugin
* Profile URL matches: @example.com/mublog/user * Profile URL matches: @example.com/mublog/user
* *
* @author GNU social * @author GNU social
*
* @param string $text The text from which to extract URL mentions * @param string $text The text from which to extract URL mentions
* @param string $preMention Character(s) that signals a mention ('@', '!'...) * @param string $preMention Character(s) that signals a mention ('@', '!'...)
*
* @return array The matching URLs (without @ or acct:) and each respective position in the given string. * @return array The matching URLs (without @ or acct:) and each respective position in the given string.
*/ */
public static function extractUrlMentions($text, $preMention='@') public static function extractUrlMentions($text, $preMention = '@')
{ {
$wmatches = []; $wmatches = [];
// In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
// with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important) // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
$result = preg_match_all( $result = preg_match_all(
'/(?:^|\s+)'.preg_quote($preMention, '/').'('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/', '/(?:^|\s+)' . preg_quote($preMention, '/') . '(' . URL_REGEX_DOMAIN_NAME . '(?:\/[' . URL_REGEX_VALID_PATH_CHARS . ']*)*)/',
$text, $text,
$wmatches, $wmatches,
PREG_OFFSET_CAPTURE PREG_OFFSET_CAPTURE
); );
if ($result === false) { if ($result === false) {
common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').'); common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error==' . preg_last_error() . ').');
return []; return [];
} elseif (count($wmatches)) { } elseif (count($wmatches)) {
common_debug(sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), _ve($wmatches))); common_debug(sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), _ve($wmatches)));
@ -637,7 +671,9 @@ class ActivityPubPlugin extends Plugin
* *
* @param XML_XRD $xrd * @param XML_XRD $xrd
* @param Managed_DataObject $object * @param Managed_DataObject $object
*
* @throws Exception * @throws Exception
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public function onEndWebFingerProfileLinks(XML_XRD $xrd, Managed_DataObject $object) public function onEndWebFingerProfileLinks(XML_XRD $xrd, Managed_DataObject $object)
@ -648,7 +684,7 @@ class ActivityPubPlugin extends Plugin
$object->getProfile()->getUri(), $object->getProfile()->getUri(),
'application/activity+json' 'application/activity+json'
); );
$xrd->links[] = clone($link); $xrd->links[] = clone $link;
} }
} }
@ -656,11 +692,15 @@ class ActivityPubPlugin extends Plugin
* Find any explicit remote mentions. Accepted forms: * Find any explicit remote mentions. Accepted forms:
* Webfinger: @user@example.com * Webfinger: @user@example.com
* Profile link: * Profile link:
*
* @param Profile $sender * @param Profile $sender
* @param string $text input markup text * @param string $text input markup text
* @param $mentions * @param $mentions
* @return boolean hook return value *
* @throws InvalidUrlException * @throws InvalidUrlException
*
* @return bool hook return value
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
* @example.com/mublog/user * @example.com/mublog/user
* *
@ -672,13 +712,13 @@ class ActivityPubPlugin extends Plugin
foreach (self::extractWebfingerIds($text, '@') as $wmatch) { foreach (self::extractWebfingerIds($text, '@') as $wmatch) {
list($target, $pos) = $wmatch; list($target, $pos) = $wmatch;
$this->log(LOG_INFO, "Checking webfinger person '$target'"); $this->log(LOG_INFO, "Checking webfinger person '{$target}'");
$profile = null; $profile = null;
try { try {
$aprofile = Activitypub_profile::ensure_webfinger($target); $aprofile = Activitypub_profile::ensure_webfinger($target);
$profile = $aprofile->local_profile(); $profile = $aprofile->local_profile();
} catch (Exception $e) { } catch (Exception $e) {
$this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage()); $this->log(LOG_ERR, 'Webfinger check failed: ' . $e->getMessage());
continue; continue;
} }
assert($profile instanceof Profile); assert($profile instanceof Profile);
@ -690,34 +730,34 @@ class ActivityPubPlugin extends Plugin
if (!common_valid_http_url($url)) { if (!common_valid_http_url($url)) {
$url = $profile->getUrl(); $url = $profile->getUrl();
} }
$matches[$pos] = array('mentioned' => array($profile), $matches[$pos] = ['mentioned' => [$profile],
'type' => 'mention', 'type' => 'mention',
'text' => $displayName, 'text' => $displayName,
'position' => $pos, 'position' => $pos,
'length' => mb_strlen($target), 'length' => mb_strlen($target),
'url' => $url); 'url' => $url, ];
} }
foreach (self::extractUrlMentions($text) as $wmatch) { foreach (self::extractUrlMentions($text) as $wmatch) {
list($target, $pos) = $wmatch; list($target, $pos) = $wmatch;
$schemes = array('https', 'http'); $schemes = ['https', 'http'];
foreach ($schemes as $scheme) { foreach ($schemes as $scheme) {
$url = "$scheme://$target"; $url = "{$scheme}://{$target}";
$this->log(LOG_INFO, "Checking profile address '$url'"); $this->log(LOG_INFO, "Checking profile address '{$url}'");
try { try {
$aprofile = Activitypub_profile::fromUri($url); $aprofile = Activitypub_profile::fromUri($url);
$profile = $aprofile->local_profile(); $profile = $aprofile->local_profile();
$displayName = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ? $displayName = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
$profile->nickname : $target; $profile->nickname : $target;
$matches[$pos] = array('mentioned' => array($profile), $matches[$pos] = ['mentioned' => [$profile],
'type' => 'mention', 'type' => 'mention',
'text' => $displayName, 'text' => $displayName,
'position' => $pos, 'position' => $pos,
'length' => mb_strlen($target), 'length' => mb_strlen($target),
'url' => $profile->getUrl()); 'url' => $profile->getUrl(), ];
break; break;
} catch (Exception $e) { } catch (Exception $e) {
$this->log(LOG_ERR, "Profile check failed: " . $e->getMessage()); $this->log(LOG_ERR, 'Profile check failed: ' . $e->getMessage());
} }
} }
} }
@ -746,16 +786,18 @@ class ActivityPubPlugin extends Plugin
* @param Command $command * @param Command $command
* @param string $arg * @param string $arg
* @param Profile &$profile * @param Profile &$profile
* @return boolean hook return code *
* @return bool hook return code
*
* @author GNU social * @author GNU social
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public function onStartCommandGetProfile($command, $arg, &$profile) public function onStartCommandGetProfile($command, $arg, &$profile)
{ {
$aprofile = self::pull_remote_profile($arg); try {
if ($aprofile instanceof Activitypub_profile) { $aprofile = $this->pull_remote_profile($arg);
$profile = $aprofile->local_profile(); $profile = $aprofile->local_profile();
} else { } catch (Exception $e) {
// No remote ActivityPub profile found // No remote ActivityPub profile found
return true; return true;
} }
@ -763,17 +805,17 @@ class ActivityPubPlugin extends Plugin
return false; return false;
} }
/******************************************************** // Discovery Events
* Discovery Events *
********************************************************/
/** /**
* Profile from URI. * Profile from URI.
* *
* @author GNU social * @author GNU social
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*
* @param string $uri * @param string $uri
* @param Profile &$profile in/out param: Profile got from URI * @param Profile &$profile in/out param: Profile got from URI
*
* @return mixed hook return code * @return mixed hook return code
*/ */
public function onStartGetProfileFromURI($uri, &$profile) public function onStartGetProfileFromURI($uri, &$profile)
@ -791,6 +833,7 @@ class ActivityPubPlugin extends Plugin
* *
* @param string $uri * @param string $uri
* @param Profile &$profile * @param Profile &$profile
*
* @return bool * @return bool
*/ */
public function onRemoteFollowPullProfile(string $uri, ?Profile &$profile): bool public function onRemoteFollowPullProfile(string $uri, ?Profile &$profile): bool
@ -806,9 +849,7 @@ class ActivityPubPlugin extends Plugin
return is_null($profile); return is_null($profile);
} }
/******************************************************** // Delivery Events
* Delivery Events *
********************************************************/
/** /**
* Having established a remote subscription, send a notification to the * Having established a remote subscription, send a notification to the
@ -816,8 +857,11 @@ class ActivityPubPlugin extends Plugin
* *
* @param Profile $profile subscriber * @param Profile $profile subscriber
* @param Profile $other subscribee * @param Profile $other subscribee
* @return bool return value *
* @throws HTTP_Request2_Exception * @throws HTTP_Request2_Exception
*
* @return bool return value
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public function onStartSubscribe(Profile $profile, Profile $other) public function onStartSubscribe(Profile $profile, Profile $other)
@ -842,8 +886,11 @@ class ActivityPubPlugin extends Plugin
* *
* @param Profile $profile * @param Profile $profile
* @param Profile $other * @param Profile $other
* @return bool return value *
* @throws HTTP_Request2_Exception * @throws HTTP_Request2_Exception
*
* @return bool return value
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public function onStartUnsubscribe(Profile $profile, Profile $other) public function onStartUnsubscribe(Profile $profile, Profile $other)
@ -943,6 +990,7 @@ class ActivityPubPlugin extends Plugin
* Federate private message * Federate private message
* *
* @param Notice $message * @param Notice $message
*
* @return void * @return void
*/ */
public function onSendDirectMessage(Notice $message): void public function onSendDirectMessage(Notice $message): void
@ -968,17 +1016,20 @@ class ActivityPubPlugin extends Plugin
* original post and show the domain it came from. * original post and show the domain it came from.
* *
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*
* @param $notice * @param $notice
* @param $name * @param $name
* @param $url * @param $url
* @param $title * @param $title
* @return mixed hook return code *
* @throws Exception * @throws Exception
*
* @return mixed hook return code
*/ */
public function onStartNoticeSourceLink($notice, &$name, &$url, &$title) public function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
{ {
// If we don't handle this, keep the event handler going // If we don't handle this, keep the event handler going
if (!in_array($notice->source, array('ActivityPub', 'share'))) { if (!in_array($notice->source, ['ActivityPub', 'share'])) {
return true; return true;
} }
@ -1016,14 +1067,16 @@ class ActivityPubReturn
* *
* @param string $res * @param string $res
* @param int $code Status Code * @param int $code Status Code
*
* @return void * @return void
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public static function answer($res = '', $code = 202) public static function answer($res = '', $code = 202)
{ {
http_response_code($code); http_response_code($code);
header('Content-Type: application/activity+json'); header('Content-Type: application/activity+json');
echo json_encode($res, JSON_UNESCAPED_SLASHES | (isset($_GET["pretty"]) ? JSON_PRETTY_PRINT : null)); echo json_encode($res, JSON_UNESCAPED_SLASHES | (isset($_GET['pretty']) ? JSON_PRETTY_PRINT : null));
exit; exit;
} }
@ -1032,7 +1085,9 @@ class ActivityPubReturn
* *
* @param string $m * @param string $m
* @param int $code Status Code * @param int $code Status Code
*
* @return void * @return void
*
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
*/ */
public static function error($m, $code = 400) public static function error($m, $code = 400)