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