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;
29 use Friendica\Database\DBStructure;
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;
41 use Friendica\Util\Strings;
46 * Fetch webfinger data
48 * @param string $addr Address
49 * @return array webfinger data
51 private static function fetchWebfingerData(string $addr)
53 $addr_parts = explode('@', $addr);
54 if (count($addr_parts) != 2) {
58 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
60 'addr' => $local_owner['addr'],
61 'baseurl' => $local_owner['baseurl'],
62 'url' => $local_owner['url'],
63 'subscribe' => $local_owner['baseurl'] . '/follow?url={uri}'];
65 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
66 $data['alias'] = $local_owner['alias'];
72 $data = ['addr' => $addr];
73 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
74 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
75 if (empty($webfinger['links'])) {
76 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
77 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
78 if (empty($webfinger['links'])) {
81 $data['baseurl'] = 'http://' . $addr_parts[1];
83 $data['baseurl'] = 'https://' . $addr_parts[1];
86 foreach ($webfinger['links'] as $link) {
87 if (empty($link['rel'])) {
91 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
92 $data['subscribe'] = $link['template'];
95 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
96 $data['url'] = $link['href'];
99 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
100 $data['alias'] = $link['href'];
104 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
105 unset($data['alias']);
112 * Fetches a profile from a given url
114 * @param string $url profile url
115 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
116 * @return array profile array
117 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
118 * @throws \ImagickException
120 public static function getByURL($url, $update = null)
122 if (empty($url) || Network::isUrlBlocked($url)) {
123 Logger::info('Domain is blocked', ['url' => $url]);
127 $fetched_contact = false;
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'];
169 // Detect multiple fast repeating request to the same address
170 // See https://github.com/friendica/friendica/issues/9303
171 $cachekey = 'apcontact:getByURL:' . $url;
172 $result = DI::cache()->get($cachekey);
173 if (!is_null($result)) {
174 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
175 if (!empty($fetched_contact)) {
176 return $fetched_contact;
179 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
182 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
184 $data = Transmitter::getProfile($local_uid);
185 $local_owner = User::getOwnerDataById($local_uid);
186 } catch(HTTPException\NotFoundException $e) {
194 $curlResult = HTTPSignature::fetchRaw($url);
195 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
196 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
199 $data = json_decode($curlResult->getBody(), true);
200 $failed = empty($data) || !is_array($data);
203 if (!$failed && ($curlResult->getReturnCode() == 410)) {
204 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
208 self::markForArchival($fetched_contact ?: []);
209 return $fetched_contact;
213 $compacted = JsonLD::compact($data);
214 if (empty($compacted['@id'])) {
215 return $fetched_contact;
218 $apcontact['url'] = $compacted['@id'];
219 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
220 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
221 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
222 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
223 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
224 self::unarchiveInbox($apcontact['inbox'], false);
226 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
228 $apcontact['sharedinbox'] = '';
229 if (!empty($compacted['as:endpoints'])) {
230 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
231 self::unarchiveInbox($apcontact['sharedinbox'], true);
234 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
235 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
237 if (empty($apcontact['name'])) {
238 $apcontact['name'] = $apcontact['nick'];
241 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
243 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
245 foreach ($ims as $link) {
246 if (substr($link, 0, 5) == 'xmpp:') {
247 $apcontact['xmpp'] = substr($link, 5);
249 if (substr($link, 0, 7) == 'matrix:') {
250 $apcontact['matrix'] = substr($link, 7);
255 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
256 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
257 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
260 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
261 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
262 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
265 if (empty($apcontact['alias'])) {
266 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
267 if (is_array($apcontact['alias'])) {
268 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
272 // Quit if none of the basic values are set
273 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
274 return $fetched_contact;
275 } elseif ($apcontact['type'] == 'Tombstone') {
276 // The "inbox" field must have a content
277 $apcontact['inbox'] = '';
280 // Quit if this doesn't seem to be an account at all
281 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
282 return $fetched_contact;
285 $parts = parse_url($apcontact['url']);
286 unset($parts['scheme']);
287 unset($parts['path']);
289 if (empty($apcontact['addr'])) {
290 if (!empty($apcontact['nick']) && is_array($parts)) {
291 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
293 $apcontact['addr'] = '';
297 $apcontact['pubkey'] = null;
298 if (!empty($compacted['w3id:publicKey'])) {
299 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
300 if (strstr($apcontact['pubkey'], 'RSA ')) {
301 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
305 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
307 if (!empty($compacted['as:generator'])) {
308 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
309 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
312 if (!empty($apcontact['following'])) {
313 if (!empty($local_owner)) {
314 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
316 $following = ActivityPub::fetchContent($apcontact['following']);
318 if (!empty($following['totalItems'])) {
319 // Mastodon seriously allows for this condition?
320 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
321 if ($following['totalItems'] < 0) {
322 $following['totalItems'] = 0;
324 $apcontact['following_count'] = $following['totalItems'];
328 if (!empty($apcontact['followers'])) {
329 if (!empty($local_owner)) {
330 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
332 $followers = ActivityPub::fetchContent($apcontact['followers']);
334 if (!empty($followers['totalItems'])) {
335 // Mastodon seriously allows for this condition?
336 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
337 if ($followers['totalItems'] < 0) {
338 $followers['totalItems'] = 0;
340 $apcontact['followers_count'] = $followers['totalItems'];
344 if (!empty($apcontact['outbox'])) {
345 if (!empty($local_owner)) {
346 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
348 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
350 if (!empty($outbox['totalItems'])) {
351 // Mastodon seriously allows for this condition?
352 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
353 if ($outbox['totalItems'] < 0) {
354 $outbox['totalItems'] = 0;
356 $apcontact['statuses_count'] = $outbox['totalItems'];
360 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
365 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
367 // Unhandled from Misskey
368 // sharedInbox, isCat
370 // Unhandled from Kroeg
371 // kroeg:blocks, updated
373 // When the photo is too large, try to shorten it by removing parts
374 if (strlen($apcontact['photo']) > 255) {
375 $parts = parse_url($apcontact['photo']);
376 unset($parts['fragment']);
377 $apcontact['photo'] = Network::unparseURL($parts);
379 if (strlen($apcontact['photo']) > 255) {
380 unset($parts['query']);
381 $apcontact['photo'] = Network::unparseURL($parts);
384 if (strlen($apcontact['photo']) > 255) {
385 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
389 if (!$webfinger && !empty($apcontact['addr'])) {
390 $data = self::fetchWebfingerData($apcontact['addr']);
392 $apcontact['baseurl'] = $data['baseurl'];
394 if (empty($apcontact['alias']) && !empty($data['alias'])) {
395 $apcontact['alias'] = $data['alias'];
397 if (!empty($data['subscribe'])) {
398 $apcontact['subscribe'] = $data['subscribe'];
401 $apcontact['addr'] = null;
405 if (empty($apcontact['baseurl'])) {
406 $apcontact['baseurl'] = null;
409 if (empty($apcontact['subscribe'])) {
410 $apcontact['subscribe'] = null;
413 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
414 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
415 } elseif (!empty($fetched_contact['gsid'])) {
416 $apcontact['gsid'] = $fetched_contact['gsid'];
418 $apcontact['gsid'] = null;
421 if ($apcontact['url'] == $apcontact['alias']) {
422 $apcontact['alias'] = null;
425 if (empty($apcontact['uuid'])) {
426 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
428 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
431 $apcontact['updated'] = DateTimeFormat::utcNow();
433 // We delete the old entry when the URL is changed
434 if ($url != $apcontact['url']) {
435 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
436 DBA::delete('apcontact', ['url' => $url]);
439 // Limit the length on incoming fields
440 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
442 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
443 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
445 DBA::replace('apcontact', $apcontact);
448 Logger::info('Updated profile', ['url' => $url]);
450 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
454 * Mark the given AP Contact as "to archive"
456 * @param array $apcontact
459 public static function markForArchival(array $apcontact)
461 if (!empty($apcontact['inbox'])) {
462 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
463 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
466 if (!empty($apcontact['sharedinbox'])) {
467 // Check if there are any available inboxes
468 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
469 $apcontact['sharedinbox']]);
471 // If all known personal inboxes are failing then set their shared inbox to failure as well
472 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
473 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
479 * Unmark the given AP Contact as "to archive"
481 * @param array $apcontact
484 public static function unmarkForArchival(array $apcontact)
486 if (!empty($apcontact['inbox'])) {
487 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
488 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
490 if (!empty($apcontact['sharedinbox'])) {
491 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
492 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
499 * @param string $url inbox url
500 * @param boolean $shared Shared Inbox
502 private static function unarchiveInbox($url, $shared)
508 HTTPSignature::setInboxStatus($url, true, $shared);