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