3 * Name: Advanced content Filter
4 * Description: Expression-based content filter
6 * Author: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
7 * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
9 * Copyright (c) 2018 Hypolite Petovan
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * * copyright notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the distribution.
19 * * Neither the name of Friendica nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL FRIENDICA BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 use Friendica\BaseModule;
38 use Friendica\Content\Text\Markdown;
39 use Friendica\Core\Hook;
40 use Friendica\Core\Logger;
41 use Friendica\Core\Renderer;
42 use Friendica\Database\DBA;
43 use Friendica\Database\DBStructure;
45 use Friendica\Model\Item;
46 use Friendica\Model\Post;
47 use Friendica\Model\Tag;
48 use Friendica\Model\User;
49 use Friendica\Module\Security\Login;
50 use Friendica\Network\HTTPException;
51 use Friendica\Util\DateTimeFormat;
52 use Psr\Http\Message\ResponseInterface;
53 use Psr\Http\Message\ServerRequestInterface;
54 use Symfony\Component\ExpressionLanguage;
56 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
58 function advancedcontentfilter_install(App $a)
60 Hook::register('dbstructure_definition' , __FILE__, 'advancedcontentfilter_dbstructure_definition');
61 Hook::register('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
62 Hook::register('addon_settings' , __FILE__, 'advancedcontentfilter_addon_settings');
64 Hook::add('dbstructure_definition' , __FILE__, 'advancedcontentfilter_dbstructure_definition');
65 DBStructure::performUpdate();
67 Logger::notice("installed advancedcontentfilter");
74 function advancedcontentfilter_dbstructure_definition(App $a, &$database)
76 $database["advancedcontentfilter_rules"] = [
77 "comment" => "Advancedcontentfilter addon rules",
79 "id" => ["type" => "int unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1", "comment" => "Auto incremented rule id"],
80 "uid" => ["type" => "int unsigned", "not null" => "1", "comment" => "Owner user id"],
81 "name" => ["type" => "varchar(255)", "not null" => "1", "comment" => "Rule name"],
82 "expression" => ["type" => "mediumtext" , "not null" => "1", "comment" => "Expression text"],
83 "serialized" => ["type" => "mediumtext" , "not null" => "1", "comment" => "Serialized parsed expression"],
84 "active" => ["type" => "boolean" , "not null" => "1", "default" => "1", "comment" => "Whether the rule is active or not"],
85 "created" => ["type" => "datetime" , "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => "Creation date"],
89 "uid_active" => ["uid", "active"],
95 * @param array $item Prepared by either Model\Item::prepareBody or advancedcontentfilter_prepare_item_row
98 function advancedcontentfilter_get_filter_fields(array $item)
102 // Convert the language JSON text into a filterable format
103 if (!empty($item['language']) && ($languages = json_decode($item['language'], true))) {
104 foreach ($languages as $key => $value) {
105 $vars['language_' . strtolower($key)] = $value;
109 foreach ($item as $key => $value) {
110 $vars[str_replace('-', '_', $key)] = $value;
118 function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
120 static $expressionLanguage;
122 if (is_null($expressionLanguage)) {
123 $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
130 $vars = advancedcontentfilter_get_filter_fields($hook_data['item']);
132 $rules = DI::cache()->get('rules_' . local_user());
133 if (!isset($rules)) {
134 $rules = DBA::toArray(DBA::select(
135 'advancedcontentfilter_rules',
136 ['name', 'expression', 'serialized'],
137 ['uid' => local_user(), 'active' => true]
140 DI::cache()->set('rules_' . local_user(), $rules);
144 foreach($rules as $rule) {
146 $serializedParsedExpression = new ExpressionLanguage\SerializedParsedExpression(
151 // The error suppression operator is used because of potentially broken user-supplied regular expressions
152 $found = (bool) @$expressionLanguage->evaluate($serializedParsedExpression, $vars);
153 } catch (Exception $e) {
158 $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered by rule: %s', $rule['name']);
166 function advancedcontentfilter_addon_settings(App $a, array &$data)
173 'addon' => 'advancedcontentfilter',
174 'title' => DI::l10n()->t('Advanced Content Filter'),
175 'href' => 'advancedcontentfilter',
183 function advancedcontentfilter_module() {}
185 function advancedcontentfilter_init(App $a)
187 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'api') {
188 $slim = new \Slim\App();
190 require __DIR__ . '/src/middlewares.php';
192 require __DIR__ . '/src/routes.php';
199 function advancedcontentfilter_content(App $a)
202 return Login::form('/' . implode('/', DI::args()->getArgv()));
205 if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'help') {
206 $user = User::getById(local_user());
208 $lang = $user['language'];
210 $default_dir = 'addon/advancedcontentfilter/doc/';
211 $help_file = 'advancedcontentfilter.md';
212 $help_path = $default_dir . $help_file;
213 if (file_exists($default_dir . $lang . '/' . $help_file)) {
214 $help_path = $default_dir . $lang . '/' . $help_file;
217 $content = file_get_contents($help_path);
219 $html = Markdown::convert($content, false);
221 $html = str_replace('code>', 'key>', $html);
225 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/advancedcontentfilter/');
226 return Renderer::replaceMacros($t, [
228 'backtosettings' => DI::l10n()->t('Back to Addon Settings'),
229 'title' => DI::l10n()->t('Advanced Content Filter'),
230 'add_a_rule' => DI::l10n()->t('Add a Rule'),
231 'help' => DI::l10n()->t('Help'),
232 'intro' => DI::l10n()->t('Add and manage your personal content filter rules in this screen. Rules have a name and an arbitrary expression that will be matched against post data. For a complete reference of the available operations and variables, check the help page.'),
233 'your_rules' => DI::l10n()->t('Your rules'),
234 'no_rules' => DI::l10n()->t('You have no rules yet! Start adding one by clicking on the button above next to the title.'),
235 'disabled' => DI::l10n()->t('Disabled'),
236 'enabled' => DI::l10n()->t('Enabled'),
237 'disable_this_rule' => DI::l10n()->t('Disable this rule'),
238 'enable_this_rule' => DI::l10n()->t('Enable this rule'),
239 'edit_this_rule' => DI::l10n()->t('Edit this rule'),
240 'edit_the_rule' => DI::l10n()->t('Edit the rule'),
241 'save_this_rule' => DI::l10n()->t('Save this rule'),
242 'delete_this_rule' => DI::l10n()->t('Delete this rule'),
243 'rule' => DI::l10n()->t('Rule'),
244 'close' => DI::l10n()->t('Close'),
245 'addtitle' => DI::l10n()->t('Add new rule'),
246 'rule_name' => DI::l10n()->t('Rule Name'),
247 'rule_expression' => DI::l10n()->t('Rule Expression'),
248 'cancel' => DI::l10n()->t('Cancel'),
250 '$current_theme' => $a->getCurrentTheme(),
251 '$rules' => advancedcontentfilter_get_rules(),
252 '$form_security_token' => BaseModule::getFormSecurityToken()
260 function advancedcontentfilter_build_fields($data)
264 if (!empty($data['name'])) {
265 $fields['name'] = $data['name'];
268 if (!empty($data['expression'])) {
269 // Using a dummy item to validate the field existence
270 $condition = ["(`uid` = ? OR `uid` = 0)", local_user()];
271 $params = ['order' => ['uid' => true]];
272 $item_row = Post::selectFirstForUser(local_user(), [], $condition, $params);
274 if (!DBA::isResult($item_row)) {
275 throw new HTTPException\NotFoundException(DI::l10n()->t('This addon requires this node having at least one post'));
278 $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
279 $parsedExpression = $expressionLanguage->parse(
281 array_keys(advancedcontentfilter_get_filter_fields(advancedcontentfilter_prepare_item_row($item_row)))
284 $serialized = serialize($parsedExpression->getNodes());
286 $fields['expression'] = $data['expression'];
287 $fields['serialized'] = $serialized;
290 if (isset($data['active'])) {
291 $fields['active'] = intval($data['active']);
293 $fields['active'] = 1;
303 function advancedcontentfilter_get_rules()
306 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
309 $rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => local_user()]));
311 return json_encode($rules);
314 function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
317 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
320 $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => $args['id'], 'uid' => local_user()]);
322 return json_encode($rule);
325 function advancedcontentfilter_post_rules(ServerRequestInterface $request)
328 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
331 if (!BaseModule::checkFormSecurityToken()) {
332 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
335 $data = json_decode($request->getBody(), true);
338 $fields = advancedcontentfilter_build_fields($data);
339 } catch (Exception $e) {
340 throw new HTTPException\BadRequestException($e->getMessage(), $e);
343 if (empty($fields['name']) || empty($fields['expression'])) {
344 throw new HTTPException\BadRequestException(DI::l10n()->t('The rule name and expression are required.'));
347 $fields['uid'] = local_user();
348 $fields['created'] = DateTimeFormat::utcNow();
350 if (!DBA::insert('advancedcontentfilter_rules', $fields)) {
351 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
354 $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => DBA::lastInsertId()]);
356 DI::cache()->delete('rules_' . local_user());
358 return json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]);
361 function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
364 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
367 if (!BaseModule::checkFormSecurityToken()) {
368 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
371 if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
372 throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
375 $data = json_decode($request->getBody(), true);
378 $fields = advancedcontentfilter_build_fields($data);
379 } catch (Exception $e) {
380 throw new HTTPException\BadRequestException($e->getMessage(), $e);
383 if (!DBA::update('advancedcontentfilter_rules', $fields, ['id' => $args['id']])) {
384 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
387 DI::cache()->delete('rules_' . local_user());
389 return json_encode(['message' => DI::l10n()->t('Rule successfully updated')]);
392 function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
395 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
398 if (!BaseModule::checkFormSecurityToken()) {
399 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
402 if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
403 throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
406 if (!DBA::delete('advancedcontentfilter_rules', ['id' => $args['id']])) {
407 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
410 DI::cache()->delete('rules_' . local_user());
412 return json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]);
415 function advancedcontentfilter_get_variables_guid(ServerRequestInterface $request, ResponseInterface $response, $args)
418 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
421 if (!isset($args['guid'])) {
422 throw new HTTPException\BadRequestException(DI::l10n()->t('Missing argument: guid.'));
425 $condition = ["`guid` = ? AND (`uid` = ? OR `uid` = 0)", $args['guid'], local_user()];
426 $params = ['order' => ['uid' => true]];
427 $item_row = Post::selectFirstForUser(local_user(), [], $condition, $params);
429 if (!DBA::isResult($item_row)) {
430 throw new HTTPException\NotFoundException(DI::l10n()->t('Unknown post with guid: %s', $args['guid']));
433 $return = advancedcontentfilter_get_filter_fields(advancedcontentfilter_prepare_item_row($item_row));
435 return json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]);
439 * This mimimcs the processing performed in Model\Item::prepareBody
441 * @param array $item_row
443 * @throws HTTPException\InternalServerErrorException
444 * @throws ImagickException
446 function advancedcontentfilter_prepare_item_row(array $item_row): array
448 $tags = Tag::populateFromItem($item_row);
450 $item_row['tags'] = $tags['tags'];
451 $item_row['hashtags'] = $tags['hashtags'];
452 $item_row['mentions'] = $tags['mentions'];
453 $item_row['attachments'] = Post\Media::splitAttachments($item_row['uri-id'], $item_row['guid'] ?? '');