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