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