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\Logger;
26 use Friendica\Database\DBA;
28 use Friendica\Protocol\ActivityPub;
29 use Friendica\Util\Crypto;
30 use Friendica\Util\Network;
31 use Friendica\Util\JsonLD;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\Strings;
38 * Resolves the profile url from the address by using webfinger
40 * @param string $addr profile address (user@domain.tld)
41 * @param string $url profile URL. When set then we return "true" when this profile url can be found at the address
42 * @return string|boolean url
43 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
45 private static function addrToUrl($addr, $url = null)
47 $addr_parts = explode('@', $addr);
48 if (count($addr_parts) != 2) {
52 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
54 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
56 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
57 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
58 $webfinger = Strings::normaliseLink($webfinger);
60 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
62 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
67 $data = json_decode($curlResult->getBody(), true);
69 if (empty($data['links'])) {
73 foreach ($data['links'] as $link) {
74 if (!empty($url) && !empty($link['href']) && ($link['href'] == $url)) {
78 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
82 if (empty($url) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
91 * Fetches a profile from a given url
93 * @param string $url profile url
94 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
95 * @return array profile array
96 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
97 * @throws \ImagickException
99 public static function getByURL($url, $update = null)
105 $fetched_contact = false;
107 if (empty($update)) {
108 if (is_null($update)) {
109 $ref_update = DateTimeFormat::utc('now - 1 month');
111 $ref_update = DBA::NULL_DATETIME;
114 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
115 if (!DBA::isResult($apcontact)) {
116 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
119 if (!DBA::isResult($apcontact)) {
120 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
123 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
127 if (!is_null($update)) {
128 return DBA::isResult($apcontact) ? $apcontact : [];
131 if (DBA::isResult($apcontact)) {
132 $fetched_contact = $apcontact;
136 if (empty(parse_url($url, PHP_URL_SCHEME))) {
137 $url = self::addrToUrl($url);
139 return $fetched_contact;
143 $data = ActivityPub::fetchContent($url);
145 return $fetched_contact;
148 $compacted = JsonLD::compact($data);
150 if (empty($compacted['@id'])) {
151 return $fetched_contact;
155 $apcontact['url'] = $compacted['@id'];
156 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
157 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
158 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
159 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
160 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
161 self::unarchiveInbox($apcontact['inbox'], false);
163 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
165 $apcontact['sharedinbox'] = '';
166 if (!empty($compacted['as:endpoints'])) {
167 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
168 self::unarchiveInbox($apcontact['sharedinbox'], true);
171 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
172 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
174 if (empty($apcontact['name'])) {
175 $apcontact['name'] = $apcontact['nick'];
178 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
180 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
181 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
182 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
185 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
186 if (is_array($apcontact['alias'])) {
187 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
190 // Quit if none of the basic values are set
191 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
192 return $fetched_contact;
195 // Quit if this doesn't seem to be an account at all
196 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
197 return $fetched_contact;
200 $parts = parse_url($apcontact['url']);
201 unset($parts['scheme']);
202 unset($parts['path']);
204 if (!empty($apcontact['nick'])) {
205 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
207 $apcontact['addr'] = '';
210 $apcontact['pubkey'] = null;
211 if (!empty($compacted['w3id:publicKey'])) {
212 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
213 if (strstr($apcontact['pubkey'], 'RSA ')) {
214 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
218 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
220 if (!empty($compacted['as:generator'])) {
221 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
222 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
225 if (!empty($apcontact['following'])) {
226 $data = ActivityPub::fetchContent($apcontact['following']);
228 if (!empty($data['totalItems'])) {
229 $apcontact['following_count'] = $data['totalItems'];
234 if (!empty($apcontact['followers'])) {
235 $data = ActivityPub::fetchContent($apcontact['followers']);
237 if (!empty($data['totalItems'])) {
238 $apcontact['followers_count'] = $data['totalItems'];
243 if (!empty($apcontact['outbox'])) {
244 $data = ActivityPub::fetchContent($apcontact['outbox']);
246 if (!empty($data['totalItems'])) {
247 $apcontact['statuses_count'] = $data['totalItems'];
255 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
257 // Unhandled from Misskey
258 // sharedInbox, isCat
260 // Unhandled from Kroeg
261 // kroeg:blocks, updated
263 // When the photo is too large, try to shorten it by removing parts
264 if (strlen($apcontact['photo']) > 255) {
265 $parts = parse_url($apcontact['photo']);
266 unset($parts['fragment']);
267 $apcontact['photo'] = Network::unparseURL($parts);
269 if (strlen($apcontact['photo']) > 255) {
270 unset($parts['query']);
271 $apcontact['photo'] = Network::unparseURL($parts);
274 if (strlen($apcontact['photo']) > 255) {
275 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
279 $parts = parse_url($apcontact['url']);
280 unset($parts['path']);
281 $baseurl = Network::unparseURL($parts);
283 // Check if the address is resolvable or the profile url is identical with the base url of the system
284 if (self::addrToUrl($apcontact['addr'], $apcontact['url']) || Strings::compareLink($apcontact['url'], $baseurl)) {
285 $apcontact['baseurl'] = $baseurl;
287 $apcontact['addr'] = null;
290 if (empty($apcontact['baseurl'])) {
291 $apcontact['baseurl'] = null;
294 if (!empty($apcontact['baseurl'])) {
295 $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
298 if ($apcontact['url'] == $apcontact['alias']) {
299 $apcontact['alias'] = null;
302 $apcontact['updated'] = DateTimeFormat::utcNow();
304 DBA::update('apcontact', $apcontact, ['url' => $url], true);
306 // We delete the old entry when the URL is changed
307 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
308 DBA::delete('apcontact', ['url' => $url]);
311 Logger::log('Updated profile for ' . $url, Logger::DEBUG);
319 * @param string $url inbox url
321 private static function unarchiveInbox($url, $shared)
327 $now = DateTimeFormat::utcNow();
329 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
331 if (!DBA::exists('inbox-status', ['url' => $url])) {
332 $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
333 DBA::insert('inbox-status', $fields);
335 DBA::update('inbox-status', $fields, ['url' => $url]);