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