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\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'] . '/contact/follow?url={uri}'];
66 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
67 $data['alias'] = $local_owner['alias'];
73 $webfinger = Probe::getWebfingerArray($addr);
74 if (empty($webfinger['webfinger']['links'])) {
78 $data['baseurl'] = $webfinger['baseurl'];
80 foreach ($webfinger['webfinger']['links'] as $link) {
81 if (empty($link['rel'])) {
85 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
86 $data['subscribe'] = $link['template'];
89 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
90 $data['url'] = $link['href'];
93 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
94 $data['alias'] = $link['href'];
98 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
99 unset($data['alias']);
106 * Fetches a profile from a given url
108 * @param string $url profile url
109 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
110 * @return array profile array
111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
112 * @throws \ImagickException
113 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
115 public static function getByURL(string $url, $update = null): array
117 if (empty($url) || Network::isUrlBlocked($url)) {
118 Logger::info('Domain is blocked', ['url' => $url]);
122 $fetched_contact = [];
124 if (empty($update)) {
125 if (is_null($update)) {
126 $ref_update = DateTimeFormat::utc('now - 1 month');
128 $ref_update = DBA::NULL_DATETIME;
131 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
132 if (!DBA::isResult($apcontact)) {
133 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
136 if (!DBA::isResult($apcontact)) {
137 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
140 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
144 if (!is_null($update)) {
145 return DBA::isResult($apcontact) ? $apcontact : [];
148 if (DBA::isResult($apcontact)) {
149 $fetched_contact = $apcontact;
155 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
157 $apcontact = self::fetchWebfingerData($url);
158 if (empty($apcontact['url'])) {
159 return $fetched_contact;
161 $url = $apcontact['url'];
162 } elseif (empty(parse_url($url, PHP_URL_PATH))) {
163 $apcontact['baseurl'] = $url;
166 // Detect multiple fast repeating request to the same address
167 // See https://github.com/friendica/friendica/issues/9303
168 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
169 $result = DI::cache()->get($cachekey);
170 if (!is_null($result)) {
171 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
172 if (!empty($fetched_contact)) {
173 return $fetched_contact;
176 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
179 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
181 $data = Transmitter::getProfile($local_uid);
182 $local_owner = User::getOwnerDataById($local_uid);
183 } catch(HTTPException\NotFoundException $e) {
191 $curlResult = HTTPSignature::fetchRaw($url);
192 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
193 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
196 $data = json_decode($curlResult->getBody(), true);
197 $failed = empty($data) || !is_array($data);
200 if (!$failed && ($curlResult->getReturnCode() == 410)) {
201 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
205 self::markForArchival($fetched_contact ?: []);
206 return $fetched_contact;
210 $compacted = JsonLD::compact($data);
211 if (empty($compacted['@id'])) {
212 return $fetched_contact;
215 $apcontact['url'] = $compacted['@id'];
216 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
217 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
218 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
219 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
220 $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
221 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
223 $apcontact['sharedinbox'] = '';
224 if (!empty($compacted['as:endpoints'])) {
225 $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
228 $apcontact['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
229 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
231 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
232 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
234 if (empty($apcontact['name'])) {
235 $apcontact['name'] = $apcontact['nick'];
238 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
240 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
243 foreach ($ims as $link) {
244 if (substr($link, 0, 5) == 'xmpp:') {
245 $apcontact['xmpp'] = substr($link, 5);
247 if (substr($link, 0, 7) == 'matrix:') {
248 $apcontact['matrix'] = substr($link, 7);
253 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
254 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
255 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
258 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
259 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
260 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
263 if (empty($apcontact['alias'])) {
264 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
265 if (is_array($apcontact['alias'])) {
266 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
270 // Quit if none of the basic values are set
271 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
272 return $fetched_contact;
273 } elseif ($apcontact['type'] == 'Tombstone') {
274 // The "inbox" field must have a content
275 $apcontact['inbox'] = '';
278 // Quit if this doesn't seem to be an account at all
279 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
280 return $fetched_contact;
283 if (empty($apcontact['addr'])) {
285 $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
286 } catch (\Throwable $e) {
287 Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
288 $apcontact['addr'] = '';
292 $apcontact['pubkey'] = null;
293 if (!empty($compacted['w3id:publicKey'])) {
294 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value') ?? '');
295 if (strpos($apcontact['pubkey'], 'RSA ') !== false) {
296 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
300 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
302 $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended');
304 if (!empty($compacted['as:generator'])) {
305 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
306 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
309 if (!empty($apcontact['following'])) {
310 if (!empty($local_owner)) {
311 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
313 $following = ActivityPub::fetchContent($apcontact['following']);
315 if (!empty($following['totalItems'])) {
316 // Mastodon seriously allows for this condition?
317 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
318 if ($following['totalItems'] < 0) {
319 $following['totalItems'] = 0;
321 $apcontact['following_count'] = $following['totalItems'];
325 if (!empty($apcontact['followers'])) {
326 if (!empty($local_owner)) {
327 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
329 $followers = ActivityPub::fetchContent($apcontact['followers']);
331 if (!empty($followers['totalItems'])) {
332 // Mastodon seriously allows for this condition?
333 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
334 if ($followers['totalItems'] < 0) {
335 $followers['totalItems'] = 0;
337 $apcontact['followers_count'] = $followers['totalItems'];
341 if (!empty($apcontact['outbox'])) {
342 if (!empty($local_owner)) {
343 $statuses_count = self::getStatusesCount($local_owner);
345 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
346 $statuses_count = $outbox['totalItems'] ?? 0;
348 if (!empty($statuses_count)) {
349 // Mastodon seriously allows for this condition?
350 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
351 if ($statuses_count < 0) {
354 $apcontact['statuses_count'] = $statuses_count;
358 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
360 if (!empty($apcontact['photo'])) {
361 $apcontact['photo'] = trim($apcontact['photo']);
364 if (!empty($apcontact['photo']) && !Network::isValidHttpUrl($apcontact['photo'])) {
365 Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
366 $apcontact['photo'] = '';
369 // When the photo is too large, try to shorten it by removing parts
370 if (strlen($apcontact['photo'] ?? '') > 255) {
371 $parts = parse_url($apcontact['photo']);
372 unset($parts['fragment']);
373 $apcontact['photo'] = (string)Uri::fromParts($parts);
375 if (strlen($apcontact['photo']) > 255) {
376 unset($parts['query']);
377 $apcontact['photo'] = (string)Uri::fromParts($parts);
380 if (strlen($apcontact['photo']) > 255) {
381 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
385 if (!$webfinger && !empty($apcontact['addr'])) {
386 $data = self::fetchWebfingerData($apcontact['addr']);
388 $apcontact['baseurl'] = $data['baseurl'];
390 if (empty($apcontact['alias']) && !empty($data['alias'])) {
391 $apcontact['alias'] = $data['alias'];
393 if (!empty($data['subscribe'])) {
394 $apcontact['subscribe'] = $data['subscribe'];
397 $apcontact['addr'] = null;
401 if (empty($apcontact['baseurl'])) {
402 $apcontact['baseurl'] = null;
405 if (empty($apcontact['subscribe'])) {
406 $apcontact['subscribe'] = null;
409 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
410 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
411 } elseif (!empty($fetched_contact['gsid'])) {
412 $apcontact['gsid'] = $fetched_contact['gsid'];
414 $apcontact['gsid'] = null;
417 self::unarchiveInbox($apcontact['inbox'], false, $apcontact['gsid']);
419 if (!empty($apcontact['sharedinbox'])) {
420 self::unarchiveInbox($apcontact['sharedinbox'], true, $apcontact['gsid']);
423 if ($apcontact['url'] == $apcontact['alias']) {
424 $apcontact['alias'] = null;
427 if (empty($apcontact['uuid'])) {
428 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
430 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
433 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
434 $value = JsonLD::fetchElement($compacted, $name, '@id');
438 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
441 if (!empty($compacted['as:endpoints'])) {
442 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
443 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
447 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
448 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
449 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
450 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
451 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
452 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
457 $apcontact['updated'] = DateTimeFormat::utcNow();
459 // We delete the old entry when the URL is changed
460 if ($url != $apcontact['url']) {
461 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
462 DBA::delete('apcontact', ['url' => $url]);
465 // Limit the length on incoming fields
466 $apcontact = DI::dbaDefinition()->truncateFieldsForTable('apcontact', $apcontact);
468 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
469 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
471 DBA::replace('apcontact', $apcontact);
474 Logger::info('Updated profile', ['url' => $url]);
476 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
480 * Fetch the number of statuses for the given owner
482 * @param array $owner
486 private static function getStatusesCount(array $owner): int
489 'private' => [Item::PUBLIC, Item::UNLISTED],
490 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
491 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
492 'network' => Protocol::DFRN,
493 'parent-network' => Protocol::FEDERATED,
498 $count = Post::countPosts($condition);
504 * Mark the given AP Contact as "to archive"
506 * @param array $apcontact
509 public static function markForArchival(array $apcontact)
511 if (!empty($apcontact['inbox'])) {
512 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
513 HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
516 if (!empty($apcontact['sharedinbox'])) {
517 // Check if there are any available inboxes
518 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
519 $apcontact['sharedinbox']]);
521 // If all known personal inboxes are failing then set their shared inbox to failure as well
522 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
523 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
529 * Unmark the given AP Contact as "to archive"
531 * @param array $apcontact
534 public static function unmarkForArchival(array $apcontact)
536 if (!empty($apcontact['inbox'])) {
537 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
538 HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
540 if (!empty($apcontact['sharedinbox'])) {
541 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
542 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
549 * @param string $url inbox url
550 * @param boolean $shared Shared Inbox
551 * @param int $gsid Global server id
554 private static function unarchiveInbox(string $url, bool $shared, int $gsid = null)
560 HTTPSignature::setInboxStatus($url, true, $shared, $gsid);
564 * Check if the apcontact is a relay account
566 * @param array $apcontact
570 public static function isRelay(array $apcontact): bool
572 if (empty($apcontact['nick']) || $apcontact['nick'] != 'relay') {
576 if (!empty($apcontact['type']) && $apcontact['type'] == 'Application') {
580 if (!empty($apcontact['type']) && in_array($apcontact['type'], ['Group', 'Service']) && is_null($apcontact['outbox'])) {