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\HttpClientAccept;
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;
46 * Fetch webfinger data
48 * @param string $addr Address
49 * @return array webfinger data
51 private static function fetchWebfingerData(string $addr): array
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), HttpClientAccept::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), HttpClientAccept::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
119 * @todo Rewrite parameter $update to avoid true|false|null (boolean is binary, null adds a third case)
121 public static function getByURL(string $url, $update = null): array
123 if (empty($url) || Network::isUrlBlocked($url)) {
124 Logger::info('Domain is blocked', ['url' => $url]);
128 $fetched_contact = [];
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['featured'] = JsonLD::fetchElement($compacted, 'toot:featured', '@id');
236 $apcontact['featured-tags'] = JsonLD::fetchElement($compacted, 'toot:featuredTags', '@id');
238 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
239 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
241 if (empty($apcontact['name'])) {
242 $apcontact['name'] = $apcontact['nick'];
245 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value') ?? '');
247 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
250 foreach ($ims as $link) {
251 if (substr($link, 0, 5) == 'xmpp:') {
252 $apcontact['xmpp'] = substr($link, 5);
254 if (substr($link, 0, 7) == 'matrix:') {
255 $apcontact['matrix'] = substr($link, 7);
260 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
261 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
262 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
265 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
266 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
267 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
270 if (empty($apcontact['alias'])) {
271 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
272 if (is_array($apcontact['alias'])) {
273 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
277 // Quit if none of the basic values are set
278 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
279 return $fetched_contact;
280 } elseif ($apcontact['type'] == 'Tombstone') {
281 // The "inbox" field must have a content
282 $apcontact['inbox'] = '';
285 // Quit if this doesn't seem to be an account at all
286 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
287 return $fetched_contact;
290 $parts = parse_url($apcontact['url']);
291 unset($parts['scheme']);
292 unset($parts['path']);
294 if (empty($apcontact['addr'])) {
295 if (!empty($apcontact['nick']) && is_array($parts)) {
296 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
298 $apcontact['addr'] = '';
302 $apcontact['pubkey'] = null;
303 if (!empty($compacted['w3id:publicKey'])) {
304 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
305 if (strstr($apcontact['pubkey'], 'RSA ')) {
306 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
310 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
312 if (!empty($compacted['as:generator'])) {
313 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
314 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
317 if (!empty($apcontact['following'])) {
318 if (!empty($local_owner)) {
319 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
321 $following = ActivityPub::fetchContent($apcontact['following']);
323 if (!empty($following['totalItems'])) {
324 // Mastodon seriously allows for this condition?
325 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
326 if ($following['totalItems'] < 0) {
327 $following['totalItems'] = 0;
329 $apcontact['following_count'] = $following['totalItems'];
333 if (!empty($apcontact['followers'])) {
334 if (!empty($local_owner)) {
335 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
337 $followers = ActivityPub::fetchContent($apcontact['followers']);
339 if (!empty($followers['totalItems'])) {
340 // Mastodon seriously allows for this condition?
341 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
342 if ($followers['totalItems'] < 0) {
343 $followers['totalItems'] = 0;
345 $apcontact['followers_count'] = $followers['totalItems'];
349 if (!empty($apcontact['outbox'])) {
350 if (!empty($local_owner)) {
351 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
353 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
355 if (!empty($outbox['totalItems'])) {
356 // Mastodon seriously allows for this condition?
357 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
358 if ($outbox['totalItems'] < 0) {
359 $outbox['totalItems'] = 0;
361 $apcontact['statuses_count'] = $outbox['totalItems'];
365 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
370 // tag, attachment, image, nomadicLocations, signature, movedTo, liked
372 // Unhandled from Misskey
373 // sharedInbox, isCat
375 // Unhandled from Kroeg
376 // kroeg:blocks, updated
378 // When the photo is too large, try to shorten it by removing parts
379 if (strlen($apcontact['photo']) > 255) {
380 $parts = parse_url($apcontact['photo']);
381 unset($parts['fragment']);
382 $apcontact['photo'] = Network::unparseURL($parts);
384 if (strlen($apcontact['photo']) > 255) {
385 unset($parts['query']);
386 $apcontact['photo'] = Network::unparseURL($parts);
389 if (strlen($apcontact['photo']) > 255) {
390 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
394 if (!$webfinger && !empty($apcontact['addr'])) {
395 $data = self::fetchWebfingerData($apcontact['addr']);
397 $apcontact['baseurl'] = $data['baseurl'];
399 if (empty($apcontact['alias']) && !empty($data['alias'])) {
400 $apcontact['alias'] = $data['alias'];
402 if (!empty($data['subscribe'])) {
403 $apcontact['subscribe'] = $data['subscribe'];
406 $apcontact['addr'] = null;
410 if (empty($apcontact['baseurl'])) {
411 $apcontact['baseurl'] = null;
414 if (empty($apcontact['subscribe'])) {
415 $apcontact['subscribe'] = null;
418 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
419 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
420 } elseif (!empty($fetched_contact['gsid'])) {
421 $apcontact['gsid'] = $fetched_contact['gsid'];
423 $apcontact['gsid'] = null;
426 if ($apcontact['url'] == $apcontact['alias']) {
427 $apcontact['alias'] = null;
430 if (empty($apcontact['uuid'])) {
431 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
433 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
436 foreach (APContact\Endpoint::ENDPOINT_NAMES as $type => $name) {
437 $value = JsonLD::fetchElement($compacted, $name, '@id');
441 APContact\Endpoint::update($apcontact['uri-id'], $type, $value);
444 if (!empty($compacted['as:endpoints'])) {
445 foreach ($compacted['as:endpoints'] as $name => $endpoint) {
446 if (empty($endpoint['@id']) || !is_string($endpoint['@id'])) {
450 if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
451 $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
452 APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
453 Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
454 } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
455 Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
460 $apcontact['updated'] = DateTimeFormat::utcNow();
462 // We delete the old entry when the URL is changed
463 if ($url != $apcontact['url']) {
464 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
465 DBA::delete('apcontact', ['url' => $url]);
468 // Limit the length on incoming fields
469 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
471 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
472 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
474 DBA::replace('apcontact', $apcontact);
477 Logger::info('Updated profile', ['url' => $url]);
479 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
483 * Mark the given AP Contact as "to archive"
485 * @param array $apcontact
488 public static function markForArchival(array $apcontact)
490 if (!empty($apcontact['inbox'])) {
491 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
492 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
495 if (!empty($apcontact['sharedinbox'])) {
496 // Check if there are any available inboxes
497 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
498 $apcontact['sharedinbox']]);
500 // If all known personal inboxes are failing then set their shared inbox to failure as well
501 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
502 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
508 * Unmark the given AP Contact as "to archive"
510 * @param array $apcontact
513 public static function unmarkForArchival(array $apcontact)
515 if (!empty($apcontact['inbox'])) {
516 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
517 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
519 if (!empty($apcontact['sharedinbox'])) {
520 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
521 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
528 * @param string $url inbox url
529 * @param boolean $shared Shared Inbox
532 private static function unarchiveInbox(string $url, bool $shared)
538 HTTPSignature::setInboxStatus($url, true, $shared);