]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge pull request #13773 from annando/user-self
[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\DI;
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;
33
34 /**
35  * ActivityPub Protocol class
36  *
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/
41  *
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/
44  *
45  * Digest: https://tools.ietf.org/html/rfc5843
46  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
47  *
48  * Mastodon implementation of supported activities:
49  * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
50  *
51  * Funkwhale:
52  * http://docs-funkwhale-funkwhale-549-music-federation-documentation.preview.funkwhale.audio/federation/index.html
53  *
54  * To-do:
55  * - Polling the outboxes for missing content?
56  *
57  * Missing parts from DFRN:
58  * - Public Group
59  * - Private Group
60  * - Relocation
61  */
62 class ActivityPub
63 {
64         const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
65         const CONTEXT = [
66                 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
67                 [
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#',
73                         'featured' => [
74                                 "@id" => "toot:featured",
75                                 "@type" => "@id",
76                         ],
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',
86                 ]
87         ];
88         const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
89         /**
90          * Checks if the web request is done for the AP protocol
91          *
92          * @return bool is it AP?
93          */
94         public static function isRequest(): bool
95         {
96                 header('Vary: Accept', false);
97
98                 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
99                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
100                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
101
102                 if ($isrequest) {
103                         Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
104                 }
105
106                 return $isrequest;
107         }
108
109         private static function getAccountType(array $apcontact): int
110         {
111                 $accounttype = -1;
112
113                 switch ($apcontact['type']) {
114                         case 'Person':
115                                 $accounttype = User::ACCOUNT_TYPE_PERSON;
116                                 break;
117                         case 'Organization':
118                                 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
119                                 break;
120                         case 'Service':
121                                 $accounttype = User::ACCOUNT_TYPE_NEWS;
122                                 break;
123                         case 'Group':
124                                 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
125                                 break;
126                         case 'Application':
127                                 $accounttype = User::ACCOUNT_TYPE_RELAY;
128                                 break;
129                         case 'Tombstone':
130                                 $accounttype = User::ACCOUNT_TYPE_DELETED;
131                                 break;
132                 }
133
134                 return $accounttype;
135         }
136
137         /**
138          * Fetches a profile from the given url into an array that is compatible to Probe::uri
139          *
140          * @param string  $url    profile url
141          * @param boolean $update Update the profile
142          * @return array
143          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144          * @throws \ImagickException
145          */
146         public static function probeProfile(string $url, bool $update = true): array
147         {
148                 $apcontact = APContact::getByURL($url, $update);
149                 if (empty($apcontact)) {
150                         return [];
151                 }
152
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'];
182
183                 if (!is_null($apcontact['discoverable'])) {
184                         $profile['hide'] = !$apcontact['discoverable'];
185                 }
186
187                 // Remove all "null" fields
188                 foreach ($profile as $field => $content) {
189                         if (is_null($content)) {
190                                 unset($profile[$field]);
191                         }
192                 }
193
194                 return $profile;
195         }
196
197         /**
198          * Fetches activities from the outbox of a given profile and processes it
199          *
200          * @param string  $url
201          * @param integer $uid User ID
202          * @return void
203          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
204          */
205         public static function fetchOutbox(string $url, int $uid)
206         {
207                 $data = HTTPSignature::fetch($url, $uid);
208                 if (empty($data)) {
209                         return;
210                 }
211
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);
218                         return;
219                 } else {
220                         $items = [];
221                 }
222
223                 foreach ($items as $activity) {
224                         $ldactivity = JsonLD::compact($activity);
225                         ActivityPub\Receiver::processActivity($ldactivity, '', $uid, true);
226                 }
227         }
228
229         /**
230          * Fetch items from AP endpoints
231          *
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
236          */
237         public static function fetchItems(string $url, int $uid = 0, int $start_timestamp = 0): array
238         {
239                 $start_timestamp = $start_timestamp ?: time();
240
241                 if ((time() - $start_timestamp) > 60) {
242                         Logger::info('Fetch time limit reached', ['url' => $url, 'uid' => $uid]);
243                         return [];
244                 }
245
246                 $data = HTTPSignature::fetch($url, $uid);
247                 if (empty($data)) {
248                         return [];
249                 }
250
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);
257                 } else {
258                         return [];
259                 }
260
261                 if (!empty($data['next']) && is_string($data['next'])) {
262                         $items = array_merge($items, self::fetchItems($data['next'], $uid, $start_timestamp));
263                 }
264
265                 return $items;
266         }
267
268         /**
269          * Checks if the given contact url does support ActivityPub
270          *
271          * @param string  $url    profile url
272          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
273          * @return boolean
274          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275          * @throws \ImagickException
276          */
277         public static function isSupportedByContactUrl(string $url, $update = null): bool
278         {
279                 return !empty(APContact::getByURL($url, $update));
280         }
281
282         public static function isAcceptedRequester(int $uid = 0): bool
283         {
284                 $called_by = System::callstack(1);
285
286                 $signer = HTTPSignature::getSigner('', $_SERVER);
287                 if (!$signer) {
288                         Logger::debug('No signer or invalid signature', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]);
289                         return false;
290                 }
291
292                 $apcontact = APContact::getByURL($signer);
293                 if (empty($apcontact)) {
294                         Logger::info('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]);
295                         return false;
296                 }
297
298                 if (empty($apcontact['gsid'] || empty($apcontact['baseurl']))) {
299                         Logger::debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]);
300                         return false;
301                 }
302
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]);
306                         return false;
307                 }
308
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)) {
314                                 return false;
315                         }
316                 }
317
318                 if (DI::userGServer()->isIgnoredByUser($uid, $apcontact['gsid'])) {
319                         return false;
320                 }
321
322                 Logger::debug('Server is an accepted requester', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]);
323
324                 return true;
325         }
326 }