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