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\System;
28 use Friendica\Database\DBA;
30 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
31 use Friendica\Network\HTTPException;
32 use Friendica\Network\Probe;
33 use Friendica\Protocol\ActivityNamespace;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Protocol\ActivityPub\Transmitter;
36 use Friendica\Util\Crypto;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\HTTPSignature;
39 use Friendica\Util\JsonLD;
40 use Friendica\Util\Network;
45 * Fetch webfinger data
47 * @param string $addr Address
48 * @return array webfinger data
50 private static function fetchWebfingerData(string $addr): array
52 $addr_parts = explode('@', $addr);
53 if (count($addr_parts) != 2) {
57 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
59 'addr' => $local_owner['addr'],
60 'baseurl' => $local_owner['baseurl'],
61 'url' => $local_owner['url'],
62 'subscribe' => $local_owner['baseurl'] . '/follow?url={uri}'];
64 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
65 $data['alias'] = $local_owner['alias'];
71 $data = ['addr' => $addr];
72 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
73 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClientAccept::JRD_JSON);
74 if (empty($webfinger['links'])) {
75 $template = 'http://' . $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'])) {
80 $data['baseurl'] = 'http://' . $addr_parts[1];
82 $data['baseurl'] = 'https://' . $addr_parts[1];
85 foreach ($webfinger['links'] as $link) {
86 if (empty($link['rel'])) {
90 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
91 $data['subscribe'] = $link['template'];
94 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
95 $data['url'] = $link['href'];
98 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
99 $data['alias'] = $link['href'];
103 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
104 unset($data['alias']);
111 * Fetches a profile from a given url
113 * @param string $url profile url
114 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
115 * @return array profile array
116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117 * @throws \ImagickException
118 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
120 public static function getByURL(string $url, $update = null): array
122 if (empty($url) || Network::isUrlBlocked($url)) {
123 Logger::info('Domain is blocked', ['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 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
162 $apcontact = self::fetchWebfingerData($url);
163 if (empty($apcontact['url'])) {
164 return $fetched_contact;
166 $url = $apcontact['url'];
167 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
168 $apcontact['baseurl'] = $url;
171 // Detect multiple fast repeating request to the same address
172 // See https://github.com/friendica/friendica/issues/9303
173 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
174 $result = DI::cache()->get($cachekey);
175 if (!is_null($result)) {
176 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
177 if (!empty($fetched_contact)) {
178 return $fetched_contact;
181 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
184 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
186 $data = Transmitter::getProfile($local_uid);
187 $local_owner = User::getOwnerDataById($local_uid);
188 } catch(HTTPException\NotFoundException $e) {
196 $curlResult = HTTPSignature::fetchRaw($url);
197 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
198 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
201 $data = json_decode($curlResult->getBody(), true);
202 $failed = empty($data) || !is_array($data);
205 if (!$failed && ($curlResult->getReturnCode() == 410)) {
206 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
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 self::unarchiveInbox($apcontact['inbox'], false);
228 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
230 $apcontact['sharedinbox'] = '';
231 if (!empty($compacted['as:endpoints'])) {
232 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
233 self::unarchiveInbox($apcontact['sharedinbox'], true);
236 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
237 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
239 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
240 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
242 if (empty($apcontact['name'])) {
243 $apcontact['name'] = $apcontact['nick'];
246 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
248 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
251 foreach ($ims as $link) {
252 if (substr($link, 0, 5) == 'xmpp:') {
253 $apcontact['xmpp'] = substr($link, 5);
255 if (substr($link, 0, 7) == 'matrix:') {
256 $apcontact['matrix'] = substr($link, 7);
261 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
262 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
263 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
266 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
267 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
268 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
271 if (empty($apcontact['alias'])) {
272 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
273 if (is_array($apcontact['alias'])) {
274 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
278 // Quit if none of the basic values are set
279 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
280 return $fetched_contact;
281 } elseif ($apcontact['type'] == 'Tombstone') {
282 // The "inbox" field must have a content
283 $apcontact['inbox'] = '';
286 // Quit if this doesn't seem to be an account at all
287 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
288 return $fetched_contact;
291 $parts = parse_url($apcontact['url']);
292 unset($parts['scheme']);
293 unset($parts['path']);
295 if (empty($apcontact['addr'])) {
296 if (!empty($apcontact['nick']) && is_array($parts)) {
297 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
299 $apcontact['addr'] = '';
303 $apcontact['pubkey'] = null;
304 if (!empty($compacted['w3id:publicKey'])) {
305 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
306 if (strstr($apcontact['pubkey'], 'RSA ')) {
307 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
311 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
313 if (!empty($compacted['as:generator'])) {
314 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
315 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
318 if (!empty($apcontact['following'])) {
319 if (!empty($local_owner)) {
320 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
322 $following = ActivityPub::fetchContent($apcontact['following']);
324 if (!empty($following['totalItems'])) {
325 // Mastodon seriously allows for this condition?
326 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
327 if ($following['totalItems'] < 0) {
328 $following['totalItems'] = 0;
330 $apcontact['following_count'] = $following['totalItems'];
334 if (!empty($apcontact['followers'])) {
335 if (!empty($local_owner)) {
336 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
338 $followers = ActivityPub::fetchContent($apcontact['followers']);
340 if (!empty($followers['totalItems'])) {
341 // Mastodon seriously allows for this condition?
342 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
343 if ($followers['totalItems'] < 0) {
344 $followers['totalItems'] = 0;
346 $apcontact['followers_count'] = $followers['totalItems'];
350 if (!empty($apcontact['outbox'])) {
351 if (!empty($local_owner)) {
352 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
354 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
356 if (!empty($outbox['totalItems'])) {
357 // Mastodon seriously allows for this condition?
358 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
359 if ($outbox['totalItems'] < 0) {
360 $outbox['totalItems'] = 0;
362 $apcontact['statuses_count'] = $outbox['totalItems'];
366 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
371 // tag, attachment, image, nomadicLocations, signature, movedTo, liked
373 // Unhandled from Misskey
374 // sharedInbox, isCat
376 // Unhandled from Kroeg
377 // kroeg:blocks, updated
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'] = Network::unparseURL($parts);
385 if (strlen($apcontact['photo']) > 255) {
386 unset($parts['query']);
387 $apcontact['photo'] = Network::unparseURL($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 if ($apcontact['url'] == $apcontact['alias']) {
428 $apcontact['alias'] = null;
431 if (empty($apcontact['uuid'])) {
432 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
434 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
437 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
438 $value = JsonLD::fetchElement($compacted, $name, '@id');
442 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
445 if (!empty($compacted['as:endpoints'])) {
446 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
447 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
451 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
452 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
453 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
454 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
455 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
456 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
461 $apcontact['updated'] = DateTimeFormat::utcNow();
463 // We delete the old entry when the URL is changed
464 if ($url != $apcontact['url']) {
465 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
466 DBA::delete('apcontact', ['url' => $url]);
469 // Limit the length on incoming fields
470 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
472 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
473 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
475 DBA::replace('apcontact', $apcontact);
478 Logger::info('Updated profile', ['url' => $url]);
480 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
484 * Mark the given AP Contact as "to archive"
486 * @param array $apcontact
489 public static function markForArchival(array $apcontact)
491 if (!empty($apcontact['inbox'])) {
492 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
493 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
496 if (!empty($apcontact['sharedinbox'])) {
497 // Check if there are any available inboxes
498 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
499 $apcontact['sharedinbox']]);
501 // If all known personal inboxes are failing then set their shared inbox to failure as well
502 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
503 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
509 * Unmark the given AP Contact as "to archive"
511 * @param array $apcontact
514 public static function unmarkForArchival(array $apcontact)
516 if (!empty($apcontact['inbox'])) {
517 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
518 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
520 if (!empty($apcontact['sharedinbox'])) {
521 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
522 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
529 * @param string $url inbox url
530 * @param boolean $shared Shared Inbox
533 private static function unarchiveInbox(string $url, bool $shared)
539 HTTPSignature::setInboxStatus($url, true, $shared);
543 * Check if the apcontact is a relay account
545 * @param array $apcontact
549 public static function isRelay(array $apcontact): bool
551 if ($apcontact['nick'] != 'relay') {
555 if ($apcontact['type'] == 'Application') {
559 if (in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {