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