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 if (empty($data['id'])) {
169 return $fetched_contact;
172 // Detect multiple fast repeating request to the same address
173 // See https://github.com/friendica/friendica/issues/9303
174 $cachekey = 'apcontact:getByURL:' . $url;
175 $result = DI::cache()->get($cachekey);
176 if (!is_null($result)) {
177 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
179 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
182 $apcontact['url'] = $data['id'];
183 $apcontact['uuid'] = JsonLD::fetchElement($data, 'diaspora:guid');
184 $apcontact['type'] = JsonLD::fetchElement($data, 'type');
185 $apcontact['following'] = JsonLD::fetchElement($data, 'following');
186 $apcontact['followers'] = JsonLD::fetchElement($data, 'followers');
187 $apcontact['inbox'] = JsonLD::fetchElement($data, 'inbox');
188 self::unarchiveInbox($apcontact['inbox'], false);
189 $apcontact['outbox'] = JsonLD::fetchElement($data, 'outbox');
191 $apcontact['sharedinbox'] = '';
192 if (!empty($data['endpoints'])) {
193 $apcontact['sharedinbox'] = JsonLD::fetchElement($data['endpoints'], 'sharedInbox');
194 self::unarchiveInbox($apcontact['sharedinbox'], true);
197 $apcontact['nick'] = JsonLD::fetchElement($data, 'preferredUsername') ?? '';
198 $apcontact['name'] = JsonLD::fetchElement($data, 'name');
200 if (empty($apcontact['name'])) {
201 $apcontact['name'] = $apcontact['nick'];
204 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($data, 'summary'));
206 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon');
207 if (is_array($apcontact['photo']) || !empty($data['icon']['url'])) {
208 $apcontact['photo'] = JsonLD::fetchElement($data['icon'], 'url');
211 if (empty($apcontact['alias'])) {
212 $apcontact['alias'] = JsonLD::fetchElement($data, 'url');
213 if (is_array($apcontact['alias'])) {
214 $apcontact['alias'] = JsonLD::fetchElement($data['url'], 'href');
218 // Quit if none of the basic values are set
219 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
220 return $fetched_contact;
221 } elseif ($apcontact['type'] == 'Tombstone') {
222 // The "inbox" field must have a content
223 $apcontact['inbox'] = '';
226 // Quit if this doesn't seem to be an account at all
227 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
228 return $fetched_contact;
231 $parts = parse_url($apcontact['url']);
232 unset($parts['scheme']);
233 unset($parts['path']);
235 if (empty($apcontact['addr'])) {
236 if (!empty($apcontact['nick']) && is_array($parts)) {
237 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
239 $apcontact['addr'] = '';
243 $apcontact['pubkey'] = null;
244 if (!empty($data['publicKey'])) {
245 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data['publicKey'], 'publicKeyPem'));
246 if (strstr($apcontact['pubkey'], 'RSA ')) {
247 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
251 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($data, 'manuallyApprovesFollowers');
253 if (!empty($data['generator'])) {
254 $apcontact['baseurl'] = JsonLD::fetchElement($data['generator'], 'url');
255 $apcontact['generator'] = JsonLD::fetchElement($data['generator'], 'name');
258 if (!empty($apcontact['following'])) {
259 $content = ActivityPub::fetchContent($apcontact['following']);
260 if (!empty($content)) {
261 if (!empty($content['totalItems'])) {
262 $apcontact['following_count'] = $content['totalItems'];
267 if (!empty($apcontact['followers'])) {
268 $content = ActivityPub::fetchContent($apcontact['followers']);
269 if (!empty($content)) {
270 if (!empty($content['totalItems'])) {
271 $apcontact['followers_count'] = $content['totalItems'];
276 if (!empty($apcontact['outbox'])) {
277 $content = ActivityPub::fetchContent($apcontact['outbox']);
278 if (!empty($content)) {
279 if (!empty($content['totalItems'])) {
280 $apcontact['statuses_count'] = $content['totalItems'];
288 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
290 // Unhandled from Misskey
291 // sharedInbox, isCat
293 // Unhandled from Kroeg
294 // kroeg:blocks, updated
296 // When the photo is too large, try to shorten it by removing parts
297 if (strlen($apcontact['photo']) > 255) {
298 $parts = parse_url($apcontact['photo']);
299 unset($parts['fragment']);
300 $apcontact['photo'] = Network::unparseURL($parts);
302 if (strlen($apcontact['photo']) > 255) {
303 unset($parts['query']);
304 $apcontact['photo'] = Network::unparseURL($parts);
307 if (strlen($apcontact['photo']) > 255) {
308 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
312 if (!$webfinger && !empty($apcontact['addr'])) {
313 $data = self::fetchWebfingerData($apcontact['addr']);
315 $apcontact['baseurl'] = $data['baseurl'];
317 if (empty($apcontact['alias']) && !empty($data['alias'])) {
318 $apcontact['alias'] = $data['alias'];
320 if (!empty($data['subscribe'])) {
321 $apcontact['subscribe'] = $data['subscribe'];
324 $apcontact['addr'] = null;
328 if (empty($apcontact['baseurl'])) {
329 $apcontact['baseurl'] = null;
332 if (empty($apcontact['subscribe'])) {
333 $apcontact['subscribe'] = null;
336 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
337 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
338 } elseif (!empty($fetched_contact['gsid'])) {
339 $apcontact['gsid'] = $fetched_contact['gsid'];
341 $apcontact['gsid'] = null;
344 if ($apcontact['url'] == $apcontact['alias']) {
345 $apcontact['alias'] = null;
348 $apcontact['updated'] = DateTimeFormat::utcNow();
350 // We delete the old entry when the URL is changed
351 if ($url != $apcontact['url']) {
352 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
353 DBA::delete('apcontact', ['url' => $url]);
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);