code:
<?php

// {{{ License

// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

// }}}

/**
 * ActivityPub's Remote Actor
 *
 * @category  Plugin
 * @package   GNUsocial
 *
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @author    Hugo Sales <hugo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace Plugin\ActivityPub\Entity;

class ActivityPubActor
{
    // {{{ Autocode

    private string $uri;
    private int $profile_id;
    private string $inboxuri;
    private ?string $sharedInboxuri;
    private ?DateTimeInterface $created;
    private DateTimeInterface $modified;

    public function setUri(string $uri): self
    {
        $this->uri = $uri;
        return $this;
    }

    public function getUri(): string
    {
        return $this->uri;
    }

    public function setProfileId(int $profile_id): self
    {
        $this->profile_id = $profile_id;
        return $this;
    }

    public function getProfileId(): int
    {
        return $this->profile_id;
    }

    public function setInboxuri(string $inboxuri): self
    {
        $this->inboxuri = $inboxuri;
        return $this;
    }

    public function getInboxuri(): string
    {
        return $this->inboxuri;
    }

    public function setSharedInboxuri(?string $sharedInboxuri): self
    {
        $this->sharedInboxuri = $sharedInboxuri;
        return $this;
    }

    public function getSharedInboxuri(): ?string
    {
        return $this->sharedInboxuri;
    }

    public function setCreated(?DateTimeInterface $created): self
    {
        $this->created = $created;
        return $this;
    }

    public function getCreated(): ?DateTimeInterface
    {
        return $this->created;
    }

    public function setModified(DateTimeInterface $modified): self
    {
        $this->modified = $modified;
        return $this;
    }

    public function getModified(): DateTimeInterface
    {
        return $this->modified;
    }

    // }}} Autocode

    /**
     * Generates a pretty profile from a Profile object
     *
     * @param Profile $profile
     *
     * @throws InvalidUrlException
     * @throws ServerException
     * @throws Exception
     *
     * @return array array to be used in a response
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function profile_to_array(Profile $profile): array
    {
        $uri        = $profile->getUri();
        $id         = $profile->getID();
        $rsa        = new Activitypub_rsa();
        $public_key = $rsa->ensure_public_key($profile);
        unset($rsa);
        $res = [
            '@context' => [
                'https://www.w3.org/ns/activitystreams',
                'https://w3id.org/security/v1',
                [
                    'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
                ],
            ],
            'id'                        => $uri,
            'type'                      => 'Person',
            'following'                 => common_local_url('apActorFollowing', ['id' => $id]),
            'followers'                 => common_local_url('apActorFollowers', ['id' => $id]),
            'liked'                     => common_local_url('apActorLiked', ['id' => $id]),
            'inbox'                     => common_local_url('apInbox', ['id' => $id]),
            'outbox'                    => common_local_url('apActorOutbox', ['id' => $id]),
            'preferredUsername'         => $profile->getNickname(),
            'name'                      => $profile->getBestName(),
            'summary'                   => ($desc = $profile->getDescription()) == null ? '' : $desc,
            'url'                       => $profile->getUrl(),
            'manuallyApprovesFollowers' => false,
            'publicKey'                 => [
                'id'           => $uri . '#public-key',
                'owner'        => $uri,
                'publicKeyPem' => $public_key,
            ],
            'tag'        => [],
            'attachment' => [],
            'icon'       => [
                'type'      => 'Image',
                'mediaType' => 'image/png',
                'height'    => AVATAR_PROFILE_SIZE,
                'width'     => AVATAR_PROFILE_SIZE,
                'url'       => $profile->avatarUrl(AVATAR_PROFILE_SIZE),
            ],
        ];

        if ($profile->isLocal()) {
            $res['endpoints']['sharedInbox'] = common_local_url('apInbox');
        } else {
            $aprofile                        = new Activitypub_profile();
            $aprofile                        = $aprofile->from_profile($profile);
            $res['endpoints']['sharedInbox'] = $aprofile->sharedInboxuri;
        }

        return $res;
    }

    /**
     * Insert the current object variables into the database
     *
     * @throws ServerException
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function do_insert(): void
    {
        // Does any other protocol have this remote entity we're about to add ?
        Event::handle('StartTFNLookup', [$this->uri, get_class($this), &$profile_id]);
        if (!is_null($profile_id)) {
            // Yes! Avoid creating a new profile
            $this->profile_id = $profile_id;
            $this->created    = $this->modified    = common_sql_now();

            if ($this->insert() === false) {
                $this->query('ROLLBACK');
                throw new ServerException('Cannot save ActivityPub profile.');
            }

            // Update existing profile with received data
            $profile = Profile::getKV('id', $profile_id);
            self::update_local_profile($profile, $this);

            // Ask TFN to handle profile duplication
            Event::handle('EndTFNLookup', [get_class($this), $profile_id]);
        } else {
            // No, create both a new profile and remote profile
            $profile          = new Profile();
            $profile->created = $this->created = $this->modified = common_sql_now();
            self::update_local_profile($profile, $this);

            $this->profile_id = $profile->insert();
            if ($this->profile_id === false) {
                $profile->query('ROLLBACK');
                throw new ServerException('Profile insertion failed.');
            }

            $ok = $this->insert();

            if ($ok === false) {
                $profile->query('ROLLBACK');
                $this->query('ROLLBACK');
                throw new ServerException('Cannot save ActivityPub profile.');
            }
        }
    }

    /**
     * Fetch the locally stored profile for this Activitypub_profile
     *
     * @throws NoProfileException if it was not found
     *
     * @return Profile
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function local_profile(): Profile
    {
        $profile = Profile::getKV('id', $this->profile_id);
        if (!$profile instanceof Profile) {
            throw new NoProfileException($this->profile_id);
        }
        return $profile;
    }

    /**
     * Generates an Activitypub_profile from a Profile
     *
     * @param Profile $profile
     *
     * @throws Exception if no Activitypub_profile exists for given Profile
     *
     * @return Activitypub_profile
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function from_profile(Profile $profile): Activitypub_profile
    {
        $profile_id = $profile->getID();

        $aprofile = self::getKV('profile_id', $profile_id);
        if (!$aprofile instanceof Activitypub_profile) {
            // No Activitypub_profile for this profile_id,
            if (!$profile->isLocal()) {
                // create one!
                $aprofile = self::create_from_local_profile($profile);
            } else {
                throw new Exception('No Activitypub_profile for Profile ID: ' . $profile_id . ', this is a local user.');
            }
        }

        // extend the ap_profile with some information we
        // don't store in the database
        $fields = [
            'nickname' => 'nickname',
            'fullname' => 'fullname',
            'bio'      => 'bio',
        ];

        foreach ($fields as $af => $pf) {
            $aprofile->{$af} = $profile->{$pf};
        }

        return $aprofile;
    }

    /**
     * Travels an array of Profile and returns an array of Activitypub_profile
     *
     * @param array of Profile $profiles
     *
     * @return array of Activitypub_profile
     */
    public static function from_profile_collection(array $profiles): array
    {
        $ap_profiles = [];

        foreach ($profiles as $profile) {
            try {
                $ap_profiles[] = self::from_profile($profile);
            } catch (Exception $e) {
                // Don't mind local profiles
            }
        }

        return $ap_profiles;
    }

    /**
     * Given an existent local profile creates an ActivityPub profile.
     * One must be careful not to give a user profile to this function
     * as only remote users have ActivityPub_profiles on local instance
     *
     * @param Profile $profile
     *
     * @throws HTTP_Request2_Exception
     * @throws Exception
     * @throws Exception
     *
     * @return Activitypub_profile
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    private static function create_from_local_profile(Profile $profile): Activitypub_profile
    {
        $aprofile = new Activitypub_profile();

        $url     = $profile->getUri();
        $inboxes = Activitypub_explorer::get_actor_inboxes_uri($url);
        if ($inboxes === false) {
            throw new Exception('This is not an ActivityPub user thus AProfile is politely refusing to proceed.');
        }

        $aprofile->created = $aprofile->modified = common_sql_now();

        $aprofile                 = new Activitypub_profile;
        $aprofile->profile_id     = $profile->getID();
        $aprofile->uri            = $url;
        $aprofile->nickname       = $profile->getNickname();
        $aprofile->fullname       = $profile->getFullname();
        $aprofile->bio            = substr($profile->getDescription(), 0, 1000);
        $aprofile->inboxuri       = $inboxes['inbox'];
        $aprofile->sharedInboxuri = $inboxes['sharedInbox'];

        $aprofile->insert();

        return $aprofile;
    }

    /**
     * Returns sharedInbox if possible, inbox otherwise
     *
     * @return string Inbox URL
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function get_inbox(): string
    {
        if (is_null($this->sharedInboxuri)) {
            return $this->inboxuri;
        }

        return $this->sharedInboxuri;
    }

    /**
     * Ensures a valid Activitypub_profile when provided with a valid URI.
     *
     * @param string $url
     * @param bool   $grab_online whether to try online grabbing, defaults to true
     *
     * @throws Exception if it isn't possible to return an Activitypub_profile
     *
     * @return Activitypub_profile
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function fromUri(string $url, bool $grab_online = true): Activitypub_profile
    {
        try {
            return self::from_profile(Activitypub_explorer::get_profile_from_url($url, $grab_online));
        } catch (Exception $e) {
            throw new Exception('No valid ActivityPub profile found for given URI.');
        }
    }

    /**
     * Look up, and if necessary create, an Activitypub_profile for the remote
     * entity with the given WebFinger address.
     * This should never return null -- you will either get an object or
     * an exception will be thrown.
     *
     * @param string $addr WebFinger address
     *
     * @throws Exception on error conditions
     *
     * @return Activitypub_profile
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     * @author GNU social
     */
    public static function ensure_webfinger(string $addr): Activitypub_profile
    {
        // Normalize $addr, i.e. add 'acct:' if missing
        $addr = Discovery::normalize($addr);

        // Try the cache
        $uri = self::cacheGet(sprintf('activitypub_profile:webfinger:%s', $addr));

        if ($uri !== false) {
            if (is_null($uri)) {
                // Negative cache entry
                // TRANS: Exception.
                throw new Exception(_m('Not a valid WebFinger address (via cache).'));
            }
            try {
                return self::fromUri($uri);
            } catch (Exception $e) {
                common_log(LOG_ERR, sprintf(__METHOD__ . ': WebFinger address cache inconsistent with database, did not find Activitypub_profile uri==%s', $uri));
                self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), false);
            }
        }

        // Now, try some discovery

        $disco = new Discovery();

        try {
            $xrd = $disco->lookup($addr);
        } catch (Exception $e) {
            // Save negative cache entry so we don't waste time looking it up again.
            // @todo FIXME: Distinguish temporary failures?
            self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), null);
            // TRANS: Exception.
            throw new Exception(_m('Not a valid WebFinger address.'));
        }

        $hints = array_merge(
            ['webfinger' => $addr],
            DiscoveryHints::fromXRD($xrd)
        );

        // If there's an Hcard, let's grab its info
        if (array_key_exists('hcard', $hints)) {
            if (!array_key_exists('profileurl', $hints) || $hints['hcard'] != $hints['profileurl']) {
                $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
                $hints      = array_merge($hcardHints, $hints);
            }
        }

        // If we got a profile page, try that!
        $profileUrl = null;
        if (array_key_exists('profileurl', $hints)) {
            $profileUrl = $hints['profileurl'];
            try {
                common_log(LOG_INFO, "Discovery on acct:{$addr} with profile URL {$profileUrl}");
                $aprofile = self::fromUri($hints['profileurl']);
                self::cacheSet(sprintf('activitypub_profile:webfinger:%s', $addr), $aprofile->getUri());
                return $aprofile;
            } catch (Exception $e) {
                common_log(LOG_WARNING, "Failed creating profile from profile URL '{$profileUrl}': " . $e->getMessage());
                // keep looking
                //
                // @todo FIXME: This means an error discovering from profile page
                // may give us a corrupt entry using the webfinger URI, which
                // will obscure the correct page-keyed profile later on.
            }
        }

        // XXX: try hcard
        // XXX: try FOAF

        // TRANS: Exception. %s is a WebFinger address.
        throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'), $addr));
    }

    /**
     * Update local profile with info from some AP profile
     *
     * @param Profile             $profile
     * @param Activitypub_profile $aprofile
     *
     * @return void
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function update_local_profile(Profile $profile, Activitypub_profile $aprofile): void
    {
        $fields = [
            'profileurl' => 'profileurl',
            'nickname'   => 'nickname',
            'fullname'   => 'fullname',
            'bio'        => 'bio',
        ];

        $orig = clone $profile;

        foreach ($fields as $af => $pf) {
            $profile->{$pf} = $aprofile->{$af};
        }

        if ($profile->id) {
            common_debug('Updating local Profile:' . $profile->id . ' from remote ActivityPub profile');
            $profile->modified = common_sql_now();
            $profile->update($orig);
        }
    }

    /**
     * Update remote user profile in local instance
     *
     * @param Activitypub_profile $aprofile
     * @param array|false         $res      remote response, if array it updates, if false it deletes
     *
     * @throws NoProfileException
     *
     * @return Profile remote Profile object
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function update_profile(Activitypub_profile $aprofile, $res): Profile
    {
        if ($res === false) {
            $profile = $aprofile->local_profile();
            $id      = $profile->getID();
            $profile->delete();
            throw new NoProfileException($id, '410 Gone');
        }

        if (!is_array($res)) {
            throw new InvalidArgumentException('TypeError: Argument 2 passed to Activitypub_profile::update_profile() must be of the type array or bool(false).');
        }

        // ActivityPub Profile
        $aprofile->uri            = $res['id'];
        $aprofile->nickname       = $res['preferredUsername'];
        $aprofile->fullname       = $res['name'] ?? null;
        $aprofile->bio            = isset($res['summary']) ? substr(strip_tags($res['summary']), 0, 1000) : null;
        $aprofile->inboxuri       = $res['inbox'];
        $aprofile->sharedInboxuri = $res['endpoints']['sharedInbox'] ?? $res['inbox'];
        $aprofile->profileurl     = $res['url']                      ?? $aprofile->uri;
        $aprofile->modified       = common_sql_now();

        $profile = $aprofile->local_profile();

        // Profile
        self::update_local_profile($profile, $aprofile);
        $aprofile->update();

        // Public Key
        Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);

        // Avatar
        if (isset($res['icon']['url'])) {
            try {
                Activitypub_explorer::update_avatar($profile, $res['icon']['url']);
            } catch (Exception $e) {
                // Let the exception go, it isn't a serious issue
                common_debug('An error ocurred while grabbing remote avatar' . $e->getMessage());
            }
        }

        return $profile;
    }

    /**
     * Update remote user profile URI in local instance
     *
     * @param string $uri
     *
     * @throws Exception (if the update fails)
     *
     * @return void
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public function updateUri(string $uri): void
    {
        $orig      = clone $this;
        $this->uri = $uri;
        $this->updateWithKeys($orig);
    }

    /**
     * Getter for the number of subscribers of a
     * given local profile
     *
     * @param Profile $profile profile object
     *
     * @return int number of subscribers
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function subscriberCount(Profile $profile): int
    {
        $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));

        if ($cnt !== false && is_int($cnt)) {
            return $cnt;
        }

        $user_table      = common_database_tablename('user');
        $sub             = new Subscription();
        $sub->subscribed = $profile->id;
        $sub->_join .= "\n" . <<<END
            INNER JOIN (
              SELECT id AS subscriber FROM {$user_table}
              UNION ALL
              SELECT profile_id FROM activitypub_profile
            ) AS t1 USING (subscriber)
            END;
        $sub->whereAdd('subscriber <> subscribed');
        $cnt = $sub->count('DISTINCT subscriber');

        self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt);

        return $cnt;
    }

    /**
     * Getter for the number of subscriptions of a
     * given local profile
     *
     * @param Profile $profile profile object
     *
     * @return int number of subscriptions
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function subscriptionCount(Profile $profile): int
    {
        $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));

        if ($cnt !== false && is_int($cnt)) {
            return $cnt;
        }

        $user_table      = common_database_tablename('user');
        $sub             = new Subscription();
        $sub->subscriber = $profile->id;
        $sub->_join .= "\n" . <<<END
            INNER JOIN (
              SELECT id AS subscribed FROM {$user_table}
              UNION ALL
              SELECT profile_id FROM activitypub_profile
            ) AS t1 USING (subscribed)
            END;
        $sub->whereAdd('subscriber <> subscribed');
        $cnt = $sub->count('DISTINCT subscribed');

        self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt);

        return $cnt;
    }

    /**
     * Increment or decrement subscriber count
     *
     * @param Profile $profile
     * @param $adder
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function updateSubscriberCount(Profile $profile, $adder): void
    {
        $cnt = self::cacheGet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id));

        if ($cnt !== false && is_int($cnt)) {
            self::cacheSet(sprintf('activitypub_profile:subscriberCount:%d', $profile->id), $cnt + $adder);
        }
    }

    /**
     * Increment or decrement subscription count
     *
     * @param Profile $profile
     * @param $adder
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function updateSubscriptionCount(Profile $profile, $adder): void
    {
        $cnt = self::cacheGet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id));

        if ($cnt !== false && is_int($cnt)) {
            self::cacheSet(sprintf('activitypub_profile:subscriptionCount:%d', $profile->id), $cnt + $adder);
        }
    }

    /**
     * Getter for the subscriber profiles of a
     * given local profile
     *
     * @param Profile  $profile profile object
     * @param int      $offset  [optional] index of the starting row to fetch from
     * @param null|int $limit   [optional] maximum number of rows allowed for fetching. If it is omitted,
     *                          then the sequence will have everything
     *                          from offset up until the end.
     *
     * @return array subscriber profile objects
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function getSubscribers(Profile $profile, int $offset = 0, ?int $limit = null): array
    {
        $cache = false;
        if ($offset + $limit <= Subscription::CACHE_WINDOW) {
            $subs = self::cacheGet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id));
            if ($subs !== false && is_array($subs)) {
                return array_slice($subs, $offset, $limit);
            }

            $cache = true;
        }

        $subs     = Subscription::getSubscriberIDs($profile->id, $offset, $limit);
        $profiles = [];

        $users = User::multiGet('id', $subs);
        foreach ($users->fetchAll() as $user) {
            $profiles[$user->id] = $user->getProfile();
        }

        $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
        foreach ($ap_profiles->fetchAll() as $ap) {
            $profiles[$ap->getID()] = $ap->local_profile();
        }

        if ($cache) {
            self::cacheSet(sprintf('activitypub_profile:subscriberCollection:%d', $profile->id), $profiles);
        }

        return $profiles;
    }

    /**
     * Getter for the subscribed profiles of a
     * given local profile
     *
     * @param Profile  $profile profile object
     * @param int      $offset  index of the starting row to fetch from
     * @param null|int $limit   maximum number of rows allowed for fetching
     *
     * @return array subscribed profile objects
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function getSubscribed(Profile $profile, int $offset = 0, ?int $limit = null): array
    {
        $cache = false;
        if ($offset + $limit <= Subscription::CACHE_WINDOW) {
            $subs = self::cacheGet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id));
            if (is_array($subs)) {
                return array_slice($subs, $offset, $limit);
            }

            $cache = true;
        }

        $subs = Subscription::getSubscribedIDs($profile->id, $offset, $limit);

        $profiles = [];

        $users = User::multiGet('id', $subs);
        foreach ($users->fetchAll() as $user) {
            $profiles[$user->id] = $user->getProfile();
        }

        $ap_profiles = Activitypub_profile::multiGet('profile_id', $subs);
        foreach ($ap_profiles->fetchAll() as $ap) {
            $profiles[$ap->getID()] = $ap->local_profile();
        }

        if ($cache) {
            self::cacheSet(sprintf('activitypub_profile:subscribedCollection:%d', $profile->id), $profiles);
        }

        return $profiles;
    }

    /**
     * Update cached values that are relevant to
     * the users involved in a subscription
     *
     * @param Profile $actor subscriber profile object
     * @param Profile $other subscribed profile object
     *
     * @throws Exception
     *
     * @return void
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function subscribeCacheUpdate(Profile $actor, Profile $other): void
    {
        self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
        self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
        self::updateSubscriptionCount($actor, +1);
        self::updateSubscriberCount($other, +1);
    }

    /**
     * Update cached values that are relevant to
     * the users involved in an unsubscription
     *
     * @param Profile $actor subscriber profile object
     * @param Profile $other subscribed profile object
     *
     * @throws Exception
     *
     * @return void
     *
     * @author Bruno Casteleiro <brunoccast@fc.up.pt>
     */
    public static function unsubscribeCacheUpdate(Profile $actor, Profile $other): void
    {
        self::blow('activitypub_profile:subscribedCollection:%d', $actor->getID());
        self::blow('activitypub_profile:subscriberCollection:%d', $other->id);
        self::updateSubscriptionCount($actor, -1);
        self::updateSubscriberCount($other, -1);
    }

    public static function schemaDef()
    {
        return [
            'name'        => 'activitypub_actor',
            'description' => 'remote actor profiles',
            'fields'      => [
                'uri'            => ['type' => 'text', 'not null' => true],
                'profile_id'     => ['type' => 'int', 'not null' => true],
                'inboxuri'       => ['type' => 'text', 'not null' => true],
                'sharedInboxuri' => ['type' => 'text'],
                'created'        => ['type' => 'datetime', 'description' => 'date this record was created'],
                'modified'       => ['type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'],
            ],
            'primary key'  => ['profile_id'],
            'foreign keys' => [
                'activitypub_profile_profile_id_fkey' => ['profile', ['profile_id' => 'id']],
            ],
        ];
    }
}


code:
<?php

// {{{ License

// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

// }}}

/**
 * ActivityPub Assymetric Key Storage System
 *
 * @package   GNUsocial
 *
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @author    Hugo Sales <hugo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace Plugin\ActivityPub\Entity;

class ActivityPubCryptKey
{
    // {{{ Autocode

    private int $gsactor_id;
    private ?string $private_key;
    private string $public_key;
    private ?DateTimeInterface $created;
    private DateTimeInterface $modified;

    public function setGsactorId(int $gsactor_id): self
    {
        $this->gsactor_id = $gsactor_id;
        return $this;
    }

    public function getGsactorId(): int
    {
        return $this->gsactor_id;
    }

    public function setPrivateKey(?string $private_key): self
    {
        $this->private_key = $private_key;
        return $this;
    }

    public function getPrivateKey(): ?string
    {
        return $this->private_key;
    }

    public function setPublicKey(string $public_key): self
    {
        $this->public_key = $public_key;
        return $this;
    }

    public function getPublicKey(): string
    {
        return $this->public_key;
    }

    public function setCreated(?DateTimeInterface $created): self
    {
        $this->created = $created;
        return $this;
    }

    public function getCreated(): ?DateTimeInterface
    {
        return $this->created;
    }

    public function setModified(DateTimeInterface $modified): self
    {
        $this->modified = $modified;
        return $this;
    }

    public function getModified(): DateTimeInterface
    {
        return $this->modified;
    }

    // }}} Autocode

    /**
     * Private key getter
     *
     * @param Profile $profile
     *
     * @throws Exception Throws exception if tries to fetch a private key of an actor we don't own
     *
     * @return string The private key
     */
    public function get_private_key(Profile $profile): string
    {
        $this->profile_id = $profile->getID();
        $apRSA            = self::getKV('profile_id', $this->profile_id);
        if (!$apRSA instanceof Activitypub_rsa) {
            // Nonexistent key pair for this profile
            if ($profile->isLocal()) {
                self::generate_keys($this->private_key, $this->public_key);
                $this->store_keys();
                $apRSA->private_key = $this->private_key;
            } else {
                throw new Exception('This is a remote Profile, there is no Private Key for this Profile.');
            }
        }
        return $apRSA->private_key;
    }

    /**
     * Guarantees a Public Key for a given profile.
     *
     * @param Profile $profile
     * @param bool    $fetch=true Should attempt to fetch keys from a remote profile?
     *
     * @throws ServerException It should never occur, but if so, we break everything!
     * @throws Exception
     *
     * @return string The public key
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function ensure_public_key(Profile $profile, bool $fetch = true): string
    {
        $this->profile_id = $profile->getID();
        $apRSA            = self::getKV('profile_id', $this->profile_id);
        if (!$apRSA instanceof Activitypub_rsa) {
            // No existing key pair for this profile
            if ($profile->isLocal()) {
                self::generate_keys($this->private_key, $this->public_key);
                $this->store_keys();
                $apRSA->public_key = $this->public_key;
            } else {
                // ASSERT: This should never happen, but try to recover!
                common_log(LOG_ERR, 'Activitypub_rsa: An impossible thing has happened... Please let the devs know that it entered in line 116 at Activitypub_rsa.php');
                if ($fetch) {
                    $res = Activitypub_explorer::get_remote_user_activity($profile->getUri());
                    Activitypub_rsa::update_public_key($profile, $res['publicKey']['publicKeyPem']);
                    return self::ensure_public_key($profile, false);
                } else {
                    throw new ServerException('Activitypub_rsa: Failed to find keys for given profile. That should have not happened!');
                }
            }
        }
        return $apRSA->public_key;
    }

    /**
     * Insert the current object variables into the database.
     *
     * @throws ServerException
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function store_keys(): void
    {
        $this->created = $this->modified = common_sql_now();
        $ok            = $this->insert();
        if ($ok === false) {
            throw new ServerException('Cannot save ActivityPub RSA.');
        }
    }

    /**
     * Generates a pair of RSA keys.
     *
     * @param string $private_key out
     * @param string $public_key  out
     *
     * @author PHP Manual Contributed Notes <dirt@awoms.com>
     */
    public static function generate_keys(?string &$private_key, ?string &$public_key): void
    {
        $config = [
            'digest_alg'       => 'sha512',
            'private_key_bits' => 2048,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ];

        // Create the private and public key
        $res = openssl_pkey_new($config);

        // Extract the private key from $res to $private_key
        openssl_pkey_export($res, $private_key);

        // Extract the public key from $res to $pubKey
        $pubKey     = openssl_pkey_get_details($res);
        $public_key = $pubKey['key'];
        unset($pubKey);
    }

    /**
     * Update public key.
     *
     * @param Activitypub_profile|Profile $profile
     * @param string                      $public_key
     *
     * @throws Exception
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function update_public_key($profile, string $public_key): void
    {
        // Public Key
        $apRSA             = new Activitypub_rsa();
        $apRSA->profile_id = $profile->getID();
        $apRSA->public_key = $public_key;
        $apRSA->created    = common_sql_now();
        if (!$apRSA->update()) {
            $apRSA->insert();
        }
    }

    public static function schemaDef()
    {
        return [
            'name'        => 'activitypub_crypt_key',
            'description' => 'assymetric key storage for activitypub',
            'fields'      => [
                'gsactor_id'  => ['type' => 'int', 'not null' => true],
                'private_key' => ['type' => 'text'],
                'public_key'  => ['type' => 'text', 'not null' => true],
                'created'     => ['type' => 'datetime', 'description' => 'date this record was created'],
                'modified'    => ['type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'],
            ],
            'primary key'  => ['gsactor_id'],
            'foreign keys' => [
                'activitypub_rsa_gsactor_id_fkey' => ['gsactor', ['gsactor_id' => 'id']],
            ],
        ];
    }
}

repo_name: ksuudilla/gnu

license: mit


code:
<?php

// {{{ License

// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

// }}}

/**
 * ActivityPub's Pending follow requests
 *
 * @category  Plugin
 * @package   GNUsocial
 *
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @author    Hugo Sales <hugo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

namespace Plugin\ActivityPub\Entity;

class ActivityPubFollowRequests
{
    // {{{ Autocode

    private int $local_gsactor_id;
    private int $remote_gsactor_id;
    private int $relation_id;

    public function setLocalGsactorId(int $local_gsactor_id): self
    {
        $this->local_gsactor_id = $local_gsactor_id;
        return $this;
    }

    public function getLocalGsactorId(): int
    {
        return $this->local_gsactor_id;
    }

    public function setRemoteGsactorId(int $remote_gsactor_id): self
    {
        $this->remote_gsactor_id = $remote_gsactor_id;
        return $this;
    }

    public function getRemoteGsactorId(): int
    {
        return $this->remote_gsactor_id;
    }

    public function setRelationId(int $relation_id): self
    {
        $this->relation_id = $relation_id;
        return $this;
    }

    public function getRelationId(): int
    {
        return $this->relation_id;
    }

    // }}} Autocode

    public static function schemaDef()
    {
        return [
            'name'   => 'activitypub_pending_follow_requests',
            'fields' => [
                'local_gsactor_id'  => ['type' => 'int', 'not null' => true],
                'remote_gsactor_id' => ['type' => 'int', 'not null' => true],
                'relation_id'       => ['type' => 'serial', 'not null' => true],
            ],
            'primary key'  => ['relation_id'],
            'foreign keys' => [
                'activitypub_pending_follow_requests_local_gsactor_id_fkey'  => ['gsactor', ['local_gsactor_id' => 'id']],
                'activitypub_pending_follow_requests_remote_gsactor_id_fkey' => ['gsactor', ['remote_gsactor_id' => 'id']],
            ],
            'indexes' => [
                'activitypub_pending_follow_requests_local_gsactor_id_idx'  => ['local_gsactor_id'],
                'activitypub_pending_follow_requests_remote_gsactor_id_idx' => ['remote_gsactor_id'],
            ],
        ];
    }
}


code:
# ActivityPub plugin for GNU social
(c) 2018-2019 Free Software Foundation, Inc

This is the README file for GNU social's ActivityPub plugin.
It includes general information about the plugin.

## About

This plugin adds [ActivityPub](https://www.w3.org/TR/activitypub/) support to GNU social.

## Additional functionality

The RemoteFollow plugin is recommended as it increases the UX significatively,
it adds a remote follow button to user profiles.

## Credits

* **[Diogo Cordeiro](https://www.diogo.site/)**

## Special thanks

* **[Daniel Supernault](https://github.com/dansup)**
* **[Mikael Nordfeldth](https://mmn-o.se/)**

## License

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with this program, in the file "COPYING".  If not, see
<http://www.gnu.org/licenses/>.

    IMPORTANT NOTE: The GNU Affero General Public License (AGPL) has
    *different requirements* from the "regular" GPL. In particular, if
    you make modifications to the plugin source code on your server,
    you *MUST MAKE AVAILABLE* the modified version of the source code
    to your users under the same license. This is a legal requirement
    of using the software, and if you do not wish to share your
    modifications, *YOU MAY NOT USE THIS PLUGIN*.


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Actor's Followers Collection
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apActorFollowersAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Followers Collection request
     *
     * @return void
     * @throws Exception
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        try {
            $profile = Profile::getByID($this->trimmed('id'));
            $profile_id = $profile->getID();
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid Actor URI.', 404);
        }

        if (!$profile->isLocal()) {
            ActivityPubReturn::error("This is not a local user.", 403);
        }

        if (!isset($_GET["page"])) {
            $page = 0;
        } else {
            $page = intval($this->trimmed('page'));
        }

        if ($page < 0) {
            ActivityPubReturn::error('Invalid page number.');
        }

        $since = ($page - 1) * PROFILES_PER_MINILIST;
        $limit = PROFILES_PER_MINILIST;

        /* Calculate total items */
        $total_subs  = Activitypub_profile::subscriberCount($profile);
        $total_pages = ceil($total_subs / PROFILES_PER_MINILIST);

        $res = [
            '@context'     => [
              "https://www.w3.org/ns/activitystreams",
              "https://w3id.org/security/v1",
            ],
            'id'           => common_local_url('apActorFollowers', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
            'type'         => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
            'totalItems'   => $total_subs
        ];

        if ($page == 0) {
            $res['first'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'?page=1';
        } else {
            $res['orderedItems'] = $this->generate_followers($profile, $since, $limit);
            $res['partOf'] = common_local_url('apActorFollowers', ['id' => $profile_id]);

            if ($page+1 < $total_pages) {
                $res['next'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
            }

            if ($page > 1) {
                $res['prev'] = common_local_url('apActorFollowers', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
            }
        }

        ActivityPubReturn::answer($res);
    }

    /**
     * Generates a list of stalkers for a given profile.
     *
     * @param Profile $profile
     * @param int $since
     * @param int $limit
     * @return array of URIs
     * @throws Exception
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public static function generate_followers($profile, $since, $limit)
    {
        $subs = [];
        try {
            $sub = Activitypub_profile::getSubscribers($profile, $since, $limit);

            /* Get followers' URLs */
            foreach ($sub as $s) {
                $subs[] = $s->getUri();
            }
        } catch (NoResultException $e) {
            // Just let the exception go on its merry way
        }

        return $subs;
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Actor's Following Collection
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apActorFollowingAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Following Collection request
     *
     * @return void
     * @throws Exception
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        try {
            $profile = Profile::getByID($this->trimmed('id'));
            $profile_id = $profile->getID();
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid Actor URI.', 404);
        }

        if (!$profile->isLocal()) {
            ActivityPubReturn::error("This is not a local user.", 403);
        }

        if (!isset($_GET["page"])) {
            $page = 0;
        } else {
            $page = intval($this->trimmed('page'));
        }

        if ($page < 0) {
            ActivityPubReturn::error('Invalid page number.');
        }

        $since = ($page - 1) * PROFILES_PER_MINILIST;
        $limit = PROFILES_PER_MINILIST;

        /* Calculate total items */
        $total_subs  = Activitypub_profile::subscriptionCount($profile);
        $total_pages = ceil($total_subs / PROFILES_PER_MINILIST);

        $res = [
            '@context'     => [
              "https://www.w3.org/ns/activitystreams",
              "https://w3id.org/security/v1",
            ],
            'id'           => common_local_url('apActorFollowing', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
            'type'         => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
            'totalItems'   => $total_subs
        ];

        if ($page == 0) {
            $res['first'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'?page=1';
        } else {
            $res['orderedItems'] = $this->generate_following($profile, $since, $limit);
            $res['partOf'] = common_local_url('apActorFollowing', ['id' => $profile_id]);

            if ($page+1 < $total_pages) {
                $res['next'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
            }

            if ($page > 1) {
                $res['prev'] = common_local_url('apActorFollowing', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
            }
        }

        ActivityPubReturn::answer($res);
    }

    /**
     * Generates the list of those a given profile is stalking.
     *
     * @param Profile $profile
     * @param int $since
     * @param int $limit
     * @return array of URIs
     * @throws Exception
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function generate_following($profile, $since, $limit)
    {
        $subs = [];
        try {
            $sub = Activitypub_profile::getSubscribed($profile, $since, $limit);

            /* Get followed' URLs */
            foreach ($sub as $s) {
                $subs[] = $s->getUri();
            }
        } catch (NoResultException $e) {
            // Just let the exception go on its merry way
        }

        return $subs;
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Actor's Liked Collection
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apActorLikedAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Liked Collection request
     *
     * @return void
     * @throws EmptyPkeyValueException
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        try {
            $profile = Profile::getByID($this->trimmed('id'));
            $profile_id = $profile->getID();
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid Actor URI.', 404);
        }

        if (!$profile->isLocal()) {
            ActivityPubReturn::error("This is not a local user.", 403);
        }

        $limit    = intval($this->trimmed('limit'));
        $since_id = intval($this->trimmed('since_id'));
        $max_id   = intval($this->trimmed('max_id'));

        $limit    = empty($limit) ? 40 : $limit;       // Default is 40
        $since_id = empty($since_id) ? null : $since_id;
        $max_id   = empty($max_id) ? null : $max_id;

        // Max is 80
        if ($limit > 80) {
            $limit = 80;
        }

        $fave = $this->fetch_faves($profile_id, $limit, $since_id, $max_id);

        $faves = array();
        while ($fave->fetch()) {
            $faves[] = $this->pretty_fave(clone ($fave));
        }

        $res = [
            '@context'     => [
              "https://www.w3.org/ns/activitystreams",
              "https://w3id.org/security/v1",
            ],
            'id'           => common_local_url('apActorLiked', ['id' => $profile_id]),
            'type'         => 'OrderedCollection',
            'totalItems'   => Fave::countByProfile($profile),
            'orderedItems' => $faves
        ];

        ActivityPubReturn::answer($res);
    }

    /**
     * Take a fave object and turns it in a pretty array to be used
     * as a plugin answer
     *
     * @param Fave $fave_object
     * @return array pretty array representating a Fave
     * @throws EmptyPkeyValueException
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function pretty_fave($fave_object)
    {
        $res = [
            'created' => $fave_object->created,
            'object' => Activitypub_notice::notice_to_array(Notice::getByID($fave_object->notice_id))
        ];

        return $res;
    }

    /**
     * Fetch faves
     *
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     * @param int $user_id
     * @param int $limit
     * @param int $since_id
     * @param int $max_id
     * @return Fave fetchable fave collection
     */
    private static function fetch_faves(
        $user_id,
        $limit = 40,
        $since_id = null,
        $max_id = null
        ) {
        $fav = new Fave();

        $fav->user_id = $user_id;

        $fav->orderBy('modified DESC');

        if ($since_id != null) {
            $fav->whereAdd("notice_id  > {$since_id}");
        }

        if ($max_id != null) {
            $fav->whereAdd("notice_id  < {$max_id}");
        }

        $fav->limit($limit);

        $fav->find();

        return $fav;
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Inbox Request Handler
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apActorOutboxAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Outbox request
     *
     * @author Daniel Supernault <danielsupernault@gmail.com>
     */
    protected function handle()
    {
        try {
            $profile = Profile::getByID($this->trimmed('id'));
            $profile_id = $profile->getID();
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid Actor URI.', 404);
        }

        if (!$profile->isLocal()) {
            ActivityPubReturn::error("This is not a local user.", 403);
        }

        if (!isset($_GET["page"])) {
            $page = 0;
        } else {
            $page = intval($this->trimmed('page'));
        }

        if ($page < 0) {
            ActivityPubReturn::error('Invalid page number.');
        }

        $since = ($page - 1) * PROFILES_PER_MINILIST;
        $limit = (($page - 1) == 0 ? 1 : $page) * PROFILES_PER_MINILIST;

        /* Calculate total items */
        $total_notes = $profile->noticeCount();
        $total_pages = ceil($total_notes / PROFILES_PER_MINILIST);

        $res = [
            '@context'     => [
              "https://www.w3.org/ns/activitystreams",
              "https://w3id.org/security/v1",
            ],
            'id'           => common_local_url('apActorOutbox', ['id' => $profile_id]).(($page != 0) ? '?page='.$page : ''),
            'type'         => ($page == 0 ? 'OrderedCollection' : 'OrderedCollectionPage'),
            'totalItems'   => $total_notes
        ];

        if ($page == 0) {
            $res['first'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'?page=1';
        } else {
            $res['orderedItems'] = $this->generate_outbox($profile);
            $res['partOf'] = common_local_url('apActorOutbox', ['id' => $profile_id]);

            if ($page+1 < $total_pages) {
                $res['next'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'page='.($page+1 == 1 ? 2 : $page+1);
            }

            if ($page > 1) {
                $res['prev'] = common_local_url('apActorOutbox', ['id' => $profile_id]).'?page='.($page-1 <= 0 ? 1 : $page-1);
            }
        }

        ActivityPubReturn::answer($res);
    }

    /**
     * Generates a list of people following given profile.
     *
     * @param Profile $profile
     * @return array of Notices
     * @throws EmptyPkeyValueException
     * @throws InvalidUrlException
     * @throws ServerException
     * @author Daniel Supernault <danielsupernault@gmail.com>
     */
    public function generate_outbox($profile)
    {
        /* Fetch Notices */
        $notices = [];
        $notice = $profile->getNotices();
        while ($notice->fetch()) {
            $note = $notice;

            // TODO: Handle other types
            if ($note->object_type == 'http://activitystrea.ms/schema/1.0/note') {
                $notices[] = Activitypub_create::create_to_array(
                    $note->getProfile()->getUri(),
                    Activitypub_notice::notice_to_array($note)
                );
            }
        }

        return $notices;
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Actor's profile (Local users only)
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apActorProfileAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Actor Profile request
     *
     * @return void
     * @throws InvalidUrlException
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        if (!empty($id = $this->trimmed('id'))) {
            try {
                $profile = Profile::getByID($id);
            } catch (Exception $e) {
                ActivityPubReturn::error('Invalid Actor URI.', 404);
            }
            unset($id);
        } else {
            try {
                $profile = User::getByNickname($this->trimmed('nickname'))->getProfile();
            } catch (Exception $e) {
                ActivityPubReturn::error('Invalid username.', 404);
            }
        }

        if (!$profile->isLocal()) {
            ActivityPubReturn::error("This is not a local user.", 403);
        }

        $res = Activitypub_profile::profile_to_array($profile);

        ActivityPubReturn::answer($res, 200);
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Inbox Request Handler
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apInboxAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost = true;

    /**
     * Handle the Inbox request
     *
     * @return void
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        $path = !empty($this->trimmed('id')) ? common_local_url('apInbox', ['id' => $this->trimmed('id')]) : common_local_url('apInbox');
        $path = parse_url($path, PHP_URL_PATH);

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            ActivityPubReturn::error('Only POST requests allowed.');
        }

        common_debug('ActivityPub Inbox: Received a POST request.');
        $body = $data = file_get_contents('php://input');
        common_debug('ActivityPub Inbox: Request contents: ' . $data);
        $data = json_decode(file_get_contents('php://input'), true);

        if (!isset($data['actor'])) {
            ActivityPubReturn::error('Actor not found in the request.');
        }

        try {
            $actor = Activitypub_explorer::get_profile_from_url($data['actor']);
        } catch (HTTP_Request2_Exception $e) {
            ActivityPubReturn::error('Failed to retrieve remote actor information.');
        } catch (NoProfileException $e) {
            // Assert: This won't happen.
            common_log(LOG_ERR, 'PLEASE REPORT THIS: ActivityPub Inbox Handler failed with NoProfileException while retrieving remote actor information: ' . $e->getMessage());
            ActivityPubReturn::error('An unknown error has occurred. This was logged, please alert the sysadmin.');
        } catch (ServerException $e) {
            ActivityPubReturn::error('Could not store this remote actor.');
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid actor.');
        }
        try {
            $aprofile = Activitypub_profile::from_profile($actor);
        } catch (Exception $e) {
            // Assert: This won't happen.
            common_log(LOG_ERR, 'PLEASE REPORT THIS: ActivityPub Inbox Handler failed while retrieving AProfile from Profile: ' . $e->getMessage());
            ActivityPubReturn::error('An unknown error has occurred. This was logged, please alert the sysadmin.');
        }

        $actor_public_key = new Activitypub_rsa();
        $actor_public_key = $actor_public_key->ensure_public_key($actor);

        common_debug('ActivityPub Inbox: HTTP Signature: Validation will now start!');

        $headers = getallheaders();
        common_debug('ActivityPub Inbox: Request Headers: ' . print_r($headers, true));

        if (!isset($headers['Signature'])) {
            common_debug('ActivityPub Inbox: HTTP Signature: Missing Signature header.');
            ActivityPubReturn::error('Missing Signature header.', 400);
        }

        // Extract the signature properties
        $signatureData = HTTPSignature::parseSignatureHeader($headers['Signature']);
        common_debug('ActivityPub Inbox: HTTP Signature Data: ' . print_r($signatureData, true));
        if (isset($signatureData['error'])) {
            common_debug('ActivityPub Inbox: HTTP Signature: ' . json_encode($signatureData, true));
            ActivityPubReturn::error(json_encode($signatureData, true), 400);
        }

        list($verified, /*$headers*/) = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);

        // If the signature fails verification the first time, update profile as it might have changed public key
        if ($verified !== 1) {
            try {
                $res = Activitypub_explorer::get_remote_user_activity($aprofile->getUri());
            } catch (Exception $e) {
                ActivityPubReturn::error('Invalid remote actor.');
            }
            try {
                $actor = Activitypub_profile::update_profile($aprofile, $res);
            } catch (Exception $e) {
                ActivityPubReturn::error('Failed to updated remote actor information.');
            }
            $actor_public_key = new Activitypub_rsa();
            $actor_public_key = $actor_public_key->ensure_public_key($actor);
            list($verified, /*$headers*/) = HTTPSignature::verify($actor_public_key, $signatureData, $headers, $path, $body);
        }

        // If it still failed despite profile update
        if ($verified !== 1) {
            common_debug('ActivityPub Inbox: HTTP Signature: Invalid signature.');
            ActivityPubReturn::error('Invalid signature.');
        }

        // HTTP signature checked out, make sure the "actor" of the activity matches that of the signature
        common_debug('ActivityPub Inbox: HTTP Signature: Authorized request. Will now start the inbox handler.');

        try {
            new Activitypub_inbox_handler($data, $actor);
            ActivityPubReturn::answer();
        } catch (Exception $e) {
            ActivityPubReturn::error($e->getMessage());
        }
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Notice (Local notices only)
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class apNoticeAction extends ManagedAction
{
    protected $needLogin = false;
    protected $canPost   = true;

    /**
     * Handle the Notice request
     *
     * @return void
     * @throws EmptyPkeyValueException
     * @throws InvalidUrlException
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    protected function handle()
    {
        try {
            $notice = Notice::getByID($this->trimmed('id'));
        } catch (Exception $e) {
            ActivityPubReturn::error('Invalid Notice URI.', 404);
        }

        if (!$notice->isLocal()) {
            ActivityPubReturn::error("This is not a local notice.", 403);
        }

        $res = Activitypub_notice::notice_to_array($notice);

        ActivityPubReturn::answer($res);
    }
}


code:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>ActivityPub plugin for GNU Social API Documentation</title>
    <!-- needed for adaptive design -->
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <link rel="icon" href="https://git.gnu.io/gnu/gnu-social/raw/b286e8798b7f89cd72ef19dc335624100f43ce94/theme/neo-gnu/favicon.ico">
    <!--
    ReDoc doesn't change outer page styles
    -->
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <redoc spec-url='openapi.json'></redoc>
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
  </body>
</html>


code:
ActivityPub Plugin for GNU Social Doc
=====================================

## Contents

- [Objects](#entities)
    - [Attachment](#attachment)
    - [Error](#error)
    - [Image](#image)
    - [Notice](#notice)
    - [Profile](#profile)
    - [Tag](#tag)
- [Activities](#activities)
    - [Create](#create)
    - [Announce](#announce)
    - [Delete](#delete)
    - [Undo](#undo)
    - [Accept](#accept)
    - [Reject](#reject)
    - [Like](#like)
    - [Follow](#follow)

## Objects

### Attachment

| Attribute                | Description                                     | Nullable | Type    |
| ------------------------ | ----------------------------------------------- | -------- | ------- |
| `id`                     | ID of the attachment                            | no       | int32   |
| `mimetype`               | Mimetype                                        | no       | string  |
| `url`                    | URL of the locally hosted version of the image  | no       | string  |
| `meta`                   | See **attachment metadata** below               | yes      | Array   |
| `title`                  | Attachment title                                | no       | string  |

**Attachment metadata:**

Images may contain `width`, `height`, `size`.

### Error

The most important part of an error response is the HTTP status code. Standard semantics are followed. The body of an error is a JSON object with this structure:

| Attribute                | Description                         | Nullable | Type    |
| ------------------------ | ----------------------------------- | -------- | ------- |
| `error`                  | A textual description of the error  | no       | string  |

### Image

| Attribute                | Description     | Nullable | Type    |
| ------------------------ | --------------- | -------- | ------- |
| `type`                   | "Image"         | no       | string  |
| `width`                  | Image's width   | no       | int32   |
| `height`                 | Image's height  | no       | int32   |
| `url`                    | Image URL       | no       | string  |

### Notice

| Attribute                | Description                                       | Nullable | Type                                 |
| ------------------------ | ------------------------------------------------- | -------- | ------------------------------------ |
| `id`                     | Notice's URL                                      | no       | string                               |
| `type`                   | Notice's Type                                     | no       | string                               |
| `actor`                  | URL of Notice owner profile page (can be remote)  | no       | string                               |
| `published`              | DateTime of notice creation                       | no       | datetime                             |
| `to`                     | To                                                | no       | string                               |
| `cc`                     | CC                                                | no       | string                               |
| `content`                | Notice's Content in plain text                    | no       | string                               |
| `url`                    | Notice's URL                                      | no       | string                               |
| `reply_to`               | ID of the notice this replies                     | yes      | int32                                |
| `is_local`               | Boolean, true if local, false otherwise           | no       | bool                                 |
| `conversation`           | Notice conversation id                            | no       | int32                                |
| `attachment`             | Array of [Attachments](#attachment)               | no       | Array of [Attachments](#attachment)  |
| `tag`                    | Array of [Tags](#tag)                             | no       | Array of [Tags](#tag)                |

### Profile

| Attribute                | Description                                      | Nullable | Type             |
| ------------------------ | ------------------------------------------------ | -------- | ---------------- |
| `@context`               | Standard compliance                              | no       | string           |
| `id`                     | Actor's id                                       | no       | int32            |
| `type`                   | "Person"                                         | no       | string           |
| `nickname`               | Actor's nickname                                 | no       | string           |
| `is_local`               | True if local, false otherwise                   | no       | bool             |
| `inbox`                  | URL to Actor's inbox endpoint                    | no       | string           |
| `outbox`                 | URL to Actor's outbox endpoint                   | no       | string           |
| `display_name`           | The Actor's display name                         | no       | string           |
| `followers`              | URL to Actor's followers endpoint                | no       | string           |
| `followers_count`        | Total number of followers                        | no       | int32            |
| `following`              | URL to Actor's following endpoint                | no       | string           |
| `following_count`        | Total number of following                        | no       | int32            |
| `liked`                  | URL to Actor's Liked collection endpoint         | no       | string           |
| `liked_count`            | Total number of favorites                        | no       | int32            |
| `summary`                | Actor's biography                                | no       | string           |
| `url`                    | URL of the Actor's profile page (can be remote)  | no       | string           |
| `avatar`                 | Actor's avatar                                   | no       | [Image](#image)  |

### Tag

| Attribute                | Description                                  | Nullable | Type       |
| ------------------------ | -------------------------------------------- | -------- | ---------- |
| `name`                   | The hashtag, not including the preceding `#` | no       | string     |
| `url`                    | The URL of the hashtag                       | no       | string     |


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

/**
 * Utility class to hold a bunch of constant defining default verb types
 *
 * @category  Plugin
 * @package   GNUsocial
 * @author    Diogo Cordeiro <diogo@fc.up.pt>
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class Activitypub_activityverb2 extends Managed_DataObject
{
    const FULL_LIST =
    [
        'Accept'          => 'https://www.w3.org/ns/activitystreams#Accept',
        'TentativeAccept' => 'https://www.w3.org/ns/activitystreams#TentativeAccept',
        'Add'             => 'https://www.w3.org/ns/activitystreams#Add',
        'Arrive'          => 'https://www.w3.org/ns/activitystreams#Arrive',
        'Create'          => 'https://www.w3.org/ns/activitystreams#Create',
        'Delete'          => 'https://www.w3.org/ns/activitystreams#Delete',
        'Follow'          => 'https://www.w3.org/ns/activitystreams#Follow',
        'Ignore'          => 'https://www.w3.org/ns/activitystreams#Ignore',
        'Join'            => 'https://www.w3.org/ns/activitystreams#Join',
        'Leave'           => 'https://www.w3.org/ns/activitystreams#Leave',
        'Like'            => 'https://www.w3.org/ns/activitystreams#Like',
        'Offer'           => 'https://www.w3.org/ns/activitystreams#Offer',
        'Invite'          => 'https://www.w3.org/ns/activitystreams#Invite',
        'Reject'          => 'https://www.w3.org/ns/activitystreams#Reject',
        'TentativeReject' => 'https://www.w3.org/ns/activitystreams#TentativeReject',
        'Remove'          => 'https://www.w3.org/ns/activitystreams#Remove',
        'Undo'            => 'https://www.w3.org/ns/activitystreams#Undo',
        'Update'          => 'https://www.w3.org/ns/activitystreams#Update',
        'View'            => 'https://www.w3.org/ns/activitystreams#View',
        'Listen'          => 'https://www.w3.org/ns/activitystreams#Listen',
        'Read'            => 'https://www.w3.org/ns/activitystreams#Read',
        'Move'            => 'https://www.w3.org/ns/activitystreams#Move',
        'Travel'          => 'https://www.w3.org/ns/activitystreams#Travel',
        'Announce'        => 'https://www.w3.org/ns/activitystreams#Announce',
        'Block'           => 'https://www.w3.org/ns/activitystreams#Block',
        'Flag'            => 'https://www.w3.org/ns/activitystreams#Flag',
        'Dislike'         => 'https://www.w3.org/ns/activitystreams#Dislike',
        'Question'        => 'https://www.w3.org/ns/activitystreams#Question'
    ];

    const KNOWN =
    [
        'Accept',
        'Create',
        'Delete',
        'Follow',
        'Like',
        'Undo',
        'Announce'
    ];

    /**
     * Converts canonical into verb.
     *
     * @author GNU social
     * @param string $verb
     * @return string
     */
    public static function canonical($verb)
    {
        $ns = 'https://www.w3.org/ns/activitystreams#';
        if (substr($verb, 0, mb_strlen($ns)) == $ns) {
            return substr($verb, mb_strlen($ns));
        } else {
            return $verb;
        }
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub queue handler for notice distribution
 *
 * @package   GNUsocial
 * @author    Bruno Casteleiro <brunoccast@fc.up.pt>
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */

defined('GNUSOCIAL') || die();

/**
 * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 */
class ActivityPubQueueHandler extends QueueHandler
{
    /**
     * Getter of the queue transport name.
     *
     * @return string transport name
     */
    public function transport(): string
    {
        return 'activitypub';
    }

    /**
     * Notice distribution handler.
     *
     * @param Notice $notice notice to be distributed.
     * @return bool true on success, false otherwise
     * @throws HTTP_Request2_Exception
     * @throws InvalidUrlException
     * @throws ServerException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function handle($notice): bool
    {
        if (!($notice instanceof Notice)) {
            common_log(LOG_ERR, "Got a bogus notice, not distributing");
            return true;
        }

        $profile = $notice->getProfile();

        if (!$profile->isLocal()) {
            return true;
        }

        if ($notice->source == 'activity') {
            common_log(LOG_ERR, "Ignoring distribution of notice:{$notice->id}: activity source");
            return true;
        }

        $other = Activitypub_profile::from_profile_collection(
            $notice->getAttentionProfiles()
        );

        // Handling a Create?
        if (ActivityUtils::compareVerbs($notice->verb, [ActivityVerb::POST])) {
            return $this->handle_create($profile, $notice, $other);
        }

        // Handling a Like?
        if (ActivityUtils::compareVerbs($notice->verb, [ActivityVerb::FAVORITE])) {
            return $this->onEndFavorNotice($profile, $notice, $other);
        }

        // Handling a Undo Like?
        if (ActivityUtils::compareVerbs($notice->verb, [ActivityVerb::UNFAVORITE])) {
            return $this->onEndDisfavorNotice($profile, $notice, $other);
        }

        // Handling a Delete Note?
        if (ActivityUtils::compareVerbs($notice->verb, [ActivityVerb::DELETE])) {
            return $this->onStartDeleteOwnNotice($profile, $notice, $other);
        }

        return true;
    }

    private function handle_create($profile, $notice, $other)
    {
        // Handling a reply?
        if ($notice->reply_to) {
            try {
                $parent_notice = $notice->getParent();

                try {
                    $other[] = Activitypub_profile::from_profile($parent_notice->getProfile());
                } catch (Exception $e) {
                    // Local user can be ignored
                }

                foreach ($parent_notice->getAttentionProfiles() as $mention) {
                    try {
                        $other[] = Activitypub_profile::from_profile($mention);
                    } catch (Exception $e) {
                        // Local user can be ignored
                    }
                }
            } catch (NoParentNoticeException $e) {
                // This is not a reply to something (has no parent)
            } catch (NoResultException $e) {
                // Parent author's profile not found! Complain louder?
                common_log(
                    LOG_ERR,
                    "Parent notice's author not found: " . $e->getMessage()
                );
            }
        }

        // Handling an Announce?
        if ($notice->isRepeat()) {
            $repeated_notice = Notice::getKV('id', $notice->repeat_of);
            if ($repeated_notice instanceof Notice) {
                $other = array_merge(
                    $other,
                    Activitypub_profile::from_profile_collection(
                        $repeated_notice->getAttentionProfiles()
                    )
                );

                try {
                    $other[] = Activitypub_profile::from_profile(
                        $repeated_notice->getProfile()
                    );
                } catch (Exception $e) {
                    // Local user can be ignored
                }

                // That was it
                $postman = new Activitypub_postman($profile, $other);
                $postman->announce($repeated_notice);
            }

            // either made the announce or found nothing to repeat
            return true;
        }

        // That was it
        $postman = new Activitypub_postman($profile, $other);
        $postman->create_note($notice);
        return true;
    }

    /**
     * Notify remote users when their notices get favourited.
     *
     * @param Profile $profile of local user doing the faving
     * @param Notice $notice Notice being favored
     * @return bool return value
     * @throws HTTP_Request2_Exception
     * @throws InvalidUrlException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function onEndFavorNotice(Profile $profile, Notice $notice, $other)
    {
        if ($notice->reply_to) {
            try {
                $parent_notice = $notice->getParent();

                try {
                    $other[] = Activitypub_profile::from_profile($parent_notice->getProfile());
                } catch (Exception $e) {
                    // Local user can be ignored
                }

                $other = array_merge(
                    $other,
                    Activitypub_profile::from_profile_collection(
                        $parent_notice->getAttentionProfiles()
                    )
                );
            } catch (NoParentNoticeException $e) {
                // This is not a reply to something (has no parent)
            } catch (NoResultException $e) {
                // Parent author's profile not found! Complain louder?
                common_log(LOG_ERR, "Parent notice's author not found: ".$e->getMessage());
            }
        }

        $postman = new Activitypub_postman($profile, $other);
        $postman->like($notice);

        return true;
    }

    /**
     * Notify remote users when their notices get de-favourited.
     *
     * @param Profile $profile of local user doing the de-faving
     * @param Notice $notice Notice being favored
     * @return bool return value
     * @throws HTTP_Request2_Exception
     * @throws InvalidUrlException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function onEndDisfavorNotice(Profile $profile, Notice $notice, $other)
    {
        if ($notice->reply_to) {
            try {
                $parent_notice = $notice->getParent();

                try {
                    $other[] = Activitypub_profile::from_profile($parent_notice->getProfile());
                } catch (Exception $e) {
                    // Local user can be ignored
                }

                $other = array_merge(
                    $other,
                    Activitypub_profile::from_profile_collection(
                        $parent_notice->getAttentionProfiles()
                    )
                );
            } catch (NoParentNoticeException $e) {
                // This is not a reply to something (has no parent)
            } catch (NoResultException $e) {
                // Parent author's profile not found! Complain louder?
                common_log(LOG_ERR, "Parent notice's author not found: ".$e->getMessage());
            }
        }

        $postman = new Activitypub_postman($profile, $other);
        $postman->undo_like($notice);

        return true;
    }

    /**
     * Notify remote users when their notices get deleted
     *
     * @param $user
     * @param $notice
     * @return boolean hook flag
     * @throws HTTP_Request2_Exception
     * @throws InvalidUrlException
     * @author Diogo Cordeiro <diogo@fc.up.pt>
     */
    public function onStartDeleteOwnNotice($profile, $notice, $other)
    {
        // Handle delete locally either because:
        // 1. There's no undo-share logic yet
        // 2. The deleting user has privileges to do so (locally)
        if ($notice->isRepeat() || ($notice->getProfile()->getID() != $profile->getID())) {
            return true;
        }

        $other = Activitypub_profile::from_profile_collection(
            $notice->getAttentionProfiles()
        );

        if ($notice->reply_to) {
            try {
                $parent_notice = $notice->getParent();

                try {
                    $other[] = Activitypub_profile::from_profile($parent_notice->getProfile());
                } catch (Exception $e) {
                    // Local user can be ignored
                }

                $other = array_merge(
                    $other,
                    Activitypub_profile::from_profile_collection(
                        $parent_notice->getAttentionProfiles()
                    )
                );
            } catch (NoParentNoticeException $e) {
                // This is not a reply to something (has no parent)
            } catch (NoResultException $e) {
                // Parent author's profile not found! Complain louder?
                common_log(LOG_ERR, "Parent notice's author not found: ".$e->getMessage());
            }
        }

        $postman = new Activitypub_postman($profile, $other);
        $postman->delete_note($notice);
        return true;
    }
}


code:
<?php
// 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
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// 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/>.

/**
 * ActivityPub implementation for GNU social
 *
 * @package   GNUsocial
 * @author    Evan Prodromou
 * @author    Brion Vibber
 * @author    James Walker
 * @author    Siebrand Mazeland
 * @author    Mikael Nordfeldth
 * @author    Diogo Cordeiro
 * @copyright 2010-2019 Free Software Foundation, Inc http://www.fsf.org
 * @license   https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
 * @link      http://www.gnu.org/software/social/
 */

defined('GNUSOCIAL') || die();

class DiscoveryHints
{
    public static function fromXRD(XML_XRD $xrd)
    {
        $hints = [];

        if (Event::handle('StartDiscoveryHintsFromXRD', [$xrd, &$hints])) {
            foreach ($xrd->links as $link) {
                switch ($link->rel) {
                case WebFingerResource_Profile::PROFILEPAGE:
                    $hints['profileurl'] = $link->href;
                    break;
                case Discovery::UPDATESFROM:
                    if (empty($link->type) || $link->type == 'application/atom+xml') {
                        $hints['feedurl'] = $link->href;
                    }
                    break;
                case Discovery::HCARD:
                case Discovery::MF2_HCARD:
                    $hints['hcard'] = $link->href;
                    break;
                default:
                    break;
                }
            }
            Event::handle('EndDiscoveryHintsFromXRD', [$xrd, &$hints]);
        }

        return $hints;
    }

    public static function fromHcardUrl($url)
    {
        $client = new HTTPClient();
        $client->setHeader('Accept', 'text/html,application/xhtml+xml');
        try {
            $response = $client->get($url);

            if (!$response->isOk()) {
                return null;
            }
        } catch (HTTP_Request2_Exception $e) {
            // Any HTTPClient error that might've been thrown
            common_log(LOG_ERR, __METHOD__ . ':'.$e->getMessage());
            return null;
        }

        return self::hcardHints(
            $response->getBody(),
            $response->getEffectiveUrl()
        );
    }

    public static function hcardHints($body, $url)
    {
        $hcard = self::_hcard($body, $url);

        if (empty($hcard)) {
            return [];
        }

        $hints = [];

        // XXX: don't copy stuff into an array and then copy it again

        if (array_key_exists('nickname', $hcard) && !empty($hcard['nickname'][0])) {
            $hints['nickname'] = $hcard['nickname'][0];
        }

        if (array_key_exists('name', $hcard) && !empty($hcard['name'][0])) {
            $hints['fullname'] = $hcard['name'][0];
        }

        if (array_key_exists('photo', $hcard) && count($hcard['photo'])) {
            $hints['avatar'] = $hcard['photo'][0];
        }

        if (array_key_exists('note', $hcard) && !empty($hcard['note'][0])) {
            $hints['bio'] = $hcard['note'][0];
        }

        if (array_key_exists('adr', $hcard) && !empty($hcard['adr'][0])) {
            $hints['location'] = $hcard['adr'][0]['value'];
        }

        if (array_key_exists('url', $hcard) && !empty($hcard['url'][0])) {
            $hints['homepage'] = $hcard['url'][0];
        }

        return $hints;
    }

    public static function _hcard($body, $url)
    {
        $mf2 = new Mf2\Parser($body, $url);
        $mf2 = $mf2->parse();

        if (empty($mf2['items'])) {
            return null;
        }

        $hcards = [];

        foreach ($mf2['items'] as $item) {
            if (!in_array('h-card', $item['type'])) {
                continue;
            }

            // We found a match, return it immediately
            if (isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
                return $item['properties'];
            }

            // Let's keep all the hcards for later, to return one of them at least
            $hcards[] = $item['properties'];
        }

        // No match immediately for the url we expected, but there were h-cards found
        if (count($hcards) > 0) {
            return $hcards[0];
        }

        return null;
    }
}