]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge pull request #13629 from annando/transmitted-languages
[friendica.git] / src / Protocol / ActivityPub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Model\APContact;
28 use Friendica\Model\Contact;
29 use Friendica\Model\User;
30 use Friendica\Util\HTTPSignature;
31 use Friendica\Util\JsonLD;
32
33 /**
34  * ActivityPub Protocol class
35  *
36  * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
37  * https://www.w3.org/TR/activitypub/
38  * https://www.w3.org/TR/activitystreams-core/
39  * https://www.w3.org/TR/activitystreams-vocabulary/
40  *
41  * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
42  * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
43  *
44  * Digest: https://tools.ietf.org/html/rfc5843
45  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
46  *
47  * Mastodon implementation of supported activities:
48  * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
49  *
50  * Funkwhale:
51  * http://docs-funkwhale-funkwhale-549-music-federation-documentation.preview.funkwhale.audio/federation/index.html
52  *
53  * To-do:
54  * - Polling the outboxes for missing content?
55  *
56  * Missing parts from DFRN:
57  * - Public Group
58  * - Private Group
59  * - Relocation
60  */
61 class ActivityPub
62 {
63         const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
64         const CONTEXT = [
65                 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
66                 [
67                         'vcard' => 'http://www.w3.org/2006/vcard/ns#',
68                         'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/',
69                         'diaspora' => 'https://diasporafoundation.org/ns/',
70                         'litepub' => 'http://litepub.social/ns#',
71                         'toot' => 'http://joinmastodon.org/ns#',
72                         'featured' => [
73                                 "@id" => "toot:featured",
74                                 "@type" => "@id",
75                         ],
76                         'schema' => 'http://schema.org#',
77                         'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
78                         'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
79                         'quoteUrl' => 'as:quoteUrl',
80                         'conversation' => 'ostatus:conversation',
81                         'directMessage' => 'litepub:directMessage',
82                         'discoverable' => 'toot:discoverable',
83                         'PropertyValue' => 'schema:PropertyValue',
84                         'value' => 'schema:value',
85                 ]
86         ];
87         const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
88         /**
89          * Checks if the web request is done for the AP protocol
90          *
91          * @return bool is it AP?
92          */
93         public static function isRequest(): bool
94         {
95                 header('Vary: Accept', false);
96
97                 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
98                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
99                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
100
101                 if ($isrequest) {
102                         Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
103                 }
104
105                 return $isrequest;
106         }
107
108         private static function getAccountType(array $apcontact): int
109         {
110                 $accounttype = -1;
111
112                 switch ($apcontact['type']) {
113                         case 'Person':
114                                 $accounttype = User::ACCOUNT_TYPE_PERSON;
115                                 break;
116                         case 'Organization':
117                                 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
118                                 break;
119                         case 'Service':
120                                 $accounttype = User::ACCOUNT_TYPE_NEWS;
121                                 break;
122                         case 'Group':
123                                 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
124                                 break;
125                         case 'Application':
126                                 $accounttype = User::ACCOUNT_TYPE_RELAY;
127                                 break;
128                         case 'Tombstone':
129                                 $accounttype = User::ACCOUNT_TYPE_DELETED;
130                                 break;
131                 }
132
133                 return $accounttype;
134         }
135
136         /**
137          * Fetches a profile from the given url into an array that is compatible to Probe::uri
138          *
139          * @param string  $url    profile url
140          * @param boolean $update Update the profile
141          * @return array
142          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
143          * @throws \ImagickException
144          */
145         public static function probeProfile(string $url, bool $update = true): array
146         {
147                 $apcontact = APContact::getByURL($url, $update);
148                 if (empty($apcontact)) {
149                         return [];
150                 }
151
152                 $profile = ['network' => Protocol::ACTIVITYPUB];
153                 $profile['nick'] = $apcontact['nick'];
154                 $profile['name'] = $apcontact['name'];
155                 $profile['guid'] = $apcontact['uuid'];
156                 $profile['url'] = $apcontact['url'];
157                 $profile['addr'] = $apcontact['addr'];
158                 $profile['alias'] = $apcontact['alias'];
159                 $profile['following'] = $apcontact['following'];
160                 $profile['followers'] = $apcontact['followers'];
161                 $profile['inbox'] = $apcontact['inbox'];
162                 $profile['outbox'] = $apcontact['outbox'];
163                 $profile['sharedinbox'] = $apcontact['sharedinbox'];
164                 $profile['photo'] = $apcontact['photo'];
165                 $profile['header'] = $apcontact['header'];
166                 $profile['account-type'] = self::getAccountType($apcontact);
167                 $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
168                 // $profile['keywords']
169                 // $profile['location']
170                 $profile['about'] = $apcontact['about'];
171                 $profile['xmpp'] = $apcontact['xmpp'];
172                 $profile['matrix'] = $apcontact['matrix'];
173                 $profile['batch'] = $apcontact['sharedinbox'];
174                 $profile['notify'] = $apcontact['inbox'];
175                 $profile['poll'] = $apcontact['outbox'];
176                 $profile['pubkey'] = $apcontact['pubkey'];
177                 $profile['subscribe'] = $apcontact['subscribe'];
178                 $profile['manually-approve'] = $apcontact['manually-approve'];
179                 $profile['baseurl'] = $apcontact['baseurl'];
180                 $profile['gsid'] = $apcontact['gsid'];
181
182                 if (!is_null($apcontact['discoverable'])) {
183                         $profile['hide'] = !$apcontact['discoverable'];
184                 }
185
186                 // Remove all "null" fields
187                 foreach ($profile as $field => $content) {
188                         if (is_null($content)) {
189                                 unset($profile[$field]);
190                         }
191                 }
192
193                 return $profile;
194         }
195
196         /**
197          * Fetches activities from the outbox of a given profile and processes it
198          *
199          * @param string  $url
200          * @param integer $uid User ID
201          * @return void
202          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203          */
204         public static function fetchOutbox(string $url, int $uid)
205         {
206                 $data = HTTPSignature::fetch($url, $uid);
207                 if (empty($data)) {
208                         return;
209                 }
210
211                 if (!empty($data['orderedItems'])) {
212                         $items = $data['orderedItems'];
213                 } elseif (!empty($data['first']['orderedItems'])) {
214                         $items = $data['first']['orderedItems'];
215                 } elseif (!empty($data['first'])) {
216                         self::fetchOutbox($data['first'], $uid);
217                         return;
218                 } else {
219                         $items = [];
220                 }
221
222                 foreach ($items as $activity) {
223                         $ldactivity = JsonLD::compact($activity);
224                         ActivityPub\Receiver::processActivity($ldactivity, '', $uid, true);
225                 }
226         }
227
228         /**
229          * Fetch items from AP endpoints
230          *
231          * @param string $url              Address of the endpoint
232          * @param integer $uid             Optional user id
233          * @param integer $start_timestamp Internally used parameter to stop fetching after some time
234          * @return array Endpoint items
235          */
236         public static function fetchItems(string $url, int $uid = 0, int $start_timestamp = 0): array
237         {
238                 $start_timestamp = $start_timestamp ?: time();
239
240                 if ((time() - $start_timestamp) > 60) {
241                         Logger::info('Fetch time limit reached', ['url' => $url, 'uid' => $uid]);
242                         return [];
243                 }
244
245                 $data = HTTPSignature::fetch($url, $uid);
246                 if (empty($data)) {
247                         return [];
248                 }
249
250                 if (!empty($data['orderedItems'])) {
251                         $items = $data['orderedItems'];
252                 } elseif (!empty($data['first']['orderedItems'])) {
253                         $items = $data['first']['orderedItems'];
254                 } elseif (!empty($data['first']) && is_string($data['first']) && ($data['first'] != $url)) {
255                         return self::fetchItems($data['first'], $uid, $start_timestamp);
256                 } else {
257                         return [];
258                 }
259
260                 if (!empty($data['next']) && is_string($data['next'])) {
261                         $items = array_merge($items, self::fetchItems($data['next'], $uid, $start_timestamp));
262                 }
263
264                 return $items;
265         }
266
267         /**
268          * Checks if the given contact url does support ActivityPub
269          *
270          * @param string  $url    profile url
271          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
272          * @return boolean
273          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274          * @throws \ImagickException
275          */
276         public static function isSupportedByContactUrl(string $url, $update = null): bool
277         {
278                 return !empty(APContact::getByURL($url, $update));
279         }
280
281         public static function isAcceptedRequester(int $uid = 0): bool
282         {
283                 $called_by = System::callstack(1);
284
285                 $signer = HTTPSignature::getSigner('', $_SERVER);
286                 if (!$signer) {
287                         Logger::debug('No signer or invalid signature', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]);
288                         return false;
289                 }
290
291                 $apcontact = APContact::getByURL($signer);
292                 if (empty($apcontact)) {
293                         Logger::info('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]);
294                         return false;
295                 }
296
297                 if (empty($apcontact['gsid'] || empty($apcontact['baseurl']))) {
298                         Logger::debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]);
299                         return false;
300                 }
301
302                 $contact = Contact::getByURL($signer, false, ['id', 'baseurl', 'gsid']);
303                 if (!empty($contact) && Contact\User::isBlocked($contact['id'], $uid)) {
304                         Logger::info('Requesting contact is blocked', ['uid' => $uid, 'id' => $contact['id'], 'signer' => $signer, 'baseurl' => $contact['baseurl'], 'called_by' => $called_by]);
305                         return false;
306                 }
307
308                 // @todo Look for user blocked domains
309
310                 Logger::debug('Server is an accepted requester', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]);
311
312                 return true;
313         }
314 }