3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\HTML;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Item;
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 use GuzzleHttp\Psr7\Uri;
47 * Fetch webfinger data
49 * @param string $addr Address
50 * @return array webfinger data
52 private static function fetchWebfingerData(string $addr): array
54 $addr_parts = explode('@', $addr);
55 if (count($addr_parts) != 2) {
59 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
61 'addr' => $local_owner['addr'],
62 'baseurl' => $local_owner['baseurl'],
63 'url' => $local_owner['url'],
64 'subscribe' => $local_owner['baseurl'] . '/contact/follow?url={uri}'];
66 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
67 $data['alias'] = $local_owner['alias'];
73 $webfinger = Probe::getWebfingerArray($addr);
74 if (empty($webfinger['webfinger']['links'])) {
78 $data['baseurl'] = $webfinger['baseurl'];
80 foreach ($webfinger['webfinger']['links'] as $link) {
81 if (empty($link['rel'])) {
85 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
86 $data['subscribe'] = $link['template'];
89 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
90 $data['url'] = $link['href'];
93 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
94 $data['alias'] = $link['href'];
98 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
99 unset($data['alias']);
106 * Fetches a profile from a given url
108 * @param string $url profile url
109 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
110 * @return array profile array
111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
112 * @throws \ImagickException
113 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
115 public static function getByURL(string $url, $update = null): array
117 if (empty($url) || Network::isUrlBlocked($url)) {
118 Logger::info('Domain is blocked', ['url' => $url]);
122 if (!Network::isValidHttpUrl($url) && !filter_var($url, FILTER_VALIDATE_EMAIL)) {
123 Logger::info('Invalid URL', ['url' => $url]);
127 $fetched_contact = [];
129 if (empty($update)) {
130 if (is_null($update)) {
131 $ref_update = DateTimeFormat::utc('now - 1 month');
133 $ref_update = DBA::NULL_DATETIME;
136 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
137 if (!DBA::isResult($apcontact)) {
138 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
141 if (!DBA::isResult($apcontact)) {
142 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
145 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
149 if (!is_null($update)) {
150 return DBA::isResult($apcontact) ? $apcontact : [];
153 if (DBA::isResult($apcontact)) {
154 $fetched_contact = $apcontact;
160 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
162 $apcontact = self::fetchWebfingerData($url);
163 if (empty($apcontact['url'])) {
164 return $fetched_contact;
166 $url = $apcontact['url'];
167 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
168 $apcontact['baseurl'] = $url;
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::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
177 if (!empty($fetched_contact)) {
178 return $fetched_contact;
181 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
184 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
186 $data = Transmitter::getProfile($local_uid);
187 $local_owner = User::getOwnerDataById($local_uid);
188 } catch(HTTPException\NotFoundException $e) {
197 $curlResult = HTTPSignature::fetchRaw($url);
198 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
199 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
202 $data = json_decode($curlResult->getBody(), true);
203 $failed = empty($data) || !is_array($data);
206 if (!$failed && ($curlResult->getReturnCode() == 410)) {
207 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
209 } catch (\Exception $exception) {
210 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
215 self::markForArchival($fetched_contact ?: []);
216 return $fetched_contact;
220 $compacted = JsonLD::compact($data);
221 if (empty($compacted['@id'])) {
222 return $fetched_contact;
225 $apcontact['url'] = $compacted['@id'];
226 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
227 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
228 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
229 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
230 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
231 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
233 $apcontact['sharedinbox'] = '';
234 if (!empty($compacted['as:endpoints'])) {
235 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
238 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
239 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
241 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
242 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
244 if (empty($apcontact['name'])) {
245 $apcontact['name'] = $apcontact['nick'];
248 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
250 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
253 foreach ($ims as $link) {
254 if (substr($link, 0, 5) == 'xmpp:') {
255 $apcontact['xmpp'] = substr($link, 5);
257 if (substr($link, 0, 7) == 'matrix:') {
258 $apcontact['matrix'] = substr($link, 7);
263 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
264 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
265 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
266 } elseif (empty($apcontact['photo'])) {
267 $photo = JsonLD::fetchElementArray($compacted, 'as:icon', 'as:url');
268 if (!empty($photo[0]['@id'])) {
269 $apcontact['photo'] = $photo[0]['@id'];
273 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
274 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
275 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
278 if (empty($apcontact['alias'])) {
279 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
280 if (is_array($apcontact['alias'])) {
281 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
285 // Quit if none of the basic values are set
286 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
287 return $fetched_contact;
288 } elseif ($apcontact['type'] == 'Tombstone') {
289 // The "inbox" field must have a content
290 $apcontact['inbox'] = '';
293 // Quit if this doesn't seem to be an account at all
294 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
295 return $fetched_contact;
298 if (empty($apcontact['addr'])) {
300 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
301 } catch (\Throwable $e) {
302 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
303 $apcontact['addr'] = '';
307 $apcontact['pubkey'] = null;
308 if (!empty($compacted['w3id:publicKey'])) {
309 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
310 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
311 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
315 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
317 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
319 if (!empty($compacted['as:generator'])) {
320 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
321 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
324 if (!empty($apcontact['following'])) {
325 if (!empty($local_owner)) {
326 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
328 $following = ActivityPub::fetchContent($apcontact['following']);
330 if (!empty($following['totalItems'])) {
331 // Mastodon seriously allows for this condition?
332 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
333 if ($following['totalItems'] < 0) {
334 $following['totalItems'] = 0;
336 $apcontact['following_count'] = $following['totalItems'];
340 if (!empty($apcontact['followers'])) {
341 if (!empty($local_owner)) {
342 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
344 $followers = ActivityPub::fetchContent($apcontact['followers']);
346 if (!empty($followers['totalItems'])) {
347 // Mastodon seriously allows for this condition?
348 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
349 if ($followers['totalItems'] < 0) {
350 $followers['totalItems'] = 0;
352 $apcontact['followers_count'] = $followers['totalItems'];
356 if (!empty($apcontact['outbox'])) {
357 if (!empty($local_owner)) {
358 $statuses_count = self::getStatusesCount($local_owner);
360 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
361 $statuses_count = $outbox['totalItems'] ?? 0;
363 if (!empty($statuses_count)) {
364 // Mastodon seriously allows for this condition?
365 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
366 if ($statuses_count < 0) {
369 $apcontact['statuses_count'] = $statuses_count;
373 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
375 if (!empty($apcontact['photo'])) {
376 $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
378 if (!Network::isValidHttpUrl($apcontact['photo'])) {
379 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
380 $apcontact['photo'] = '';
384 // When the photo is too large, try to shorten it by removing parts
385 if (strlen($apcontact['photo'] ?? '') > 255) {
386 $parts = parse_url($apcontact['photo']);
387 unset($parts['fragment']);
388 $apcontact['photo'] = (string)Uri::fromParts($parts);
390 if (strlen($apcontact['photo']) > 255) {
391 unset($parts['query']);
392 $apcontact['photo'] = (string)Uri::fromParts($parts);
395 if (strlen($apcontact['photo']) > 255) {
396 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
400 if (!$webfinger && !empty($apcontact['addr'])) {
401 $data = self::fetchWebfingerData($apcontact['addr']);
403 $apcontact['baseurl'] = $data['baseurl'];
405 if (empty($apcontact['alias']) && !empty($data['alias'])) {
406 $apcontact['alias'] = $data['alias'];
408 if (!empty($data['subscribe'])) {
409 $apcontact['subscribe'] = $data['subscribe'];
412 $apcontact['addr'] = null;
416 if (empty($apcontact['baseurl'])) {
417 $apcontact['baseurl'] = null;
420 if (empty($apcontact['subscribe'])) {
421 $apcontact['subscribe'] = null;
424 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
425 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
426 } elseif (!empty($fetched_contact['gsid'])) {
427 $apcontact['gsid'] = $fetched_contact['gsid'];
429 $apcontact['gsid'] = null;
432 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
434 if (!empty($apcontact['sharedinbox'])) {
435 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
438 if ($apcontact['url'] == $apcontact['alias']) {
439 $apcontact['alias'] = null;
442 if (empty($apcontact['uuid'])) {
443 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
445 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
448 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
449 $value = JsonLD::fetchElement($compacted, $name, '@id');
453 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
456 if (!empty($compacted['as:endpoints'])) {
457 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
458 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
462 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
463 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
464 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
465 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
466 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
467 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
472 $apcontact['updated'] = DateTimeFormat::utcNow();
474 // We delete the old entry when the URL is changed
475 if ($url != $apcontact['url']) {
476 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
477 DBA::delete('apcontact', ['url' => $url]);
480 // Limit the length on incoming fields
481 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
483 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
484 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
486 DBA::replace('apcontact', $apcontact);
489 Logger::info('Updated profile', ['url' => $url]);
491 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
495 * Fetch the number of statuses for the given owner
497 * @param array $owner
501 private static function getStatusesCount(array $owner): int
504 'private' => [Item::PUBLIC, Item::UNLISTED],
505 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
506 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
507 'network' => Protocol::DFRN,
508 'parent-network' => Protocol::FEDERATED,
513 $count = Post::countPosts($condition);
519 * Mark the given AP Contact as "to archive"
521 * @param array $apcontact
524 public static function markForArchival(array $apcontact)
526 if (!empty($apcontact['inbox'])) {
527 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
528 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
531 if (!empty($apcontact['sharedinbox'])) {
532 // Check if there are any available inboxes
533 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
534 $apcontact['sharedinbox']]);
536 // If all known personal inboxes are failing then set their shared inbox to failure as well
537 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
538 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
544 * Unmark the given AP Contact as "to archive"
546 * @param array $apcontact
549 public static function unmarkForArchival(array $apcontact)
551 if (!empty($apcontact['inbox'])) {
552 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
553 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
555 if (!empty($apcontact['sharedinbox'])) {
556 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
557 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
564 * @param string $url inbox url
565 * @param boolean $shared Shared Inbox
566 * @param int $gsid Global server id
569 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
575 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
579 * Check if the apcontact is a relay account
581 * @param array $apcontact
585 public static function isRelay(array $apcontact): bool
587 if (in_array($apcontact['type'], ['Person', 'Organization'])) {
591 if (($apcontact['type'] == 'Service') && empty($apcontact['outbox']) && empty($apcontact['sharedinbox']) && empty($apcontact['following']) && empty($apcontact['followers']) && empty($apcontact['statuses_count'])) {
595 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
599 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
603 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {