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