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