3 * @copyright Copyright (C) 2010-2021, 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\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\Probe;
32 use Friendica\Protocol\ActivityNamespace;
33 use Friendica\Protocol\ActivityPub;
34 use Friendica\Protocol\ActivityPub\Transmitter;
35 use Friendica\Util\Crypto;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
45 * Fetch webfinger data
47 * @param string $addr Address
48 * @return array webfinger data
50 private static function fetchWebfingerData(string $addr)
52 $addr_parts = explode('@', $addr);
53 if (count($addr_parts) != 2) {
57 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
59 'addr' => $local_owner['addr'],
60 'baseurl' => $local_owner['baseurl'],
61 'url' => $local_owner['url'],
62 'subscribe' => $local_owner['baseurl'] . '/follow?url={uri}'];
64 if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
65 $data['alias'] = $local_owner['alias'];
71 $data = ['addr' => $addr];
72 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
73 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
74 if (empty($webfinger['links'])) {
75 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
76 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
77 if (empty($webfinger['links'])) {
80 $data['baseurl'] = 'http://' . $addr_parts[1];
82 $data['baseurl'] = 'https://' . $addr_parts[1];
85 foreach ($webfinger['links'] as $link) {
86 if (empty($link['rel'])) {
90 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
91 $data['subscribe'] = $link['template'];
94 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
95 $data['url'] = $link['href'];
98 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
99 $data['alias'] = $link['href'];
103 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
104 unset($data['alias']);
111 * Fetches a profile from a given url
113 * @param string $url profile url
114 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
115 * @return array profile array
116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117 * @throws \ImagickException
119 public static function getByURL($url, $update = null)
125 $fetched_contact = false;
127 if (empty($update)) {
128 if (is_null($update)) {
129 $ref_update = DateTimeFormat::utc('now - 1 month');
131 $ref_update = DBA::NULL_DATETIME;
134 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
135 if (!DBA::isResult($apcontact)) {
136 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
139 if (!DBA::isResult($apcontact)) {
140 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
143 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
147 if (!is_null($update)) {
148 return DBA::isResult($apcontact) ? $apcontact : [];
151 if (DBA::isResult($apcontact)) {
152 $fetched_contact = $apcontact;
158 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
160 $apcontact = self::fetchWebfingerData($url);
161 if (empty($apcontact['url'])) {
162 return $fetched_contact;
164 $url = $apcontact['url'];
167 // Detect multiple fast repeating request to the same address
168 // See https://github.com/friendica/friendica/issues/9303
169 $cachekey = 'apcontact:getByURL:' . $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))) {
181 $data = Transmitter::getProfile($local_uid);
182 $local_owner = User::getOwnerDataById($local_uid);
188 $curlResult = HTTPSignature::fetchRaw($url);
189 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
190 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
193 $data = json_decode($curlResult->getBody(), true);
194 $failed = empty($data) || !is_array($data);
197 if (!$failed && ($curlResult->getReturnCode() == 410)) {
198 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
202 self::markForArchival($fetched_contact ?: []);
203 return $fetched_contact;
207 $compacted = JsonLD::compact($data);
208 if (empty($compacted['@id'])) {
209 return $fetched_contact;
212 $apcontact['url'] = $compacted['@id'];
213 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
214 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
215 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
216 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
217 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
218 self::unarchiveInbox($apcontact['inbox'], false);
220 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
222 $apcontact['sharedinbox'] = '';
223 if (!empty($compacted['as:endpoints'])) {
224 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
225 self::unarchiveInbox($apcontact['sharedinbox'], true);
228 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
229 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
231 if (empty($apcontact['name'])) {
232 $apcontact['name'] = $apcontact['nick'];
235 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
237 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
238 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
239 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
242 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
243 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
244 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
247 if (empty($apcontact['alias'])) {
248 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
249 if (is_array($apcontact['alias'])) {
250 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
254 // Quit if none of the basic values are set
255 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
256 return $fetched_contact;
257 } elseif ($apcontact['type'] == 'Tombstone') {
258 // The "inbox" field must have a content
259 $apcontact['inbox'] = '';
262 // Quit if this doesn't seem to be an account at all
263 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
264 return $fetched_contact;
267 $parts = parse_url($apcontact['url']);
268 unset($parts['scheme']);
269 unset($parts['path']);
271 if (empty($apcontact['addr'])) {
272 if (!empty($apcontact['nick']) && is_array($parts)) {
273 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
275 $apcontact['addr'] = '';
279 $apcontact['pubkey'] = null;
280 if (!empty($compacted['w3id:publicKey'])) {
281 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
282 if (strstr($apcontact['pubkey'], 'RSA ')) {
283 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
287 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
289 if (!empty($compacted['as:generator'])) {
290 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
291 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
294 if (!empty($apcontact['following'])) {
295 if (!empty($local_owner)) {
296 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
298 $following = ActivityPub::fetchContent($apcontact['following']);
300 if (!empty($following['totalItems'])) {
301 // Mastodon seriously allows for this condition?
302 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
303 if ($following['totalItems'] < 0) {
304 $following['totalItems'] = 0;
306 $apcontact['following_count'] = $following['totalItems'];
310 if (!empty($apcontact['followers'])) {
311 if (!empty($local_owner)) {
312 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
314 $followers = ActivityPub::fetchContent($apcontact['followers']);
316 if (!empty($followers['totalItems'])) {
317 // Mastodon seriously allows for this condition?
318 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
319 if ($followers['totalItems'] < 0) {
320 $followers['totalItems'] = 0;
322 $apcontact['followers_count'] = $followers['totalItems'];
326 if (!empty($apcontact['outbox'])) {
327 if (!empty($local_owner)) {
328 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
330 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
332 if (!empty($outbox['totalItems'])) {
333 $apcontact['statuses_count'] = $outbox['totalItems'];
337 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
342 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
344 // Unhandled from Misskey
345 // sharedInbox, isCat
347 // Unhandled from Kroeg
348 // kroeg:blocks, updated
350 // When the photo is too large, try to shorten it by removing parts
351 if (strlen($apcontact['photo']) > 255) {
352 $parts = parse_url($apcontact['photo']);
353 unset($parts['fragment']);
354 $apcontact['photo'] = Network::unparseURL($parts);
356 if (strlen($apcontact['photo']) > 255) {
357 unset($parts['query']);
358 $apcontact['photo'] = Network::unparseURL($parts);
361 if (strlen($apcontact['photo']) > 255) {
362 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
366 if (!$webfinger && !empty($apcontact['addr'])) {
367 $data = self::fetchWebfingerData($apcontact['addr']);
369 $apcontact['baseurl'] = $data['baseurl'];
371 if (empty($apcontact['alias']) && !empty($data['alias'])) {
372 $apcontact['alias'] = $data['alias'];
374 if (!empty($data['subscribe'])) {
375 $apcontact['subscribe'] = $data['subscribe'];
378 $apcontact['addr'] = null;
382 if (empty($apcontact['baseurl'])) {
383 $apcontact['baseurl'] = null;
386 if (empty($apcontact['subscribe'])) {
387 $apcontact['subscribe'] = null;
390 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
391 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
392 } elseif (!empty($fetched_contact['gsid'])) {
393 $apcontact['gsid'] = $fetched_contact['gsid'];
395 $apcontact['gsid'] = null;
398 if ($apcontact['url'] == $apcontact['alias']) {
399 $apcontact['alias'] = null;
402 if (empty($apcontact['uuid'])) {
403 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
405 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
408 $apcontact['updated'] = DateTimeFormat::utcNow();
410 // We delete the old entry when the URL is changed
411 if ($url != $apcontact['url']) {
412 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
413 DBA::delete('apcontact', ['url' => $url]);
416 // Limit the length on incoming fields
417 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
419 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
420 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
422 DBA::replace('apcontact', $apcontact);
425 Logger::info('Updated profile', ['url' => $url]);
427 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
431 * Mark the given AP Contact as "to archive"
433 * @param array $apcontact
436 public static function markForArchival(array $apcontact)
438 if (!empty($apcontact['inbox'])) {
439 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
440 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
443 if (!empty($apcontact['sharedinbox'])) {
444 // Check if there are any available inboxes
445 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
446 $apcontact['sharedinbox']]);
448 // If all known personal inboxes are failing then set their shared inbox to failure as well
449 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
450 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
456 * Unmark the given AP Contact as "to archive"
458 * @param array $apcontact
461 public static function unmarkForArchival(array $apcontact)
463 if (!empty($apcontact['inbox'])) {
464 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
465 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
467 if (!empty($apcontact['sharedinbox'])) {
468 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
469 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
476 * @param string $url inbox url
477 * @param boolean $shared Shared Inbox
479 private static function unarchiveInbox($url, $shared)
485 HTTPSignature::setInboxStatus($url, true, $shared);