]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
"accept" constants introduced and used
[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\HttpClient;
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 use Friendica\Util\Strings;
43
44 class APContact
45 {
46         /**
47          * Fetch webfinger data
48          *
49          * @param string $addr Address
50          * @return array webfinger data
51          */
52         private static function fetchWebfingerData(string $addr)
53         {
54                 $addr_parts = explode('@', $addr);
55                 if (count($addr_parts) != 2) {
56                         return [];
57                 }
58
59                 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
60                         $data = [
61                                 'addr'      => $local_owner['addr'],
62                                 'baseurl'   => $local_owner['baseurl'],
63                                 'url'       => $local_owner['url'],
64                                 'subscribe' => $local_owner['baseurl'] . '/follow?url={uri}'];
65
66                         if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
67                                 $data['alias'] = $local_owner['alias'];
68                         }
69
70                         return $data;
71                 }
72
73                 $data = ['addr' => $addr];
74                 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
75                 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClient::ACCEPT_JRD_JSON);
76                 if (empty($webfinger['links'])) {
77                         $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
78                         $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), HttpClient::ACCEPT_JRD_JSON);
79                         if (empty($webfinger['links'])) {
80                                 return [];
81                         }
82                         $data['baseurl'] = 'http://' . $addr_parts[1];
83                 } else {
84                         $data['baseurl'] = 'https://' . $addr_parts[1];
85                 }
86
87                 foreach ($webfinger['links'] as $link) {
88                         if (empty($link['rel'])) {
89                                 continue;
90                         }
91
92                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
93                                 $data['subscribe'] = $link['template'];
94                         }
95
96                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
97                                 $data['url'] = $link['href'];
98                         }
99
100                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
101                                 $data['alias'] = $link['href'];
102                         }
103                 }
104
105                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
106                         unset($data['alias']);
107                 }
108
109                 return $data;
110         }
111
112         /**
113          * Fetches a profile from a given url
114          *
115          * @param string  $url    profile url
116          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
117          * @return array profile array
118          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119          * @throws \ImagickException
120          */
121         public static function getByURL($url, $update = null)
122         {
123                 if (empty($url) || Network::isUrlBlocked($url)) {
124                         Logger::info('Domain is blocked', ['url' => $url]);
125                         return [];
126                 }
127
128                 $fetched_contact = false;
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['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
236                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
237
238                 if (empty($apcontact['name'])) {
239                         $apcontact['name'] = $apcontact['nick'];
240                 }
241
242                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
243
244                 $ims = JsonLD::fetchElementArray($compacted, 'vcard:hasInstantMessage');
245                 if (!empty($ims)) {
246                         foreach ($ims as $link) {
247                                 if (substr($link, 0, 5) == 'xmpp:') {
248                                         $apcontact['xmpp'] = substr($link, 5);
249                                 }
250                                 if (substr($link, 0, 7) == 'matrix:') {
251                                         $apcontact['matrix'] = substr($link, 7);
252                                 }
253                         }
254                 }
255
256                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
257                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
258                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
259                 }
260
261                 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
262                 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
263                         $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
264                 }
265
266                 if (empty($apcontact['alias'])) {
267                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
268                         if (is_array($apcontact['alias'])) {
269                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
270                         }
271                 }
272
273                 // Quit if none of the basic values are set
274                 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
275                         return $fetched_contact;
276                 } elseif ($apcontact['type'] == 'Tombstone') {
277                         // The "inbox" field must have a content
278                         $apcontact['inbox'] = '';
279                 }
280
281                 // Quit if this doesn't seem to be an account at all
282                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
283                         return $fetched_contact;
284                 }
285
286                 $parts = parse_url($apcontact['url']);
287                 unset($parts['scheme']);
288                 unset($parts['path']);
289
290                 if (empty($apcontact['addr'])) {
291                         if (!empty($apcontact['nick']) && is_array($parts)) {
292                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
293                         } else {
294                                 $apcontact['addr'] = '';
295                         }
296                 }
297
298                 $apcontact['pubkey'] = null;
299                 if (!empty($compacted['w3id:publicKey'])) {
300                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
301                         if (strstr($apcontact['pubkey'], 'RSA ')) {
302                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
303                         }
304                 }
305
306                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
307
308                 if (!empty($compacted['as:generator'])) {
309                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
310                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
311                 }
312
313                 if (!empty($apcontact['following'])) {
314                         if (!empty($local_owner)) {
315                                 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
316                         } else {
317                                 $following = ActivityPub::fetchContent($apcontact['following']);
318                         }
319                         if (!empty($following['totalItems'])) {
320                                 // Mastodon seriously allows for this condition?
321                                 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
322                                 if ($following['totalItems'] < 0) {
323                                         $following['totalItems'] = 0;
324                                 }
325                                 $apcontact['following_count'] = $following['totalItems'];
326                         }
327                 }
328
329                 if (!empty($apcontact['followers'])) {
330                         if (!empty($local_owner)) {
331                                 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
332                         } else {
333                                 $followers = ActivityPub::fetchContent($apcontact['followers']);
334                         }
335                         if (!empty($followers['totalItems'])) {
336                                 // Mastodon seriously allows for this condition?
337                                 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
338                                 if ($followers['totalItems'] < 0) {
339                                         $followers['totalItems'] = 0;
340                                 }
341                                 $apcontact['followers_count'] = $followers['totalItems'];
342                         }
343                 }
344
345                 if (!empty($apcontact['outbox'])) {
346                         if (!empty($local_owner)) {
347                                 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
348                         } else {
349                                 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
350                         }
351                         if (!empty($outbox['totalItems'])) {
352                                 // Mastodon seriously allows for this condition?
353                                 // Jul 20 2021 - See https://chaos.social/@m11 for a negative posts count
354                                 if ($outbox['totalItems'] < 0) {
355                                         $outbox['totalItems'] = 0;
356                                 }
357                                 $apcontact['statuses_count'] = $outbox['totalItems'];
358                         }
359                 }
360
361                 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
362
363                 // To-Do
364
365                 // Unhandled
366                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
367
368                 // Unhandled from Misskey
369                 // sharedInbox, isCat
370
371                 // Unhandled from Kroeg
372                 // kroeg:blocks, updated
373
374                 // When the photo is too large, try to shorten it by removing parts
375                 if (strlen($apcontact['photo']) > 255) {
376                         $parts = parse_url($apcontact['photo']);
377                         unset($parts['fragment']);
378                         $apcontact['photo'] = Network::unparseURL($parts);
379
380                         if (strlen($apcontact['photo']) > 255) {
381                                 unset($parts['query']);
382                                 $apcontact['photo'] = Network::unparseURL($parts);
383                         }
384
385                         if (strlen($apcontact['photo']) > 255) {
386                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
387                         }
388                 }
389
390                 if (!$webfinger && !empty($apcontact['addr'])) {
391                         $data = self::fetchWebfingerData($apcontact['addr']);
392                         if (!empty($data)) {
393                                 $apcontact['baseurl'] = $data['baseurl'];
394
395                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
396                                         $apcontact['alias'] = $data['alias'];
397                                 }
398                                 if (!empty($data['subscribe'])) {
399                                         $apcontact['subscribe'] = $data['subscribe'];
400                                 }
401                         } else {
402                                 $apcontact['addr'] = null;
403                         }
404                 }
405
406                 if (empty($apcontact['baseurl'])) {
407                         $apcontact['baseurl'] = null;
408                 }
409
410                 if (empty($apcontact['subscribe'])) {
411                         $apcontact['subscribe'] = null;
412                 }
413
414                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
415                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
416                 } elseif (!empty($fetched_contact['gsid'])) {
417                         $apcontact['gsid'] = $fetched_contact['gsid'];
418                 } else {
419                         $apcontact['gsid'] = null;
420                 }
421
422                 if ($apcontact['url'] == $apcontact['alias']) {
423                         $apcontact['alias'] = null;
424                 }
425
426                 if (empty($apcontact['uuid'])) {
427                         $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
428                 } else {
429                         $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
430                 }
431
432                 $apcontact['updated'] = DateTimeFormat::utcNow();
433
434                 // We delete the old entry when the URL is changed
435                 if ($url != $apcontact['url']) {
436                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
437                         DBA::delete('apcontact', ['url' => $url]);
438                 }
439
440                 // Limit the length on incoming fields
441                 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
442
443                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
444                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
445                 } else {
446                         DBA::replace('apcontact', $apcontact);
447                 }
448
449                 Logger::info('Updated profile', ['url' => $url]);
450
451                 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
452         }
453
454         /**
455          * Mark the given AP Contact as "to archive"
456          *
457          * @param array $apcontact
458          * @return void
459          */
460         public static function markForArchival(array $apcontact)
461         {
462                 if (!empty($apcontact['inbox'])) {
463                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
464                         HTTPSignature::setInboxStatus($apcontact['inbox'], false);
465                 }
466
467                 if (!empty($apcontact['sharedinbox'])) {
468                         // Check if there are any available inboxes
469                         $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
470                                 $apcontact['sharedinbox']]);
471                         if (!$available) {
472                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
473                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
474                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
475                         }
476                 }
477         }
478
479         /**
480          * Unmark the given AP Contact as "to archive"
481          *
482          * @param array $apcontact
483          * @return void
484          */
485         public static function unmarkForArchival(array $apcontact)
486         {
487                 if (!empty($apcontact['inbox'])) {
488                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
489                         HTTPSignature::setInboxStatus($apcontact['inbox'], true);
490                 }
491                 if (!empty($apcontact['sharedinbox'])) {
492                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
493                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
494                 }
495         }
496
497         /**
498          * Unarchive inboxes
499          *
500          * @param string  $url    inbox url
501          * @param boolean $shared Shared Inbox
502          */
503         private static function unarchiveInbox($url, $shared)
504         {
505                 if (empty($url)) {
506                         return;
507                 }
508
509                 HTTPSignature::setInboxStatus($url, true, $shared);
510         }
511 }