3 * @copyright Copyright (C) 2010-2022, 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 $data = ['addr' => $addr];
75 $template = 'https://' . $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 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
79 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClientAccept::JRD_JSON);
80 if (empty($webfinger['links'])) {
83 $data['baseurl'] = 'http://' . $addr_parts[1];
85 $data['baseurl'] = 'https://' . $addr_parts[1];
88 foreach ($webfinger['links'] as $link) {
89 if (empty($link['rel'])) {
93 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
94 $data['subscribe'] = $link['template'];
97 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
98 $data['url'] = $link['href'];
101 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
102 $data['alias'] = $link['href'];
106 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
107 unset($data['alias']);
114 * Fetches a profile from a given url
116 * @param string $url profile url
117 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
118 * @return array profile array
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
120 * @throws \ImagickException
121 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
123 public static function getByURL(string $url, $update = null): array
125 if (empty($url) || Network::isUrlBlocked($url)) {
126 Logger::info('Domain is blocked', ['url' => $url]);
130 $fetched_contact = [];
132 if (empty($update)) {
133 if (is_null($update)) {
134 $ref_update = DateTimeFormat::utc('now - 1 month');
136 $ref_update = DBA::NULL_DATETIME;
139 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
140 if (!DBA::isResult($apcontact)) {
141 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
144 if (!DBA::isResult($apcontact)) {
145 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
148 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
152 if (!is_null($update)) {
153 return DBA::isResult($apcontact) ? $apcontact : [];
156 if (DBA::isResult($apcontact)) {
157 $fetched_contact = $apcontact;
163 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
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::notice('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) {
199 $curlResult = HTTPSignature::fetchRaw($url);
200 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
201 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
204 $data = json_decode($curlResult->getBody(), true);
205 $failed = empty($data) || !is_array($data);
208 if (!$failed && ($curlResult->getReturnCode() == 410)) {
209 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
213 self::markForArchival($fetched_contact ?: []);
214 return $fetched_contact;
218 $compacted = JsonLD::compact($data);
219 if (empty($compacted['@id'])) {
220 return $fetched_contact;
223 $apcontact['url'] = $compacted['@id'];
224 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
225 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
226 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
227 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
228 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
229 self::unarchiveInbox($apcontact['inbox'], false);
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') ?? '');
236 self::unarchiveInbox($apcontact['sharedinbox'], true);
239 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
240 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
242 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
243 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
245 if (empty($apcontact['name'])) {
246 $apcontact['name'] = $apcontact['nick'];
249 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
251 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
254 foreach ($ims as $link) {
255 if (substr($link, 0, 5) == 'xmpp:') {
256 $apcontact['xmpp'] = substr($link, 5);
258 if (substr($link, 0, 7) == 'matrix:') {
259 $apcontact['matrix'] = substr($link, 7);
264 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
265 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
266 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
269 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
270 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
271 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
274 if (empty($apcontact['alias'])) {
275 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
276 if (is_array($apcontact['alias'])) {
277 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
281 // Quit if none of the basic values are set
282 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
283 return $fetched_contact;
284 } elseif ($apcontact['type'] == 'Tombstone') {
285 // The "inbox" field must have a content
286 $apcontact['inbox'] = '';
289 // Quit if this doesn't seem to be an account at all
290 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
291 return $fetched_contact;
294 $parts = parse_url($apcontact['url']);
295 unset($parts['scheme']);
296 unset($parts['path']);
298 if (empty($apcontact['addr'])) {
299 if (!empty($apcontact['nick']) && is_array($parts)) {
300 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
302 $apcontact['addr'] = '';
306 $apcontact['pubkey'] = null;
307 if (!empty($compacted['w3id:publicKey'])) {
308 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
309 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
310 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
314 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
316 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
318 if (!empty($compacted['as:generator'])) {
319 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
320 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
323 if (!empty($apcontact['following'])) {
324 if (!empty($local_owner)) {
325 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
327 $following = ActivityPub::fetchContent($apcontact['following']);
329 if (!empty($following['totalItems'])) {
330 // Mastodon seriously allows for this condition?
331 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
332 if ($following['totalItems'] < 0) {
333 $following['totalItems'] = 0;
335 $apcontact['following_count'] = $following['totalItems'];
339 if (!empty($apcontact['followers'])) {
340 if (!empty($local_owner)) {
341 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
343 $followers = ActivityPub::fetchContent($apcontact['followers']);
345 if (!empty($followers['totalItems'])) {
346 // Mastodon seriously allows for this condition?
347 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
348 if ($followers['totalItems'] < 0) {
349 $followers['totalItems'] = 0;
351 $apcontact['followers_count'] = $followers['totalItems'];
355 if (!empty($apcontact['outbox'])) {
356 if (!empty($local_owner)) {
357 $statuses_count = self::getStatusesCount($local_owner);
359 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
360 $statuses_count = $outbox['totalItems'] ?? 0;
362 if (!empty($statuses_count)) {
363 // Mastodon seriously allows for this condition?
364 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
365 if ($statuses_count < 0) {
368 $apcontact['statuses_count'] = $statuses_count;
372 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
377 // tag, attachment, image, nomadicLocations, signature, movedTo, liked
379 // Unhandled from Misskey
380 // sharedInbox, isCat
382 // Unhandled from Kroeg
383 // kroeg:blocks, updated
385 // When the photo is too large, try to shorten it by removing parts
386 if (strlen($apcontact['photo'] ?? '') > 255) {
387 $parts = parse_url($apcontact['photo']);
388 unset($parts['fragment']);
389 $apcontact['photo'] = (string)Uri::fromParts($parts);
391 if (strlen($apcontact['photo']) > 255) {
392 unset($parts['query']);
393 $apcontact['photo'] = (string)Uri::fromParts($parts);
396 if (strlen($apcontact['photo']) > 255) {
397 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
401 if (!$webfinger && !empty($apcontact['addr'])) {
402 $data = self::fetchWebfingerData($apcontact['addr']);
404 $apcontact['baseurl'] = $data['baseurl'];
406 if (empty($apcontact['alias']) && !empty($data['alias'])) {
407 $apcontact['alias'] = $data['alias'];
409 if (!empty($data['subscribe'])) {
410 $apcontact['subscribe'] = $data['subscribe'];
413 $apcontact['addr'] = null;
417 if (empty($apcontact['baseurl'])) {
418 $apcontact['baseurl'] = null;
421 if (empty($apcontact['subscribe'])) {
422 $apcontact['subscribe'] = null;
425 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
426 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
427 } elseif (!empty($fetched_contact['gsid'])) {
428 $apcontact['gsid'] = $fetched_contact['gsid'];
430 $apcontact['gsid'] = null;
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);
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);
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);
550 if (!empty($apcontact['sharedinbox'])) {
551 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
552 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
559 * @param string $url inbox url
560 * @param boolean $shared Shared Inbox
563 private static function unarchiveInbox(string $url, bool $shared)
569 HTTPSignature::setInboxStatus($url, true, $shared);
573 * Check if the apcontact is a relay account
575 * @param array $apcontact
579 public static function isRelay(array $apcontact): bool
581 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
585 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
589 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {