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\Util\Crypto;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\JsonLD;
38 use Friendica\Util\Network;
43 * Fetch webfinger data
45 * @param string $addr Address
46 * @return array webfinger data
48 private static function fetchWebfingerData(string $addr)
50 $addr_parts = explode('@', $addr);
51 if (count($addr_parts) != 2) {
55 $data = ['addr' => $addr];
56 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
57 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
58 if (empty($webfinger['links'])) {
59 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
60 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
61 if (empty($webfinger['links'])) {
64 $data['baseurl'] = 'http://' . $addr_parts[1];
66 $data['baseurl'] = 'https://' . $addr_parts[1];
69 foreach ($webfinger['links'] as $link) {
70 if (empty($link['rel'])) {
74 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
75 $data['subscribe'] = $link['template'];
78 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
79 $data['url'] = $link['href'];
82 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
83 $data['alias'] = $link['href'];
87 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
88 unset($data['alias']);
95 * Fetches a profile from a given url
97 * @param string $url profile url
98 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
99 * @return array profile array
100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 * @throws \ImagickException
103 public static function getByURL($url, $update = null)
109 $fetched_contact = false;
111 if (empty($update)) {
112 if (is_null($update)) {
113 $ref_update = DateTimeFormat::utc('now - 1 month');
115 $ref_update = DBA::NULL_DATETIME;
118 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
119 if (!DBA::isResult($apcontact)) {
120 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
123 if (!DBA::isResult($apcontact)) {
124 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
127 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
131 if (!is_null($update)) {
132 return DBA::isResult($apcontact) ? $apcontact : [];
135 if (DBA::isResult($apcontact)) {
136 $fetched_contact = $apcontact;
142 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
144 $apcontact = self::fetchWebfingerData($url);
145 if (empty($apcontact['url'])) {
146 return $fetched_contact;
148 $url = $apcontact['url'];
151 $curlResult = HTTPSignature::fetchRaw($url);
152 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
153 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
156 $data = json_decode($curlResult->getBody(), true);
157 $failed = empty($data) || !is_array($data);
160 if (!$failed && ($curlResult->getReturnCode() == 410)) {
161 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
165 self::markForArchival($fetched_contact ?: []);
166 return $fetched_contact;
169 $compacted = JsonLD::compact($data);
170 if (empty($compacted['@id'])) {
171 return $fetched_contact;
174 // Detect multiple fast repeating request to the same address
175 // See https://github.com/friendica/friendica/issues/9303
176 $cachekey = 'apcontact:getByURL:' . $url;
177 $result = DI::cache()->get($cachekey);
178 if (!is_null($result)) {
179 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
181 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
184 $apcontact['url'] = $compacted['@id'];
185 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
186 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
187 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
188 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
189 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
190 self::unarchiveInbox($apcontact['inbox'], false);
192 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
194 $apcontact['sharedinbox'] = '';
195 if (!empty($compacted['as:endpoints'])) {
196 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
197 self::unarchiveInbox($apcontact['sharedinbox'], true);
200 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
201 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
203 if (empty($apcontact['name'])) {
204 $apcontact['name'] = $apcontact['nick'];
207 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
209 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
210 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
211 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
214 if (empty($apcontact['alias'])) {
215 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
216 if (is_array($apcontact['alias'])) {
217 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
221 // Quit if none of the basic values are set
222 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
223 return $fetched_contact;
224 } elseif ($apcontact['type'] == 'Tombstone') {
225 // The "inbox" field must have a content
226 $apcontact['inbox'] = '';
229 // Quit if this doesn't seem to be an account at all
230 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
231 return $fetched_contact;
234 $parts = parse_url($apcontact['url']);
235 unset($parts['scheme']);
236 unset($parts['path']);
238 if (empty($apcontact['addr'])) {
239 if (!empty($apcontact['nick']) && is_array($parts)) {
240 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
242 $apcontact['addr'] = '';
246 $apcontact['pubkey'] = null;
247 if (!empty($compacted['w3id:publicKey'])) {
248 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
249 if (strstr($apcontact['pubkey'], 'RSA ')) {
250 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
254 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
256 if (!empty($compacted['as:generator'])) {
257 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
258 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
261 if (!empty($apcontact['following'])) {
262 $following = ActivityPub::fetchContent($apcontact['following']);
263 if (!empty($following['totalItems'])) {
264 $apcontact['following_count'] = $following['totalItems'];
268 if (!empty($apcontact['followers'])) {
269 $followers = ActivityPub::fetchContent($apcontact['followers']);
270 if (!empty($followers['totalItems'])) {
271 $apcontact['followers_count'] = $followers['totalItems'];
275 if (!empty($apcontact['outbox'])) {
276 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
277 if (!empty($outbox['totalItems'])) {
278 $apcontact['statuses_count'] = $outbox['totalItems'];
285 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
287 // Unhandled from Misskey
288 // sharedInbox, isCat
290 // Unhandled from Kroeg
291 // kroeg:blocks, updated
293 // When the photo is too large, try to shorten it by removing parts
294 if (strlen($apcontact['photo']) > 255) {
295 $parts = parse_url($apcontact['photo']);
296 unset($parts['fragment']);
297 $apcontact['photo'] = Network::unparseURL($parts);
299 if (strlen($apcontact['photo']) > 255) {
300 unset($parts['query']);
301 $apcontact['photo'] = Network::unparseURL($parts);
304 if (strlen($apcontact['photo']) > 255) {
305 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
309 if (!$webfinger && !empty($apcontact['addr'])) {
310 $data = self::fetchWebfingerData($apcontact['addr']);
312 $apcontact['baseurl'] = $data['baseurl'];
314 if (empty($apcontact['alias']) && !empty($data['alias'])) {
315 $apcontact['alias'] = $data['alias'];
317 if (!empty($data['subscribe'])) {
318 $apcontact['subscribe'] = $data['subscribe'];
321 $apcontact['addr'] = null;
325 if (empty($apcontact['baseurl'])) {
326 $apcontact['baseurl'] = null;
329 if (empty($apcontact['subscribe'])) {
330 $apcontact['subscribe'] = null;
333 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
334 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
335 } elseif (!empty($fetched_contact['gsid'])) {
336 $apcontact['gsid'] = $fetched_contact['gsid'];
338 $apcontact['gsid'] = null;
341 if ($apcontact['url'] == $apcontact['alias']) {
342 $apcontact['alias'] = null;
345 $apcontact['updated'] = DateTimeFormat::utcNow();
347 // We delete the old entry when the URL is changed
348 if ($url != $apcontact['url']) {
349 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
350 DBA::delete('apcontact', ['url' => $url]);
353 // Limit the length on incoming fields
354 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
356 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
357 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
359 DBA::replace('apcontact', $apcontact);
362 Logger::info('Updated profile', ['url' => $url]);
368 * Mark the given AP Contact as "to archive"
370 * @param array $apcontact
373 public static function markForArchival(array $apcontact)
375 if (!empty($apcontact['inbox'])) {
376 Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
377 HTTPSignature::setInboxStatus($apcontact['inbox'], false);
380 if (!empty($apcontact['sharedinbox'])) {
381 // Check if there are any available inboxes
382 $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
383 $apcontact['sharedinbox']]);
385 // If all known personal inboxes are failing then set their shared inbox to failure as well
386 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
387 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
393 * Unmark the given AP Contact as "to archive"
395 * @param array $apcontact
398 public static function unmarkForArchival(array $apcontact)
400 if (!empty($apcontact['inbox'])) {
401 Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
402 HTTPSignature::setInboxStatus($apcontact['inbox'], true);
404 if (!empty($apcontact['sharedinbox'])) {
405 Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
406 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
413 * @param string $url inbox url
414 * @param boolean $shared Shared Inbox
416 private static function unarchiveInbox($url, $shared)
422 HTTPSignature::setInboxStatus($url, true, $shared);