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