]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Use getByNickname as suggested in code review.
[friendica.git] / src / Model / APContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
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\DI;
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;
38
39 class APContact
40 {
41         /**
42          * Fetch webfinger data
43          *
44          * @param string $addr Address
45          * @return array webfinger data
46          */
47         private static function fetchWebfingerData(string $addr)
48         {
49                 $addr_parts = explode('@', $addr);
50                 if (count($addr_parts) != 2) {
51                         return [];
52                 }
53
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'])) {
61                                 return [];
62                         }
63                         $data['baseurl'] = 'http://' . $addr_parts[1];
64                 } else {
65                         $data['baseurl'] = 'https://' . $addr_parts[1];
66                 }
67
68                 foreach ($webfinger['links'] as $link) {
69                         if (empty($link['rel'])) {
70                                 continue;
71                         }
72
73                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
74                                 $data['subscribe'] = $link['template'];
75                         }
76
77                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
78                                 $data['url'] = $link['href'];
79                         }
80
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'];
83                         }
84                 }
85
86                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
87                         unset($data['alias']);
88                 }
89
90                 return $data;
91         }
92
93         /**
94          * Fetches a profile from a given url
95          *
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
101          */
102         public static function getByURL($url, $update = null)
103         {
104                 if (empty($url)) {
105                         return [];
106                 }
107
108                 $fetched_contact = false;
109
110                 if (empty($update)) {
111                         if (is_null($update)) {
112                                 $ref_update = DateTimeFormat::utc('now - 1 month');
113                         } else {
114                                 $ref_update = DBA::NULL_DATETIME;
115                         }
116
117                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
118                         if (!DBA::isResult($apcontact)) {
119                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
120                         }
121
122                         if (!DBA::isResult($apcontact)) {
123                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
124                         }
125
126                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
127                                 return $apcontact;
128                         }
129
130                         if (!is_null($update)) {
131                                 return DBA::isResult($apcontact) ? $apcontact : [];
132                         }
133
134                         if (DBA::isResult($apcontact)) {
135                                 $fetched_contact = $apcontact;
136                         }
137                 }
138
139                 $apcontact = [];
140
141                 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
142                 if ($webfinger) {
143                         $apcontact = self::fetchWebfingerData($url);
144                         if (empty($apcontact['url'])) {
145                                 return $fetched_contact;
146                         }
147                         $url = $apcontact['url'];
148                 }
149
150                 $curlResult = HTTPSignature::fetchRaw($url);
151                 $failed = empty($curlResult) || empty($curlResult->getBody()) ||
152                         (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
153
154                 if (!$failed) {
155                         $data = json_decode($curlResult->getBody(), true);
156                         $failed = empty($data) || !is_array($data);
157                 }
158
159                 if (!$failed && ($curlResult->getReturnCode() == 410)) {
160                         $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
161                 }
162
163                 if ($failed) {
164                         self::markForArchival($fetched_contact ?: []);
165                         return $fetched_contact;
166                 }
167
168                 $compacted = JsonLD::compact($data);
169                 if (empty($compacted['@id'])) {
170                         return $fetched_contact;
171                 }
172
173                 // Detect multiple fast repeating request to the same address
174                 // See https://github.com/friendica/friendica/issues/9303
175                 $cachekey = 'apcontact:getByURL:' . $url;
176                 $result = DI::cache()->get($cachekey);
177                 if (!is_null($result)) {
178                         Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
179                 } else {
180                         DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
181                 }
182
183                 $apcontact['url'] = $compacted['@id'];
184                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
185                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
186                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
187                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
188                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
189                 self::unarchiveInbox($apcontact['inbox'], false);
190
191                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
192
193                 $apcontact['sharedinbox'] = '';
194                 if (!empty($compacted['as:endpoints'])) {
195                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
196                         self::unarchiveInbox($apcontact['sharedinbox'], true);
197                 }
198
199                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
200                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
201
202                 if (empty($apcontact['name'])) {
203                         $apcontact['name'] = $apcontact['nick'];
204                 }
205
206                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
207
208                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
209                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
210                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
211                 }
212
213                 if (empty($apcontact['alias'])) {
214                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
215                         if (is_array($apcontact['alias'])) {
216                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
217                         }
218                 }
219
220                 // Quit if none of the basic values are set
221                 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
222                         return $fetched_contact;
223                 } elseif ($apcontact['type'] == 'Tombstone') {
224                         // The "inbox" field must have a content
225                         $apcontact['inbox'] = '';
226                 }
227
228                 // Quit if this doesn't seem to be an account at all
229                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
230                         return $fetched_contact;
231                 }
232
233                 $parts = parse_url($apcontact['url']);
234                 unset($parts['scheme']);
235                 unset($parts['path']);
236
237                 if (empty($apcontact['addr'])) {
238                         if (!empty($apcontact['nick']) && is_array($parts)) {
239                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
240                         } else {
241                                 $apcontact['addr'] = '';
242                         }
243                 }
244
245                 $apcontact['pubkey'] = null;
246                 if (!empty($compacted['w3id:publicKey'])) {
247                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
248                         if (strstr($apcontact['pubkey'], 'RSA ')) {
249                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
250                         }
251                 }
252
253                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
254
255                 if (!empty($compacted['as:generator'])) {
256                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
257                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
258                 }
259
260                 if (!empty($apcontact['following'])) {
261                         $following = ActivityPub::fetchContent($apcontact['following']);
262                         if (!empty($following['totalItems'])) {
263                                 $apcontact['following_count'] = $following['totalItems'];
264                         }
265                 }
266
267                 if (!empty($apcontact['followers'])) {
268                         $followers = ActivityPub::fetchContent($apcontact['followers']);
269                         if (!empty($followers['totalItems'])) {
270                                 $apcontact['followers_count'] = $followers['totalItems'];
271                         }
272                 }
273
274                 if (!empty($apcontact['outbox'])) {
275                         $outbox = ActivityPub::fetchContent($apcontact['outbox']);
276                         if (!empty($outbox['totalItems'])) {
277                                 $apcontact['statuses_count'] = $outbox['totalItems'];
278                         }
279                 }
280
281                 // To-Do
282
283                 // Unhandled
284                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
285
286                 // Unhandled from Misskey
287                 // sharedInbox, isCat
288
289                 // Unhandled from Kroeg
290                 // kroeg:blocks, updated
291
292                 // When the photo is too large, try to shorten it by removing parts
293                 if (strlen($apcontact['photo']) > 255) {
294                         $parts = parse_url($apcontact['photo']);
295                         unset($parts['fragment']);
296                         $apcontact['photo'] = Network::unparseURL($parts);
297
298                         if (strlen($apcontact['photo']) > 255) {
299                                 unset($parts['query']);
300                                 $apcontact['photo'] = Network::unparseURL($parts);
301                         }
302
303                         if (strlen($apcontact['photo']) > 255) {
304                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
305                         }
306                 }
307
308                 if (!$webfinger && !empty($apcontact['addr'])) {
309                         $data = self::fetchWebfingerData($apcontact['addr']);
310                         if (!empty($data)) {
311                                 $apcontact['baseurl'] = $data['baseurl'];
312
313                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
314                                         $apcontact['alias'] = $data['alias'];
315                                 }
316                                 if (!empty($data['subscribe'])) {
317                                         $apcontact['subscribe'] = $data['subscribe'];
318                                 }
319                         } else {
320                                 $apcontact['addr'] = null;
321                         }
322                 }
323
324                 if (empty($apcontact['baseurl'])) {
325                         $apcontact['baseurl'] = null;
326                 }
327
328                 if (empty($apcontact['subscribe'])) {
329                         $apcontact['subscribe'] = null;
330                 }
331
332                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
333                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
334                 } elseif (!empty($fetched_contact['gsid'])) {
335                         $apcontact['gsid'] = $fetched_contact['gsid'];
336                 } else {
337                         $apcontact['gsid'] = null;
338                 }
339
340                 if ($apcontact['url'] == $apcontact['alias']) {
341                         $apcontact['alias'] = null;
342                 }
343
344                 $apcontact['updated'] = DateTimeFormat::utcNow();
345
346                 // We delete the old entry when the URL is changed
347                 if ($url != $apcontact['url']) {
348                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
349                         DBA::delete('apcontact', ['url' => $url]);
350                 }
351
352                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
353                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
354                 } else {
355                         DBA::replace('apcontact', $apcontact);
356                 }
357
358                 Logger::info('Updated profile', ['url' => $url]);
359
360                 return $apcontact;
361         }
362
363         /**
364          * Mark the given AP Contact as "to archive"
365          *
366          * @param array $apcontact
367          * @return void
368          */
369         public static function markForArchival(array $apcontact)
370         {
371                 if (!empty($apcontact['inbox'])) {
372                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
373                         HTTPSignature::setInboxStatus($apcontact['inbox'], false);
374                 }
375
376                 if (!empty($apcontact['sharedinbox'])) {
377                         // Check if there are any available inboxes
378                         $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
379                                 $apcontact['sharedinbox']]);
380                         if (!$available) {
381                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
382                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
383                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
384                         }
385                 }
386         }
387
388         /**
389          * Unmark the given AP Contact as "to archive"
390          *
391          * @param array $apcontact
392          * @return void
393          */
394         public static function unmarkForArchival(array $apcontact)
395         {
396                 if (!empty($apcontact['inbox'])) {
397                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
398                         HTTPSignature::setInboxStatus($apcontact['inbox'], true);
399                 }
400                 if (!empty($apcontact['sharedinbox'])) {
401                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
402                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
403                 }
404         }
405
406         /**
407          * Unarchive inboxes
408          *
409          * @param string  $url    inbox url
410          * @param boolean $shared Shared Inbox
411          */
412         private static function unarchiveInbox($url, $shared)
413         {
414                 if (empty($url)) {
415                         return;
416                 }
417
418                 HTTPSignature::setInboxStatus($url, true, $shared);
419         }
420 }