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