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