]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Move internal recursion-counter to the end of all cur/fetchUrl parameters
[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          * @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                 if (empty($apcontact['url']) || empty($apcontact['inbox'])) {
156                         return false;
157                 }
158
159                 $parts = parse_url($apcontact['url']);
160                 unset($parts['scheme']);
161                 unset($parts['path']);
162                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
163
164                 if (!empty($compacted['w3id:publicKey'])) {
165                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
166                 }
167
168                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
169
170                 if (!empty($compacted['as:generator'])) {
171                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
172                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
173                 }
174
175                 // To-Do
176
177                 // Unhandled
178                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
179
180                 // Unhandled from Misskey
181                 // sharedInbox, isCat
182
183                 // Unhandled from Kroeg
184                 // kroeg:blocks, updated
185
186                 // Check if the address is resolvable
187                 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
188                         $parts = parse_url($apcontact['url']);
189                         unset($parts['path']);
190                         $apcontact['baseurl'] = Network::unparseURL($parts);
191                 } else {
192                         $apcontact['addr'] = null;
193                 }
194
195                 if (empty($apcontact['baseurl'])) {
196                         $apcontact['baseurl'] = null;
197                 }
198
199                 if ($apcontact['url'] == $apcontact['alias']) {
200                         $apcontact['alias'] = null;
201                 }
202
203                 $apcontact['updated'] = DateTimeFormat::utcNow();
204
205                 DBA::update('apcontact', $apcontact, ['url' => $url], true);
206
207                 // Update some data in the contact table with various ways to catch them all
208                 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about'], 'alias' => $apcontact['alias']];
209
210                 // Fetch the type and match it with the contact type
211                 $contact_types = array_keys(ActivityPub::ACCOUNT_TYPES, $apcontact['type']);
212                 if (!empty($contact_types)) {
213                         $contact_type = array_pop($contact_types);
214                         if (is_int($contact_type)) {
215                                 $contact_fields['contact-type'] = $contact_type;
216
217                                 if ($contact_fields['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
218                                         // Resetting the 'forum' and 'prv' field when it isn't a forum
219                                         $contact_fields['forum'] = false;
220                                         $contact_fields['prv'] = false;
221                                 } else {
222                                         // Otherwise set the corresponding forum type
223                                         $contact_fields['forum'] = !$apcontact['manually-approve'];
224                                         $contact_fields['prv'] = $apcontact['manually-approve'];
225                                 }
226                         }
227                 }
228
229                 DBA::update('contact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
230
231                 $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => Strings::normaliseLink($url)]);
232                 while ($contact = DBA::fetch($contacts)) {
233                         Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
234                 }
235                 DBA::close($contacts);
236
237                 // Update the gcontact table
238                 // These two fields don't exist in the gcontact table
239                 unset($contact_fields['forum']);
240                 unset($contact_fields['prv']);
241                 DBA::update('gcontact', $contact_fields, ['nurl' => Strings::normaliseLink($url)]);
242
243                 Logger::log('Updated profile for ' . $url, Logger::DEBUG);
244
245                 return $apcontact;
246         }
247
248         /**
249          * Unarchive inboxes
250          *
251          * @param string $url inbox url
252          */
253         private static function unarchiveInbox($url, $shared)
254         {
255                 if (empty($url)) {
256                         return;
257                 }
258
259                 $now = DateTimeFormat::utcNow();
260
261                 $fields = ['archive' => false, 'success' => $now, 'shared' => $shared];
262
263                 if (!DBA::exists('inbox-status', ['url' => $url])) {
264                         $fields = array_merge($fields, ['url' => $url, 'created' => $now]);
265                         DBA::insert('inbox-status', $fields);
266                 } else {
267                         DBA::update('inbox-status', $fields, ['url' => $url]);
268                 }
269         }
270 }