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 $data = ['addr' => $addr];
58 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
59 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
60 if (empty($webfinger['links'])) {
61 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
62 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
63 if (empty($webfinger['links'])) {
66 $data['baseurl'] = 'http://' . $addr_parts[1];
68 $data['baseurl'] = 'https://' . $addr_parts[1];
71 foreach ($webfinger['links'] as $link) {
72 if (empty($link['rel'])) {
76 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
77 $data['subscribe'] = $link['template'];
80 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
81 $data['url'] = $link['href'];
84 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
85 $data['alias'] = $link['href'];
89 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
90 unset($data['alias']);
97 * Fetches a profile from a given url
99 * @param string $url profile url
100 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
101 * @return array profile array
102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
103 * @throws \ImagickException
105 public static function getByURL($url, $update = null)
111 $fetched_contact = false;
113 if (empty($update)) {
114 if (is_null($update)) {
115 $ref_update = DateTimeFormat::utc('now - 1 month');
117 $ref_update = DBA::NULL_DATETIME;
120 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
121 if (!DBA::isResult($apcontact)) {
122 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
125 if (!DBA::isResult($apcontact)) {
126 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
129 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
133 if (!is_null($update)) {
134 return DBA::isResult($apcontact) ? $apcontact : [];
137 if (DBA::isResult($apcontact)) {
138 $fetched_contact = $apcontact;
144 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
146 $apcontact = self::fetchWebfingerData($url);
147 if (empty($apcontact['url'])) {
148 return $fetched_contact;
150 $url = $apcontact['url'];
153 // Detect multiple fast repeating request to the same address
154 // See https://github.com/friendica/friendica/issues/9303
155 $cachekey = 'apcontact:getByURL:' . $url;
156 $result = DI::cache()->get($cachekey);
157 if (!is_null($result)) {
158 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
159 if (!empty($fetched_contact)) {
160 return $fetched_contact;
163 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
166 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
167 $data = Transmitter::getProfile($local_uid);
168 $local_owner = User::getOwnerDataById($local_uid);
174 $curlResult = HTTPSignature::fetchRaw($url);
175 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
176 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
179 $data = json_decode($curlResult->getBody(), true);
180 $failed = empty($data) || !is_array($data);
183 if (!$failed && ($curlResult->getReturnCode() == 410)) {
184 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
188 self::markForArchival($fetched_contact ?: []);
189 return $fetched_contact;
193 $compacted = JsonLD::compact($data);
194 if (empty($compacted['@id'])) {
195 return $fetched_contact;
198 $apcontact['url'] = $compacted['@id'];
199 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
200 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
201 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
202 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
203 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
204 self::unarchiveInbox($apcontact['inbox'], false);
206 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
208 $apcontact['sharedinbox'] = '';
209 if (!empty($compacted['as:endpoints'])) {
210 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
211 self::unarchiveInbox($apcontact['sharedinbox'], true);
214 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
215 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
217 if (empty($apcontact['name'])) {
218 $apcontact['name'] = $apcontact['nick'];
221 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
223 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
224 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
225 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
228 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
229 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
230 $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
233 if (empty($apcontact['alias'])) {
234 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
235 if (is_array($apcontact['alias'])) {
236 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
240 // Quit if none of the basic values are set
241 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
242 return $fetched_contact;
243 } elseif ($apcontact['type'] == 'Tombstone') {
244 // The "inbox" field must have a content
245 $apcontact['inbox'] = '';
248 // Quit if this doesn't seem to be an account at all
249 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
250 return $fetched_contact;
253 $parts = parse_url($apcontact['url']);
254 unset($parts['scheme']);
255 unset($parts['path']);
257 if (empty($apcontact['addr'])) {
258 if (!empty($apcontact['nick']) && is_array($parts)) {
259 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
261 $apcontact['addr'] = '';
265 $apcontact['pubkey'] = null;
266 if (!empty($compacted['w3id:publicKey'])) {
267 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
268 if (strstr($apcontact['pubkey'], 'RSA ')) {
269 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
273 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
275 if (!empty($compacted['as:generator'])) {
276 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
277 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
280 if (!empty($apcontact['following'])) {
281 if (!empty($local_owner)) {
282 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
284 $following = ActivityPub::fetchContent($apcontact['following']);
286 if (!empty($following['totalItems'])) {
287 // Mastodon seriously allows for this condition?
288 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
289 if ($following['totalItems'] < 0) {
290 $following['totalItems'] = 0;
292 $apcontact['following_count'] = $following['totalItems'];
296 if (!empty($apcontact['followers'])) {
297 if (!empty($local_owner)) {
298 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
300 $followers = ActivityPub::fetchContent($apcontact['followers']);
302 if (!empty($followers['totalItems'])) {
303 // Mastodon seriously allows for this condition?
304 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
305 if ($followers['totalItems'] < 0) {
306 $followers['totalItems'] = 0;
308 $apcontact['followers_count'] = $followers['totalItems'];
312 if (!empty($apcontact['outbox'])) {
313 if (!empty($local_owner)) {
314 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
316 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
318 if (!empty($outbox['totalItems'])) {
319 $apcontact['statuses_count'] = $outbox['totalItems'];
323 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
328 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
330 // Unhandled from Misskey
331 // sharedInbox, isCat
333 // Unhandled from Kroeg
334 // kroeg:blocks, updated
336 // When the photo is too large, try to shorten it by removing parts
337 if (strlen($apcontact['photo']) > 255) {
338 $parts = parse_url($apcontact['photo']);
339 unset($parts['fragment']);
340 $apcontact['photo'] = Network::unparseURL($parts);
342 if (strlen($apcontact['photo']) > 255) {
343 unset($parts['query']);
344 $apcontact['photo'] = Network::unparseURL($parts);
347 if (strlen($apcontact['photo']) > 255) {
348 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
352 if (!$webfinger && !empty($apcontact['addr'])) {
353 $data = self::fetchWebfingerData($apcontact['addr']);
355 $apcontact['baseurl'] = $data['baseurl'];
357 if (empty($apcontact['alias']) && !empty($data['alias'])) {
358 $apcontact['alias'] = $data['alias'];
360 if (!empty($data['subscribe'])) {
361 $apcontact['subscribe'] = $data['subscribe'];
364 $apcontact['addr'] = null;
368 if (empty($apcontact['baseurl'])) {
369 $apcontact['baseurl'] = null;
372 if (empty($apcontact['subscribe'])) {
373 $apcontact['subscribe'] = null;
376 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
377 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
378 } elseif (!empty($fetched_contact['gsid'])) {
379 $apcontact['gsid'] = $fetched_contact['gsid'];
381 $apcontact['gsid'] = null;
384 if ($apcontact['url'] == $apcontact['alias']) {
385 $apcontact['alias'] = null;
388 if (empty($apcontact['uuid'])) {
389 $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
391 $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
394 $apcontact['updated'] = DateTimeFormat::utcNow();
396 // We delete the old entry when the URL is changed
397 if ($url != $apcontact['url']) {
398 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
399 DBA::delete('apcontact', ['url' => $url]);
402 // Limit the length on incoming fields
403 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
405 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
406 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
408 DBA::replace('apcontact', $apcontact);
411 Logger::info('Updated profile', ['url' => $url]);
413 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
417 * Mark the given AP Contact as "to archive"
419 * @param array $apcontact
422 public static function markForArchival(array $apcontact)
424 if (!empty($apcontact['inbox'])) {
425 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
426 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
429 if (!empty($apcontact['sharedinbox'])) {
430 // Check if there are any available inboxes
431 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
432 $apcontact['sharedinbox']]);
434 // If all known personal inboxes are failing then set their shared inbox to failure as well
435 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
436 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
442 * Unmark the given AP Contact as "to archive"
444 * @param array $apcontact
447 public static function unmarkForArchival(array $apcontact)
449 if (!empty($apcontact['inbox'])) {
450 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
451 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
453 if (!empty($apcontact['sharedinbox'])) {
454 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
455 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
462 * @param string $url inbox url
463 * @param boolean $shared Shared Inbox
465 private static function unarchiveInbox($url, $shared)
471 HTTPSignature::setInboxStatus($url, true, $shared);