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;
30 use Friendica\Network\Probe;
31 use Friendica\Protocol\ActivityNamespace;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\HTTPSignature;
36 use Friendica\Util\JsonLD;
37 use Friendica\Util\Network;
42 * Fetch webfinger data
44 * @param string $addr Address
45 * @return array webfinger data
47 private static function fetchWebfingerData(string $addr)
49 $addr_parts = explode('@', $addr);
50 if (count($addr_parts) != 2) {
54 $data = ['addr' => $addr];
55 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
56 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
57 if (empty($webfinger['links'])) {
58 $template = 'http://' . $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'])) {
63 $data['baseurl'] = 'http://' . $addr_parts[1];
65 $data['baseurl'] = 'https://' . $addr_parts[1];
68 foreach ($webfinger['links'] as $link) {
69 if (empty($link['rel'])) {
73 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
74 $data['subscribe'] = $link['template'];
77 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
78 $data['url'] = $link['href'];
81 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
82 $data['alias'] = $link['href'];
86 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
87 unset($data['alias']);
94 * Fetches a profile from a given url
96 * @param string $url profile url
97 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
98 * @return array profile array
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 * @throws \ImagickException
102 public static function getByURL($url, $update = null)
108 $fetched_contact = false;
110 if (empty($update)) {
111 if (is_null($update)) {
112 $ref_update = DateTimeFormat::utc('now - 1 month');
114 $ref_update = DBA::NULL_DATETIME;
117 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
118 if (!DBA::isResult($apcontact)) {
119 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
122 if (!DBA::isResult($apcontact)) {
123 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
126 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
130 if (!is_null($update)) {
131 return DBA::isResult($apcontact) ? $apcontact : [];
134 if (DBA::isResult($apcontact)) {
135 $fetched_contact = $apcontact;
141 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
143 $apcontact = self::fetchWebfingerData($url);
144 if (empty($apcontact['url'])) {
145 return $fetched_contact;
147 $url = $apcontact['url'];
150 $curlResult = HTTPSignature::fetchRaw($url);
151 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
152 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
155 $data = json_decode($curlResult->getBody(), true);
156 $failed = empty($data) || !is_array($data);
159 if (!$failed && ($curlResult->getReturnCode() == 410)) {
160 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
164 self::markForArchival($fetched_contact ?: []);
165 return $fetched_contact;
168 $compacted = JsonLD::compact($data);
169 if (empty($compacted['@id'])) {
170 return $fetched_contact;
173 // Detect multiple fast repeating request to the same address
174 // See https://github.com/friendica/friendica/issues/9303
175 $cachekey = 'apcontact:getByURL:' . $url;
176 $result = DI::cache()->get($cachekey);
177 if (!is_null($result)) {
178 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
180 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
183 $apcontact['url'] = $compacted['@id'];
184 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
185 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
186 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
187 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
188 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
189 self::unarchiveInbox($apcontact['inbox'], false);
191 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
193 $apcontact['sharedinbox'] = '';
194 if (!empty($compacted['as:endpoints'])) {
195 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
196 self::unarchiveInbox($apcontact['sharedinbox'], true);
199 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
200 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
202 if (empty($apcontact['name'])) {
203 $apcontact['name'] = $apcontact['nick'];
206 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
208 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
209 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
210 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
213 if (empty($apcontact['alias'])) {
214 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
215 if (is_array($apcontact['alias'])) {
216 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
220 // Quit if none of the basic values are set
221 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
222 return $fetched_contact;
223 } elseif ($apcontact['type'] == 'Tombstone') {
224 // The "inbox" field must have a content
225 $apcontact['inbox'] = '';
228 // Quit if this doesn't seem to be an account at all
229 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
230 return $fetched_contact;
233 $parts = parse_url($apcontact['url']);
234 unset($parts['scheme']);
235 unset($parts['path']);
237 if (empty($apcontact['addr'])) {
238 if (!empty($apcontact['nick']) && is_array($parts)) {
239 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
241 $apcontact['addr'] = '';
245 $apcontact['pubkey'] = null;
246 if (!empty($compacted['w3id:publicKey'])) {
247 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
248 if (strstr($apcontact['pubkey'], 'RSA ')) {
249 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
253 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
255 if (!empty($compacted['as:generator'])) {
256 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
257 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
260 if (!empty($apcontact['following'])) {
261 $data = ActivityPub::fetchContent($apcontact['following']);
263 if (!empty($data['totalItems'])) {
264 $apcontact['following_count'] = $data['totalItems'];
269 if (!empty($apcontact['followers'])) {
270 $data = ActivityPub::fetchContent($apcontact['followers']);
272 if (!empty($data['totalItems'])) {
273 $apcontact['followers_count'] = $data['totalItems'];
278 if (!empty($apcontact['outbox'])) {
279 $data = ActivityPub::fetchContent($apcontact['outbox']);
281 if (!empty($data['totalItems'])) {
282 $apcontact['statuses_count'] = $data['totalItems'];
290 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
292 // Unhandled from Misskey
293 // sharedInbox, isCat
295 // Unhandled from Kroeg
296 // kroeg:blocks, updated
298 // When the photo is too large, try to shorten it by removing parts
299 if (strlen($apcontact['photo']) > 255) {
300 $parts = parse_url($apcontact['photo']);
301 unset($parts['fragment']);
302 $apcontact['photo'] = Network::unparseURL($parts);
304 if (strlen($apcontact['photo']) > 255) {
305 unset($parts['query']);
306 $apcontact['photo'] = Network::unparseURL($parts);
309 if (strlen($apcontact['photo']) > 255) {
310 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
314 if (!$webfinger && !empty($apcontact['addr'])) {
315 $data = self::fetchWebfingerData($apcontact['addr']);
317 $apcontact['baseurl'] = $data['baseurl'];
319 if (empty($apcontact['alias']) && !empty($data['alias'])) {
320 $apcontact['alias'] = $data['alias'];
322 if (!empty($data['subscribe'])) {
323 $apcontact['subscribe'] = $data['subscribe'];
326 $apcontact['addr'] = null;
330 if (empty($apcontact['baseurl'])) {
331 $apcontact['baseurl'] = null;
334 if (empty($apcontact['subscribe'])) {
335 $apcontact['subscribe'] = null;
338 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
339 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
340 } elseif (!empty($fetched_contact['gsid'])) {
341 $apcontact['gsid'] = $fetched_contact['gsid'];
343 $apcontact['gsid'] = null;
346 if ($apcontact['url'] == $apcontact['alias']) {
347 $apcontact['alias'] = null;
350 $apcontact['updated'] = DateTimeFormat::utcNow();
352 // We delete the old entry when the URL is changed
353 if ($url != $apcontact['url']) {
354 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
355 DBA::delete('apcontact', ['url' => $url]);
358 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
359 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
361 DBA::replace('apcontact', $apcontact);
364 Logger::info('Updated profile', ['url' => $url]);
370 * Mark the given AP Contact as "to archive"
372 * @param array $apcontact
375 public static function markForArchival(array $apcontact)
377 if (!empty($apcontact['inbox'])) {
378 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
379 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
382 if (!empty($apcontact['sharedinbox'])) {
383 // Check if there are any available inboxes
384 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
385 $apcontact['sharedinbox']]);
387 // If all known personal inboxes are failing then set their shared inbox to failure as well
388 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
389 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
395 * Unmark the given AP Contact as "to archive"
397 * @param array $apcontact
400 public static function unmarkForArchival(array $apcontact)
402 if (!empty($apcontact['inbox'])) {
403 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
404 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
406 if (!empty($apcontact['sharedinbox'])) {
407 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
408 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
415 * @param string $url inbox url
416 * @param boolean $shared Shared Inbox
418 private static function unarchiveInbox($url, $shared)
424 HTTPSignature::setInboxStatus($url, true, $shared);