3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Protocol;
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;
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;
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
47 const SCOPE_NONE = '';
48 const SCOPE_ALL = 'all';
49 const SCOPE_TAGS = 'tags';
52 * Check if a post is wanted
56 * @param int $authorid
58 * @return boolean "true" is the post is wanted by the system
60 public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = '', int $causerid = 0): bool
62 $config = DI::config();
64 $scope = $config->get('system', 'relay_scope');
66 if ($scope == self::SCOPE_NONE) {
67 Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]);
71 if (Contact::isBlocked($authorid)) {
72 Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
76 if (Contact::isHidden($authorid)) {
77 Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
81 if (!empty($causerid)) {
82 $contact = Contact::getById($causerid, ['url']);
83 $causer = $contact['url'] ?? '';
88 $body = ActivityPub\Processor::normalizeMentionLinks($body);
92 if ($scope == self::SCOPE_TAGS) {
93 $tagList = self::getSubscribedTags();
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, '# ');
105 if (!empty($tagList) || !empty($denyTags)) {
106 $content = mb_strtolower(BBCode::toPlaintext($body, false));
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]);
115 if (in_array($tag, $tagList)) {
116 Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
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]);
129 if (!self::isWantedLanguage($body, 0, $authorid)) {
130 Logger::info('Unwanted or Undetected language found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
134 if ($scope == self::SCOPE_ALL) {
135 Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
139 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
144 * Get a list of subscribed tags by both the users and the tags that are defined by the admin
148 public static function getSubscribedTags(): array
151 $server_tags = DI::config()->get('system', 'relay_server_tags');
153 foreach (explode(',', mb_strtolower($server_tags)) as $tag) {
154 $systemTags[] = trim($tag, '# ');
157 if (DI::config()->get('system', 'relay_user_tags')) {
158 $userTags = Search::getUserTags();
163 return array_unique(array_merge($systemTags, $userTags));
167 * Detect the language of a post and decide if the post should be accepted
169 * @param string $body
171 * @param int $author_id
174 public static function isWantedLanguage(string $body, int $uri_id = 0, int $author_id = 0)
176 if (empty($body) || Smilies::isEmojiPost($body)) {
177 Logger::debug('Empty body or only emojis', ['body' => $body]);
182 foreach (Item::getLanguageArray($body, 10, $uri_id, $author_id) as $language => $reliability) {
183 if ($reliability > 0) {
184 $languages[] = $language;
188 Logger::debug('Got languages', ['languages' => $languages, 'body' => $body]);
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]]);
195 } elseif (DI::config()->get('system', 'relay_deny_undetected_language')) {
196 Logger::info('Undetected language found', ['body' => $body]);
204 * Update or insert a relay contact
206 * @param array $gserver Global server record
207 * @param array $fields Optional network specific fields
211 public static function updateContact(array $gserver, array $fields = [])
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]);
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']]);
233 } elseif (empty($fields)) {
234 Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
238 if (DBA::isResult($old)) {
239 $fields['updated'] = DateTimeFormat::utcNow();
241 Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
242 Contact::update($fields, ['id' => $old['id']], $old);
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];
254 $fields = array_merge($default, $fields);
256 Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
257 Contact::insert($fields);
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.
267 * @param array $contact of the relay contact
270 public static function markForArchival(array $contact)
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);
283 $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
284 'url' => $contact['baseurl'], 'network' => $contact['network']];
285 $relay_contact = self::getContact($gserver, []);
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);
295 * Return a list of servers that we serve via the direct relay
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
303 public static function getDirectRelayList(int $item_id): array
307 if (!DI::config()->get('system', 'relay_directly', false)) {
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)) {
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;
322 DBA::close($servers);
324 // All tags of the current post
325 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
327 while ($tag = DBA::fetch($tags)) {
328 $taglist[] = $tag['name'];
332 // All servers who wants content with this tag
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'];
339 DBA::close($tagserver);
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;
348 DBA::close($servers);
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())) {
359 $contact = self::getContact($gserver);
360 if (empty($contact)) {
369 * Return a list of relay servers
371 * @param array $fields Field list
372 * @return array List of relay servers
375 public static function getList(array $fields = []): array
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]);
382 * Return a contact for a given server address or creates a dummy entry
384 * @param array $gserver Global server record
385 * @param array $fields Fieldlist
386 * @return array|bool Array with the contact or false on error
389 private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
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']) {
400 self::updateContact($gserver);
402 $contact = DBA::selectFirst('contact', $fields, $condition);
403 if (DBA::isResult($contact)) {
408 // It should never happen that we arrive here
413 * Resubscribe to all relay servers
417 public static function reSubscribe()
419 foreach (self::getList() as $server) {
420 $success = ActivityPub\Transmitter::sendRelayFollow($server['url']);
421 Logger::debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]);