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