]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Relay.php
Merge pull request #13610 from MrPetovan/bug/13334-calendar-public-event
[friendica.git] / src / Protocol / Relay.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Protocol;
23
24 use Friendica\Content\Smilies;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Cache\Enum\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\Search;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Strings;
41
42 /**
43  * Base class for relay handling
44  * @see https://github.com/jaywink/social-relay
45  * @see https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
46  */
47 class Relay
48 {
49         const SCOPE_NONE = '';
50         const SCOPE_ALL = 'all';
51         const SCOPE_TAGS = 'tags';
52
53         /**
54          * Check if a post is wanted
55          *
56          * @param array $tags
57          * @param string $body
58          * @param int $authorid
59          * @param string $url
60          * @return boolean "true" is the post is wanted by the system
61          */
62         public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = '', int $causerid = 0): bool
63         {
64                 $config = DI::config();
65
66                 $scope = $config->get('system', 'relay_scope');
67
68                 if ($scope == self::SCOPE_NONE) {
69                         Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]);
70                         return false;
71                 }
72
73                 if (Contact::isBlocked($authorid)) {
74                         Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
75                         return false;
76                 }
77
78                 if (Contact::isHidden($authorid)) {
79                         Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
80                         return false;
81                 }
82
83                 if (!empty($causerid)) {
84                         $contact = Contact::getById($causerid, ['url']);
85                         $causer = $contact['url'] ?? '';
86                 } else {
87                         $causer = '';
88                 }
89
90                 $body = ActivityPub\Processor::normalizeMentionLinks($body);
91
92                 $denyTags = [];
93
94                 if ($scope == self::SCOPE_TAGS) {
95                         $tagList = self::getSubscribedTags();
96                 } else {
97                         $tagList  = [];
98                 }
99
100                 $deny_tags = $config->get('system', 'relay_deny_tags');
101                 $tagitems = explode(',', mb_strtolower($deny_tags));
102                 foreach ($tagitems as $tag) {
103                         $tag = trim($tag, '# ');
104                         $denyTags[] = $tag;
105                 }
106
107                 if (!empty($tagList) || !empty($denyTags)) {
108                         $content = mb_strtolower(BBCode::toPlaintext($body, false));
109
110                         foreach ($tags as $tag) {
111                                 $tag = mb_strtolower($tag);
112                                 if (in_array($tag, $denyTags)) {
113                                         Logger::info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
114                                         return false;
115                                 }
116
117                                 if (in_array($tag, $tagList)) {
118                                         Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
119                                         return true;
120                                 }
121
122                                 // We check with "strpos" for performance issues. Only when this is true, the regular expression check is used
123                                 // RegExp is taken from here: https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
124                                 if ((strpos($content, $tag) !== false) && preg_match('/(?<=[\s,.:;"\']|^)' . preg_quote($tag, '/') . '(?=[\s,.:;"\']|$)/', $content)) {
125                                         Logger::info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
126                                         return true;
127                                 }
128                         }
129                 }
130
131                 if (!self::isWantedLanguage($body, 0, $authorid)) {
132                         Logger::info('Unwanted or Undetected language found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
133                         return false;
134                 }
135
136                 if ($scope == self::SCOPE_ALL) {
137                         Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
138                         return true;
139                 }
140
141                 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
142                 return false;
143         }
144
145         /**
146          * Get a list of subscribed tags by both the users and the tags that are defined by the admin
147          *
148          * @return array
149          */
150         public static function getSubscribedTags(): array
151         {
152                 $systemTags  = [];
153                 $server_tags = DI::config()->get('system', 'relay_server_tags');
154
155                 foreach (explode(',', mb_strtolower($server_tags)) as $tag) {
156                         $systemTags[] = trim($tag, '# ');
157                 }
158
159                 if (DI::config()->get('system', 'relay_user_tags')) {
160                         $userTags = Search::getUserTags();
161                 } else {
162                         $userTags = [];
163                 }
164
165                 return array_unique(array_merge($systemTags, $userTags));
166         }
167
168         /**
169          * Detect the language of a post and decide if the post should be accepted
170          *
171          * @param string $body
172          * @param int    $uri_id
173          * @param int    $author_id
174          * @return boolean
175          */
176         public static function isWantedLanguage(string $body, int $uri_id = 0, int $author_id = 0)
177         {
178                 if (empty($body) || Smilies::isEmojiPost($body)) {
179                         Logger::debug('Empty body or only emojis', ['body' => $body]);
180                         return true;
181                 }
182
183                 $languages = [];
184                 foreach (Item::getLanguageArray($body, 10, $uri_id, $author_id) as $language => $reliability) {
185                         if ($reliability > 0) {
186                                 $languages[] = $language;
187                         }
188                 }
189
190                 if (!empty($languages)) {
191                         $cachekey = 'relay:isWantedLanguage';
192                         $user_languages = DI::cache()->get($cachekey);
193                         if (is_null($user_languages)) {
194                                 $user_languages = User::getLanguages();
195                                 DI::cache()->set($cachekey, $user_languages, Duration::HALF_HOUR);
196                         }
197
198                         foreach ($languages as $language) {
199                                 if (in_array($language, $user_languages)) {
200                                         Logger::debug('Wanted language found', ['language' => $language, 'languages' => $languages, 'userlang' => $user_languages, 'body' => $body]);
201                                         return true;
202                                 }
203                         }
204                         Logger::debug('No wanted language found', ['languages' => $languages, 'userlang' => $user_languages, 'body' => $body]);
205                         return false;
206                 } elseif (DI::config()->get('system', 'relay_deny_undetected_language')) {
207                         Logger::info('Undetected language found', ['body' => $body]);
208                         return false;
209                 }
210
211                 return true;
212         }
213
214         /**
215          * Update or insert a relay contact
216          *
217          * @param array $gserver Global server record
218          * @param array $fields  Optional network specific fields
219          * @return void
220          * @throws \Exception
221          */
222         public static function updateContact(array $gserver, array $fields = [])
223         {
224                 if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
225                         $system = APContact::getByURL($gserver['url'] . '/friendica');
226                         if (!empty($system['sharedinbox'])) {
227                                 Logger::info('Successfully probed for relay contact', ['server' => $gserver['url']]);
228                                 $id = Contact::updateFromProbeByURL($system['url']);
229                                 Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]);
230                                 return;
231                         }
232                 }
233
234                 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
235                 $old = DBA::selectFirst('contact', [], $condition);
236                 if (!DBA::isResult($old)) {
237                         $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])];
238                         $old = DBA::selectFirst('contact', [], $condition);
239                         if (DBA::isResult($old)) {
240                                 $fields['gsid'] = $gserver['id'];
241                                 $fields['contact-type'] = Contact::TYPE_RELAY;
242                                 Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]);
243                         }
244                 } elseif (empty($fields)) {
245                         Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
246                         return;
247                 }
248
249                 if (DBA::isResult($old)) {
250                         $fields['updated'] = DateTimeFormat::utcNow();
251
252                         Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
253                         Contact::update($fields, ['id' => $old['id']], $old);
254                 } else {
255                         $default = ['created' => DateTimeFormat::utcNow(),
256                                 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'],
257                                 'nurl' => Strings::normaliseLink($gserver['url']),
258                                 'network' => Protocol::DIASPORA, 'uid' => 0,
259                                 'batch' => $gserver['url'] . '/receive/public',
260                                 'rel' => Contact::FOLLOWER, 'blocked' => false,
261                                 'pending' => false, 'writable' => true,
262                                 'gsid' => $gserver['id'],
263                                 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY];
264
265                         $fields = array_merge($default, $fields);
266
267                         Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
268                         Contact::insert($fields);
269                 }
270         }
271
272         /**
273          * Mark the relay contact of the given contact for archival
274          * This is called whenever there is a communication issue with the server.
275          * It avoids sending stuff to servers who don't exist anymore.
276          * The relay contact is a technical contact entry that exists once per server.
277          *
278          * @param array $contact of the relay contact
279          * @return void
280          */
281         public static function markForArchival(array $contact)
282         {
283                 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
284                         // This is already the relay contact, we don't need to fetch it
285                         $relay_contact = $contact;
286                 } elseif (empty($contact['baseurl'])) {
287                         if (!empty($contact['batch'])) {
288                                 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
289                                 $relay_contact = DBA::selectFirst('contact', [], $condition);
290                         } else {
291                                 return;
292                         }
293                 } else {
294                         $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
295                                 'url' => $contact['baseurl'], 'network' => $contact['network']];
296                         $relay_contact = self::getContact($gserver, []);
297                 }
298
299                 if (!empty($relay_contact)) {
300                         Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
301                         Contact::markForArchival($relay_contact);
302                 }
303         }
304
305         /**
306          * Return a list of servers that we serve via the direct relay
307          *
308          * @param integer $item_id  id of the item that is sent
309          * @param array   $contacts Previously fetched contacts
310          * @param array   $networks Networks of the relay servers
311          * @return array of relay servers
312          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313          */
314         public static function getDirectRelayList(int $item_id): array
315         {
316                 $serverlist = [];
317
318                 if (!DI::config()->get('system', 'relay_directly', false)) {
319                         return [];
320                 }
321
322                 // We distribute our stuff based on the parent to ensure that the thread will be complete
323                 $parent = Post::selectFirst(['uri-id'], ['id' => $item_id]);
324                 if (!DBA::isResult($parent)) {
325                         return [];
326                 }
327
328                 // Servers that want to get all content
329                 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
330                 while ($server = DBA::fetch($servers)) {
331                         $serverlist[$server['id']] = $server;
332                 }
333                 DBA::close($servers);
334
335                 // All tags of the current post
336                 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
337                 $taglist = [];
338                 while ($tag = DBA::fetch($tags)) {
339                         $taglist[] = $tag['name'];
340                 }
341                 DBA::close($tags);
342
343                 // All servers who wants content with this tag
344                 $tagserverlist = [];
345                 if (!empty($taglist)) {
346                         $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
347                         while ($server = DBA::fetch($tagserver)) {
348                                 $tagserverlist[] = $server['gserver-id'];
349                         }
350                         DBA::close($tagserver);
351                 }
352
353                 // All addresses with the given id
354                 if (!empty($tagserverlist)) {
355                         $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
356                         while ($server = DBA::fetch($servers)) {
357                                 $serverlist[$server['id']] = $server;
358                         }
359                         DBA::close($servers);
360                 }
361
362                 $contacts = [];
363
364                 // Now we are collecting all relay contacts
365                 foreach ($serverlist as $gserver) {
366                         // We don't send messages to ourselves
367                         if (Strings::compareLink($gserver['url'], DI::baseUrl())) {
368                                 continue;
369                         }
370                         $contact = self::getContact($gserver);
371                         if (empty($contact)) {
372                                 continue;
373                         }
374                 }
375
376                 return $contacts;
377         }
378
379         /**
380          * Return a list of relay servers
381          *
382          * @param array $fields Field list
383          * @return array List of relay servers
384          * @throws Exception
385          */
386         public static function getList(array $fields = []): array
387         {
388                 return DBA::selectToArray('apcontact', $fields,
389                         ["`type` IN (?, ?) AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 'Service', 0, Contact::FRIEND]);
390         }
391
392         /**
393          * Return a contact for a given server address or creates a dummy entry
394          *
395          * @param array $gserver Global server record
396          * @param array $fields  Fieldlist
397          * @return array|bool Array with the contact or false on error
398          * @throws \Exception
399          */
400         private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
401         {
402                 // Fetch the relay contact
403                 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
404                 $contact = DBA::selectFirst('contact', $fields, $condition);
405                 if (DBA::isResult($contact)) {
406                         if ($contact['archive'] || $contact['blocked']) {
407                                 return false;
408                         }
409                         return $contact;
410                 } else {
411                         self::updateContact($gserver);
412
413                         $contact = DBA::selectFirst('contact', $fields, $condition);
414                         if (DBA::isResult($contact)) {
415                                 return $contact;
416                         }
417                 }
418
419                 // It should never happen that we arrive here
420                 return [];
421         }
422
423         /**
424          * Resubscribe to all relay servers
425          *
426          * @return void
427          */
428         public static function reSubscribe()
429         {
430                 foreach (self::getList() as $server) {
431                         $success = ActivityPub\Transmitter::sendRelayFollow($server['url']);
432                         Logger::debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]);
433                 }
434         }
435 }