]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Don't transmit to archived inboxes
[friendica.git] / src / Model / APContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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                 $data = ActivityPub::fetchContent($url);
151                 if (empty($data)) {
152                         self::markForArchival($fetched_contact ?: []);
153                         return $fetched_contact;
154                 }
155
156                 $compacted = JsonLD::compact($data);
157
158                 if (empty($compacted['@id'])) {
159                         return $fetched_contact;
160                 }
161
162                 // Detect multiple fast repeating request to the same address
163                 // See https://github.com/friendica/friendica/issues/9303
164                 $cachekey = 'apcontact:getByURL:' . $url;
165                 $result = DI::cache()->get($cachekey);
166                 if (!is_null($result)) {
167                         Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
168                 } else {
169                         DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
170                 }
171
172                 $apcontact['url'] = $compacted['@id'];
173                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
174                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
175                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
176                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
177                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
178                 self::unarchiveInbox($apcontact['inbox'], false);
179
180                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
181
182                 $apcontact['sharedinbox'] = '';
183                 if (!empty($compacted['as:endpoints'])) {
184                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
185                         self::unarchiveInbox($apcontact['sharedinbox'], true);
186                 }
187
188                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
189                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
190
191                 if (empty($apcontact['name'])) {
192                         $apcontact['name'] = $apcontact['nick'];
193                 }
194
195                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
196
197                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
198                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
199                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
200                 }
201
202                 if (empty($apcontact['alias'])) {
203                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
204                         if (is_array($apcontact['alias'])) {
205                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
206                         }
207                 }
208
209                 // Quit if none of the basic values are set
210                 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
211                         return $fetched_contact;
212                 }
213
214                 // Quit if this doesn't seem to be an account at all
215                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
216                         return $fetched_contact;
217                 }
218
219                 $parts = parse_url($apcontact['url']);
220                 unset($parts['scheme']);
221                 unset($parts['path']);
222
223                 if (empty($apcontact['addr'])) {
224                         if (!empty($apcontact['nick'])) {
225                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
226                         } else {
227                                 $apcontact['addr'] = '';
228                         }
229                 }
230
231                 $apcontact['pubkey'] = null;
232                 if (!empty($compacted['w3id:publicKey'])) {
233                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
234                         if (strstr($apcontact['pubkey'], 'RSA ')) {
235                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
236                         }
237                 }
238
239                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
240
241                 if (!empty($compacted['as:generator'])) {
242                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
243                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
244                 }
245
246                 if (!empty($apcontact['following'])) {
247                         $data = ActivityPub::fetchContent($apcontact['following']);
248                         if (!empty($data)) {
249                                 if (!empty($data['totalItems'])) {
250                                         $apcontact['following_count'] = $data['totalItems'];
251                                 }
252                         }
253                 }
254
255                 if (!empty($apcontact['followers'])) {
256                         $data = ActivityPub::fetchContent($apcontact['followers']);
257                         if (!empty($data)) {
258                                 if (!empty($data['totalItems'])) {
259                                         $apcontact['followers_count'] = $data['totalItems'];
260                                 }
261                         }
262                 }
263
264                 if (!empty($apcontact['outbox'])) {
265                         $data = ActivityPub::fetchContent($apcontact['outbox']);
266                         if (!empty($data)) {
267                                 if (!empty($data['totalItems'])) {
268                                         $apcontact['statuses_count'] = $data['totalItems'];
269                                 }
270                         }
271                 }
272
273                 // To-Do
274
275                 // Unhandled
276                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
277
278                 // Unhandled from Misskey
279                 // sharedInbox, isCat
280
281                 // Unhandled from Kroeg
282                 // kroeg:blocks, updated
283
284                 // When the photo is too large, try to shorten it by removing parts
285                 if (strlen($apcontact['photo']) > 255) {
286                         $parts = parse_url($apcontact['photo']);
287                         unset($parts['fragment']);
288                         $apcontact['photo'] = Network::unparseURL($parts);
289
290                         if (strlen($apcontact['photo']) > 255) {
291                                 unset($parts['query']);
292                                 $apcontact['photo'] = Network::unparseURL($parts);
293                         }
294
295                         if (strlen($apcontact['photo']) > 255) {
296                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
297                         }
298                 }
299
300                 if (!$webfinger && !empty($apcontact['addr'])) {
301                         $data = self::fetchWebfingerData($apcontact['addr']);
302                         if (!empty($data)) {
303                                 $apcontact['baseurl'] = $data['baseurl'];
304
305                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
306                                         $apcontact['alias'] = $data['alias'];
307                                 }
308                                 if (!empty($data['subscribe'])) {
309                                         $apcontact['subscribe'] = $data['subscribe'];
310                                 }
311                         } else {
312                                 $apcontact['addr'] = null;
313                         }
314                 }
315
316                 if (empty($apcontact['baseurl'])) {
317                         $apcontact['baseurl'] = null;
318                 }
319
320                 if (empty($apcontact['subscribe'])) {
321                         $apcontact['subscribe'] = null;
322                 }               
323
324                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
325                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
326                 } elseif (!empty($fetched_contact['gsid'])) {
327                         $apcontact['gsid'] = $fetched_contact['gsid'];
328                 } else {
329                         $apcontact['gsid'] = null;
330                 }
331
332                 if ($apcontact['url'] == $apcontact['alias']) {
333                         $apcontact['alias'] = null;
334                 }
335
336                 $apcontact['updated'] = DateTimeFormat::utcNow();
337
338                 // We delete the old entry when the URL is changed
339                 if ($url != $apcontact['url']) {
340                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
341                         DBA::delete('apcontact', ['url' => $url]);
342                 }
343
344                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
345                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
346                 } else {
347                         DBA::replace('apcontact', $apcontact);
348                 }
349
350                 Logger::info('Updated profile', ['url' => $url]);
351
352                 return $apcontact;
353         }
354
355         /**
356          * Mark the given AP Contact as "to archive"
357          *
358          * @param array $apcontact
359          * @return void
360          */
361         public static function markForArchival(array $apcontact)
362         {
363                 if (!empty($apcontact['inbox'])) {
364                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
365                         HTTPSignature::setInboxStatus($apcontact['inbox'], false);
366                 }
367
368                 if (!empty($apcontact['sharedinbox'])) {
369                         // Check if there are any vital inboxes
370                         $vital = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
371                                 $apcontact['sharedinbox']]);
372                         if (!$vital) {
373                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
374                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
375                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
376                         }
377                 }
378         }
379
380         /**
381          * Unmark the given AP Contact as "to archive"
382          *
383          * @param array $apcontact
384          * @return void
385          */
386         public static function unmarkForArchival(array $apcontact)
387         {
388                 if (!empty($apcontact['inbox'])) {
389                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
390                         HTTPSignature::setInboxStatus($apcontact['inbox'], true);
391                 }
392                 if (!empty($apcontact['sharedinbox'])) {
393                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
394                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
395                 }
396         }
397
398         /**
399          * Unarchive inboxes
400          *
401          * @param string  $url    inbox url
402          * @param boolean $shared Shared Inbox
403          */
404         private static function unarchiveInbox($url, $shared)
405         {
406                 if (empty($url)) {
407                         return;
408                 }
409
410                 HTTPSignature::setInboxStatus($url, true, $shared);
411         }
412 }