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