]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Merge pull request #8728 from annando/ap-webfinger
[friendica.git] / src / Model / APContact.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\Model;
23
24 use Friendica\Content\Text\HTML;
25 use Friendica\Core\Logger;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Network\Probe;
29 use Friendica\Protocol\ActivityNamespace;
30 use Friendica\Protocol\ActivityPub;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\Network;
33 use Friendica\Util\JsonLD;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Strings;
36
37 class APContact
38 {
39         /**
40          * Fetch webfinger data
41          *
42          * @param string $addr Address
43          * @return array webfinger data
44          */
45         public static function fetchWebfingerData(string $addr)
46         {
47                 $addr_parts = explode('@', $addr);
48                 if (count($addr_parts) != 2) {
49                         return [];
50                 }
51
52                 $data = ['addr' => $addr];
53                 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
54                 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
55                 if (empty($webfinger['links'])) {
56                         $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
57                         $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
58                         if (empty($webfinger['links'])) {
59                                 return [];
60                         }
61                         $data['baseurl'] = 'http://' . $addr_parts[1];
62                 } else {
63                         $data['baseurl'] = 'https://' . $addr_parts[1];
64                 }
65
66                 foreach ($webfinger['links'] as $link) {
67                         if (empty($link['rel'])) {
68                                 continue;
69                         }
70
71                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
72                                 $data['subscribe'] = $link['template'];
73                         }
74
75                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
76                                 $data['url'] = $link['href'];
77                         }
78
79                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
80                                 $data['alias'] = $link['href'];
81                         }
82                 }
83
84                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
85                         unset($data['alias']);
86                 }
87
88                 return $data;
89         }
90
91         /**
92          * Fetches a profile from a given url
93          *
94          * @param string  $url    profile url
95          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
96          * @return array profile array
97          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
98          * @throws \ImagickException
99          */
100         public static function getByURL($url, $update = null)
101         {
102                 if (empty($url)) {
103                         return [];
104                 }
105
106                 $fetched_contact = false;
107
108                 if (empty($update)) {
109                         if (is_null($update)) {
110                                 $ref_update = DateTimeFormat::utc('now - 1 month');
111                         } else {
112                                 $ref_update = DBA::NULL_DATETIME;
113                         }
114
115                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
116                         if (!DBA::isResult($apcontact)) {
117                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
118                         }
119
120                         if (!DBA::isResult($apcontact)) {
121                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
122                         }
123
124                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
125                                 return $apcontact;
126                         }
127
128                         if (!is_null($update)) {
129                                 return DBA::isResult($apcontact) ? $apcontact : [];
130                         }
131
132                         if (DBA::isResult($apcontact)) {
133                                 $fetched_contact = $apcontact;
134                         }
135                 }
136
137                 $apcontact = [];
138
139                 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
140                 if ($webfinger) {
141                         $apcontact = self::fetchWebfingerData($url);
142                         if (empty($apcontact['url'])) {
143                                 return $fetched_contact;
144                         }
145                         $url = $apcontact['url'];
146                 }
147
148                 $data = ActivityPub::fetchContent($url);
149                 if (empty($data)) {
150                         return $fetched_contact;
151                 }
152
153                 $compacted = JsonLD::compact($data);
154
155                 if (empty($compacted['@id'])) {
156                         return $fetched_contact;
157                 }
158
159                 $apcontact['url'] = $compacted['@id'];
160                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
161                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
162                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
163                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
164                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
165                 self::unarchiveInbox($apcontact['inbox'], false);
166
167                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
168
169                 $apcontact['sharedinbox'] = '';
170                 if (!empty($compacted['as:endpoints'])) {
171                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
172                         self::unarchiveInbox($apcontact['sharedinbox'], true);
173                 }
174
175                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
176                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
177
178                 if (empty($apcontact['name'])) {
179                         $apcontact['name'] = $apcontact['nick'];
180                 }
181
182                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
183
184                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
185                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
186                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
187                 }
188
189                 if (empty($apcontact['alias'])) {
190                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
191                         if (is_array($apcontact['alias'])) {
192                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
193                         }
194                 }
195
196                 // Quit if none of the basic values are set
197                 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
198                         return $fetched_contact;
199                 }
200
201                 // Quit if this doesn't seem to be an account at all
202                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
203                         return $fetched_contact;
204                 }
205
206                 $parts = parse_url($apcontact['url']);
207                 unset($parts['scheme']);
208                 unset($parts['path']);
209
210                 if (empty($apcontact['addr'])) {
211                         if (!empty($apcontact['nick'])) {
212                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
213                         } else {
214                                 $apcontact['addr'] = '';
215                         }
216                 }
217
218                 $apcontact['pubkey'] = null;
219                 if (!empty($compacted['w3id:publicKey'])) {
220                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
221                         if (strstr($apcontact['pubkey'], 'RSA ')) {
222                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
223                         }
224                 }
225
226                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
227
228                 if (!empty($compacted['as:generator'])) {
229                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
230                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
231                 }
232
233                 if (!empty($apcontact['following'])) {
234                         $data = ActivityPub::fetchContent($apcontact['following']);
235                         if (!empty($data)) {
236                                 if (!empty($data['totalItems'])) {
237                                         $apcontact['following_count'] = $data['totalItems'];
238                                 }
239                         }
240                 }
241
242                 if (!empty($apcontact['followers'])) {
243                         $data = ActivityPub::fetchContent($apcontact['followers']);
244                         if (!empty($data)) {
245                                 if (!empty($data['totalItems'])) {
246                                         $apcontact['followers_count'] = $data['totalItems'];
247                                 }
248                         }
249                 }
250
251                 if (!empty($apcontact['outbox'])) {
252                         $data = ActivityPub::fetchContent($apcontact['outbox']);
253                         if (!empty($data)) {
254                                 if (!empty($data['totalItems'])) {
255                                         $apcontact['statuses_count'] = $data['totalItems'];
256                                 }
257                         }
258                 }
259
260                 // To-Do
261
262                 // Unhandled
263                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
264
265                 // Unhandled from Misskey
266                 // sharedInbox, isCat
267
268                 // Unhandled from Kroeg
269                 // kroeg:blocks, updated
270
271                 // When the photo is too large, try to shorten it by removing parts
272                 if (strlen($apcontact['photo']) > 255) {
273                         $parts = parse_url($apcontact['photo']);
274                         unset($parts['fragment']);
275                         $apcontact['photo'] = Network::unparseURL($parts);
276
277                         if (strlen($apcontact['photo']) > 255) {
278                                 unset($parts['query']);
279                                 $apcontact['photo'] = Network::unparseURL($parts);
280                         }
281
282                         if (strlen($apcontact['photo']) > 255) {
283                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
284                         }
285                 }
286
287                 if (!$webfinger && !empty($apcontact['addr'])) {
288                         $data = self::fetchWebfingerData($apcontact['addr']);
289                         if (!empty($data)) {
290                                 $apcontact['baseurl'] = $data['baseurl'];
291
292                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
293                                         $apcontact['alias'] = $data['alias'];
294                                 }
295                                 if (!empty($data['subscribe'])) {
296                                         $apcontact['subscribe'] = $data['subscribe'];
297                                 }
298                         } else {
299                                 $apcontact['addr'] = null;
300                         }
301                 }
302
303                 if (empty($apcontact['baseurl'])) {
304                         $apcontact['baseurl'] = null;
305                 }
306
307                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
308                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
309                 } elseif (!empty($fetched_contact['gsid'])) {
310                         $apcontact['gsid'] = $fetched_contact['gsid'];
311                 } else {
312                         $apcontact['gsid'] = null;
313                 }
314
315                 if ($apcontact['url'] == $apcontact['alias']) {
316                         $apcontact['alias'] = null;
317                 }
318
319                 $apcontact['updated'] = DateTimeFormat::utcNow();
320
321                 DBA::update('apcontact', $apcontact, ['url' => $url], true);
322
323                 // We delete the old entry when the URL is changed
324                 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
325                         DBA::delete('apcontact', ['url' => $url]);
326                 }
327
328                 Logger::info('Updated profile', ['url' => $url]);
329
330                 return $apcontact;
331         }
332
333         /**
334          * Unarchive inboxes
335          *
336          * @param string $url inbox url
337          */
338         private static function unarchiveInbox($url, $shared)
339         {
340                 if (empty($url)) {
341                         return;
342                 }
343
344                 $now = DateTimeFormat::utcNow();
345
346                 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
347
348                 if (!DBA::exists('inbox-status', ['url' => $url])) {
349                         $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
350                         DBA::insert('inbox-status', $fields);
351                 } else {
352                         DBA::update('inbox-status', $fields, ['url' => $url]);
353                 }
354         }
355 }