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