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\Network\HTTPClient\Client\HttpClientAccept;
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'] . '/follow?url={uri}'];
66 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
67 $data['alias'] = $local_owner['alias'];
73 $data = ['addr' => $addr];
74 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
75 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClientAccept::JRD_JSON);
76 if (empty($webfinger['links'])) {
77 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
78 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClientAccept::JRD_JSON);
79 if (empty($webfinger['links'])) {
82 $data['baseurl'] = 'http://' . $addr_parts[1];
84 $data['baseurl'] = 'https://' . $addr_parts[1];
87 foreach ($webfinger['links'] as $link) {
88 if (empty($link['rel'])) {
92 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
93 $data['subscribe'] = $link['template'];
96 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
97 $data['url'] = $link['href'];
100 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
101 $data['alias'] = $link['href'];
105 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
106 unset($data['alias']);
113 * Fetches a profile from a given url
115 * @param string $url profile url
116 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
117 * @return array profile array
118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119 * @throws \ImagickException
120 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
122 public static function getByURL(string $url, $update = null): array
124 if (empty($url) || Network::isUrlBlocked($url)) {
125 Logger::info('Domain is blocked', ['url' => $url]);
129 $fetched_contact = [];
131 if (empty($update)) {
132 if (is_null($update)) {
133 $ref_update = DateTimeFormat::utc('now - 1 month');
135 $ref_update = DBA::NULL_DATETIME;
138 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
139 if (!DBA::isResult($apcontact)) {
140 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
143 if (!DBA::isResult($apcontact)) {
144 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
147 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
151 if (!is_null($update)) {
152 return DBA::isResult($apcontact) ? $apcontact : [];
155 if (DBA::isResult($apcontact)) {
156 $fetched_contact = $apcontact;
162 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
164 $apcontact = self::fetchWebfingerData($url);
165 if (empty($apcontact['url'])) {
166 return $fetched_contact;
168 $url = $apcontact['url'];
169 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
170 $apcontact['baseurl'] = $url;
173 // Detect multiple fast repeating request to the same address
174 // See https://github.com/friendica/friendica/issues/9303
175 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
176 $result = DI::cache()->get($cachekey);
177 if (!is_null($result)) {
178 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
179 if (!empty($fetched_contact)) {
180 return $fetched_contact;
183 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
186 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
188 $data = Transmitter::getProfile($local_uid);
189 $local_owner = User::getOwnerDataById($local_uid);
190 } catch(HTTPException\NotFoundException $e) {
198 $curlResult = HTTPSignature::fetchRaw($url);
199 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
200 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
203 $data = json_decode($curlResult->getBody(), true);
204 $failed = empty($data) || !is_array($data);
207 if (!$failed && ($curlResult->getReturnCode() == 410)) {
208 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
212 self::markForArchival($fetched_contact ?: []);
213 return $fetched_contact;
217 $compacted = JsonLD::compact($data);
218 if (empty($compacted['@id'])) {
219 return $fetched_contact;
222 $apcontact['url'] = $compacted['@id'];
223 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
224 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
225 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
226 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
227 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
228 self::unarchiveInbox($apcontact['inbox'], false);
230 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
232 $apcontact['sharedinbox'] = '';
233 if (!empty($compacted['as:endpoints'])) {
234 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
235 self::unarchiveInbox($apcontact['sharedinbox'], true);
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');
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 $parts = parse_url($apcontact['url']);
294 unset($parts['scheme']);
295 unset($parts['path']);
297 if (empty($apcontact['addr'])) {
298 if (!empty($apcontact['nick']) && is_array($parts)) {
299 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
301 $apcontact['addr'] = '';
305 $apcontact['pubkey'] = null;
306 if (!empty($compacted['w3id:publicKey'])) {
307 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
308 if (strstr($apcontact['pubkey'], 'RSA ')) {
309 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
313 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
315 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
317 if (!empty($compacted['as:generator'])) {
318 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
319 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
322 if (!empty($apcontact['following'])) {
323 if (!empty($local_owner)) {
324 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
326 $following = ActivityPub::fetchContent($apcontact['following']);
328 if (!empty($following['totalItems'])) {
329 // Mastodon seriously allows for this condition?
330 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
331 if ($following['totalItems'] < 0) {
332 $following['totalItems'] = 0;
334 $apcontact['following_count'] = $following['totalItems'];
338 if (!empty($apcontact['followers'])) {
339 if (!empty($local_owner)) {
340 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
342 $followers = ActivityPub::fetchContent($apcontact['followers']);
344 if (!empty($followers['totalItems'])) {
345 // Mastodon seriously allows for this condition?
346 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
347 if ($followers['totalItems'] < 0) {
348 $followers['totalItems'] = 0;
350 $apcontact['followers_count'] = $followers['totalItems'];
354 if (!empty($apcontact['outbox'])) {
355 if (!empty($local_owner)) {
356 $statuses_count = self::getStatusesCount($local_owner);
358 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
359 $statuses_count = $outbox['totalItems'] ?? 0;
361 if (!empty($statuses_count)) {
362 // Mastodon seriously allows for this condition?
363 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
364 if ($statuses_count < 0) {
367 $apcontact['statuses_count'] = $statuses_count;
371 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
376 // tag, attachment, image, nomadicLocations, signature, movedTo, liked
378 // Unhandled from Misskey
379 // sharedInbox, isCat
381 // Unhandled from Kroeg
382 // kroeg:blocks, updated
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 if ($apcontact['url'] == $apcontact['alias']) {
433 $apcontact['alias'] = null;
436 if (empty($apcontact['uuid'])) {
437 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
439 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
442 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
443 $value = JsonLD::fetchElement($compacted, $name, '@id');
447 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
450 if (!empty($compacted['as:endpoints'])) {
451 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
452 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
456 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
457 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
458 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
459 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
460 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
461 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
466 $apcontact['updated'] = DateTimeFormat::utcNow();
468 // We delete the old entry when the URL is changed
469 if ($url != $apcontact['url']) {
470 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
471 DBA::delete('apcontact', ['url' => $url]);
474 // Limit the length on incoming fields
475 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
477 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
478 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
480 DBA::replace('apcontact', $apcontact);
483 Logger::info('Updated profile', ['url' => $url]);
485 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
489 * Fetch the number of statuses for the given owner
491 * @param array $owner
495 private static function getStatusesCount(array $owner): int
498 'private' => [Item::PUBLIC, Item::UNLISTED],
499 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
500 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
501 'network' => Protocol::DFRN,
502 'parent-network' => Protocol::FEDERATED,
507 $count = Post::countPosts($condition);
513 * Mark the given AP Contact as "to archive"
515 * @param array $apcontact
518 public static function markForArchival(array $apcontact)
520 if (!empty($apcontact['inbox'])) {
521 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
522 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
525 if (!empty($apcontact['sharedinbox'])) {
526 // Check if there are any available inboxes
527 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
528 $apcontact['sharedinbox']]);
530 // If all known personal inboxes are failing then set their shared inbox to failure as well
531 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
532 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
538 * Unmark the given AP Contact as "to archive"
540 * @param array $apcontact
543 public static function unmarkForArchival(array $apcontact)
545 if (!empty($apcontact['inbox'])) {
546 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
547 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
549 if (!empty($apcontact['sharedinbox'])) {
550 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
551 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
558 * @param string $url inbox url
559 * @param boolean $shared Shared Inbox
562 private static function unarchiveInbox(string $url, bool $shared)
568 HTTPSignature::setInboxStatus($url, true, $shared);
572 * Check if the apcontact is a relay account
574 * @param array $apcontact
578 public static function isRelay(array $apcontact): bool
580 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
584 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
588 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {