]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge remote-tracking branch 'upstream/develop' into json-ld
[friendica.git] / src / Protocol / ActivityPub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Model\APContact;
27 use Friendica\Model\User;
28 use Friendica\Protocol\ActivityPub\FetchQueue;
29 use Friendica\Util\HTTPSignature;
30 use Friendica\Util\JsonLD;
31
32 /**
33  * ActivityPub Protocol class
34  *
35  * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
36  * https://www.w3.org/TR/activitypub/
37  * https://www.w3.org/TR/activitystreams-core/
38  * https://www.w3.org/TR/activitystreams-vocabulary/
39  *
40  * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
41  * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
42  *
43  * Digest: https://tools.ietf.org/html/rfc5843
44  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
45  *
46  * Mastodon implementation of supported activities:
47  * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
48  *
49  * Funkwhale:
50  * http://docs-funkwhale-funkwhale-549-music-federation-documentation.preview.funkwhale.audio/federation/index.html
51  *
52  * To-do:
53  * - Polling the outboxes for missing content?
54  *
55  * Missing parts from DFRN:
56  * - Public Forum
57  * - Private Forum
58  * - Relocation
59  */
60 class ActivityPub
61 {
62         const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
63         const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
64                 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
65                 'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/',
66                 'diaspora' => 'https://diasporafoundation.org/ns/',
67                 'litepub' => 'http://litepub.social/ns#',
68                 'toot' => 'http://joinmastodon.org/ns#',
69                 'featured' => [
70                         "@id" => "toot:featured",
71                         "@type" => "@id",
72                 ],
73                 'schema' => 'http://schema.org#',
74                 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
75                 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
76                 'directMessage' => 'litepub:directMessage',
77                 'discoverable' => 'toot:discoverable',
78                 'PropertyValue' => 'schema:PropertyValue',
79                 'value' => 'schema:value',
80         ]];
81         const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
82         /**
83          * Checks if the web request is done for the AP protocol
84          *
85          * @return bool is it AP?
86          */
87         public static function isRequest(): bool
88         {
89                 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
90                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
91                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
92
93                 if ($isrequest) {
94                         Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
95                 }
96
97                 return $isrequest;
98         }
99
100         /**
101          * Fetches ActivityPub content from the given url
102          *
103          * @param string  $url content url
104          * @param integer $uid User ID for the signature
105          * @return array
106          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
107          */
108         public static function fetchContent(string $url, int $uid = 0): array
109         {
110                 return HTTPSignature::fetch($url, $uid);
111         }
112
113         private static function getAccountType(array $apcontact): int
114         {
115                 $accounttype = -1;
116
117                 switch($apcontact['type']) {
118                         case 'Person':
119                                 $accounttype = User::ACCOUNT_TYPE_PERSON;
120                                 break;
121                         case 'Organization':
122                                 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
123                                 break;
124                         case 'Service':
125                                 $accounttype = User::ACCOUNT_TYPE_NEWS;
126                                 break;
127                         case 'Group':
128                                 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
129                                 break;
130                         case 'Application':
131                                 $accounttype = User::ACCOUNT_TYPE_RELAY;
132                                 break;
133                         case 'Tombstone':
134                                 $accounttype = User::ACCOUNT_TYPE_DELETED;
135                                 break;
136                 }
137
138                 return $accounttype;
139         }
140
141         /**
142          * Fetches a profile from the given url into an array that is compatible to Probe::uri
143          *
144          * @param string  $url    profile url
145          * @param boolean $update Update the profile
146          * @return array
147          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148          * @throws \ImagickException
149          */
150         public static function probeProfile(string $url, bool $update = true): array
151         {
152                 $apcontact = APContact::getByURL($url, $update);
153                 if (empty($apcontact)) {
154                         return [];
155                 }
156
157                 $profile = ['network' => Protocol::ACTIVITYPUB];
158                 $profile['nick'] = $apcontact['nick'];
159                 $profile['name'] = $apcontact['name'];
160                 $profile['guid'] = $apcontact['uuid'];
161                 $profile['url'] = $apcontact['url'];
162                 $profile['addr'] = $apcontact['addr'];
163                 $profile['alias'] = $apcontact['alias'];
164                 $profile['following'] = $apcontact['following'];
165                 $profile['followers'] = $apcontact['followers'];
166                 $profile['inbox'] = $apcontact['inbox'];
167                 $profile['outbox'] = $apcontact['outbox'];
168                 $profile['sharedinbox'] = $apcontact['sharedinbox'];
169                 $profile['photo'] = $apcontact['photo'];
170                 $profile['header'] = $apcontact['header'];
171                 $profile['account-type'] = self::getAccountType($apcontact);
172                 $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
173                 // $profile['keywords']
174                 // $profile['location']
175                 $profile['about'] = $apcontact['about'];
176                 $profile['xmpp'] = $apcontact['xmpp'];
177                 $profile['matrix'] = $apcontact['matrix'];
178                 $profile['batch'] = $apcontact['sharedinbox'];
179                 $profile['notify'] = $apcontact['inbox'];
180                 $profile['poll'] = $apcontact['outbox'];
181                 $profile['pubkey'] = $apcontact['pubkey'];
182                 $profile['subscribe'] = $apcontact['subscribe'];
183                 $profile['manually-approve'] = $apcontact['manually-approve'];
184                 $profile['baseurl'] = $apcontact['baseurl'];
185                 $profile['gsid'] = $apcontact['gsid'];
186
187                 if (!is_null($apcontact['discoverable'])) {
188                         $profile['hide'] = !$apcontact['discoverable'];
189                 }
190
191                 // Remove all "null" fields
192                 foreach ($profile as $field => $content) {
193                         if (is_null($content)) {
194                                 unset($profile[$field]);
195                         }
196                 }
197
198                 return $profile;
199         }
200
201         /**
202          * Fetches activities from the outbox of a given profile and processes it
203          *
204          * @param string  $url
205          * @param integer $uid User ID
206          * @return void
207          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208          */
209         public static function fetchOutbox(string $url, int $uid)
210         {
211                 $data = self::fetchContent($url, $uid);
212                 if (empty($data)) {
213                         return;
214                 }
215
216                 if (!empty($data['orderedItems'])) {
217                         $items = $data['orderedItems'];
218                 } elseif (!empty($data['first']['orderedItems'])) {
219                         $items = $data['first']['orderedItems'];
220                 } elseif (!empty($data['first'])) {
221                         self::fetchOutbox($data['first'], $uid);
222                         return;
223                 } else {
224                         $items = [];
225                 }
226
227                 $fetchQueue = new FetchQueue();
228
229                 foreach ($items as $activity) {
230                         $ldactivity = JsonLD::compact($activity);
231                         ActivityPub\Receiver::processActivity($fetchQueue, $ldactivity, '', $uid, true);
232                 }
233
234                 $fetchQueue->process();
235         }
236
237         /**
238          * Fetch items from AP endpoints
239          *
240          * @param string $url  Address of the endpoint
241          * @param integer $uid Optional user id
242          * @return array Endpoint items
243          */
244         public static function fetchItems(string $url, int $uid = 0): array
245         {
246                 $data = self::fetchContent($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);
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));
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 }