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\Network;
30 use Friendica\Util\JsonLD;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
37 * Resolves the profile url from the address by using webfinger
39 * @param string $addr profile address (user@domain.tld)
40 * @param string $url profile URL. When set then we return "true" when this profile url can be found at the address
41 * @return string|boolean url
42 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
44 private static function addrToUrl($addr, $url = null)
46 $addr_parts = explode('@', $addr);
47 if (count($addr_parts) != 2) {
51 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
53 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
55 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
56 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
57 $webfinger = Strings::normaliseLink($webfinger);
59 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
61 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
66 $data = json_decode($curlResult->getBody(), true);
68 if (empty($data['links'])) {
72 foreach ($data['links'] as $link) {
73 if (!empty($url) && !empty($link['href']) && ($link['href'] == $url)) {
77 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
81 if (empty($url) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
90 * Fetches a profile from a given url
92 * @param string $url profile url
93 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
94 * @return array profile array
95 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
96 * @throws \ImagickException
98 public static function getByURL($url, $update = null)
104 $fetched_contact = false;
106 if (empty($update)) {
107 if (is_null($update)) {
108 $ref_update = DateTimeFormat::utc('now - 1 month');
110 $ref_update = DBA::NULL_DATETIME;
113 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
114 if (!DBA::isResult($apcontact)) {
115 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
118 if (!DBA::isResult($apcontact)) {
119 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
122 if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
126 if (!is_null($update)) {
127 return DBA::isResult($apcontact) ? $apcontact : [];
130 if (DBA::isResult($apcontact)) {
131 $fetched_contact = $apcontact;
135 if (empty(parse_url($url, PHP_URL_SCHEME))) {
136 $url = self::addrToUrl($url);
138 return $fetched_contact;
142 $data = ActivityPub::fetchContent($url);
144 return $fetched_contact;
147 $compacted = JsonLD::compact($data);
149 if (empty($compacted['@id'])) {
150 return $fetched_contact;
154 $apcontact['url'] = $compacted['@id'];
155 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
156 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
157 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
158 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
159 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
160 self::unarchiveInbox($apcontact['inbox'], false);
162 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
164 $apcontact['sharedinbox'] = '';
165 if (!empty($compacted['as:endpoints'])) {
166 $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
167 self::unarchiveInbox($apcontact['sharedinbox'], true);
170 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
171 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
173 if (empty($apcontact['name'])) {
174 $apcontact['name'] = $apcontact['nick'];
177 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
179 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
180 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
181 $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
184 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
185 if (is_array($apcontact['alias'])) {
186 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
189 // Quit if none of the basic values are set
190 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
191 return $fetched_contact;
194 // Quit if this doesn't seem to be an account at all
195 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
196 return $fetched_contact;
199 $parts = parse_url($apcontact['url']);
200 unset($parts['scheme']);
201 unset($parts['path']);
203 if (!empty($apcontact['nick'])) {
204 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
206 $apcontact['addr'] = '';
209 $apcontact['pubkey'] = null;
210 if (!empty($compacted['w3id:publicKey'])) {
211 $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
214 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
216 if (!empty($compacted['as:generator'])) {
217 $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
218 $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
221 if (!empty($apcontact['following'])) {
222 $data = ActivityPub::fetchContent($apcontact['following']);
224 if (!empty($data['totalItems'])) {
225 $apcontact['following_count'] = $data['totalItems'];
230 if (!empty($apcontact['followers'])) {
231 $data = ActivityPub::fetchContent($apcontact['followers']);
233 if (!empty($data['totalItems'])) {
234 $apcontact['followers_count'] = $data['totalItems'];
239 if (!empty($apcontact['outbox'])) {
240 $data = ActivityPub::fetchContent($apcontact['outbox']);
242 if (!empty($data['totalItems'])) {
243 $apcontact['statuses_count'] = $data['totalItems'];
251 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
253 // Unhandled from Misskey
254 // sharedInbox, isCat
256 // Unhandled from Kroeg
257 // kroeg:blocks, updated
259 $parts = parse_url($apcontact['url']);
260 unset($parts['path']);
261 $baseurl = Network::unparseURL($parts);
263 // Check if the address is resolvable or the profile url is identical with the base url of the system
264 if (self::addrToUrl($apcontact['addr'], $apcontact['url']) || Strings::compareLink($apcontact['url'], $baseurl)) {
265 $apcontact['baseurl'] = $baseurl;
267 $apcontact['addr'] = null;
270 if (empty($apcontact['baseurl'])) {
271 $apcontact['baseurl'] = null;
274 if ($apcontact['url'] == $apcontact['alias']) {
275 $apcontact['alias'] = null;
278 $apcontact['updated'] = DateTimeFormat::utcNow();
280 DBA::update('apcontact', $apcontact, ['url' => $url], true);
282 // We delete the old entry when the URL is changed
283 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
284 DBA::delete('apcontact', ['url' => $url]);
287 Logger::log('Updated profile for ' . $url, Logger::DEBUG);
295 * @param string $url inbox url
297 private static function unarchiveInbox($url, $shared)
303 $now = DateTimeFormat::utcNow();
305 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
307 if (!DBA::exists('inbox-status', ['url' => $url])) {
308 $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
309 DBA::insert('inbox-status', $fields);
311 DBA::update('inbox-status', $fields, ['url' => $url]);