3 * @copyright Copyright (C) 2020, Friendica
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\Text\BBCode;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Database\DBA;
29 use Friendica\Model\APContact;
30 use Friendica\Model\Contact;
31 use Friendica\Model\GServer;
32 use Friendica\Model\Item;
33 use Friendica\Model\Search;
34 use Friendica\Model\Tag;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Strings;
39 * Base class for relay handling
44 * Check if a post is wanted
48 * @param int $authorid
50 * @return boolean "true" is the post is wanted by the system
52 public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = '')
54 $config = DI::config();
56 $subscribe = $config->get('system', 'relay_subscribe', false);
58 $scope = $config->get('system', 'relay_scope', SR_SCOPE_ALL);
60 $scope = SR_SCOPE_NONE;
63 if ($scope == SR_SCOPE_NONE) {
64 Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]);
68 if (Contact::isBlocked($authorid)) {
69 Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
73 if (Contact::isHidden($authorid)) {
74 Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]);
82 if ($scope == SR_SCOPE_TAGS) {
83 $server_tags = $config->get('system', 'relay_server_tags');
84 $tagitems = explode(',', mb_strtolower($server_tags));
85 foreach ($tagitems AS $tag) {
86 $systemTags[] = trim($tag, '# ');
89 if ($config->get('system', 'relay_user_tags')) {
90 $userTags = Search::getUserTags();
94 $tagList = array_unique(array_merge($systemTags, $userTags));
96 $deny_tags = $config->get('system', 'relay_deny_tags');
97 $tagitems = explode(',', mb_strtolower($deny_tags));
98 foreach ($tagitems AS $tag) {
99 $tag = trim($tag, '# ');
103 if (!empty($tagList) || !empty($denyTags)) {
104 $content = mb_strtolower(BBCode::toPlaintext($body, false));
106 foreach ($tags as $tag) {
107 $tag = mb_strtolower($tag);
108 if (in_array($tag, $denyTags)) {
109 Logger::info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
113 if (in_array($tag, $tagList)) {
114 Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
118 // We check with "strpos" for performance issues. Only when this is true, the regular expression check is used
119 // RegExp is taken from here: https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
120 if ((strpos($content, $tag) !== false) && preg_match('/(?<=[\s,.:;"\']|^)' . preg_quote($tag, '/') . '(?=[\s,.:;"\']|$)/', $content)) {
121 Logger::info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url]);
127 if ($scope == SR_SCOPE_ALL) {
128 Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url]);
132 Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url]);
137 * Update or insert a relay contact
139 * @param array $gserver Global server record
140 * @param array $fields Optional network specific fields
143 public static function updateContact(array $gserver, array $fields = [])
145 if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
146 $system = APContact::getByURL($gserver['url'] . '/friendica');
147 if (!empty($system['sharedinbox'])) {
148 Logger::info('Sucessfully probed for relay contact', ['server' => $gserver['url']]);
149 $id = Contact::updateFromProbeByURL($system['url']);
150 Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]);
155 $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY];
156 $old = DBA::selectFirst('contact', [], $condition);
157 if (!DBA::isResult($old)) {
158 $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])];
159 $old = DBA::selectFirst('contact', [], $condition);
160 if (DBA::isResult($old)) {
161 $fields['gsid'] = $gserver['id'];
162 $fields['contact-type'] = Contact::TYPE_RELAY;
163 Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]);
165 } elseif (empty($fields)) {
166 Logger::info('No content to update, quitting', ['server' => $gserver['url']]);
170 if (DBA::isResult($old)) {
171 $fields['updated'] = DateTimeFormat::utcNow();
173 Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]);
174 DBA::update('contact', $fields, ['id' => $old['id']], $old);
176 $default = ['created' => DateTimeFormat::utcNow(),
177 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'],
178 'nurl' => Strings::normaliseLink($gserver['url']),
179 'network' => Protocol::DIASPORA, 'uid' => 0,
180 'batch' => $gserver['url'] . '/receive/public',
181 'rel' => Contact::FOLLOWER, 'blocked' => false,
182 'pending' => false, 'writable' => true,
183 'gsid' => $gserver['id'],
184 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY];
186 $fields = array_merge($default, $fields);
188 Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]);
189 Contact::insert($fields);
194 * Mark the relay contact of the given contact for archival
195 * This is called whenever there is a communication issue with the server.
196 * It avoids sending stuff to servers who don't exist anymore.
197 * The relay contact is a technical contact entry that exists once per server.
199 * @param array $contact of the relay contact
201 public static function markForArchival(array $contact)
203 if (!empty($contact['contact-type']) && ($contact['contact-type'] == Contact::TYPE_RELAY)) {
204 // This is already the relay contact, we don't need to fetch it
205 $relay_contact = $contact;
206 } elseif (empty($contact['baseurl'])) {
207 if (!empty($contact['batch'])) {
208 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY];
209 $relay_contact = DBA::selectFirst('contact', [], $condition);
214 $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true),
215 'url' => $contact['baseurl'], 'network' => $contact['network']];
216 $relay_contact = self::getContact($gserver, []);
219 if (!empty($relay_contact)) {
220 Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]);
221 Contact::markForArchival($relay_contact);
226 * Return a list of relay servers
228 * The list contains not only the official relays but also servers that we serve directly
230 * @param integer $item_id id of the item that is sent
231 * @param array $contacts Previously fetched contacts
232 * @param array $networks Networks of the relay servers
234 * @return array of relay servers
235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237 public static function getList(int $item_id, array $contacts, array $networks)
241 // Fetching relay servers
242 $serverdata = DI::config()->get("system", "relay_server");
244 if (!empty($serverdata)) {
245 $servers = explode(",", $serverdata);
246 foreach ($servers as $server) {
247 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network'], ['nurl' => Strings::normaliseLink($server)]);
248 if (DBA::isResult($gserver)) {
249 $serverlist[$gserver['id']] = $gserver;
254 if (DI::config()->get("system", "relay_directly", false)) {
255 // We distribute our stuff based on the parent to ensure that the thread will be complete
256 $parent = Item::selectFirst(['uri-id'], ['id' => $item_id]);
257 if (!DBA::isResult($parent)) {
261 // Servers that want to get all content
262 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
263 while ($server = DBA::fetch($servers)) {
264 $serverlist[$server['id']] = $server;
266 DBA::close($servers);
268 // All tags of the current post
269 $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]);
271 while ($tag = DBA::fetch($tags)) {
272 $taglist[] = $tag['name'];
276 // All servers who wants content with this tag
278 if (!empty($taglist)) {
279 $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
280 while ($server = DBA::fetch($tagserver)) {
281 $tagserverlist[] = $server['gserver-id'];
283 DBA::close($tagserver);
286 // All adresses with the given id
287 if (!empty($tagserverlist)) {
288 $servers = DBA::select('gserver', ['id', 'url', 'network'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
289 while ($server = DBA::fetch($servers)) {
290 $serverlist[$server['id']] = $server;
292 DBA::close($servers);
296 // Now we are collecting all relay contacts
297 foreach ($serverlist as $gserver) {
298 // We don't send messages to ourselves
299 if (Strings::compareLink($gserver['url'], DI::baseUrl())) {
302 $contact = self::getContact($gserver);
303 if (empty($contact)) {
307 if (in_array($contact['network'], $networks) && !in_array($contact['batch'], array_column($contacts, 'batch'))) {
308 $contacts[] = $contact;
316 * Return a contact for a given server address or creates a dummy entry
318 * @param array $gserver Global server record
319 * @param array $fields Fieldlist
320 * @return array with the contact
323 private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
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']) {
334 self::updateContact($gserver);
336 $contact = DBA::selectFirst('contact', $fields, $condition);
337 if (DBA::isResult($contact)) {
342 // It should never happen that we arrive here