]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Relay.php
Delay unprepared posts
[friendica.git] / src / Protocol / Relay.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Search;
34 use Friendica\Model\Tag;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Strings;
37
38 /**
39  * Base class for relay handling
40  */
41 class Relay
42 {
43         /**
44          * Check if a post is wanted
45          *
46          * @param array $tags
47          * @param string $body
48          * @param int $authorid
49          * @param string $url
50          * @return boolean "true" is the post is wanted by the system
51          */
52         public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = '')
53         {
54                 $config = DI::config();
55
56                 $subscribe = $config->get('system', 'relay_subscribe', false);
57                 if ($subscribe) {
58                         $scope = $config->get('system', 'relay_scope', SR_SCOPE_ALL);
59                 } else {
60                         $scope = SR_SCOPE_NONE;
61                 }
62
63                 if ($scope == SR_SCOPE_NONE) {
64                         Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]);
65                         return false;
66                 }
67
68                 if (Contact::isBlocked($authorid)) {
69                         Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
70                         return false;
71                 }
72
73                 if (Contact::isHidden($authorid)) {
74                         Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
75                         return false;
76                 }
77
78                 $systemTags = [];
79                 $userTags = [];
80                 $denyTags = [];
81
82                 if ($scope == SR_SCOPE_TAGS) {
83                         $server_tags = $config->get('system', 'relay_server_tags');
84                         $tagitems = explode(',', mb_strtolower($server_tags));
85                         foreach ($tagitems AS $tag) {
86                                 $systemTags[] = trim($tag, '# ');
87                         }
88
89                         if ($config->get('system', 'relay_user_tags')) {
90                                 $userTags = Search::getUserTags();
91                         }
92                 }
93
94                 $tagList = array_unique(array_merge($systemTags, $userTags));
95
96                 $deny_tags = $config->get('system', 'relay_deny_tags');
97                 $tagitems = explode(',', mb_strtolower($deny_tags));
98                 foreach ($tagitems AS $tag) {
99                         $tag = trim($tag, '# ');
100                         $denyTags[] = $tag;
101                 }
102
103                 if (!empty($tagList) || !empty($denyTags)) {
104                         $content = mb_strtolower(BBCode::toPlaintext($body, false));
105
106                         foreach ($tags as $tag) {
107                                 $tag = mb_strtolower($tag);
108                                 if (in_array($tag, $denyTags)) {
109                                         Logger::info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
110                                         return false;
111                                 }
112
113                                 if (in_array($tag, $tagList)) {
114                                         Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
115                                         return true;
116                                 }
117
118                                 // We check with "strpos" for performance issues. Only when this is true, the regular expression check is used
119                                 // RegExp is taken from here: https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
120                                 if ((strpos($content, $tag) !== false) && preg_match('/(?<=[\s,.:;"\']|^)' . preg_quote($tag, '/') . '(?=[\s,.:;"\']|$)/', $content)) {
121                                         Logger::info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
122                                         return true;
123                                 }
124                         }
125                 }
126
127                 if ($scope == SR_SCOPE_ALL) {
128                         Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url]);
129                         return true;
130                 }
131
132                 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url]);
133                 return false;
134         }
135
136         /**
137          * Update or insert a relay contact
138          *
139          * @param array $gserver Global server record
140          * @param array $fields  Optional network specific fields
141          * @throws \Exception
142          */
143         public static function updateContact(array $gserver, array $fields = [])
144         {
145                 if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
146                         $system = APContact::getByURL($gserver['url'] . '/friendica');
147                         if (!empty($system['sharedinbox'])) {
148                                 Logger::info('Sucessfully probed for relay contact', ['server' => $gserver['url']]);
149                                 $id = Contact::updateFromProbeByURL($system['url']);
150                                 Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]);
151                                 return;
152                         }
153                 }
154
155                 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
156                 $old = DBA::selectFirst('contact', [], $condition);
157                 if (!DBA::isResult($old)) {
158                         $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])];
159                         $old = DBA::selectFirst('contact', [], $condition);
160                         if (DBA::isResult($old)) {
161                                 $fields['gsid'] = $gserver['id'];
162                                 $fields['contact-type'] = Contact::TYPE_RELAY;
163                                 Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]);
164                         }
165                 } elseif (empty($fields)) {
166                         Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
167                         return;
168                 }
169
170                 if (DBA::isResult($old)) {      
171                         $fields['updated'] = DateTimeFormat::utcNow();
172
173                         Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
174                         DBA::update('contact', $fields, ['id' => $old['id']], $old);
175                 } else {
176                         $default = ['created' => DateTimeFormat::utcNow(),
177                                 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'],
178                                 'nurl' => Strings::normaliseLink($gserver['url']),
179                                 'network' => Protocol::DIASPORA, 'uid' => 0,
180                                 'batch' => $gserver['url'] . '/receive/public',
181                                 'rel' => Contact::FOLLOWER, 'blocked' => false,
182                                 'pending' => false, 'writable' => true,
183                                 'gsid' => $gserver['id'],
184                                 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY];
185
186                         $fields = array_merge($default, $fields);
187
188                         Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
189                         Contact::insert($fields);
190                 }
191         }
192
193         /**
194          * Mark the relay contact of the given contact for archival
195          * This is called whenever there is a communication issue with the server.
196          * It avoids sending stuff to servers who don't exist anymore.
197          * The relay contact is a technical contact entry that exists once per server.
198          *
199          * @param array $contact of the relay contact
200          */
201         public static function markForArchival(array $contact)
202         {
203                 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
204                         // This is already the relay contact, we don't need to fetch it
205                         $relay_contact = $contact;
206                 } elseif (empty($contact['baseurl'])) {
207                         if (!empty($contact['batch'])) {
208                                 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
209                                 $relay_contact = DBA::selectFirst('contact', [], $condition);
210                         } else {
211                                 return;
212                         }
213                 } else {
214                         $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
215                                 'url' => $contact['baseurl'], 'network' => $contact['network']];
216                         $relay_contact = self::getContact($gserver, []);
217                 }
218
219                 if (!empty($relay_contact)) {
220                         Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
221                         Contact::markForArchival($relay_contact);
222                 }
223         }
224
225         /**
226          * Return a list of relay servers
227          *
228          * The list contains not only the official relays but also servers that we serve directly
229          *
230          * @param integer $item_id  id of the item that is sent
231          * @param array   $contacts Previously fetched contacts
232          * @param array   $networks Networks of the relay servers 
233          *
234          * @return array of relay servers
235          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236          */
237         public static function getList(int $item_id, array $contacts, array $networks)
238         {
239                 $serverlist = [];
240
241                 // Fetching relay servers
242                 $serverdata = DI::config()->get("system", "relay_server");
243
244                 if (!empty($serverdata)) {
245                         $servers = explode(",", $serverdata);
246                         foreach ($servers as $server) {
247                                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network'], ['nurl' => Strings::normaliseLink($server)]);
248                                 if (DBA::isResult($gserver)) {
249                                         $serverlist[$gserver['id']] = $gserver;
250                                 }
251                         }
252                 }
253
254                 if (DI::config()->get("system", "relay_directly", false)) {
255                         // We distribute our stuff based on the parent to ensure that the thread will be complete
256                         $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
257                         if (!DBA::isResult($parent)) {
258                                 return;
259                         }
260
261                         // Servers that want to get all content
262                         $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
263                         while ($server = DBA::fetch($servers)) {
264                                 $serverlist[$server['id']] = $server;
265                         }
266                         DBA::close($servers);
267
268                         // All tags of the current post
269                         $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
270                         $taglist = [];
271                         while ($tag = DBA::fetch($tags)) {
272                                 $taglist[] = $tag['name'];
273                         }
274                         DBA::close($tags);
275
276                         // All servers who wants content with this tag
277                         $tagserverlist = [];
278                         if (!empty($taglist)) {
279                                 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
280                                 while ($server = DBA::fetch($tagserver)) {
281                                         $tagserverlist[] = $server['gserver-id'];
282                                 }
283                                 DBA::close($tagserver);
284                         }
285
286                         // All adresses with the given id
287                         if (!empty($tagserverlist)) {
288                                 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
289                                 while ($server = DBA::fetch($servers)) {
290                                         $serverlist[$server['id']] = $server;
291                                 }
292                                 DBA::close($servers);
293                         }
294                 }
295
296                 // Now we are collecting all relay contacts
297                 foreach ($serverlist as $gserver) {
298                         // We don't send messages to ourselves
299                         if (Strings::compareLink($gserver['url'], DI::baseUrl())) {
300                                 continue;
301                         }
302                         $contact = self::getContact($gserver);
303                         if (empty($contact)) {
304                                 continue;
305                         }
306
307                         if (in_array($contact['network'], $networks) && !in_array($contact['batch'], array_column($contacts, 'batch'))) {
308                                 $contacts[] = $contact;
309                         }
310                 }
311
312                 return $contacts;
313         }
314
315         /**
316          * Return a contact for a given server address or creates a dummy entry
317          *
318          * @param array $gserver Global server record
319          * @param array $fields  Fieldlist
320          * @return array with the contact
321          * @throws \Exception
322          */
323         private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
324         {
325                 // Fetch the relay contact
326                 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
327                 $contact = DBA::selectFirst('contact', $fields, $condition);
328                 if (DBA::isResult($contact)) {
329                         if ($contact['archive'] || $contact['blocked']) {
330                                 return false;
331                         }
332                         return $contact;
333                 } else {
334                         self::updateContact($gserver);
335
336                         $contact = DBA::selectFirst('contact', $fields, $condition);
337                         if (DBA::isResult($contact)) {
338                                 return $contact;
339                         }
340                 }
341
342                 // It should never happen that we arrive here
343                 return [];
344         }
345 }