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\HTTPClient\Client\HttpClientAccept;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\Probe;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\ActivityPub\Transmitter;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\HTTPSignature;
41 use Friendica\Util\JsonLD;
42 use Friendica\Util\Network;
43 use GuzzleHttp\Psr7\Uri;
48 * Fetch webfinger data
50 * @param string $addr Address
51 * @return array webfinger data
53 private static function fetchWebfingerData(string $addr): array
55 $addr_parts = explode('@', $addr);
56 if (count($addr_parts) != 2) {
60 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
62 'addr' => $local_owner['addr'],
63 'baseurl' => $local_owner['baseurl'],
64 'url' => $local_owner['url'],
65 'subscribe' => $local_owner['baseurl'] . '/contact/follow?url={uri}'];
67 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
68 $data['alias'] = $local_owner['alias'];
74 $webfinger = Probe::getWebfingerArray($addr);
75 if (empty($webfinger['webfinger']['links'])) {
79 $data['baseurl'] = $webfinger['baseurl'];
81 foreach ($webfinger['webfinger']['links'] as $link) {
82 if (empty($link['rel'])) {
86 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
87 $data['subscribe'] = $link['template'];
90 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
91 $data['url'] = $link['href'];
94 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
95 $data['alias'] = $link['href'];
99 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
100 unset($data['alias']);
107 * Fetches a profile from a given url
109 * @param string $url profile url
110 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
111 * @return array profile array
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
113 * @throws \ImagickException
114 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
116 public static function getByURL(string $url, $update = null): array
118 if (empty($url) || Network::isUrlBlocked($url)) {
119 Logger::info('Domain is blocked', ['url' => $url]);
123 $fetched_contact = [];
125 if (empty($update)) {
126 if (is_null($update)) {
127 $ref_update = DateTimeFormat::utc('now - 1 month');
129 $ref_update = DBA::NULL_DATETIME;
132 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
133 if (!DBA::isResult($apcontact)) {
134 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
137 if (!DBA::isResult($apcontact)) {
138 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
141 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
145 if (!is_null($update)) {
146 return DBA::isResult($apcontact) ? $apcontact : [];
149 if (DBA::isResult($apcontact)) {
150 $fetched_contact = $apcontact;
156 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
158 $apcontact = self::fetchWebfingerData($url);
159 if (empty($apcontact['url'])) {
160 return $fetched_contact;
162 $url = $apcontact['url'];
163 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
164 $apcontact['baseurl'] = $url;
167 // Detect multiple fast repeating request to the same address
168 // See https://github.com/friendica/friendica/issues/9303
169 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
170 $result = DI::cache()->get($cachekey);
171 if (!is_null($result)) {
172 Logger::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
173 if (!empty($fetched_contact)) {
174 return $fetched_contact;
177 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
180 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
182 $data = Transmitter::getProfile($local_uid);
183 $local_owner = User::getOwnerDataById($local_uid);
184 } catch(HTTPException\NotFoundException $e) {
193 $curlResult = HTTPSignature::fetchRaw($url);
194 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
195 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
198 $data = json_decode($curlResult->getBody(), true);
199 $failed = empty($data) || !is_array($data);
202 if (!$failed && ($curlResult->getReturnCode() == 410)) {
203 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
205 } catch (\Exception $exception) {
206 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
211 self::markForArchival($fetched_contact ?: []);
212 return $fetched_contact;
216 $compacted = JsonLD::compact($data);
217 if (empty($compacted['@id'])) {
218 return $fetched_contact;
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 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
229 $apcontact['sharedinbox'] = '';
230 if (!empty($compacted['as:endpoints'])) {
231 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
234 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
235 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
237 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
238 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
240 if (empty($apcontact['name'])) {
241 $apcontact['name'] = $apcontact['nick'];
244 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
246 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
249 foreach ($ims as $link) {
250 if (substr($link, 0, 5) == 'xmpp:') {
251 $apcontact['xmpp'] = substr($link, 5);
253 if (substr($link, 0, 7) == 'matrix:') {
254 $apcontact['matrix'] = substr($link, 7);
259 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
260 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
261 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
264 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
265 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
266 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
269 if (empty($apcontact['alias'])) {
270 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
271 if (is_array($apcontact['alias'])) {
272 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
276 // Quit if none of the basic values are set
277 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
278 return $fetched_contact;
279 } elseif ($apcontact['type'] == 'Tombstone') {
280 // The "inbox" field must have a content
281 $apcontact['inbox'] = '';
284 // Quit if this doesn't seem to be an account at all
285 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
286 return $fetched_contact;
289 if (empty($apcontact['addr'])) {
291 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
292 } catch (\Throwable $e) {
293 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
294 $apcontact['addr'] = '';
298 $apcontact['pubkey'] = null;
299 if (!empty($compacted['w3id:publicKey'])) {
300 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
301 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
302 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
306 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
308 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
310 if (!empty($compacted['as:generator'])) {
311 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
312 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
315 if (!empty($apcontact['following'])) {
316 if (!empty($local_owner)) {
317 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
319 $following = ActivityPub::fetchContent($apcontact['following']);
321 if (!empty($following['totalItems'])) {
322 // Mastodon seriously allows for this condition?
323 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
324 if ($following['totalItems'] < 0) {
325 $following['totalItems'] = 0;
327 $apcontact['following_count'] = $following['totalItems'];
331 if (!empty($apcontact['followers'])) {
332 if (!empty($local_owner)) {
333 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
335 $followers = ActivityPub::fetchContent($apcontact['followers']);
337 if (!empty($followers['totalItems'])) {
338 // Mastodon seriously allows for this condition?
339 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
340 if ($followers['totalItems'] < 0) {
341 $followers['totalItems'] = 0;
343 $apcontact['followers_count'] = $followers['totalItems'];
347 if (!empty($apcontact['outbox'])) {
348 if (!empty($local_owner)) {
349 $statuses_count = self::getStatusesCount($local_owner);
351 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
352 $statuses_count = $outbox['totalItems'] ?? 0;
354 if (!empty($statuses_count)) {
355 // Mastodon seriously allows for this condition?
356 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
357 if ($statuses_count < 0) {
360 $apcontact['statuses_count'] = $statuses_count;
364 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
366 if (!empty($apcontact['photo'])) {
367 $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
369 if (!Network::isValidHttpUrl($apcontact['photo'])) {
370 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
371 $apcontact['photo'] = '';
375 // When the photo is too large, try to shorten it by removing parts
376 if (strlen($apcontact['photo'] ?? '') > 255) {
377 $parts = parse_url($apcontact['photo']);
378 unset($parts['fragment']);
379 $apcontact['photo'] = (string)Uri::fromParts($parts);
381 if (strlen($apcontact['photo']) > 255) {
382 unset($parts['query']);
383 $apcontact['photo'] = (string)Uri::fromParts($parts);
386 if (strlen($apcontact['photo']) > 255) {
387 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
391 if (!$webfinger && !empty($apcontact['addr'])) {
392 $data = self::fetchWebfingerData($apcontact['addr']);
394 $apcontact['baseurl'] = $data['baseurl'];
396 if (empty($apcontact['alias']) && !empty($data['alias'])) {
397 $apcontact['alias'] = $data['alias'];
399 if (!empty($data['subscribe'])) {
400 $apcontact['subscribe'] = $data['subscribe'];
403 $apcontact['addr'] = null;
407 if (empty($apcontact['baseurl'])) {
408 $apcontact['baseurl'] = null;
411 if (empty($apcontact['subscribe'])) {
412 $apcontact['subscribe'] = null;
415 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
416 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
417 } elseif (!empty($fetched_contact['gsid'])) {
418 $apcontact['gsid'] = $fetched_contact['gsid'];
420 $apcontact['gsid'] = null;
423 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
425 if (!empty($apcontact['sharedinbox'])) {
426 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
429 if ($apcontact['url'] == $apcontact['alias']) {
430 $apcontact['alias'] = null;
433 if (empty($apcontact['uuid'])) {
434 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
436 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
439 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
440 $value = JsonLD::fetchElement($compacted, $name, '@id');
444 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
447 if (!empty($compacted['as:endpoints'])) {
448 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
449 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
453 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
454 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
455 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
456 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
457 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
458 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
463 $apcontact['updated'] = DateTimeFormat::utcNow();
465 // We delete the old entry when the URL is changed
466 if ($url != $apcontact['url']) {
467 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
468 DBA::delete('apcontact', ['url' => $url]);
471 // Limit the length on incoming fields
472 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
474 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
475 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
477 DBA::replace('apcontact', $apcontact);
480 Logger::info('Updated profile', ['url' => $url]);
482 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
486 * Fetch the number of statuses for the given owner
488 * @param array $owner
492 private static function getStatusesCount(array $owner): int
495 'private' => [Item::PUBLIC, Item::UNLISTED],
496 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
497 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
498 'network' => Protocol::DFRN,
499 'parent-network' => Protocol::FEDERATED,
504 $count = Post::countPosts($condition);
510 * Mark the given AP Contact as "to archive"
512 * @param array $apcontact
515 public static function markForArchival(array $apcontact)
517 if (!empty($apcontact['inbox'])) {
518 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
519 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
522 if (!empty($apcontact['sharedinbox'])) {
523 // Check if there are any available inboxes
524 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
525 $apcontact['sharedinbox']]);
527 // If all known personal inboxes are failing then set their shared inbox to failure as well
528 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
529 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
535 * Unmark the given AP Contact as "to archive"
537 * @param array $apcontact
540 public static function unmarkForArchival(array $apcontact)
542 if (!empty($apcontact['inbox'])) {
543 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
544 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
546 if (!empty($apcontact['sharedinbox'])) {
547 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
548 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
555 * @param string $url inbox url
556 * @param boolean $shared Shared Inbox
557 * @param int $gsid Global server id
560 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
566 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
570 * Check if the apcontact is a relay account
572 * @param array $apcontact
576 public static function isRelay(array $apcontact): bool
578 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
582 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
586 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {