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