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