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::notice('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) {
192 $curlResult = HTTPSignature::fetchRaw($url);
193 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
194 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
197 $data = json_decode($curlResult->getBody(), true);
198 $failed = empty($data) || !is_array($data);
201 if (!$failed && ($curlResult->getReturnCode() == 410)) {
202 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
206 self::markForArchival($fetched_contact ?: []);
207 return $fetched_contact;
211 $compacted = JsonLD::compact($data);
212 if (empty($compacted['@id'])) {
213 return $fetched_contact;
216 $apcontact['url'] = $compacted['@id'];
217 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
218 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
219 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
220 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
221 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
222 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
224 $apcontact['sharedinbox'] = '';
225 if (!empty($compacted['as:endpoints'])) {
226 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
229 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
230 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
232 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
233 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
235 if (empty($apcontact['name'])) {
236 $apcontact['name'] = $apcontact['nick'];
239 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
241 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
244 foreach ($ims as $link) {
245 if (substr($link, 0, 5) == 'xmpp:') {
246 $apcontact['xmpp'] = substr($link, 5);
248 if (substr($link, 0, 7) == 'matrix:') {
249 $apcontact['matrix'] = substr($link, 7);
254 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
255 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
256 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
259 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
260 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
261 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
264 if (empty($apcontact['alias'])) {
265 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
266 if (is_array($apcontact['alias'])) {
267 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
271 // Quit if none of the basic values are set
272 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
273 return $fetched_contact;
274 } elseif ($apcontact['type'] == 'Tombstone') {
275 // The "inbox" field must have a content
276 $apcontact['inbox'] = '';
279 // Quit if this doesn't seem to be an account at all
280 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
281 return $fetched_contact;
284 if (empty($apcontact['addr'])) {
286 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
287 } catch (\Throwable $e) {
288 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
289 $apcontact['addr'] = '';
293 $apcontact['pubkey'] = null;
294 if (!empty($compacted['w3id:publicKey'])) {
295 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
296 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
297 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
301 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
303 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
305 if (!empty($compacted['as:generator'])) {
306 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
307 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
310 if (!empty($apcontact['following'])) {
311 if (!empty($local_owner)) {
312 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
314 $following = ActivityPub::fetchContent($apcontact['following']);
316 if (!empty($following['totalItems'])) {
317 // Mastodon seriously allows for this condition?
318 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
319 if ($following['totalItems'] < 0) {
320 $following['totalItems'] = 0;
322 $apcontact['following_count'] = $following['totalItems'];
326 if (!empty($apcontact['followers'])) {
327 if (!empty($local_owner)) {
328 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
330 $followers = ActivityPub::fetchContent($apcontact['followers']);
332 if (!empty($followers['totalItems'])) {
333 // Mastodon seriously allows for this condition?
334 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
335 if ($followers['totalItems'] < 0) {
336 $followers['totalItems'] = 0;
338 $apcontact['followers_count'] = $followers['totalItems'];
342 if (!empty($apcontact['outbox'])) {
343 if (!empty($local_owner)) {
344 $statuses_count = self::getStatusesCount($local_owner);
346 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
347 $statuses_count = $outbox['totalItems'] ?? 0;
349 if (!empty($statuses_count)) {
350 // Mastodon seriously allows for this condition?
351 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
352 if ($statuses_count < 0) {
355 $apcontact['statuses_count'] = $statuses_count;
359 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
361 if (!empty($apcontact['photo'])) {
362 $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
364 if (!Network::isValidHttpUrl($apcontact['photo'])) {
365 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
366 $apcontact['photo'] = '';
370 // When the photo is too large, try to shorten it by removing parts
371 if (strlen($apcontact['photo'] ?? '') > 255) {
372 $parts = parse_url($apcontact['photo']);
373 unset($parts['fragment']);
374 $apcontact['photo'] = (string)Uri::fromParts($parts);
376 if (strlen($apcontact['photo']) > 255) {
377 unset($parts['query']);
378 $apcontact['photo'] = (string)Uri::fromParts($parts);
381 if (strlen($apcontact['photo']) > 255) {
382 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
386 if (!$webfinger && !empty($apcontact['addr'])) {
387 $data = self::fetchWebfingerData($apcontact['addr']);
389 $apcontact['baseurl'] = $data['baseurl'];
391 if (empty($apcontact['alias']) && !empty($data['alias'])) {
392 $apcontact['alias'] = $data['alias'];
394 if (!empty($data['subscribe'])) {
395 $apcontact['subscribe'] = $data['subscribe'];
398 $apcontact['addr'] = null;
402 if (empty($apcontact['baseurl'])) {
403 $apcontact['baseurl'] = null;
406 if (empty($apcontact['subscribe'])) {
407 $apcontact['subscribe'] = null;
410 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
411 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
412 } elseif (!empty($fetched_contact['gsid'])) {
413 $apcontact['gsid'] = $fetched_contact['gsid'];
415 $apcontact['gsid'] = null;
418 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
420 if (!empty($apcontact['sharedinbox'])) {
421 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
424 if ($apcontact['url'] == $apcontact['alias']) {
425 $apcontact['alias'] = null;
428 if (empty($apcontact['uuid'])) {
429 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
431 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
434 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
435 $value = JsonLD::fetchElement($compacted, $name, '@id');
439 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
442 if (!empty($compacted['as:endpoints'])) {
443 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
444 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
448 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
449 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
450 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
451 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
452 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
453 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
458 $apcontact['updated'] = DateTimeFormat::utcNow();
460 // We delete the old entry when the URL is changed
461 if ($url != $apcontact['url']) {
462 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
463 DBA::delete('apcontact', ['url' => $url]);
466 // Limit the length on incoming fields
467 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
469 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
470 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
472 DBA::replace('apcontact', $apcontact);
475 Logger::info('Updated profile', ['url' => $url]);
477 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
481 * Fetch the number of statuses for the given owner
483 * @param array $owner
487 private static function getStatusesCount(array $owner): int
490 'private' => [Item::PUBLIC, Item::UNLISTED],
491 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
492 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
493 'network' => Protocol::DFRN,
494 'parent-network' => Protocol::FEDERATED,
499 $count = Post::countPosts($condition);
505 * Mark the given AP Contact as "to archive"
507 * @param array $apcontact
510 public static function markForArchival(array $apcontact)
512 if (!empty($apcontact['inbox'])) {
513 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
514 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
517 if (!empty($apcontact['sharedinbox'])) {
518 // Check if there are any available inboxes
519 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
520 $apcontact['sharedinbox']]);
522 // If all known personal inboxes are failing then set their shared inbox to failure as well
523 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
524 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
530 * Unmark the given AP Contact as "to archive"
532 * @param array $apcontact
535 public static function unmarkForArchival(array $apcontact)
537 if (!empty($apcontact['inbox'])) {
538 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
539 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
541 if (!empty($apcontact['sharedinbox'])) {
542 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
543 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
550 * @param string $url inbox url
551 * @param boolean $shared Shared Inbox
552 * @param int $gsid Global server id
555 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
561 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
565 * Check if the apcontact is a relay account
567 * @param array $apcontact
571 public static function isRelay(array $apcontact): bool
573 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
577 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
581 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {