ff282997419f87a67443bcf06c5ba5f66c2250bf
[friendica.git/.git] / src / Model / APContact.php
1 <?php
2
3 /**
4  * @file src/Model/APContact.php
5  */
6
7 namespace Friendica\Model;
8
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Config;
13 use Friendica\Database\DBA;
14 use Friendica\Protocol\ActivityPub;
15 use Friendica\Util\Network;
16 use Friendica\Util\JsonLD;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Strings;
19
20 class APContact extends BaseObject
21 {
22         /**
23          * Resolves the profile url from the address by using webfinger
24          *
25          * @param string $addr profile address (user@domain.tld)
26          * @param string $url profile URL. When set then we return "true" when this profile url can be found at the address
27          * @return string|boolean url
28          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
29          */
30         private static function addrToUrl($addr, $url = null)
31         {
32                 $addr_parts = explode('@', $addr);
33                 if (count($addr_parts) != 2) {
34                         return false;
35                 }
36
37                 $xrd_timeout = Config::get('system', 'xrd_timeout');
38
39                 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
40
41                 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
42                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
43                         $webfinger = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
44
45                         $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
46
47                         if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
48                                 return false;
49                         }
50                 }
51
52                 $data = json_decode($curlResult->getBody(), true);
53
54                 if (empty($data['links'])) {
55                         return false;
56                 }
57
58                 foreach ($data['links'] as $link) {
59                         if (!empty($url) && !empty($link['href']) && ($link['href'] == $url)) {
60                                 return true;
61                         }
62
63                         if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
64                                 continue;
65                         }
66
67                         if (empty($url) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
68                                 return $link['href'];
69                         }
70                 }
71
72                 return false;
73         }
74
75         /**
76          * Fetches a profile from a given url
77          *
78          * @param string  $url    profile url
79          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
80          * @return array profile array
81          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
82          * @throws \ImagickException
83          */
84         public static function getByURL($url, $update = null)
85         {
86                 if (empty($url)) {
87                         return false;
88                 }
89
90                 if (empty($update)) {
91                         if (is_null($update)) {
92                                 $ref_update = DateTimeFormat::utc('now - 1 month');
93                         } else {
94                                 $ref_update = DBA::NULL_DATETIME;
95                         }
96
97                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
98                         if (!DBA::isResult($apcontact)) {
99                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
100                         }
101
102                         if (!DBA::isResult($apcontact)) {
103                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
104                         }
105
106                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
107                                 return $apcontact;
108                         }
109
110                         if (!is_null($update)) {
111                                 return DBA::isResult($apcontact) ? $apcontact : false;
112                         }
113                 }
114
115                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
116                         $url = self::addrToUrl($url);
117                         if (empty($url)) {
118                                 return false;
119                         }
120                 }
121
122                 $data = ActivityPub::fetchContent($url);
123                 if (empty($data)) {
124                         return false;
125                 }
126
127                 $compacted = JsonLD::compact($data);
128
129                 if (empty($compacted['@id'])) {
130                         return false;
131                 }
132
133                 $apcontact = [];
134                 $apcontact['url'] = $compacted['@id'];
135                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
136                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
137                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
138                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
139                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
140                 self::unarchiveInbox($apcontact['inbox'], false);
141
142                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
143
144                 $apcontact['sharedinbox'] = '';
145                 if (!empty($compacted['as:endpoints'])) {
146                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
147                         self::unarchiveInbox($apcontact['sharedinbox'], true);
148                 }
149
150                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value');
151                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
152
153                 if (empty($apcontact['name'])) {
154                         $apcontact['name'] = $apcontact['nick'];
155                 }
156
157                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
158
159                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
160                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
161                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
162                 }
163
164                 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
165                 if (is_array($apcontact['alias'])) {
166                         $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
167                 }
168
169                 // Quit if none of the basic values are set
170                 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
171                         return false;
172                 }
173
174                 // Quit if this doesn't seem to be an account at all
175                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
176                         return false;
177                 }
178
179                 $parts = parse_url($apcontact['url']);
180                 unset($parts['scheme']);
181                 unset($parts['path']);
182                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
183
184                 if (!empty($compacted['w3id:publicKey'])) {
185                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
186                 }
187
188                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
189
190                 if (!empty($compacted['as:generator'])) {
191                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
192                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
193                 }
194
195                 // To-Do
196
197                 // Unhandled
198                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
199
200                 // Unhandled from Misskey
201                 // sharedInbox, isCat
202
203                 // Unhandled from Kroeg
204                 // kroeg:blocks, updated
205
206                 $parts = parse_url($apcontact['url']);
207                 unset($parts['path']);
208                 $baseurl = Network::unparseURL($parts);
209
210                 // Check if the address is resolvable or the profile url is identical with the base url of the system
211                 if (self::addrToUrl($apcontact['addr'], $apcontact['url']) || Strings::compareLink($apcontact['url'], $baseurl)) {
212                         $apcontact['baseurl'] = $baseurl;
213                 } else {
214                         $apcontact['addr'] = null;
215                 }
216
217                 if (empty($apcontact['baseurl'])) {
218                         $apcontact['baseurl'] = null;
219                 }
220
221                 if ($apcontact['url'] == $apcontact['alias']) {
222                         $apcontact['alias'] = null;
223                 }
224
225                 $apcontact['updated'] = DateTimeFormat::utcNow();
226
227                 DBA::update('apcontact', $apcontact, ['url' => $url], true);
228
229                 // We delete the old entry when the URL is changed
230                 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
231                         DBA::delete('apcontact', ['url' => $url]);
232                 }
233
234                 // Update some data in the contact table with various ways to catch them all
235                 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about'], 'alias' => $apcontact['alias']];
236
237                 // Fetch the type and match it with the contact type
238                 $contact_types = array_keys(ActivityPub::ACCOUNT_TYPES, $apcontact['type']);
239                 if (!empty($contact_types)) {
240                         $contact_type = array_pop($contact_types);
241                         if (is_int($contact_type)) {
242                                 $contact_fields['contact-type'] = $contact_type;
243
244                                 if ($contact_fields['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
245                                         // Resetting the 'forum' and 'prv' field when it isn't a forum
246                                         $contact_fields['forum'] = false;
247                                         $contact_fields['prv'] = false;
248                                 } else {
249                                         // Otherwise set the corresponding forum type
250                                         $contact_fields['forum'] = !$apcontact['manually-approve'];
251                                         $contact_fields['prv'] = $apcontact['manually-approve'];
252                                 }
253                         }
254                 }
255
256                 DBA::update('contact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
257
258                 if (!empty($apcontact['photo'])) {
259                         $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => Strings::normaliseLink($url)]);
260                         while ($contact = DBA::fetch($contacts)) {
261                                 Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
262                         }
263                         DBA::close($contacts);
264                 }
265
266                 // Update the gcontact table
267                 // These two fields don't exist in the gcontact table
268                 unset($contact_fields['forum']);
269                 unset($contact_fields['prv']);
270                 DBA::update('gcontact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
271
272                 Logger::log('Updated profile for ' . $url, Logger::DEBUG);
273
274                 return $apcontact;
275         }
276
277         /**
278          * Unarchive inboxes
279          *
280          * @param string $url inbox url
281          */
282         private static function unarchiveInbox($url, $shared)
283         {
284                 if (empty($url)) {
285                         return;
286                 }
287
288                 $now = DateTimeFormat::utcNow();
289
290                 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
291
292                 if (!DBA::exists('inbox-status', ['url' => $url])) {
293                         $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
294                         DBA::insert('inbox-status', $fields);
295                 } else {
296                         DBA::update('inbox-status', $fields, ['url' => $url]);
297                 }
298         }
299 }