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