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\HTTPClient\Client\HttpClient;
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 Friendica\Util\Strings;
47 * Fetch webfinger data
49 * @param string $addr Address
50 * @return array webfinger data
52 private static function fetchWebfingerData(string $addr)
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), HttpClient::ACCEPT_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), HttpClient::ACCEPT_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
121 public static function getByURL($url, $update = null)
123 if (empty($url) || Network::isUrlBlocked($url)) {
124 Logger::info('Domain is blocked', ['url' => $url]);
128 $fetched_contact = false;
130 if (empty($update)) {
131 if (is_null($update)) {
132 $ref_update = DateTimeFormat::utc('now - 1 month');
134 $ref_update = DBA::NULL_DATETIME;
137 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
138 if (!DBA::isResult($apcontact)) {
139 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
142 if (!DBA::isResult($apcontact)) {
143 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
146 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
150 if (!is_null($update)) {
151 return DBA::isResult($apcontact) ? $apcontact : [];
154 if (DBA::isResult($apcontact)) {
155 $fetched_contact = $apcontact;
161 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
163 $apcontact = self::fetchWebfingerData($url);
164 if (empty($apcontact['url'])) {
165 return $fetched_contact;
167 $url = $apcontact['url'];
170 // Detect multiple fast repeating request to the same address
171 // See https://github.com/friendica/friendica/issues/9303
172 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
173 $result = DI::cache()->get($cachekey);
174 if (!is_null($result)) {
175 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
176 if (!empty($fetched_contact)) {
177 return $fetched_contact;
180 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
183 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
185 $data = Transmitter::getProfile($local_uid);
186 $local_owner = User::getOwnerDataById($local_uid);
187 } catch(HTTPException\NotFoundException $e) {
195 $curlResult = HTTPSignature::fetchRaw($url);
196 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
197 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
200 $data = json_decode($curlResult->getBody(), true);
201 $failed = empty($data) || !is_array($data);
204 if (!$failed && ($curlResult->getReturnCode() == 410)) {
205 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
209 self::markForArchival($fetched_contact ?: []);
210 return $fetched_contact;
214 $compacted = JsonLD::compact($data);
215 if (empty($compacted['@id'])) {
216 return $fetched_contact;
219 $apcontact['url'] = $compacted['@id'];
220 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
221 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
222 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
223 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
224 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
225 self::unarchiveInbox($apcontact['inbox'], false);
227 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
229 $apcontact['sharedinbox'] = '';
230 if (!empty($compacted['as:endpoints'])) {
231 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
232 self::unarchiveInbox($apcontact['sharedinbox'], true);
235 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
236 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
238 if (empty($apcontact['name'])) {
239 $apcontact['name'] = $apcontact['nick'];
242 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
244 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
246 foreach ($ims as $link) {
247 if (substr($link, 0, 5) == 'xmpp:') {
248 $apcontact['xmpp'] = substr($link, 5);
250 if (substr($link, 0, 7) == 'matrix:') {
251 $apcontact['matrix'] = substr($link, 7);
256 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
257 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
258 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
261 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
262 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
263 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
266 if (empty($apcontact['alias'])) {
267 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
268 if (is_array($apcontact['alias'])) {
269 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
273 // Quit if none of the basic values are set
274 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
275 return $fetched_contact;
276 } elseif ($apcontact['type'] == 'Tombstone') {
277 // The "inbox" field must have a content
278 $apcontact['inbox'] = '';
281 // Quit if this doesn't seem to be an account at all
282 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
283 return $fetched_contact;
286 $parts = parse_url($apcontact['url']);
287 unset($parts['scheme']);
288 unset($parts['path']);
290 if (empty($apcontact['addr'])) {
291 if (!empty($apcontact['nick']) && is_array($parts)) {
292 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
294 $apcontact['addr'] = '';
298 $apcontact['pubkey'] = null;
299 if (!empty($compacted['w3id:publicKey'])) {
300 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
301 if (strstr($apcontact['pubkey'], 'RSA ')) {
302 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
306 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
308 if (!empty($compacted['as:generator'])) {
309 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
310 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
313 if (!empty($apcontact['following'])) {
314 if (!empty($local_owner)) {
315 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
317 $following = ActivityPub::fetchContent($apcontact['following']);
319 if (!empty($following['totalItems'])) {
320 // Mastodon seriously allows for this condition?
321 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
322 if ($following['totalItems'] < 0) {
323 $following['totalItems'] = 0;
325 $apcontact['following_count'] = $following['totalItems'];
329 if (!empty($apcontact['followers'])) {
330 if (!empty($local_owner)) {
331 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
333 $followers = ActivityPub::fetchContent($apcontact['followers']);
335 if (!empty($followers['totalItems'])) {
336 // Mastodon seriously allows for this condition?
337 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
338 if ($followers['totalItems'] < 0) {
339 $followers['totalItems'] = 0;
341 $apcontact['followers_count'] = $followers['totalItems'];
345 if (!empty($apcontact['outbox'])) {
346 if (!empty($local_owner)) {
347 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
349 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
351 if (!empty($outbox['totalItems'])) {
352 // Mastodon seriously allows for this condition?
353 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
354 if ($outbox['totalItems'] < 0) {
355 $outbox['totalItems'] = 0;
357 $apcontact['statuses_count'] = $outbox['totalItems'];
361 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
366 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
368 // Unhandled from Misskey
369 // sharedInbox, isCat
371 // Unhandled from Kroeg
372 // kroeg:blocks, updated
374 // When the photo is too large, try to shorten it by removing parts
375 if (strlen($apcontact['photo']) > 255) {
376 $parts = parse_url($apcontact['photo']);
377 unset($parts['fragment']);
378 $apcontact['photo'] = Network::unparseURL($parts);
380 if (strlen($apcontact['photo']) > 255) {
381 unset($parts['query']);
382 $apcontact['photo'] = Network::unparseURL($parts);
385 if (strlen($apcontact['photo']) > 255) {
386 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
390 if (!$webfinger && !empty($apcontact['addr'])) {
391 $data = self::fetchWebfingerData($apcontact['addr']);
393 $apcontact['baseurl'] = $data['baseurl'];
395 if (empty($apcontact['alias']) && !empty($data['alias'])) {
396 $apcontact['alias'] = $data['alias'];
398 if (!empty($data['subscribe'])) {
399 $apcontact['subscribe'] = $data['subscribe'];
402 $apcontact['addr'] = null;
406 if (empty($apcontact['baseurl'])) {
407 $apcontact['baseurl'] = null;
410 if (empty($apcontact['subscribe'])) {
411 $apcontact['subscribe'] = null;
414 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
415 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
416 } elseif (!empty($fetched_contact['gsid'])) {
417 $apcontact['gsid'] = $fetched_contact['gsid'];
419 $apcontact['gsid'] = null;
422 if ($apcontact['url'] == $apcontact['alias']) {
423 $apcontact['alias'] = null;
426 if (empty($apcontact['uuid'])) {
427 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
429 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
432 $apcontact['updated'] = DateTimeFormat::utcNow();
434 // We delete the old entry when the URL is changed
435 if ($url != $apcontact['url']) {
436 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
437 DBA::delete('apcontact', ['url' => $url]);
440 // Limit the length on incoming fields
441 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
443 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
444 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
446 DBA::replace('apcontact', $apcontact);
449 Logger::info('Updated profile', ['url' => $url]);
451 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
455 * Mark the given AP Contact as "to archive"
457 * @param array $apcontact
460 public static function markForArchival(array $apcontact)
462 if (!empty($apcontact['inbox'])) {
463 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
464 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
467 if (!empty($apcontact['sharedinbox'])) {
468 // Check if there are any available inboxes
469 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
470 $apcontact['sharedinbox']]);
472 // If all known personal inboxes are failing then set their shared inbox to failure as well
473 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
474 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
480 * Unmark the given AP Contact as "to archive"
482 * @param array $apcontact
485 public static function unmarkForArchival(array $apcontact)
487 if (!empty($apcontact['inbox'])) {
488 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
489 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
491 if (!empty($apcontact['sharedinbox'])) {
492 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
493 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
500 * @param string $url inbox url
501 * @param boolean $shared Shared Inbox
503 private static function unarchiveInbox($url, $shared)
509 HTTPSignature::setInboxStatus($url, true, $shared);