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 $fetched_contact = [];
124 if (empty($update)) {
125 if (is_null($update)) {
126 $ref_update = DateTimeFormat::utc('now - 1 month');
128 $ref_update = DBA::NULL_DATETIME;
131 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
132 if (!DBA::isResult($apcontact)) {
133 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
136 if (!DBA::isResult($apcontact)) {
137 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
140 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
144 if (!is_null($update)) {
145 return DBA::isResult($apcontact) ? $apcontact : [];
148 if (DBA::isResult($apcontact)) {
149 $fetched_contact = $apcontact;
155 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
157 $apcontact = self::fetchWebfingerData($url);
158 if (empty($apcontact['url'])) {
159 return $fetched_contact;
161 $url = $apcontact['url'];
162 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
163 $apcontact['baseurl'] = $url;
166 // Detect multiple fast repeating request to the same address
167 // See https://github.com/friendica/friendica/issues/9303
168 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
169 $result = DI::cache()->get($cachekey);
170 if (!is_null($result)) {
171 Logger::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
172 if (!empty($fetched_contact)) {
173 return $fetched_contact;
176 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
179 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
181 $data = Transmitter::getProfile($local_uid);
182 $local_owner = User::getOwnerDataById($local_uid);
183 } catch(HTTPException\NotFoundException $e) {
192 $curlResult = HTTPSignature::fetchRaw($url);
193 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
194 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
197 $data = json_decode($curlResult->getBody(), true);
198 $failed = empty($data) || !is_array($data);
201 if (!$failed && ($curlResult->getReturnCode() == 410)) {
202 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
204 } catch (\Exception $exception) {
205 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
210 self::markForArchival($fetched_contact ?: []);
211 return $fetched_contact;
215 $compacted = JsonLD::compact($data);
216 if (empty($compacted['@id'])) {
217 return $fetched_contact;
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 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
228 $apcontact['sharedinbox'] = '';
229 if (!empty($compacted['as:endpoints'])) {
230 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
233 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
234 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
236 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
237 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
239 if (empty($apcontact['name'])) {
240 $apcontact['name'] = $apcontact['nick'];
243 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
245 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
248 foreach ($ims as $link) {
249 if (substr($link, 0, 5) == 'xmpp:') {
250 $apcontact['xmpp'] = substr($link, 5);
252 if (substr($link, 0, 7) == 'matrix:') {
253 $apcontact['matrix'] = substr($link, 7);
258 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
259 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
260 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
261 } elseif (empty($apcontact['photo'])) {
262 $photo = JsonLD::fetchElementArray($compacted, 'as:icon', 'as:url');
263 if (!empty($photo[0]['@id'])) {
264 $apcontact['photo'] = $photo[0]['@id'];
268 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
269 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
270 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
273 if (empty($apcontact['alias'])) {
274 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
275 if (is_array($apcontact['alias'])) {
276 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
280 // Quit if none of the basic values are set
281 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
282 return $fetched_contact;
283 } elseif ($apcontact['type'] == 'Tombstone') {
284 // The "inbox" field must have a content
285 $apcontact['inbox'] = '';
288 // Quit if this doesn't seem to be an account at all
289 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
290 return $fetched_contact;
293 if (empty($apcontact['addr'])) {
295 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
296 } catch (\Throwable $e) {
297 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
298 $apcontact['addr'] = '';
302 $apcontact['pubkey'] = null;
303 if (!empty($compacted['w3id:publicKey'])) {
304 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
305 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
306 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
310 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
312 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
314 if (!empty($compacted['as:generator'])) {
315 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
316 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
319 if (!empty($apcontact['following'])) {
320 if (!empty($local_owner)) {
321 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
323 $following = ActivityPub::fetchContent($apcontact['following']);
325 if (!empty($following['totalItems'])) {
326 // Mastodon seriously allows for this condition?
327 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
328 if ($following['totalItems'] < 0) {
329 $following['totalItems'] = 0;
331 $apcontact['following_count'] = $following['totalItems'];
335 if (!empty($apcontact['followers'])) {
336 if (!empty($local_owner)) {
337 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
339 $followers = ActivityPub::fetchContent($apcontact['followers']);
341 if (!empty($followers['totalItems'])) {
342 // Mastodon seriously allows for this condition?
343 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
344 if ($followers['totalItems'] < 0) {
345 $followers['totalItems'] = 0;
347 $apcontact['followers_count'] = $followers['totalItems'];
351 if (!empty($apcontact['outbox'])) {
352 if (!empty($local_owner)) {
353 $statuses_count = self::getStatusesCount($local_owner);
355 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
356 $statuses_count = $outbox['totalItems'] ?? 0;
358 if (!empty($statuses_count)) {
359 // Mastodon seriously allows for this condition?
360 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
361 if ($statuses_count < 0) {
364 $apcontact['statuses_count'] = $statuses_count;
368 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
370 if (!empty($apcontact['photo'])) {
371 $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
373 if (!Network::isValidHttpUrl($apcontact['photo'])) {
374 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
375 $apcontact['photo'] = '';
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'] = (string)Uri::fromParts($parts);
385 if (strlen($apcontact['photo']) > 255) {
386 unset($parts['query']);
387 $apcontact['photo'] = (string)Uri::fromParts($parts);
390 if (strlen($apcontact['photo']) > 255) {
391 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
395 if (!$webfinger && !empty($apcontact['addr'])) {
396 $data = self::fetchWebfingerData($apcontact['addr']);
398 $apcontact['baseurl'] = $data['baseurl'];
400 if (empty($apcontact['alias']) && !empty($data['alias'])) {
401 $apcontact['alias'] = $data['alias'];
403 if (!empty($data['subscribe'])) {
404 $apcontact['subscribe'] = $data['subscribe'];
407 $apcontact['addr'] = null;
411 if (empty($apcontact['baseurl'])) {
412 $apcontact['baseurl'] = null;
415 if (empty($apcontact['subscribe'])) {
416 $apcontact['subscribe'] = null;
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'];
424 $apcontact['gsid'] = null;
427 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
429 if (!empty($apcontact['sharedinbox'])) {
430 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
433 if ($apcontact['url'] == $apcontact['alias']) {
434 $apcontact['alias'] = null;
437 if (empty($apcontact['uuid'])) {
438 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
440 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
443 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
444 $value = JsonLD::fetchElement($compacted, $name, '@id');
448 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
451 if (!empty($compacted['as:endpoints'])) {
452 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
453 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
457 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
458 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
459 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
460 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
461 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
462 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
467 $apcontact['updated'] = DateTimeFormat::utcNow();
469 // We delete the old entry when the URL is changed
470 if ($url != $apcontact['url']) {
471 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
472 DBA::delete('apcontact', ['url' => $url]);
475 // Limit the length on incoming fields
476 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
478 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
479 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
481 DBA::replace('apcontact', $apcontact);
484 Logger::info('Updated profile', ['url' => $url]);
486 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
490 * Fetch the number of statuses for the given owner
492 * @param array $owner
496 private static function getStatusesCount(array $owner): int
499 'private' => [Item::PUBLIC, Item::UNLISTED],
500 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
501 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
502 'network' => Protocol::DFRN,
503 'parent-network' => Protocol::FEDERATED,
508 $count = Post::countPosts($condition);
514 * Mark the given AP Contact as "to archive"
516 * @param array $apcontact
519 public static function markForArchival(array $apcontact)
521 if (!empty($apcontact['inbox'])) {
522 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
523 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
526 if (!empty($apcontact['sharedinbox'])) {
527 // Check if there are any available inboxes
528 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
529 $apcontact['sharedinbox']]);
531 // If all known personal inboxes are failing then set their shared inbox to failure as well
532 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
533 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
539 * Unmark the given AP Contact as "to archive"
541 * @param array $apcontact
544 public static function unmarkForArchival(array $apcontact)
546 if (!empty($apcontact['inbox'])) {
547 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
548 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
550 if (!empty($apcontact['sharedinbox'])) {
551 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
552 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
559 * @param string $url inbox url
560 * @param boolean $shared Shared Inbox
561 * @param int $gsid Global server id
564 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
570 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
574 * Check if the apcontact is a relay account
576 * @param array $apcontact
580 public static function isRelay(array $apcontact): bool
582 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
586 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
590 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {