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