Don't send activities to "null" endpoints
[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 = Strings::normaliseLink($webfinger);
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                 $fetched_contact = false;
91
92                 if (empty($update)) {
93                         if (is_null($update)) {
94                                 $ref_update = DateTimeFormat::utc('now - 1 month');
95                         } else {
96                                 $ref_update = DBA::NULL_DATETIME;
97                         }
98
99                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
100                         if (!DBA::isResult($apcontact)) {
101                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
102                         }
103
104                         if (!DBA::isResult($apcontact)) {
105                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
106                         }
107
108                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
109                                 return $apcontact;
110                         }
111
112                         if (!is_null($update)) {
113                                 return DBA::isResult($apcontact) ? $apcontact : false;
114                         }
115
116                         if (DBA::isResult($apcontact)) {
117                                 $fetched_contact = $apcontact;
118                         }
119                 }
120
121                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
122                         $url = self::addrToUrl($url);
123                         if (empty($url)) {
124                                 return $fetched_contact;
125                         }
126                 }
127
128                 $data = ActivityPub::fetchContent($url);
129                 if (empty($data)) {
130                         return $fetched_contact;
131                 }
132
133                 $compacted = JsonLD::compact($data);
134
135                 if (empty($compacted['@id'])) {
136                         return $fetched_contact;
137                 }
138
139                 $apcontact = [];
140                 $apcontact['url'] = $compacted['@id'];
141                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
142                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
143                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
144                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
145                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
146                 self::unarchiveInbox($apcontact['inbox'], false);
147
148                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
149
150                 $apcontact['sharedinbox'] = '';
151                 if (!empty($compacted['as:endpoints'])) {
152                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
153                         self::unarchiveInbox($apcontact['sharedinbox'], true);
154                 }
155
156                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value');
157                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
158
159                 if (empty($apcontact['name'])) {
160                         $apcontact['name'] = $apcontact['nick'];
161                 }
162
163                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
164
165                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
166                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
167                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
168                 }
169
170                 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
171                 if (is_array($apcontact['alias'])) {
172                         $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
173                 }
174
175                 // Quit if none of the basic values are set
176                 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
177                         return $fetched_contact;
178                 }
179
180                 // Quit if this doesn't seem to be an account at all
181                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
182                         return $fetched_contact;
183                 }
184
185                 $parts = parse_url($apcontact['url']);
186                 unset($parts['scheme']);
187                 unset($parts['path']);
188                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
189
190                 if (!empty($compacted['w3id:publicKey'])) {
191                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
192                 }
193
194                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
195
196                 if (!empty($compacted['as:generator'])) {
197                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
198                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
199                 }
200
201                 // To-Do
202
203                 // Unhandled
204                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
205
206                 // Unhandled from Misskey
207                 // sharedInbox, isCat
208
209                 // Unhandled from Kroeg
210                 // kroeg:blocks, updated
211
212                 $parts = parse_url($apcontact['url']);
213                 unset($parts['path']);
214                 $baseurl = Network::unparseURL($parts);
215
216                 // Check if the address is resolvable or the profile url is identical with the base url of the system
217                 if (self::addrToUrl($apcontact['addr'], $apcontact['url']) || Strings::compareLink($apcontact['url'], $baseurl)) {
218                         $apcontact['baseurl'] = $baseurl;
219                 } else {
220                         $apcontact['addr'] = null;
221                 }
222
223                 if (empty($apcontact['baseurl'])) {
224                         $apcontact['baseurl'] = null;
225                 }
226
227                 if ($apcontact['url'] == $apcontact['alias']) {
228                         $apcontact['alias'] = null;
229                 }
230
231                 $apcontact['updated'] = DateTimeFormat::utcNow();
232
233                 DBA::update('apcontact', $apcontact, ['url' => $url], true);
234
235                 // We delete the old entry when the URL is changed
236                 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
237                         DBA::delete('apcontact', ['url' => $url]);
238                 }
239
240                 // Update some data in the contact table with various ways to catch them all
241                 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about'], 'alias' => $apcontact['alias']];
242
243                 // Fetch the type and match it with the contact type
244                 $contact_types = array_keys(ActivityPub::ACCOUNT_TYPES, $apcontact['type']);
245                 if (!empty($contact_types)) {
246                         $contact_type = array_pop($contact_types);
247                         if (is_int($contact_type)) {
248                                 $contact_fields['contact-type'] = $contact_type;
249
250                                 if ($contact_fields['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
251                                         // Resetting the 'forum' and 'prv' field when it isn't a forum
252                                         $contact_fields['forum'] = false;
253                                         $contact_fields['prv'] = false;
254                                 } else {
255                                         // Otherwise set the corresponding forum type
256                                         $contact_fields['forum'] = !$apcontact['manually-approve'];
257                                         $contact_fields['prv'] = $apcontact['manually-approve'];
258                                 }
259                         }
260                 }
261
262                 DBA::update('contact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
263
264                 if (!empty($apcontact['photo'])) {
265                         $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => Strings::normaliseLink($url)]);
266                         while ($contact = DBA::fetch($contacts)) {
267                                 Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
268                         }
269                         DBA::close($contacts);
270                 }
271
272                 // Update the gcontact table
273                 // These two fields don't exist in the gcontact table
274                 unset($contact_fields['forum']);
275                 unset($contact_fields['prv']);
276                 DBA::update('gcontact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
277
278                 Logger::log('Updated profile for ' . $url, Logger::DEBUG);
279
280                 return $apcontact;
281         }
282
283         /**
284          * Unarchive inboxes
285          *
286          * @param string $url inbox url
287          */
288         private static function unarchiveInbox($url, $shared)
289         {
290                 if (empty($url)) {
291                         return;
292                 }
293
294                 $now = DateTimeFormat::utcNow();
295
296                 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
297
298                 if (!DBA::exists('inbox-status', ['url' => $url])) {
299                         $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
300                         DBA::insert('inbox-status', $fields);
301                 } else {
302                         DBA::update('inbox-status', $fields, ['url' => $url]);
303                 }
304         }
305 }