]> git.mxchange.org Git - friendica.git/blob - src/Model/APContact.php
Manually add Persian to post body language detection
[friendica.git] / src / Model / APContact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Content\Text\HTML;
25 use Friendica\Core\Cache\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\DBA;
29 use Friendica\Database\DBStructure;
30 use Friendica\DI;
31 use Friendica\Network\Probe;
32 use Friendica\Protocol\ActivityNamespace;
33 use Friendica\Protocol\ActivityPub;
34 use Friendica\Protocol\ActivityPub\Transmitter;
35 use Friendica\Util\Crypto;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41
42 class APContact
43 {
44         /**
45          * Fetch webfinger data
46          *
47          * @param string $addr Address
48          * @return array webfinger data
49          */
50         private static function fetchWebfingerData(string $addr)
51         {
52                 $addr_parts = explode('@', $addr);
53                 if (count($addr_parts) != 2) {
54                         return [];
55                 }
56
57                 if (Contact::isLocal($addr) && ($local_uid = User::getIdForURL($addr)) && ($local_owner = User::getOwnerDataById($local_uid))) {
58                         $data = [
59                                 'addr'      => $local_owner['addr'],
60                                 'baseurl'   => $local_owner['baseurl'],
61                                 'url'       => $local_owner['url'],
62                                 'subscribe' => $local_owner['baseurl'] . '/follow?url={uri}'];
63
64                         if (!empty($local_owner['alias']) && ($local_owner['url'] != $local_owner['alias'])) {
65                                 $data['alias'] = $local_owner['alias'];
66                         }
67
68                         return $data;
69                 }
70
71                 $data = ['addr' => $addr];
72                 $template = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
73                 $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
74                 if (empty($webfinger['links'])) {
75                         $template = 'http://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
76                         $webfinger = Probe::webfinger(str_replace('{uri}', urlencode($addr), $template), 'application/jrd+json');
77                         if (empty($webfinger['links'])) {
78                                 return [];
79                         }
80                         $data['baseurl'] = 'http://' . $addr_parts[1];
81                 } else {
82                         $data['baseurl'] = 'https://' . $addr_parts[1];
83                 }
84
85                 foreach ($webfinger['links'] as $link) {
86                         if (empty($link['rel'])) {
87                                 continue;
88                         }
89
90                         if (!empty($link['template']) && ($link['rel'] == ActivityNamespace::OSTATUSSUB)) {
91                                 $data['subscribe'] = $link['template'];
92                         }
93
94                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
95                                 $data['url'] = $link['href'];
96                         }
97
98                         if (!empty($link['href']) && !empty($link['type']) && ($link['rel'] == 'http://webfinger.net/rel/profile-page') && ($link['type'] == 'text/html')) {
99                                 $data['alias'] = $link['href'];
100                         }
101                 }
102
103                 if (!empty($data['url']) && !empty($data['alias']) && ($data['url'] == $data['alias'])) {
104                         unset($data['alias']);
105                 }
106
107                 return $data;
108         }
109
110         /**
111          * Fetches a profile from a given url
112          *
113          * @param string  $url    profile url
114          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
115          * @return array profile array
116          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117          * @throws \ImagickException
118          */
119         public static function getByURL($url, $update = null)
120         {
121                 if (empty($url)) {
122                         return [];
123                 }
124
125                 $fetched_contact = false;
126
127                 if (empty($update)) {
128                         if (is_null($update)) {
129                                 $ref_update = DateTimeFormat::utc('now - 1 month');
130                         } else {
131                                 $ref_update = DBA::NULL_DATETIME;
132                         }
133
134                         $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
135                         if (!DBA::isResult($apcontact)) {
136                                 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
137                         }
138
139                         if (!DBA::isResult($apcontact)) {
140                                 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
141                         }
142
143                         if (DBA::isResult($apcontact) && ($apcontact['updated'] > $ref_update) && !empty($apcontact['pubkey']) && !empty($apcontact['uri-id'])) {
144                                 return $apcontact;
145                         }
146
147                         if (!is_null($update)) {
148                                 return DBA::isResult($apcontact) ? $apcontact : [];
149                         }
150
151                         if (DBA::isResult($apcontact)) {
152                                 $fetched_contact = $apcontact;
153                         }
154                 }
155
156                 $apcontact = [];
157
158                 $webfinger = empty(parse_url($url, PHP_URL_SCHEME));
159                 if ($webfinger) {
160                         $apcontact = self::fetchWebfingerData($url);
161                         if (empty($apcontact['url'])) {
162                                 return $fetched_contact;
163                         }
164                         $url = $apcontact['url'];
165                 }
166
167                 // Detect multiple fast repeating request to the same address
168                 // See https://github.com/friendica/friendica/issues/9303
169                 $cachekey = 'apcontact:getByURL:' . $url;
170                 $result = DI::cache()->get($cachekey);
171                 if (!is_null($result)) {
172                         Logger::notice('Multiple requests for the address', ['url' => $url, 'update' => $update, 'callstack' => System::callstack(20), 'result' => $result]);
173                         if (!empty($fetched_contact)) {
174                                 return $fetched_contact;
175                         }
176                 } else {
177                         DI::cache()->set($cachekey, System::callstack(20), Duration::FIVE_MINUTES);
178                 }
179
180                 if (Network::isLocalLink($url) && ($local_uid = User::getIdForURL($url))) {
181                         $data  = Transmitter::getProfile($local_uid);
182                         $local_owner = User::getOwnerDataById($local_uid);
183                 }
184
185                 if (empty($data)) {
186                         $local_owner = [];
187
188                         $curlResult = HTTPSignature::fetchRaw($url);
189                         $failed = empty($curlResult) || empty($curlResult->getBody()) ||
190                                 (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410));
191
192                         if (!$failed) {
193                                 $data = json_decode($curlResult->getBody(), true);
194                                 $failed = empty($data) || !is_array($data);
195                         }
196
197                         if (!$failed && ($curlResult->getReturnCode() == 410)) {
198                                 $data = ['@context' => ActivityPub::CONTEXT, 'id' => $url, 'type' => 'Tombstone'];
199                         }
200
201                         if ($failed) {
202                                 self::markForArchival($fetched_contact ?: []);
203                                 return $fetched_contact;
204                         }
205                 }
206
207                 $compacted = JsonLD::compact($data);
208                 if (empty($compacted['@id'])) {
209                         return $fetched_contact;
210                 }
211
212                 $apcontact['url'] = $compacted['@id'];
213                 $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value');
214                 $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
215                 $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
216                 $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
217                 $apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id');
218                 self::unarchiveInbox($apcontact['inbox'], false);
219
220                 $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
221
222                 $apcontact['sharedinbox'] = '';
223                 if (!empty($compacted['as:endpoints'])) {
224                         $apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id');
225                         self::unarchiveInbox($apcontact['sharedinbox'], true);
226                 }
227
228                 $apcontact['nick'] = JsonLD::fetchElement($compacted, 'as:preferredUsername', '@value') ?? '';
229                 $apcontact['name'] = JsonLD::fetchElement($compacted, 'as:name', '@value');
230
231                 if (empty($apcontact['name'])) {
232                         $apcontact['name'] = $apcontact['nick'];
233                 }
234
235                 $apcontact['about'] = HTML::toBBCode(JsonLD::fetchElement($compacted, 'as:summary', '@value'));
236
237                 $apcontact['photo'] = JsonLD::fetchElement($compacted, 'as:icon', '@id');
238                 if (is_array($apcontact['photo']) || !empty($compacted['as:icon']['as:url']['@id'])) {
239                         $apcontact['photo'] = JsonLD::fetchElement($compacted['as:icon'], 'as:url', '@id');
240                 }
241
242                 $apcontact['header'] = JsonLD::fetchElement($compacted, 'as:image', '@id');
243                 if (is_array($apcontact['header']) || !empty($compacted['as:image']['as:url']['@id'])) {
244                         $apcontact['header'] = JsonLD::fetchElement($compacted['as:image'], 'as:url', '@id');
245                 }
246
247                 if (empty($apcontact['alias'])) {
248                         $apcontact['alias'] = JsonLD::fetchElement($compacted, 'as:url', '@id');
249                         if (is_array($apcontact['alias'])) {
250                                 $apcontact['alias'] = JsonLD::fetchElement($compacted['as:url'], 'as:href', '@id');
251                         }
252                 }
253
254                 // Quit if none of the basic values are set
255                 if (empty($apcontact['url']) || empty($apcontact['type']) || (($apcontact['type'] != 'Tombstone') && empty($apcontact['inbox']))) {
256                         return $fetched_contact;
257                 } elseif ($apcontact['type'] == 'Tombstone') {
258                         // The "inbox" field must have a content
259                         $apcontact['inbox'] = '';
260                 }
261
262                 // Quit if this doesn't seem to be an account at all
263                 if (!in_array($apcontact['type'], ActivityPub::ACCOUNT_TYPES)) {
264                         return $fetched_contact;
265                 }
266
267                 $parts = parse_url($apcontact['url']);
268                 unset($parts['scheme']);
269                 unset($parts['path']);
270
271                 if (empty($apcontact['addr'])) {
272                         if (!empty($apcontact['nick']) && is_array($parts)) {
273                                 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
274                         } else {
275                                 $apcontact['addr'] = '';
276                         }
277                 }
278
279                 $apcontact['pubkey'] = null;
280                 if (!empty($compacted['w3id:publicKey'])) {
281                         $apcontact['pubkey'] = trim(JsonLD::fetchElement($compacted['w3id:publicKey'], 'w3id:publicKeyPem', '@value'));
282                         if (strstr($apcontact['pubkey'], 'RSA ')) {
283                                 $apcontact['pubkey'] = Crypto::rsaToPem($apcontact['pubkey']);
284                         }
285                 }
286
287                 $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers');
288
289                 if (!empty($compacted['as:generator'])) {
290                         $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id');
291                         $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value');
292                 }
293
294                 if (!empty($apcontact['following'])) {
295                         if (!empty($local_owner)) {
296                                 $following = ActivityPub\Transmitter::getContacts($local_owner, [Contact::SHARING, Contact::FRIEND], 'following');
297                         } else {
298                                 $following = ActivityPub::fetchContent($apcontact['following']);
299                         }
300                         if (!empty($following['totalItems'])) {
301                                 // Mastodon seriously allows for this condition?
302                                 // Jul 14 2021 - See https://mastodon.social/@BLUW for a negative following count
303                                 if ($following['totalItems'] < 0) {
304                                         $following['totalItems'] = 0;
305                                 }
306                                 $apcontact['following_count'] = $following['totalItems'];
307                         }
308                 }
309
310                 if (!empty($apcontact['followers'])) {
311                         if (!empty($local_owner)) {
312                                 $followers = ActivityPub\Transmitter::getContacts($local_owner, [Contact::FOLLOWER, Contact::FRIEND], 'followers');
313                         } else {
314                                 $followers = ActivityPub::fetchContent($apcontact['followers']);
315                         }
316                         if (!empty($followers['totalItems'])) {
317                                 // Mastodon seriously allows for this condition?
318                                 // Jul 14 2021 - See https://mastodon.online/@goes11 for a negative followers count
319                                 if ($followers['totalItems'] < 0) {
320                                         $followers['totalItems'] = 0;
321                                 }
322                                 $apcontact['followers_count'] = $followers['totalItems'];
323                         }
324                 }
325
326                 if (!empty($apcontact['outbox'])) {
327                         if (!empty($local_owner)) {
328                                 $outbox = ActivityPub\Transmitter::getOutbox($local_owner);
329                         } else {
330                                 $outbox = ActivityPub::fetchContent($apcontact['outbox']);
331                         }
332                         if (!empty($outbox['totalItems'])) {
333                                 $apcontact['statuses_count'] = $outbox['totalItems'];
334                         }
335                 }
336
337                 $apcontact['discoverable'] = JsonLD::fetchElement($compacted, 'toot:discoverable', '@value');
338
339                 // To-Do
340
341                 // Unhandled
342                 // tag, attachment, image, nomadicLocations, signature, featured, movedTo, liked
343
344                 // Unhandled from Misskey
345                 // sharedInbox, isCat
346
347                 // Unhandled from Kroeg
348                 // kroeg:blocks, updated
349
350                 // When the photo is too large, try to shorten it by removing parts
351                 if (strlen($apcontact['photo']) > 255) {
352                         $parts = parse_url($apcontact['photo']);
353                         unset($parts['fragment']);
354                         $apcontact['photo'] = Network::unparseURL($parts);
355
356                         if (strlen($apcontact['photo']) > 255) {
357                                 unset($parts['query']);
358                                 $apcontact['photo'] = Network::unparseURL($parts);
359                         }
360
361                         if (strlen($apcontact['photo']) > 255) {
362                                 $apcontact['photo'] = substr($apcontact['photo'], 0, 255);
363                         }
364                 }
365
366                 if (!$webfinger && !empty($apcontact['addr'])) {
367                         $data = self::fetchWebfingerData($apcontact['addr']);
368                         if (!empty($data)) {
369                                 $apcontact['baseurl'] = $data['baseurl'];
370
371                                 if (empty($apcontact['alias']) && !empty($data['alias'])) {
372                                         $apcontact['alias'] = $data['alias'];
373                                 }
374                                 if (!empty($data['subscribe'])) {
375                                         $apcontact['subscribe'] = $data['subscribe'];
376                                 }
377                         } else {
378                                 $apcontact['addr'] = null;
379                         }
380                 }
381
382                 if (empty($apcontact['baseurl'])) {
383                         $apcontact['baseurl'] = null;
384                 }
385
386                 if (empty($apcontact['subscribe'])) {
387                         $apcontact['subscribe'] = null;
388                 }
389
390                 if (!empty($apcontact['baseurl']) && empty($fetched_contact['gsid'])) {
391                         $apcontact['gsid'] = GServer::getID($apcontact['baseurl']);
392                 } elseif (!empty($fetched_contact['gsid'])) {
393                         $apcontact['gsid'] = $fetched_contact['gsid'];
394                 } else {
395                         $apcontact['gsid'] = null;
396                 }
397
398                 if ($apcontact['url'] == $apcontact['alias']) {
399                         $apcontact['alias'] = null;
400                 }
401
402                 if (empty($apcontact['uuid'])) {
403                         $apcontact['uri-id'] = ItemURI::getIdByURI($apcontact['url']);
404                 } else {
405                         $apcontact['uri-id'] = ItemURI::insert(['uri' => $apcontact['url'], 'guid' => $apcontact['uuid']]);
406                 }
407
408                 $apcontact['updated'] = DateTimeFormat::utcNow();
409
410                 // We delete the old entry when the URL is changed
411                 if ($url != $apcontact['url']) {
412                         Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
413                         DBA::delete('apcontact', ['url' => $url]);
414                 }
415
416                 // Limit the length on incoming fields
417                 $apcontact = DBStructure::getFieldsForTable('apcontact', $apcontact);
418
419                 if (DBA::exists('apcontact', ['url' => $apcontact['url']])) {
420                         DBA::update('apcontact', $apcontact, ['url' => $apcontact['url']]);
421                 } else {
422                         DBA::replace('apcontact', $apcontact);
423                 }
424
425                 Logger::info('Updated profile', ['url' => $url]);
426
427                 return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
428         }
429
430         /**
431          * Mark the given AP Contact as "to archive"
432          *
433          * @param array $apcontact
434          * @return void
435          */
436         public static function markForArchival(array $apcontact)
437         {
438                 if (!empty($apcontact['inbox'])) {
439                         Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
440                         HTTPSignature::setInboxStatus($apcontact['inbox'], false);
441                 }
442
443                 if (!empty($apcontact['sharedinbox'])) {
444                         // Check if there are any available inboxes
445                         $available = DBA::exists('apcontact', ["`sharedinbox` = ? AnD `inbox` IN (SELECT `url` FROM `inbox-status` WHERE `success` > `failure`)",
446                                 $apcontact['sharedinbox']]);
447                         if (!$available) {
448                                 // If all known personal inboxes are failing then set their shared inbox to failure as well
449                                 Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
450                                 HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true);
451                         }
452                 }
453         }
454
455         /**
456          * Unmark the given AP Contact as "to archive"
457          *
458          * @param array $apcontact
459          * @return void
460          */
461         public static function unmarkForArchival(array $apcontact)
462         {
463                 if (!empty($apcontact['inbox'])) {
464                         Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
465                         HTTPSignature::setInboxStatus($apcontact['inbox'], true);
466                 }
467                 if (!empty($apcontact['sharedinbox'])) {
468                         Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
469                         HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true);
470                 }
471         }
472
473         /**
474          * Unarchive inboxes
475          *
476          * @param string  $url    inbox url
477          * @param boolean $shared Shared Inbox
478          */
479         private static function unarchiveInbox($url, $shared)
480         {
481                 if (empty($url)) {
482                         return;
483                 }
484
485                 HTTPSignature::setInboxStatus($url, true, $shared);
486         }
487 }