]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
e9500f85b89c585dd301a0e54ee3db6f3a54c5c1
[friendica.git] / src / Model / APContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Model;
23
24 use Friendica\Content\Text\HTML;
25 use Friendica\Core\Cache\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
30 use Friendica\DI;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\ActivityNamespace;
33 use Friendica\Protocol\ActivityPub;
34 use Friendica\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\JsonLD;
38 use Friendica\Util\Network;
39
40 class APContact
41 {
42         /**
43          * Fetch webfinger data
44          *
45          * @param string $addr Address
46          * @return array webfinger data
47          */
48         private static function fetchWebfingerData(string $addr)
49         {
50                 $addr_parts = explode('@', $addr);
51                 if (count($addr_parts) != 2) {
52                         return [];
53                 }
54
55                 $data = ['addr' => $addr];
56                 $template = 'https://' . $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                         $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
60                         $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
61                         if (empty($webfinger['links'])) {
62                                 return [];
63                         }
64                         $data['baseurl'] = 'http://' . $addr_parts[1];
65                 } else {
66                         $data['baseurl'] = 'https://' . $addr_parts[1];
67                 }
68
69                 foreach ($webfinger['links'] as $link) {
70                         if (empty($link['rel'])) {
71                                 continue;
72                         }
73
74                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
75                                 $data['subscribe'] = $link['template'];
76                         }
77
78                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
79                                 $data['url'] = $link['href'];
80                         }
81
82                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
83                                 $data['alias'] = $link['href'];
84                         }
85                 }
86
87                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
88                         unset($data['alias']);
89                 }
90
91                 return $data;
92         }
93
94         /**
95          * Fetches a profile from a given url
96          *
97          * @param string  $url    profile url
98          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
99          * @return array profile array
100          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101          * @throws \ImagickException
102          */
103         public static function getByURL($url, $update = null)
104         {
105                 if (empty($url)) {
106                         return [];
107                 }
108
109                 $fetched_contact = false;
110
111                 if (empty($update)) {
112                         if (is_null($update)) {
113                                 $ref_update = DateTimeFormat::utc('now - 1 month');
114                         } else {
115                                 $ref_update = DBA::NULL_DATETIME;
116                         }
117
118                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
119                         if (!DBA::isResult($apcontact)) {
120                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
121                         }
122
123                         if (!DBA::isResult($apcontact)) {
124                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
125                         }
126
127                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
128                                 return $apcontact;
129                         }
130
131                         if (!is_null($update)) {
132                                 return DBA::isResult($apcontact) ? $apcontact : [];
133                         }
134
135                         if (DBA::isResult($apcontact)) {
136                                 $fetched_contact = $apcontact;
137                         }
138                 }
139
140                 $apcontact = [];
141
142                 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
143                 if ($webfinger) {
144                         $apcontact = self::fetchWebfingerData($url);
145                         if (empty($apcontact['url'])) {
146                                 return $fetched_contact;
147                         }
148                         $url = $apcontact['url'];
149                 }
150
151                 // Detect multiple fast repeating request to the same address
152                 // See https://github.com/friendica/friendica/issues/9303
153                 $cachekey = 'apcontact:getByURL:' . $url;
154                 $result = DI::cache()->get($cachekey);
155                 if (!is_null($result)) {
156                         Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
157                         if (!empty($fetched_contact)) {
158                                 return $fetched_contact;
159                         }
160                 } else {
161                         DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
162                 }
163
164                 $curlResult = HTTPSignature::fetchRaw($url);
165                 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
166                         (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
167
168                 if (!$failed) {
169                         $data = json_decode($curlResult->getBody(), true);
170                         $failed = empty($data) || !is_array($data);
171                 }
172
173                 if (!$failed && ($curlResult->getReturnCode() == 410)) {
174                         $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
175                 }
176
177                 if ($failed) {
178                         self::markForArchival($fetched_contact ?: []);
179                         return $fetched_contact;
180                 }
181
182                 $compacted = JsonLD::compact($data);
183                 if (empty($compacted['@id'])) {
184                         return $fetched_contact;
185                 }
186
187                 $apcontact['url'] = $compacted['@id'];
188                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
189                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
190                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
191                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
192                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
193                 self::unarchiveInbox($apcontact['inbox'], false);
194
195                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
196
197                 $apcontact['sharedinbox'] = '';
198                 if (!empty($compacted['as:endpoints'])) {
199                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
200                         self::unarchiveInbox($apcontact['sharedinbox'], true);
201                 }
202
203                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
204                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
205
206                 if (empty($apcontact['name'])) {
207                         $apcontact['name'] = $apcontact['nick'];
208                 }
209
210                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
211
212                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
213                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
214                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
215                 }
216
217                 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
218                 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
219                         $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
220                 }
221
222                 if (empty($apcontact['alias'])) {
223                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
224                         if (is_array($apcontact['alias'])) {
225                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
226                         }
227                 }
228
229                 // Quit if none of the basic values are set
230                 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
231                         return $fetched_contact;
232                 } elseif ($apcontact['type'] == 'Tombstone') {
233                         // The "inbox" field must have a content
234                         $apcontact['inbox'] = '';
235                 }
236
237                 // Quit if this doesn't seem to be an account at all
238                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
239                         return $fetched_contact;
240                 }
241
242                 $parts = parse_url($apcontact['url']);
243                 unset($parts['scheme']);
244                 unset($parts['path']);
245
246                 if (empty($apcontact['addr'])) {
247                         if (!empty($apcontact['nick']) && is_array($parts)) {
248                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
249                         } else {
250                                 $apcontact['addr'] = '';
251                         }
252                 }
253
254                 $apcontact['pubkey'] = null;
255                 if (!empty($compacted['w3id:publicKey'])) {
256                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
257                         if (strstr($apcontact['pubkey'], 'RSA ')) {
258                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
259                         }
260                 }
261
262                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
263
264                 if (!empty($compacted['as:generator'])) {
265                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
266                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
267                 }
268
269                 if (!empty($apcontact['following'])) {
270                         $following = ActivityPub::fetchContent($apcontact['following']);
271                         if (!empty($following['totalItems'])) {
272                                 // Mastodon seriously allows for this condition? 
273                                 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
274                                 if ($following['totalItems'] < 0) {
275                                         $following['totalItems'] = 0;
276                                 }
277                                 $apcontact['following_count'] = $following['totalItems'];
278                         }
279                 }
280
281                 if (!empty($apcontact['followers'])) {
282                         $followers = ActivityPub::fetchContent($apcontact['followers']);
283                         if (!empty($followers['totalItems'])) {
284                                 // Mastodon seriously allows for this condition? 
285                                 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
286                                 if ($followers['totalItems'] < 0) {
287                                         $followers['totalItems'] = 0;
288                                 }
289                                 $apcontact['followers_count'] = $followers['totalItems'];
290                         }
291                 }
292
293                 if (!empty($apcontact['outbox'])) {
294                         $outbox = ActivityPub::fetchContent($apcontact['outbox']);
295                         if (!empty($outbox['totalItems'])) {
296                                 $apcontact['statuses_count'] = $outbox['totalItems'];
297                         }
298                 }
299
300                 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
301
302                 // To-Do
303
304                 // Unhandled
305                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
306
307                 // Unhandled from Misskey
308                 // sharedInbox, isCat
309
310                 // Unhandled from Kroeg
311                 // kroeg:blocks, updated
312
313                 // When the photo is too large, try to shorten it by removing parts
314                 if (strlen($apcontact['photo']) > 255) {
315                         $parts = parse_url($apcontact['photo']);
316                         unset($parts['fragment']);
317                         $apcontact['photo'] = Network::unparseURL($parts);
318
319                         if (strlen($apcontact['photo']) > 255) {
320                                 unset($parts['query']);
321                                 $apcontact['photo'] = Network::unparseURL($parts);
322                         }
323
324                         if (strlen($apcontact['photo']) > 255) {
325                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
326                         }
327                 }
328
329                 if (!$webfinger && !empty($apcontact['addr'])) {
330                         $data = self::fetchWebfingerData($apcontact['addr']);
331                         if (!empty($data)) {
332                                 $apcontact['baseurl'] = $data['baseurl'];
333
334                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
335                                         $apcontact['alias'] = $data['alias'];
336                                 }
337                                 if (!empty($data['subscribe'])) {
338                                         $apcontact['subscribe'] = $data['subscribe'];
339                                 }
340                         } else {
341                                 $apcontact['addr'] = null;
342                         }
343                 }
344
345                 if (empty($apcontact['baseurl'])) {
346                         $apcontact['baseurl'] = null;
347                 }
348
349                 if (empty($apcontact['subscribe'])) {
350                         $apcontact['subscribe'] = null;
351                 }
352
353                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
354                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
355                 } elseif (!empty($fetched_contact['gsid'])) {
356                         $apcontact['gsid'] = $fetched_contact['gsid'];
357                 } else {
358                         $apcontact['gsid'] = null;
359                 }
360
361                 if ($apcontact['url'] == $apcontact['alias']) {
362                         $apcontact['alias'] = null;
363                 }
364
365                 if (empty($apcontact['uuid'])) {
366                         $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
367                 } else {
368                         $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
369                 }
370
371                 $apcontact['updated'] = DateTimeFormat::utcNow();
372
373                 // We delete the old entry when the URL is changed
374                 if ($url != $apcontact['url']) {
375                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
376                         DBA::delete('apcontact', ['url' => $url]);
377                 }
378
379                 // Limit the length on incoming fields
380                 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
381
382                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
383                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
384                 } else {
385                         DBA::replace('apcontact', $apcontact);
386                 }
387
388                 Logger::info('Updated profile', ['url' => $url]);
389
390                 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
391         }
392
393         /**
394          * Mark the given AP Contact as "to archive"
395          *
396          * @param array $apcontact
397          * @return void
398          */
399         public static function markForArchival(array $apcontact)
400         {
401                 if (!empty($apcontact['inbox'])) {
402                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
403                         HTTPSignature::setInboxStatus($apcontact['inbox'], false);
404                 }
405
406                 if (!empty($apcontact['sharedinbox'])) {
407                         // Check if there are any available inboxes
408                         $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
409                                 $apcontact['sharedinbox']]);
410                         if (!$available) {
411                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
412                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
413                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
414                         }
415                 }
416         }
417
418         /**
419          * Unmark the given AP Contact as "to archive"
420          *
421          * @param array $apcontact
422          * @return void
423          */
424         public static function unmarkForArchival(array $apcontact)
425         {
426                 if (!empty($apcontact['inbox'])) {
427                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
428                         HTTPSignature::setInboxStatus($apcontact['inbox'], true);
429                 }
430                 if (!empty($apcontact['sharedinbox'])) {
431                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
432                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
433                 }
434         }
435
436         /**
437          * Unarchive inboxes
438          *
439          * @param string  $url    inbox url
440          * @param boolean $shared Shared Inbox
441          */
442         private static function unarchiveInbox($url, $shared)
443         {
444                 if (empty($url)) {
445                         return;
446                 }
447
448                 HTTPSignature::setInboxStatus($url, true, $shared);
449         }
450 }