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