]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Relay.php
$id in Transmitter::sendContactAccept() is a string, see Introduction class
[friendica.git] / src / Protocol / Relay.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Post;
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  * @see https://github.com/jaywink/social-relay
41  * @see https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
42  */
43 class Relay
44 {
45         const SCOPE_NONE = '';
46         const SCOPE_ALL = 'all';
47         const SCOPE_TAGS = 'tags';
48
49         /**
50          * Check if a post is wanted
51          *
52          * @param array $tags
53          * @param string $body
54          * @param int $authorid
55          * @param string $url
56          * @return boolean "true" is the post is wanted by the system
57          */
58         public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = ''): bool
59         {
60                 $config = DI::config();
61
62                 $scope = $config->get('system', 'relay_scope');
63
64                 if ($scope == self::SCOPE_NONE) {
65                         Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]);
66                         return false;
67                 }
68
69                 if (Contact::isBlocked($authorid)) {
70                         Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
71                         return false;
72                 }
73
74                 if (Contact::isHidden($authorid)) {
75                         Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
76                         return false;
77                 }
78
79                 $systemTags = [];
80                 $userTags = [];
81                 $denyTags = [];
82
83                 if ($scope == self::SCOPE_TAGS) {
84                         $server_tags = $config->get('system', 'relay_server_tags');
85                         $tagitems = explode(',', mb_strtolower($server_tags));
86                         foreach ($tagitems as $tag) {
87                                 $systemTags[] = trim($tag, '# ');
88                         }
89
90                         if ($config->get('system', 'relay_user_tags')) {
91                                 $userTags = Search::getUserTags();
92                         }
93                 }
94
95                 $tagList = array_unique(array_merge($systemTags, $userTags));
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]);
111                                         return false;
112                                 }
113
114                                 if (in_array($tag, $tagList)) {
115                                         Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
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]);
123                                         return true;
124                                 }
125                         }
126                 }
127
128                 if ($scope == self::SCOPE_ALL) {
129                         Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url]);
130                         return true;
131                 }
132
133                 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url]);
134                 return false;
135         }
136
137         /**
138          * Update or insert a relay contact
139          *
140          * @param array $gserver Global server record
141          * @param array $fields  Optional network specific fields
142          * @return void
143          * @throws \Exception
144          */
145         public static function updateContact(array $gserver, array $fields = [])
146         {
147                 if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
148                         $system = APContact::getByURL($gserver['url'] . '/friendica');
149                         if (!empty($system['sharedinbox'])) {
150                                 Logger::info('Sucessfully probed for relay contact', ['server' => $gserver['url']]);
151                                 $id = Contact::updateFromProbeByURL($system['url']);
152                                 Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]);
153                                 return;
154                         }
155                 }
156
157                 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
158                 $old = DBA::selectFirst('contact', [], $condition);
159                 if (!DBA::isResult($old)) {
160                         $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])];
161                         $old = DBA::selectFirst('contact', [], $condition);
162                         if (DBA::isResult($old)) {
163                                 $fields['gsid'] = $gserver['id'];
164                                 $fields['contact-type'] = Contact::TYPE_RELAY;
165                                 Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]);
166                         }
167                 } elseif (empty($fields)) {
168                         Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
169                         return;
170                 }
171
172                 if (DBA::isResult($old)) {
173                         $fields['updated'] = DateTimeFormat::utcNow();
174
175                         Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
176                         Contact::update($fields, ['id' => $old['id']], $old);
177                 } else {
178                         $default = ['created' => DateTimeFormat::utcNow(),
179                                 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'],
180                                 'nurl' => Strings::normaliseLink($gserver['url']),
181                                 'network' => Protocol::DIASPORA, 'uid' => 0,
182                                 'batch' => $gserver['url'] . '/receive/public',
183                                 'rel' => Contact::FOLLOWER, 'blocked' => false,
184                                 'pending' => false, 'writable' => true,
185                                 'gsid' => $gserver['id'],
186                                 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY];
187
188                         $fields = array_merge($default, $fields);
189
190                         Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
191                         Contact::insert($fields);
192                 }
193         }
194
195         /**
196          * Mark the relay contact of the given contact for archival
197          * This is called whenever there is a communication issue with the server.
198          * It avoids sending stuff to servers who don't exist anymore.
199          * The relay contact is a technical contact entry that exists once per server.
200          *
201          * @param array $contact of the relay contact
202          * @return void
203          */
204         public static function markForArchival(array $contact)
205         {
206                 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
207                         // This is already the relay contact, we don't need to fetch it
208                         $relay_contact = $contact;
209                 } elseif (empty($contact['baseurl'])) {
210                         if (!empty($contact['batch'])) {
211                                 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
212                                 $relay_contact = DBA::selectFirst('contact', [], $condition);
213                         } else {
214                                 return;
215                         }
216                 } else {
217                         $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
218                                 'url' => $contact['baseurl'], 'network' => $contact['network']];
219                         $relay_contact = self::getContact($gserver, []);
220                 }
221
222                 if (!empty($relay_contact)) {
223                         Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
224                         Contact::markForArchival($relay_contact);
225                 }
226         }
227
228         /**
229          * Return a list of servers that we serve via the direct relay
230          *
231          * @param integer $item_id  id of the item that is sent
232          * @param array   $contacts Previously fetched contacts
233          * @param array   $networks Networks of the relay servers
234          * @return array of relay servers
235          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236          */
237         public static function getDirectRelayList(int $item_id): array
238         {
239                 $serverlist = [];
240
241                 if (!DI::config()->get('system', 'relay_directly', false)) {
242                         return [];
243                 }
244
245                 // We distribute our stuff based on the parent to ensure that the thread will be complete
246                 $parent = Post::selectFirst(['uri-id'], ['id' => $item_id]);
247                 if (!DBA::isResult($parent)) {
248                         return [];
249                 }
250
251                 // Servers that want to get all content
252                 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
253                 while ($server = DBA::fetch($servers)) {
254                         $serverlist[$server['id']] = $server;
255                 }
256                 DBA::close($servers);
257
258                 // All tags of the current post
259                 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
260                 $taglist = [];
261                 while ($tag = DBA::fetch($tags)) {
262                         $taglist[] = $tag['name'];
263                 }
264                 DBA::close($tags);
265
266                 // All servers who wants content with this tag
267                 $tagserverlist = [];
268                 if (!empty($taglist)) {
269                         $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
270                         while ($server = DBA::fetch($tagserver)) {
271                                 $tagserverlist[] = $server['gserver-id'];
272                         }
273                         DBA::close($tagserver);
274                 }
275
276                 // All adresses with the given id
277                 if (!empty($tagserverlist)) {
278                         $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
279                         while ($server = DBA::fetch($servers)) {
280                                 $serverlist[$server['id']] = $server;
281                         }
282                         DBA::close($servers);
283                 }
284
285                 $contacts = [];
286
287                 // Now we are collecting all relay contacts
288                 foreach ($serverlist as $gserver) {
289                         // We don't send messages to ourselves
290                         if (Strings::compareLink($gserver['url'], DI::baseUrl())) {
291                                 continue;
292                         }
293                         $contact = self::getContact($gserver);
294                         if (empty($contact)) {
295                                 continue;
296                         }
297                 }
298
299                 return $contacts;
300         }
301
302         /**
303          * Return a list of relay servers
304          *
305          * @param array $fields Field list
306          * @return array List of relay servers
307          * @throws Exception 
308          */
309         public static function getList(array $fields = []): array
310         {
311                 return DBA::selectToArray('apcontact', $fields,
312                         ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 0, Contact::FRIEND]);
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|bool Array with the contact or false on error
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
346         /**
347          * Resubscribe to all relay servers
348          *
349          * @return void
350          */
351         public static function reSubscribe()
352         {
353                 foreach (self::getList() as $server) {
354                         $success = ActivityPub\Transmitter::sendRelayFollow($server['url']);
355                         Logger::debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]);
356                 }       
357         }
358 }