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