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 // Mastodon profile short-form URL https://domain.tld/@user doesn't return AP data when queried
161 // with HTTPSignature::fetchRaw, but returns the correct data when provided to WebFinger
162 // @see https://github.com/friendica/friendica/issues/13359
163 $webfinger = empty(parse_url($url, PHP_URL_SCHEME)) || strpos($url, '@') !== false;
165 $apcontact = self::fetchWebfingerData($url);
166 if (empty($apcontact['url'])) {
167 return $fetched_contact;
169 $url = $apcontact['url'];
170 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
171 $apcontact['baseurl'] = $url;
174 // Detect multiple fast repeating request to the same address
175 // See https://github.com/friendica/friendica/issues/9303
176 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
177 $result = DI::cache()->get($cachekey);
178 if (!is_null($result)) {
179 Logger::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
180 if (!empty($fetched_contact)) {
181 return $fetched_contact;
184 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
187 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
189 $data = Transmitter::getProfile($local_uid);
190 $local_owner = User::getOwnerDataById($local_uid);
191 } catch(HTTPException\NotFoundException $e) {
200 $curlResult = HTTPSignature::fetchRaw($url);
201 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
202 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
205 $data = json_decode($curlResult->getBody(), true);
206 $failed = empty($data) || !is_array($data);
209 if (!$failed && ($curlResult->getReturnCode() == 410)) {
210 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
212 } catch (\Exception $exception) {
213 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
218 self::markForArchival($fetched_contact ?: []);
219 return $fetched_contact;
223 $compacted = JsonLD::compact($data);
224 if (empty($compacted['@id'])) {
225 return $fetched_contact;
228 $apcontact['url'] = $compacted['@id'];
229 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
230 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
231 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
232 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
233 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
234 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
236 $apcontact['sharedinbox'] = '';
237 if (!empty($compacted['as:endpoints'])) {
238 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
241 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
242 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
244 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
245 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
247 if (empty($apcontact['name'])) {
248 $apcontact['name'] = $apcontact['nick'];
251 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
253 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
256 foreach ($ims as $link) {
257 if (substr($link, 0, 5) == 'xmpp:') {
258 $apcontact['xmpp'] = substr($link, 5);
260 if (substr($link, 0, 7) == 'matrix:') {
261 $apcontact['matrix'] = substr($link, 7);
266 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
267 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
268 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
269 } elseif (empty($apcontact['photo'])) {
270 $photo = JsonLD::fetchElementArray($compacted, 'as:icon', 'as:url');
271 if (!empty($photo[0]['@id'])) {
272 $apcontact['photo'] = $photo[0]['@id'];
276 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
277 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
278 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
281 if (empty($apcontact['alias'])) {
282 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
283 if (is_array($apcontact['alias'])) {
284 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
288 // Quit if none of the basic values are set
289 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
290 return $fetched_contact;
291 } elseif ($apcontact['type'] == 'Tombstone') {
292 // The "inbox" field must have a content
293 $apcontact['inbox'] = '';
296 // Quit if this doesn't seem to be an account at all
297 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
298 return $fetched_contact;
301 if (empty($apcontact['addr'])) {
303 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
304 } catch (\Throwable $e) {
305 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
306 $apcontact['addr'] = '';
310 $apcontact['pubkey'] = null;
311 if (!empty($compacted['w3id:publicKey'])) {
312 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
313 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
314 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
318 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
320 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
322 if (!empty($compacted['as:generator'])) {
323 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
324 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
327 if (!empty($apcontact['following'])) {
328 if (!empty($local_owner)) {
329 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
331 $following = ActivityPub::fetchContent($apcontact['following']);
333 if (!empty($following['totalItems'])) {
334 // Mastodon seriously allows for this condition?
335 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
336 if ($following['totalItems'] < 0) {
337 $following['totalItems'] = 0;
339 $apcontact['following_count'] = $following['totalItems'];
343 if (!empty($apcontact['followers'])) {
344 if (!empty($local_owner)) {
345 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
347 $followers = ActivityPub::fetchContent($apcontact['followers']);
349 if (!empty($followers['totalItems'])) {
350 // Mastodon seriously allows for this condition?
351 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
352 if ($followers['totalItems'] < 0) {
353 $followers['totalItems'] = 0;
355 $apcontact['followers_count'] = $followers['totalItems'];
359 if (!empty($apcontact['outbox'])) {
360 if (!empty($local_owner)) {
361 $statuses_count = self::getStatusesCount($local_owner);
363 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
364 $statuses_count = $outbox['totalItems'] ?? 0;
366 if (!empty($statuses_count)) {
367 // Mastodon seriously allows for this condition?
368 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
369 if ($statuses_count < 0) {
372 $apcontact['statuses_count'] = $statuses_count;
376 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
378 if (!empty($apcontact['photo'])) {
379 $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
381 if (!Network::isValidHttpUrl($apcontact['photo'])) {
382 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
383 $apcontact['photo'] = '';
387 // When the photo is too large, try to shorten it by removing parts
388 if (strlen($apcontact['photo'] ?? '') > 255) {
389 $parts = parse_url($apcontact['photo']);
390 unset($parts['fragment']);
391 $apcontact['photo'] = (string)Uri::fromParts($parts);
393 if (strlen($apcontact['photo']) > 255) {
394 unset($parts['query']);
395 $apcontact['photo'] = (string)Uri::fromParts($parts);
398 if (strlen($apcontact['photo']) > 255) {
399 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
403 if (!$webfinger && !empty($apcontact['addr'])) {
404 $data = self::fetchWebfingerData($apcontact['addr']);
406 $apcontact['baseurl'] = $data['baseurl'];
408 if (empty($apcontact['alias']) && !empty($data['alias'])) {
409 $apcontact['alias'] = $data['alias'];
411 if (!empty($data['subscribe'])) {
412 $apcontact['subscribe'] = $data['subscribe'];
415 $apcontact['addr'] = null;
419 if (empty($apcontact['baseurl'])) {
420 $apcontact['baseurl'] = null;
423 if (empty($apcontact['subscribe'])) {
424 $apcontact['subscribe'] = null;
427 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
428 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
429 } elseif (!empty($fetched_contact['gsid'])) {
430 $apcontact['gsid'] = $fetched_contact['gsid'];
432 $apcontact['gsid'] = null;
435 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
437 if (!empty($apcontact['sharedinbox'])) {
438 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
441 if ($apcontact['url'] == $apcontact['alias']) {
442 $apcontact['alias'] = null;
445 if (empty($apcontact['uuid'])) {
446 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
448 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
451 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
452 $value = JsonLD::fetchElement($compacted, $name, '@id');
456 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
459 if (!empty($compacted['as:endpoints'])) {
460 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
461 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
465 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
466 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
467 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
468 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
469 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
470 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
475 $apcontact['updated'] = DateTimeFormat::utcNow();
477 // We delete the old entry when the URL is changed
478 if ($url != $apcontact['url']) {
479 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
480 DBA::delete('apcontact', ['url' => $url]);
483 // Limit the length on incoming fields
484 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
486 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
487 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
489 DBA::replace('apcontact', $apcontact);
492 Logger::info('Updated profile', ['url' => $url]);
494 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
498 * Fetch the number of statuses for the given owner
500 * @param array $owner
504 private static function getStatusesCount(array $owner): int
507 'private' => [Item::PUBLIC, Item::UNLISTED],
508 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
509 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
510 'network' => Protocol::DFRN,
511 'parent-network' => Protocol::FEDERATED,
516 $count = Post::countPosts($condition);
522 * Mark the given AP Contact as "to archive"
524 * @param array $apcontact
527 public static function markForArchival(array $apcontact)
529 if (!empty($apcontact['inbox'])) {
530 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
531 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
534 if (!empty($apcontact['sharedinbox'])) {
535 // Check if there are any available inboxes
536 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
537 $apcontact['sharedinbox']]);
539 // If all known personal inboxes are failing then set their shared inbox to failure as well
540 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
541 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
547 * Unmark the given AP Contact as "to archive"
549 * @param array $apcontact
552 public static function unmarkForArchival(array $apcontact)
554 if (!empty($apcontact['inbox'])) {
555 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
556 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
558 if (!empty($apcontact['sharedinbox'])) {
559 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
560 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
567 * @param string $url inbox url
568 * @param boolean $shared Shared Inbox
569 * @param int $gsid Global server id
572 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
578 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
582 * Check if the apcontact is a relay account
584 * @param array $apcontact
588 public static function isRelay(array $apcontact): bool
590 if (in_array($apcontact['type'], ['Person', 'Organization'])) {
594 if (($apcontact['type'] == 'Service') && empty($apcontact['outbox']) && empty($apcontact['sharedinbox']) && empty($apcontact['following']) && empty($apcontact['followers']) && empty($apcontact['statuses_count'])) {
598 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
602 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
606 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {