]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Notifies => Notifications
[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\Content\Text\HTML;
10 use Friendica\Core\Logger;
11 use Friendica\Database\DBA;
12 use Friendica\DI;
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
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                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
37
38                 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
39
40                 $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
41                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
42                         $webfinger = Strings::normaliseLink($webfinger);
43
44                         $curlResult = Network::curl($webfinger, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/jrd+json,application/json']);
45
46                         if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
47                                 return false;
48                         }
49                 }
50
51                 $data = json_decode($curlResult->getBody(), true);
52
53                 if (empty($data['links'])) {
54                         return false;
55                 }
56
57                 foreach ($data['links'] as $link) {
58                         if (!empty($url) && !empty($link['href']) && ($link['href'] == $url)) {
59                                 return true;
60                         }
61
62                         if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
63                                 continue;
64                         }
65
66                         if (empty($url) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
67                                 return $link['href'];
68                         }
69                 }
70
71                 return false;
72         }
73
74         /**
75          * Fetches a profile from a given url
76          *
77          * @param string  $url    profile url
78          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
79          * @return array profile array
80          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
81          * @throws \ImagickException
82          */
83         public static function getByURL($url, $update = null)
84         {
85                 if (empty($url)) {
86                         return [];
87                 }
88
89                 $fetched_contact = false;
90
91                 if (empty($update)) {
92                         if (is_null($update)) {
93                                 $ref_update = DateTimeFormat::utc('now - 1 month');
94                         } else {
95                                 $ref_update = DBA::NULL_DATETIME;
96                         }
97
98                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
99                         if (!DBA::isResult($apcontact)) {
100                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
101                         }
102
103                         if (!DBA::isResult($apcontact)) {
104                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
105                         }
106
107                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey'])) {
108                                 return $apcontact;
109                         }
110
111                         if (!is_null($update)) {
112                                 return DBA::isResult($apcontact) ? $apcontact : [];
113                         }
114
115                         if (DBA::isResult($apcontact)) {
116                                 $fetched_contact = $apcontact;
117                         }
118                 }
119
120                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
121                         $url = self::addrToUrl($url);
122                         if (empty($url)) {
123                                 return $fetched_contact;
124                         }
125                 }
126
127                 $data = ActivityPub::fetchContent($url);
128                 if (empty($data)) {
129                         return $fetched_contact;
130                 }
131
132                 $compacted = JsonLD::compact($data);
133
134                 if (empty($compacted['@id'])) {
135                         return $fetched_contact;
136                 }
137
138                 $apcontact = [];
139                 $apcontact['url'] = $compacted['@id'];
140                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
141                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
142                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
143                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
144                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
145                 self::unarchiveInbox($apcontact['inbox'], false);
146
147                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
148
149                 $apcontact['sharedinbox'] = '';
150                 if (!empty($compacted['as:endpoints'])) {
151                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
152                         self::unarchiveInbox($apcontact['sharedinbox'], true);
153                 }
154
155                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
156                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
157
158                 if (empty($apcontact['name'])) {
159                         $apcontact['name'] = $apcontact['nick'];
160                 }
161
162                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
163
164                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
165                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
166                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
167                 }
168
169                 $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
170                 if (is_array($apcontact['alias'])) {
171                         $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
172                 }
173
174                 // Quit if none of the basic values are set
175                 if (empty($apcontact['url']) || empty($apcontact['inbox']) || empty($apcontact['type'])) {
176                         return $fetched_contact;
177                 }
178
179                 // Quit if this doesn't seem to be an account at all
180                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
181                         return $fetched_contact;
182                 }
183
184                 $parts = parse_url($apcontact['url']);
185                 unset($parts['scheme']);
186                 unset($parts['path']);
187
188                 if (!empty($apcontact['nick'])) {
189                         $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
190                 } else {
191                         $apcontact['addr'] = '';
192                 }
193
194                 $apcontact['pubkey'] = null;
195                 if (!empty($compacted['w3id:publicKey'])) {
196                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
197                 }
198
199                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
200
201                 if (!empty($compacted['as:generator'])) {
202                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
203                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
204                 }
205
206                 if (!empty($apcontact['following'])) {
207                         $data = ActivityPub::fetchContent($apcontact['following']);
208                         if (!empty($data)) {
209                                 if (!empty($data['totalItems'])) {
210                                         $apcontact['following_count'] = $data['totalItems'];
211                                 }
212                         }
213                 }
214
215                 if (!empty($apcontact['followers'])) {
216                         $data = ActivityPub::fetchContent($apcontact['followers']);
217                         if (!empty($data)) {
218                                 if (!empty($data['totalItems'])) {
219                                         $apcontact['followers_count'] = $data['totalItems'];
220                                 }
221                         }
222                 }
223
224                 if (!empty($apcontact['outbox'])) {
225                         $data = ActivityPub::fetchContent($apcontact['outbox']);
226                         if (!empty($data)) {
227                                 if (!empty($data['totalItems'])) {
228                                         $apcontact['statuses_count'] = $data['totalItems'];
229                                 }
230                         }
231                 }
232
233                 // To-Do
234
235                 // Unhandled
236                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
237
238                 // Unhandled from Misskey
239                 // sharedInbox, isCat
240
241                 // Unhandled from Kroeg
242                 // kroeg:blocks, updated
243
244                 $parts = parse_url($apcontact['url']);
245                 unset($parts['path']);
246                 $baseurl = Network::unparseURL($parts);
247
248                 // Check if the address is resolvable or the profile url is identical with the base url of the system
249                 if (self::addrToUrl($apcontact['addr'], $apcontact['url']) || Strings::compareLink($apcontact['url'], $baseurl)) {
250                         $apcontact['baseurl'] = $baseurl;
251                 } else {
252                         $apcontact['addr'] = null;
253                 }
254
255                 if (empty($apcontact['baseurl'])) {
256                         $apcontact['baseurl'] = null;
257                 }
258
259                 if ($apcontact['url'] == $apcontact['alias']) {
260                         $apcontact['alias'] = null;
261                 }
262
263                 $apcontact['updated'] = DateTimeFormat::utcNow();
264
265                 DBA::update('apcontact', $apcontact, ['url' => $url], true);
266
267                 // We delete the old entry when the URL is changed
268                 if (($url != $apcontact['url']) && DBA::exists('apcontact', ['url' => $url]) && DBA::exists('apcontact', ['url' => $apcontact['url']])) {
269                         DBA::delete('apcontact', ['url' => $url]);
270                 }
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 }