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);
94 if ($scope == self::SCOPE_TAGS) {
95 $server_tags = $config->get('system', 'relay_server_tags');
96 $tagitems = explode(',', mb_strtolower($server_tags));
97 foreach ($tagitems as $tag) {
98 $systemTags[] = trim($tag, '# ');
101 if ($config->get('system', 'relay_user_tags')) {
102 $userTags = Search::getUserTags();
106 $tagList = array_unique(array_merge($systemTags, $userTags));
108 $deny_tags = $config->get('system', 'relay_deny_tags');
109 $tagitems = explode(',', mb_strtolower($deny_tags));
110 foreach ($tagitems as $tag) {
111 $tag = trim($tag, '# ');
115 if (!empty($tagList) || !empty($denyTags)) {
116 $content = mb_strtolower(BBCode::toPlaintext($body, false));
118 foreach ($tags as $tag) {
119 $tag = mb_strtolower($tag);
120 if (in_array($tag, $denyTags)) {
121 Logger::info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
125 if (in_array($tag, $tagList)) {
126 Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
130 // We check with "strpos" for performance issues. Only when this is true, the regular expression check is used
131 // RegExp is taken from here: https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
132 if ((strpos($content, $tag) !== false) && preg_match('/(?<=[\s,.:;"\']|^)' . preg_quote($tag, '/') . '(?=[\s,.:;"\']|$)/', $content)) {
133 Logger::info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]);
139 if (!self::isWantedLanguage($body)) {
140 Logger::info('Unwanted or Undetected language found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
144 if ($scope == self::SCOPE_ALL) {
145 Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
149 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]);
154 * Detect the language of a post and decide if the post should be accepted
156 * @param string $body
159 public static function isWantedLanguage(string $body)
161 if (empty($body) || Smilies::isEmojiPost($body)) {
162 Logger::debug('Empty body or only emojis', ['body' => $body]);
167 foreach (Item::getLanguageArray($body, 10) as $language => $reliability) {
168 if ($reliability > 0) {
169 $languages[] = $language;
173 Logger::debug('Got languages', ['languages' => $languages, 'body' => $body]);
175 if (!empty($languages)) {
176 if (in_array($languages[0], DI::config()->get('system', 'relay_deny_languages'))) {
177 Logger::info('Unwanted language found', ['language' => $languages[0]]);
180 } elseif (DI::config()->get('system', 'relay_deny_undetected_language')) {
181 Logger::info('Undetected language found', ['body' => $body]);
189 * Update or insert a relay contact
191 * @param array $gserver Global server record
192 * @param array $fields Optional network specific fields
196 public static function updateContact(array $gserver, array $fields = [])
198 if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
199 $system = APContact::getByURL($gserver['url'] . '/friendica');
200 if (!empty($system['sharedinbox'])) {
201 Logger::info('Successfully probed for relay contact', ['server' => $gserver['url']]);
202 $id = Contact::updateFromProbeByURL($system['url']);
203 Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]);
208 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
209 $old = DBA::selectFirst('contact', [], $condition);
210 if (!DBA::isResult($old)) {
211 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])];
212 $old = DBA::selectFirst('contact', [], $condition);
213 if (DBA::isResult($old)) {
214 $fields['gsid'] = $gserver['id'];
215 $fields['contact-type'] = Contact::TYPE_RELAY;
216 Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]);
218 } elseif (empty($fields)) {
219 Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
223 if (DBA::isResult($old)) {
224 $fields['updated'] = DateTimeFormat::utcNow();
226 Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
227 Contact::update($fields, ['id' => $old['id']], $old);
229 $default = ['created' => DateTimeFormat::utcNow(),
230 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'],
231 'nurl' => Strings::normaliseLink($gserver['url']),
232 'network' => Protocol::DIASPORA, 'uid' => 0,
233 'batch' => $gserver['url'] . '/receive/public',
234 'rel' => Contact::FOLLOWER, 'blocked' => false,
235 'pending' => false, 'writable' => true,
236 'gsid' => $gserver['id'],
237 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY];
239 $fields = array_merge($default, $fields);
241 Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
242 Contact::insert($fields);
247 * Mark the relay contact of the given contact for archival
248 * This is called whenever there is a communication issue with the server.
249 * It avoids sending stuff to servers who don't exist anymore.
250 * The relay contact is a technical contact entry that exists once per server.
252 * @param array $contact of the relay contact
255 public static function markForArchival(array $contact)
257 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
258 // This is already the relay contact, we don't need to fetch it
259 $relay_contact = $contact;
260 } elseif (empty($contact['baseurl'])) {
261 if (!empty($contact['batch'])) {
262 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
263 $relay_contact = DBA::selectFirst('contact', [], $condition);
268 $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
269 'url' => $contact['baseurl'], 'network' => $contact['network']];
270 $relay_contact = self::getContact($gserver, []);
273 if (!empty($relay_contact)) {
274 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
275 Contact::markForArchival($relay_contact);
280 * Return a list of servers that we serve via the direct relay
282 * @param integer $item_id id of the item that is sent
283 * @param array $contacts Previously fetched contacts
284 * @param array $networks Networks of the relay servers
285 * @return array of relay servers
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function getDirectRelayList(int $item_id): array
292 if (!DI::config()->get('system', 'relay_directly', false)) {
296 // We distribute our stuff based on the parent to ensure that the thread will be complete
297 $parent = Post::selectFirst(['uri-id'], ['id' => $item_id]);
298 if (!DBA::isResult($parent)) {
302 // Servers that want to get all content
303 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
304 while ($server = DBA::fetch($servers)) {
305 $serverlist[$server['id']] = $server;
307 DBA::close($servers);
309 // All tags of the current post
310 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
312 while ($tag = DBA::fetch($tags)) {
313 $taglist[] = $tag['name'];
317 // All servers who wants content with this tag
319 if (!empty($taglist)) {
320 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
321 while ($server = DBA::fetch($tagserver)) {
322 $tagserverlist[] = $server['gserver-id'];
324 DBA::close($tagserver);
327 // All addresses with the given id
328 if (!empty($tagserverlist)) {
329 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
330 while ($server = DBA::fetch($servers)) {
331 $serverlist[$server['id']] = $server;
333 DBA::close($servers);
338 // Now we are collecting all relay contacts
339 foreach ($serverlist as $gserver) {
340 // We don't send messages to ourselves
341 if (Strings::compareLink($gserver['url'], DI::baseUrl())) {
344 $contact = self::getContact($gserver);
345 if (empty($contact)) {
354 * Return a list of relay servers
356 * @param array $fields Field list
357 * @return array List of relay servers
360 public static function getList(array $fields = []): array
362 return DBA::selectToArray('apcontact', $fields,
363 ["`type` IN (?, ?) AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 'Service', 0, Contact::FRIEND]);
367 * Return a contact for a given server address or creates a dummy entry
369 * @param array $gserver Global server record
370 * @param array $fields Fieldlist
371 * @return array|bool Array with the contact or false on error
374 private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
376 // Fetch the relay contact
377 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
378 $contact = DBA::selectFirst('contact', $fields, $condition);
379 if (DBA::isResult($contact)) {
380 if ($contact['archive'] || $contact['blocked']) {
385 self::updateContact($gserver);
387 $contact = DBA::selectFirst('contact', $fields, $condition);
388 if (DBA::isResult($contact)) {
393 // It should never happen that we arrive here
398 * Resubscribe to all relay servers
402 public static function reSubscribe()
404 foreach (self::getList() as $server) {
405 $success = ActivityPub\Transmitter::sendRelayFollow($server['url']);
406 Logger::debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]);