]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge pull request #11402 from annando/featured-endpoint
[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\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 Forum
56  * - Private Forum
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                 'directMessage' => 'litepub:directMessage',
76                 'discoverable' => 'toot:discoverable',
77                 'PropertyValue' => 'schema:PropertyValue',
78                 'value' => 'schema:value',
79         ]];
80         const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone'];
81         /**
82          * Checks if the web request is done for the AP protocol
83          *
84          * @return bool is it AP?
85          */
86         public static function isRequest()
87         {
88                 $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
89                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
90                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
91
92                 if ($isrequest) {
93                         Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
94                 }
95
96                 return $isrequest;
97         }
98
99         /**
100          * Fetches ActivityPub content from the given url
101          *
102          * @param string  $url content url
103          * @param integer $uid User ID for the signature
104          * @return array
105          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106          */
107         public static function fetchContent(string $url, int $uid = 0)
108         {
109                 return HTTPSignature::fetch($url, $uid);
110         }
111
112         private static function getAccountType($apcontact)
113         {
114                 $accounttype = -1;
115
116                 switch($apcontact['type']) {
117                         case 'Person':
118                                 $accounttype = User::ACCOUNT_TYPE_PERSON;
119                                 break;
120                         case 'Organization':
121                                 $accounttype = User::ACCOUNT_TYPE_ORGANISATION;
122                                 break;
123                         case 'Service':
124                                 $accounttype = User::ACCOUNT_TYPE_NEWS;
125                                 break;
126                         case 'Group':
127                                 $accounttype = User::ACCOUNT_TYPE_COMMUNITY;
128                                 break;
129                         case 'Application':
130                                 $accounttype = User::ACCOUNT_TYPE_RELAY;
131                                 break;
132                         case 'Tombstone':
133                                 $accounttype = User::ACCOUNT_TYPE_DELETED;
134                                 break;
135                 }
136
137                 return $accounttype;
138         }
139
140         /**
141          * Fetches a profile from the given url into an array that is compatible to Probe::uri
142          *
143          * @param string  $url    profile url
144          * @param boolean $update Update the profile
145          * @return array
146          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147          * @throws \ImagickException
148          */
149         public static function probeProfile($url, $update = true)
150         {
151                 $apcontact = APContact::getByURL($url, $update);
152                 if (empty($apcontact)) {
153                         return [];
154                 }
155
156                 $profile = ['network' => Protocol::ACTIVITYPUB];
157                 $profile['nick'] = $apcontact['nick'];
158                 $profile['name'] = $apcontact['name'];
159                 $profile['guid'] = $apcontact['uuid'];
160                 $profile['url'] = $apcontact['url'];
161                 $profile['addr'] = $apcontact['addr'];
162                 $profile['alias'] = $apcontact['alias'];
163                 $profile['following'] = $apcontact['following'];
164                 $profile['followers'] = $apcontact['followers'];
165                 $profile['inbox'] = $apcontact['inbox'];
166                 $profile['outbox'] = $apcontact['outbox'];
167                 $profile['sharedinbox'] = $apcontact['sharedinbox'];
168                 $profile['photo'] = $apcontact['photo'];
169                 $profile['header'] = $apcontact['header'];
170                 $profile['account-type'] = self::getAccountType($apcontact);
171                 $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
172                 // $profile['keywords']
173                 // $profile['location']
174                 $profile['about'] = $apcontact['about'];
175                 $profile['xmpp'] = $apcontact['xmpp'];
176                 $profile['matrix'] = $apcontact['matrix'];
177                 $profile['batch'] = $apcontact['sharedinbox'];
178                 $profile['notify'] = $apcontact['inbox'];
179                 $profile['poll'] = $apcontact['outbox'];
180                 $profile['pubkey'] = $apcontact['pubkey'];
181                 $profile['subscribe'] = $apcontact['subscribe'];
182                 $profile['manually-approve'] = $apcontact['manually-approve'];
183                 $profile['baseurl'] = $apcontact['baseurl'];
184                 $profile['gsid'] = $apcontact['gsid'];
185
186                 if (!is_null($apcontact['discoverable'])) {
187                         $profile['hide'] = !$apcontact['discoverable'];
188                 }
189
190                 // Remove all "null" fields
191                 foreach ($profile as $field => $content) {
192                         if (is_null($content)) {
193                                 unset($profile[$field]);
194                         }
195                 }
196
197                 return $profile;
198         }
199
200         /**
201          * Fetches activities from the outbox of a given profile and processes it
202          *
203          * @param string  $url
204          * @param integer $uid User ID
205          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206          */
207         public static function fetchOutbox($url, $uid)
208         {
209                 $data = self::fetchContent($url, $uid);
210                 if (empty($data)) {
211                         return;
212                 }
213
214                 if (!empty($data['orderedItems'])) {
215                         $items = $data['orderedItems'];
216                 } elseif (!empty($data['first']['orderedItems'])) {
217                         $items = $data['first']['orderedItems'];
218                 } elseif (!empty($data['first'])) {
219                         self::fetchOutbox($data['first'], $uid);
220                         return;
221                 } else {
222                         $items = [];
223                 }
224
225                 foreach ($items as $activity) {
226                         $ldactivity = JsonLD::compact($activity);
227                         ActivityPub\Receiver::processActivity($ldactivity, '', $uid, true);
228                 }
229         }
230
231         /**
232          * Fetch items from AP endpoints
233          *
234          * @param string $url  Address of the endpoint
235          * @param integer $uid Optional user id
236          * @return array Endpoint items
237          */
238         public static function fetchItems(string $url, int $uid = 0)
239         {
240                 $data = self::fetchContent($url, $uid);
241                 if (empty($data)) {
242                         return [];
243                 }
244
245                 if (!empty($data['orderedItems'])) {
246                         $items = $data['orderedItems'];
247                 } elseif (!empty($data['first']['orderedItems'])) {
248                         $items = $data['first']['orderedItems'];
249                 } elseif (!empty($data['first']) && is_string($data['first']) && ($data['first'] != $url)) {
250                         return self::fetchItems($data['first'], $uid);
251                 } else {
252                         return [];
253                 }
254
255                 if (!empty($data['next']) && is_string($data['next'])) {
256                         $items = array_merge($items, self::fetchItems($data['next'], $uid));
257                 }
258
259                 return $items;
260         }
261
262         /**
263          * Checks if the given contact url does support ActivityPub
264          *
265          * @param string  $url    profile url
266          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
267          * @return boolean
268          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269          * @throws \ImagickException
270          */
271         public static function isSupportedByContactUrl($url, $update = null)
272         {
273                 return !empty(APContact::getByURL($url, $update));
274         }
275 }