3 * @copyright Copyright (C) 2020, Friendica
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\JsonLD;
36 use Friendica\Util\Network;
41 * Fetch webfinger data
43 * @param string $addr Address
44 * @return array webfinger data
46 private static function fetchWebfingerData(string $addr)
48 $addr_parts = explode('@', $addr);
49 if (count($addr_parts) != 2) {
53 $data = ['addr' => $addr];
54 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
55 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
56 if (empty($webfinger['links'])) {
57 $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
58 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
59 if (empty($webfinger['links'])) {
62 $data['baseurl'] = 'http://' . $addr_parts[1];
64 $data['baseurl'] = 'https://' . $addr_parts[1];
67 foreach ($webfinger['links'] as $link) {
68 if (empty($link['rel'])) {
72 if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
73 $data['subscribe'] = $link['template'];
76 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
77 $data['url'] = $link['href'];
80 if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
81 $data['alias'] = $link['href'];
85 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
86 unset($data['alias']);
93 * Fetches a profile from a given url
95 * @param string $url profile url
96 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
97 * @return array profile array
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 * @throws \ImagickException
101 public static function getByURL($url, $update = null)
107 $fetched_contact = false;
109 if (empty($update)) {
110 if (is_null($update)) {
111 $ref_update = DateTimeFormat::utc('now - 1 month');
113 $ref_update = DBA::NULL_DATETIME;
116 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
117 if (!DBA::isResult($apcontact)) {
118 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
121 if (!DBA::isResult($apcontact)) {
122 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
125 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
129 if (!is_null($update)) {
130 return DBA::isResult($apcontact) ? $apcontact : [];
133 if (DBA::isResult($apcontact)) {
134 $fetched_contact = $apcontact;
140 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
142 $apcontact = self::fetchWebfingerData($url);
143 if (empty($apcontact['url'])) {
144 return $fetched_contact;
146 $url = $apcontact['url'];
149 $data = ActivityPub::fetchContent($url);
151 return $fetched_contact;
154 $compacted = JsonLD::compact($data);
156 if (empty($compacted['@id'])) {
157 return $fetched_contact;
160 // Detect multiple fast repeating request to the same address
161 // See https://github.com/friendica/friendica/issues/9303
162 $cachekey = 'apcontact:getByURL:' . $url;
163 $result = DI::cache()->get($cachekey);
164 if (!is_null($result)) {
165 Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
167 DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
170 $apcontact['url'] = $compacted['@id'];
171 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
172 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
173 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
174 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
175 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
176 self::unarchiveInbox($apcontact['inbox'], false);
178 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
180 $apcontact['sharedinbox'] = '';
181 if (!empty($compacted['as:endpoints'])) {
182 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
183 self::unarchiveInbox($apcontact['sharedinbox'], true);
186 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
187 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
189 if (empty($apcontact['name'])) {
190 $apcontact['name'] = $apcontact['nick'];
193 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
195 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
196 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
197 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
200 if (empty($apcontact['alias'])) {
201 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
202 if (is_array($apcontact['alias'])) {
203 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
207 // Quit if none of the basic values are set
208 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
209 return $fetched_contact;
212 // Quit if this doesn't seem to be an account at all
213 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
214 return $fetched_contact;
217 $parts = parse_url($apcontact['url']);
218 unset($parts['scheme']);
219 unset($parts['path']);
221 if (empty($apcontact['addr'])) {
222 if (!empty($apcontact['nick'])) {
223 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
225 $apcontact['addr'] = '';
229 $apcontact['pubkey'] = null;
230 if (!empty($compacted['w3id:publicKey'])) {
231 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
232 if (strstr($apcontact['pubkey'], 'RSA ')) {
233 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
237 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
239 if (!empty($compacted['as:generator'])) {
240 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
241 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
244 if (!empty($apcontact['following'])) {
245 $data = ActivityPub::fetchContent($apcontact['following']);
247 if (!empty($data['totalItems'])) {
248 $apcontact['following_count'] = $data['totalItems'];
253 if (!empty($apcontact['followers'])) {
254 $data = ActivityPub::fetchContent($apcontact['followers']);
256 if (!empty($data['totalItems'])) {
257 $apcontact['followers_count'] = $data['totalItems'];
262 if (!empty($apcontact['outbox'])) {
263 $data = ActivityPub::fetchContent($apcontact['outbox']);
265 if (!empty($data['totalItems'])) {
266 $apcontact['statuses_count'] = $data['totalItems'];
274 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
276 // Unhandled from Misskey
277 // sharedInbox, isCat
279 // Unhandled from Kroeg
280 // kroeg:blocks, updated
282 // When the photo is too large, try to shorten it by removing parts
283 if (strlen($apcontact['photo']) > 255) {
284 $parts = parse_url($apcontact['photo']);
285 unset($parts['fragment']);
286 $apcontact['photo'] = Network::unparseURL($parts);
288 if (strlen($apcontact['photo']) > 255) {
289 unset($parts['query']);
290 $apcontact['photo'] = Network::unparseURL($parts);
293 if (strlen($apcontact['photo']) > 255) {
294 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
298 if (!$webfinger && !empty($apcontact['addr'])) {
299 $data = self::fetchWebfingerData($apcontact['addr']);
301 $apcontact['baseurl'] = $data['baseurl'];
303 if (empty($apcontact['alias']) && !empty($data['alias'])) {
304 $apcontact['alias'] = $data['alias'];
306 if (!empty($data['subscribe'])) {
307 $apcontact['subscribe'] = $data['subscribe'];
310 $apcontact['addr'] = null;
314 if (empty($apcontact['baseurl'])) {
315 $apcontact['baseurl'] = null;
318 if (empty($apcontact['subscribe'])) {
319 $apcontact['subscribe'] = null;
322 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
323 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
324 } elseif (!empty($fetched_contact['gsid'])) {
325 $apcontact['gsid'] = $fetched_contact['gsid'];
327 $apcontact['gsid'] = null;
330 if ($apcontact['url'] == $apcontact['alias']) {
331 $apcontact['alias'] = null;
334 $apcontact['updated'] = DateTimeFormat::utcNow();
336 // We delete the old entry when the URL is changed
337 if ($url != $apcontact['url']) {
338 Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
339 DBA::delete('apcontact', ['url' => $url]);
342 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
343 DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
345 DBA::replace('apcontact', $apcontact);
348 Logger::info('Updated profile', ['url' => $url]);
356 * @param string $url inbox url
358 private static function unarchiveInbox($url, $shared)
364 $now = DateTimeFormat::utcNow();
366 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
368 if (!DBA::exists('inbox-status', ['url' => $url])) {
369 $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
370 DBA::replace('inbox-status', $fields);
372 DBA::update('inbox-status', $fields, ['url' => $url]);