3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
28 use Friendica\Model\APContact;
29 use Friendica\Model\Contact;
30 use Friendica\Model\User;
31 use Friendica\Util\HTTPSignature;
32 use Friendica\Util\JsonLD;
35 * ActivityPub Protocol class
37 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
38 * https://www.w3.org/TR/activitypub/
39 * https://www.w3.org/TR/activitystreams-core/
40 * https://www.w3.org/TR/activitystreams-vocabulary/
42 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
43 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
45 * Digest: https://tools.ietf.org/html/rfc5843
46 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
48 * Mastodon implementation of supported activities:
49 * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
52 * http://docs-funkwhale-funkwhale-549-music-federation-documentation.preview.funkwhale.audio/federation/index.html
55 * - Polling the outboxes for missing content?
57 * Missing parts from DFRN:
64 const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
66 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
68 'vcard' => 'http://www.w3.org/2006/vcard/ns#',
69 'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/',
70 'diaspora' => 'https://diasporafoundation.org/ns/',
71 'litepub' => 'http://litepub.social/ns#',
72 'toot' => 'http://joinmastodon.org/ns#',
74 "@id" => "toot:featured",
77 'schema' => 'http://schema.org#',
78 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
79 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
80 'quoteUrl' => 'as:quoteUrl',
81 'conversation' => 'ostatus:conversation',
82 'directMessage' => 'litepub:directMessage',
83 'discoverable' => 'toot:discoverable',
84 'PropertyValue' => 'schema:PropertyValue',
85 'value' => 'schema:value',
88 const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
90 * Checks if the web request is done for the AP protocol
92 * @return bool is it AP?
94 public static function isRequest(): bool
96 header('Vary: Accept', false);
98 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
99 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
100 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
103 Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
109 private static function getAccountType(array $apcontact): int
113 switch ($apcontact['type']) {
115 $accounttype = User::ACCOUNT_TYPE_PERSON;
118 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
121 $accounttype = User::ACCOUNT_TYPE_NEWS;
124 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
127 $accounttype = User::ACCOUNT_TYPE_RELAY;
130 $accounttype = User::ACCOUNT_TYPE_DELETED;
138 * Fetches a profile from the given url into an array that is compatible to Probe::uri
140 * @param string $url profile url
141 * @param boolean $update Update the profile
143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144 * @throws \ImagickException
146 public static function probeProfile(string $url, bool $update = true): array
148 $apcontact = APContact::getByURL($url, $update);
149 if (empty($apcontact)) {
153 $profile = ['network' => Protocol::ACTIVITYPUB];
154 $profile['nick'] = $apcontact['nick'];
155 $profile['name'] = $apcontact['name'];
156 $profile['guid'] = $apcontact['uuid'];
157 $profile['url'] = $apcontact['url'];
158 $profile['addr'] = $apcontact['addr'];
159 $profile['alias'] = $apcontact['alias'];
160 $profile['following'] = $apcontact['following'];
161 $profile['followers'] = $apcontact['followers'];
162 $profile['inbox'] = $apcontact['inbox'];
163 $profile['outbox'] = $apcontact['outbox'];
164 $profile['sharedinbox'] = $apcontact['sharedinbox'];
165 $profile['photo'] = $apcontact['photo'];
166 $profile['header'] = $apcontact['header'];
167 $profile['account-type'] = self::getAccountType($apcontact);
168 $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
169 // $profile['keywords']
170 // $profile['location']
171 $profile['about'] = $apcontact['about'];
172 $profile['xmpp'] = $apcontact['xmpp'];
173 $profile['matrix'] = $apcontact['matrix'];
174 $profile['batch'] = $apcontact['sharedinbox'];
175 $profile['notify'] = $apcontact['inbox'];
176 $profile['poll'] = $apcontact['outbox'];
177 $profile['pubkey'] = $apcontact['pubkey'];
178 $profile['subscribe'] = $apcontact['subscribe'];
179 $profile['manually-approve'] = $apcontact['manually-approve'];
180 $profile['baseurl'] = $apcontact['baseurl'];
181 $profile['gsid'] = $apcontact['gsid'];
183 if (!is_null($apcontact['discoverable'])) {
184 $profile['hide'] = !$apcontact['discoverable'];
187 // Remove all "null" fields
188 foreach ($profile as $field => $content) {
189 if (is_null($content)) {
190 unset($profile[$field]);
198 * Fetches activities from the outbox of a given profile and processes it
201 * @param integer $uid User ID
203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
205 public static function fetchOutbox(string $url, int $uid)
207 $data = HTTPSignature::fetch($url, $uid);
212 if (!empty($data['orderedItems'])) {
213 $items = $data['orderedItems'];
214 } elseif (!empty($data['first']['orderedItems'])) {
215 $items = $data['first']['orderedItems'];
216 } elseif (!empty($data['first'])) {
217 self::fetchOutbox($data['first'], $uid);
223 foreach ($items as $activity) {
224 $ldactivity = JsonLD::compact($activity);
225 ActivityPub\Receiver::processActivity($ldactivity, '', $uid, true);
230 * Fetch items from AP endpoints
232 * @param string $url Address of the endpoint
233 * @param integer $uid Optional user id
234 * @param integer $start_timestamp Internally used parameter to stop fetching after some time
235 * @return array Endpoint items
237 public static function fetchItems(string $url, int $uid = 0, int $start_timestamp = 0): array
239 $start_timestamp = $start_timestamp ?: time();
241 if ((time() - $start_timestamp) > 60) {
242 Logger::info('Fetch time limit reached', ['url' => $url, 'uid' => $uid]);
246 $data = HTTPSignature::fetch($url, $uid);
251 if (!empty($data['orderedItems'])) {
252 $items = $data['orderedItems'];
253 } elseif (!empty($data['first']['orderedItems'])) {
254 $items = $data['first']['orderedItems'];
255 } elseif (!empty($data['first']) && is_string($data['first']) && ($data['first'] != $url)) {
256 return self::fetchItems($data['first'], $uid, $start_timestamp);
261 if (!empty($data['next']) && is_string($data['next'])) {
262 $items = array_merge($items, self::fetchItems($data['next'], $uid, $start_timestamp));
269 * Checks if the given contact url does support ActivityPub
271 * @param string $url profile url
272 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275 * @throws \ImagickException
277 public static function isSupportedByContactUrl(string $url, $update = null): bool
279 return !empty(APContact::getByURL($url, $update));
282 public static function isAcceptedRequester(int $uid = 0): bool
284 $called_by = System::callstack(1);
286 $signer = HTTPSignature::getSigner('', $_SERVER);
288 Logger::debug('No signer or invalid signature', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]);
292 $apcontact = APContact::getByURL($signer);
293 if (empty($apcontact)) {
294 Logger::info('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]);
298 if (empty($apcontact['gsid'] || empty($apcontact['baseurl']))) {
299 Logger::debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]);
303 $contact = Contact::getByURL($signer, false, ['id', 'baseurl', 'gsid']);
304 if (!empty($contact) && Contact\User::isBlocked($contact['id'], $uid)) {
305 Logger::info('Requesting contact is blocked', ['uid' => $uid, 'id' => $contact['id'], 'signer' => $signer, 'baseurl' => $contact['baseurl'], 'called_by' => $called_by]);
309 $limited = DI::config()->get('system', 'limited_servers');
310 if (!empty($limited)) {
311 $servers = explode(',', str_replace(' ', '', $limited));
312 $host = parse_url($apcontact['baseurl'], PHP_URL_HOST);
313 if (!empty($host) && in_array($host, $servers)) {
318 // @todo Look for user blocked domains
320 Logger::debug('Server is an accepted requester', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]);