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