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