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