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