]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge remote-tracking branch 'upstream/develop' into restricted-access
[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 use Friendica\Util\Network;
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 = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
66                 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
67                 'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/',
68                 'diaspora' => 'https://diasporafoundation.org/ns/',
69                 'litepub' => 'http://litepub.social/ns#',
70                 'toot' => 'http://joinmastodon.org/ns#',
71                 'featured' => [
72                         "@id" => "toot:featured",
73                         "@type" => "@id",
74                 ],
75                 'schema' => 'http://schema.org#',
76                 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
77                 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
78                 'quoteUrl' => 'as:quoteUrl',
79                 'conversation' => 'ostatus:conversation',
80                 'directMessage' => 'litepub:directMessage',
81                 'discoverable' => 'toot:discoverable',
82                 'PropertyValue' => 'schema:PropertyValue',
83                 'value' => 'schema:value',
84         ]];
85         const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
86         /**
87          * Checks if the web request is done for the AP protocol
88          *
89          * @return bool is it AP?
90          */
91         public static function isRequest(): bool
92         {
93                 header('Vary: Accept', false);
94
95                 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
96                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
97                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
98
99                 if ($isrequest) {
100                         Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
101                 }
102
103                 return $isrequest;
104         }
105
106         /**
107          * Fetches ActivityPub content from the given url
108          *
109          * @param string  $url content url
110          * @param integer $uid User ID for the signature
111          * @return array
112          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
113          */
114         public static function fetchContent(string $url, int $uid = 0): array
115         {
116                 return HTTPSignature::fetch($url, $uid);
117         }
118
119         private static function getAccountType(array $apcontact): int
120         {
121                 $accounttype = -1;
122
123                 switch($apcontact['type']) {
124                         case 'Person':
125                                 $accounttype = User::ACCOUNT_TYPE_PERSON;
126                                 break;
127                         case 'Organization':
128                                 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
129                                 break;
130                         case 'Service':
131                                 $accounttype = User::ACCOUNT_TYPE_NEWS;
132                                 break;
133                         case 'Group':
134                                 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
135                                 break;
136                         case 'Application':
137                                 $accounttype = User::ACCOUNT_TYPE_RELAY;
138                                 break;
139                         case 'Tombstone':
140                                 $accounttype = User::ACCOUNT_TYPE_DELETED;
141                                 break;
142                 }
143
144                 return $accounttype;
145         }
146
147         /**
148          * Fetches a profile from the given url into an array that is compatible to Probe::uri
149          *
150          * @param string  $url    profile url
151          * @param boolean $update Update the profile
152          * @return array
153          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154          * @throws \ImagickException
155          */
156         public static function probeProfile(string $url, bool $update = true): array
157         {
158                 $apcontact = APContact::getByURL($url, $update);
159                 if (empty($apcontact)) {
160                         return [];
161                 }
162
163                 $profile = ['network' => Protocol::ACTIVITYPUB];
164                 $profile['nick'] = $apcontact['nick'];
165                 $profile['name'] = $apcontact['name'];
166                 $profile['guid'] = $apcontact['uuid'];
167                 $profile['url'] = $apcontact['url'];
168                 $profile['addr'] = $apcontact['addr'];
169                 $profile['alias'] = $apcontact['alias'];
170                 $profile['following'] = $apcontact['following'];
171                 $profile['followers'] = $apcontact['followers'];
172                 $profile['inbox'] = $apcontact['inbox'];
173                 $profile['outbox'] = $apcontact['outbox'];
174                 $profile['sharedinbox'] = $apcontact['sharedinbox'];
175                 $profile['photo'] = $apcontact['photo'];
176                 $profile['header'] = $apcontact['header'];
177                 $profile['account-type'] = self::getAccountType($apcontact);
178                 $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
179                 // $profile['keywords']
180                 // $profile['location']
181                 $profile['about'] = $apcontact['about'];
182                 $profile['xmpp'] = $apcontact['xmpp'];
183                 $profile['matrix'] = $apcontact['matrix'];
184                 $profile['batch'] = $apcontact['sharedinbox'];
185                 $profile['notify'] = $apcontact['inbox'];
186                 $profile['poll'] = $apcontact['outbox'];
187                 $profile['pubkey'] = $apcontact['pubkey'];
188                 $profile['subscribe'] = $apcontact['subscribe'];
189                 $profile['manually-approve'] = $apcontact['manually-approve'];
190                 $profile['baseurl'] = $apcontact['baseurl'];
191                 $profile['gsid'] = $apcontact['gsid'];
192
193                 if (!is_null($apcontact['discoverable'])) {
194                         $profile['hide'] = !$apcontact['discoverable'];
195                 }
196
197                 // Remove all "null" fields
198                 foreach ($profile as $field => $content) {
199                         if (is_null($content)) {
200                                 unset($profile[$field]);
201                         }
202                 }
203
204                 return $profile;
205         }
206
207         /**
208          * Fetches activities from the outbox of a given profile and processes it
209          *
210          * @param string  $url
211          * @param integer $uid User ID
212          * @return void
213          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214          */
215         public static function fetchOutbox(string $url, int $uid)
216         {
217                 $data = self::fetchContent($url, $uid);
218                 if (empty($data)) {
219                         return;
220                 }
221
222                 if (!empty($data['orderedItems'])) {
223                         $items = $data['orderedItems'];
224                 } elseif (!empty($data['first']['orderedItems'])) {
225                         $items = $data['first']['orderedItems'];
226                 } elseif (!empty($data['first'])) {
227                         self::fetchOutbox($data['first'], $uid);
228                         return;
229                 } else {
230                         $items = [];
231                 }
232
233                 foreach ($items as $activity) {
234                         $ldactivity = JsonLD::compact($activity);
235                         ActivityPub\Receiver::processActivity($ldactivity, '', $uid, true);
236                 }
237         }
238
239         /**
240          * Fetch items from AP endpoints
241          *
242          * @param string $url  Address of the endpoint
243          * @param integer $uid Optional user id
244          * @return array Endpoint items
245          */
246         public static function fetchItems(string $url, int $uid = 0): array
247         {
248                 $data = self::fetchContent($url, $uid);
249                 if (empty($data)) {
250                         return [];
251                 }
252
253                 if (!empty($data['orderedItems'])) {
254                         $items = $data['orderedItems'];
255                 } elseif (!empty($data['first']['orderedItems'])) {
256                         $items = $data['first']['orderedItems'];
257                 } elseif (!empty($data['first']) && is_string($data['first']) && ($data['first'] != $url)) {
258                         return self::fetchItems($data['first'], $uid);
259                 } else {
260                         return [];
261                 }
262
263                 if (!empty($data['next']) && is_string($data['next'])) {
264                         $items = array_merge($items, self::fetchItems($data['next'], $uid));
265                 }
266
267                 return $items;
268         }
269
270         /**
271          * Checks if the given contact url does support ActivityPub
272          *
273          * @param string  $url    profile url
274          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
275          * @return boolean
276          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277          * @throws \ImagickException
278          */
279         public static function isSupportedByContactUrl(string $url, $update = null): bool
280         {
281                 return !empty(APContact::getByURL($url, $update));
282         }
283
284         public static function isAcceptedRequester(int $uid = 0): bool
285         {
286                 $called_by = System::callstack(1);
287
288                 $signer = HTTPSignature::getSigner('', $_SERVER);
289                 if (!$signer) {
290                         Logger::debug('No signer', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]);
291                         return false;
292                 }
293
294                 $apcontact = APContact::getByURL($signer);
295                 if (empty($apcontact)) {
296                         Logger::debug('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]);
297                         return false;
298                 }
299
300                 if (empty($apcontact['gsid'] || empty($apcontact['baseurl']))) {
301                         Logger::debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]);
302                         return false;
303                 }
304
305                 // Check added as a precaution. It should not occur.
306                 if (Network::isUrlBlocked($apcontact['baseurl'])) {
307                         Logger::info('Requesting domain is blocked', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]);
308                         return false;
309                 }
310
311                 $contact = Contact::getByURL($signer, false, ['id', 'baseurl', 'gsid']);
312                 if (!empty($contact) && Contact\User::isBlocked($contact['id'], $uid)) {
313                         Logger::info('Requesting contact is blocked', ['uid' => $uid, 'id' => $contact['id'], 'signer' => $signer, 'baseurl' => $contact['baseurl'], 'called_by' => $called_by]);
314                         return false;
315                 }
316
317                 // @todo Look for user blocked domains
318
319                 Logger::debug('Server is an accepted requester', ['uid' => $uid, 'id' => $contact['gsid'], 'url' => $contact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]);
320
321                 return true;
322         }
323 }