]> git.mxchange.org Git - friendica-addons.git/blobdiff - advancedcontentfilter/advancedcontentfilter.php
Adjust php-cs
[friendica-addons.git] / advancedcontentfilter / advancedcontentfilter.php
index 47ace1c2bd98c9b56f73439676b27941b34e3a78..57c87ffd96c9e9fa8804075b84a5d04c41524e24 100644 (file)
  */
 
 use Friendica\App;
-use Friendica\Core\Addon;
-use Friendica\Core\L10n;
-use Friendica\Core\System;
+use Friendica\BaseModule;
+use Friendica\Content\Text\Markdown;
+use Friendica\Core\Hook;
+use Friendica\Core\Logger;
+use Friendica\Core\Renderer;
+use Friendica\Database\DBA;
 use Friendica\Database\DBStructure;
+use Friendica\DI;
+use Friendica\Model\Item;
+use Friendica\Model\Post;
+use Friendica\Model\Tag;
+use Friendica\Model\User;
+use Friendica\Module\Security\Login;
 use Friendica\Network\HTTPException;
+use Friendica\Util\DateTimeFormat;
 use Psr\Http\Message\ResponseInterface;
 use Psr\Http\Message\ServerRequestInterface;
 use Symfony\Component\ExpressionLanguage;
 
-require_once 'boot.php';
-require_once 'include/conversation.php';
-require_once 'include/dba.php';
-require_once 'include/security.php';
-
 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
 
-function advancedcontentfilter_install()
+function advancedcontentfilter_install(App $a)
 {
-       Addon::registerHook('dbstructure_definition'     , __FILE__, 'advancedcontentfilter_dbstructure_definition');
-       Addon::registerHook('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
-       Addon::registerHook('addon_settings'             , __FILE__, 'advancedcontentfilter_addon_settings');
-
-       DBStructure::update(false, true);
+       Hook::register('dbstructure_definition'     , __FILE__, 'advancedcontentfilter_dbstructure_definition');
+       Hook::register('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
+       Hook::register('addon_settings'             , __FILE__, 'advancedcontentfilter_addon_settings');
 
-       logger("installed advancedcontentfilter");
-}
+       Hook::add('dbstructure_definition'          , __FILE__, 'advancedcontentfilter_dbstructure_definition');
+       DBStructure::performUpdate();
 
-function advancedcontentfilter_uninstall()
-{
-       Addon::unregisterHook('dbstructure_definition'     , __FILE__, 'advancedcontentfilter_dbstructure_definition');
-       Addon::unregisterHook('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
-       Addon::unregisterHook('addon_settings'             , __FILE__, 'advancedcontentfilter_addon_settings');
+       Logger::log("installed advancedcontentfilter");
 }
 
 /*
@@ -83,7 +82,7 @@ function advancedcontentfilter_dbstructure_definition(App $a, &$database)
                        "expression" => ["type" => "mediumtext"  , "not null" => "1", "comment" => "Expression text"],
                        "serialized" => ["type" => "mediumtext"  , "not null" => "1", "comment" => "Serialized parsed expression"],
                        "active"     => ["type" => "boolean"     , "not null" => "1", "default" => "1", "comment" => "Whether the rule is active or not"],
-                       "created"    => ["type" => "datetime"    , "not null" => "1", "default" => NULL_DATE, "comment" => "Creation date"],
+                       "created"    => ["type" => "datetime"    , "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => "Creation date"],
                ],
                "indexes" => [
                        "PRIMARY" => ["id"],
@@ -92,6 +91,26 @@ function advancedcontentfilter_dbstructure_definition(App $a, &$database)
        ];
 }
 
+function advancedcontentfilter_get_filter_fields(array $item)
+{
+       $vars = [];
+
+       // Convert the language JSON text into a filterable format
+       if (!empty($item['language']) && ($languages = json_decode($item['language'], true))) {
+               foreach ($languages as $key => $value) {
+                       $vars['language_' . strtolower($key)] = $value;
+               }
+       }
+
+       foreach ($item as $key => $value) {
+               $vars[str_replace('-', '_', $key)] = $value;
+       }
+
+       ksort($vars);
+
+       return $vars;
+}
+
 function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
 {
        static $expressionLanguage;
@@ -104,18 +123,17 @@ function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
                return;
        }
 
-       $vars = [];
-       foreach ($hook_data['item'] as $key => $value) {
-               $vars[str_replace('-', '_', $key)] = $value;
-       }
+       $vars = advancedcontentfilter_get_filter_fields($hook_data['item']);
 
-       $rules = Friendica\Core\Cache::get('rules_' . local_user());
+       $rules = DI::cache()->get('rules_' . local_user());
        if (!isset($rules)) {
-               $rules = dba::inArray(dba::select(
+               $rules = DBA::toArray(DBA::select(
                        'advancedcontentfilter_rules',
                        ['name', 'expression', 'serialized'],
                        ['uid' => local_user(), 'active' => true]
                ));
+
+               DI::cache()->set('rules_' . local_user(), $rules);
        }
 
        if ($rules) {
@@ -126,13 +144,14 @@ function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
                                        $rule['serialized']
                                );
 
-                               $found = (bool) $expressionLanguage->evaluate($serializedParsedExpression, $vars);
+                               // The error suppression operator is used because of potentially broken user-supplied regular expressions
+                               $found = (bool) @$expressionLanguage->evaluate($serializedParsedExpression, $vars);
                        } catch (Exception $e) {
                                $found = false;
                        }
 
                        if ($found) {
-                               $hook_data['filter_reasons'][] = L10n::t('Filtered by rule: %s', $rule['name']);
+                               $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered by rule: %s', $rule['name']);
                                break;
                        }
                }
@@ -146,7 +165,7 @@ function advancedcontentfilter_addon_settings(App $a, &$s)
                return;
        }
 
-       $advancedcontentfilter = L10n::t('Advanced Content Filter');
+       $advancedcontentfilter = DI::l10n()->t('Advanced Content Filter');
 
        $s .= <<<HTML
                <span class="settings-block fakelink" style="display: block;"><h3><a href="advancedcontentfilter">$advancedcontentfilter <i class="glyphicon glyphicon-share"></i></a></h3></span>
@@ -163,7 +182,7 @@ function advancedcontentfilter_module() {}
 
 function advancedcontentfilter_init(App $a)
 {
-       if ($a->argv[1] == 'api') {
+       if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'api') {
                $slim = new \Slim\App();
 
                require __DIR__ . '/src/middlewares.php';
@@ -178,11 +197,13 @@ function advancedcontentfilter_init(App $a)
 function advancedcontentfilter_content(App $a)
 {
        if (!local_user()) {
-               return \Friendica\Module\Login::form('/' . implode('/', $a->argv));
+               return Login::form('/' . implode('/', DI::args()->getArgv()));
        }
 
-       if ($a->argc > 0 && $a->argv[1] == 'help') {
-               $lang = $a->user['language'];
+       if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'help') {
+               $user = User::getById(local_user());
+
+               $lang = $user['language'];
 
                $default_dir = 'addon/advancedcontentfilter/doc/';
                $help_file = 'advancedcontentfilter.md';
@@ -193,40 +214,40 @@ function advancedcontentfilter_content(App $a)
 
                $content = file_get_contents($help_path);
 
-               $html = \Friendica\Content\Text\Markdown::convert($content, false);
+               $html = Markdown::convert($content, false);
 
                $html = str_replace('code>', 'key>', $html);
 
                return $html;
        } else {
-               $t = get_markup_template('settings.tpl', 'addon/advancedcontentfilter/');
-               return replace_macros($t, [
+               $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/advancedcontentfilter/');
+               return Renderer::replaceMacros($t, [
+                       '$messages' => [
+                               'backtosettings'    => DI::l10n()->t('Back to Addon Settings'),
+                               'title'             => DI::l10n()->t('Advanced Content Filter'),
+                               'add_a_rule'        => DI::l10n()->t('Add a Rule'),
+                               'help'              => DI::l10n()->t('Help'),
+                               '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.'),
+                               'your_rules'        => DI::l10n()->t('Your rules'),
+                               'no_rules'          => DI::l10n()->t('You have no rules yet! Start adding one by clicking on the button above next to the title.'),
+                               'disabled'          => DI::l10n()->t('Disabled'),
+                               'enabled'           => DI::l10n()->t('Enabled'),
+                               'disable_this_rule' => DI::l10n()->t('Disable this rule'),
+                               'enable_this_rule'  => DI::l10n()->t('Enable this rule'),
+                               'edit_this_rule'    => DI::l10n()->t('Edit this rule'),
+                               'edit_the_rule'     => DI::l10n()->t('Edit the rule'),
+                               'save_this_rule'    => DI::l10n()->t('Save this rule'),
+                               'delete_this_rule'  => DI::l10n()->t('Delete this rule'),
+                               'rule'              => DI::l10n()->t('Rule'),
+                               'close'             => DI::l10n()->t('Close'),
+                               'addtitle'          => DI::l10n()->t('Add new rule'),
+                               'rule_name'         => DI::l10n()->t('Rule Name'),
+                               'rule_expression'   => DI::l10n()->t('Rule Expression'),
+                               'cancel'            => DI::l10n()->t('Cancel'),
+                       ],
                        '$current_theme' => $a->getCurrentTheme(),
-                       '$backtosettings' => L10n::t('Back to Addon Settings'),
-                       '$title' => L10n::t('Advanced Content Filter'),
-                       '$add_a_rule' => L10n::t('Add a Rule'),
-                       '$help' => L10n::t('Help'),
-                       '$advanced_content_filter_intro' => 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 <a href="advancedcontentfilter/help">help page</a>.'),
-                       '$your_rules' => L10n::t('Your rules'),
-                       '$no_rules' => L10n::t('You have no rules yet! Start adding one by clicking on the button above next to the title.'),
-                       '$disabled' => L10n::t('Disabled'),
-                       '$enabled' => L10n::t('Enabled'),
-                       '$disable_this_rule' => L10n::t('Disable this rule'),
-                       '$enable_this_rule' => L10n::t('Enable this rule'),
-                       '$edit_this_rule' => L10n::t('Edit this rule'),
-                       '$edit_the_rule' => L10n::t('Edit the rule'),
-                       '$save_this_rule' => L10n::t('Save this rule'),
-                       '$delete_this_rule' => L10n::t('Delete this rule'),
-                       '$rule' => L10n::t('Rule'),
-                       '$close' => L10n::t('Close'),
-                       '$addtitle' => L10n::t('Add new rule'),
-                       '$rule_name' => L10n::t('Rule Name'),
-                       '$rule_expression' => L10n::t('Rule Expression'),
-                       '$examples' => L10n::t('<p>Examples:</p><ul><li><pre>author_link == \'https://friendica.mrpetovan.com/profile/hypolite\'</pre></li><li>tags</li></ul>'),
-                       '$cancel' => L10n::t('Cancel'),
                        '$rules' => advancedcontentfilter_get_rules(),
-                       '$baseurl' => System::baseUrl(true),
-                       '$form_security_token' => get_form_security_token()
+                       '$form_security_token' => BaseModule::getFormSecurityToken()
                ]);
        }
 }
@@ -261,6 +282,7 @@ function advancedcontentfilter_build_fields($data)
                        'event_created', 'event_edited', 'event_start', 'event_finish', 'event_summary',
                        'event_desc', 'event_location', 'event_type', 'event_nofinish', 'event_adjust', 'event_ignore',
                        'children', 'pagedrop', 'tags', 'hashtags', 'mentions',
+                       'attachments',
                ];
 
                $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
@@ -289,10 +311,10 @@ function advancedcontentfilter_build_fields($data)
 function advancedcontentfilter_get_rules()
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       $rules = dba::inArray(dba::select('advancedcontentfilter_rules', [], ['uid' => local_user()]));
+       $rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => local_user()]));
 
        return json_encode($rules);
 }
@@ -300,10 +322,10 @@ function advancedcontentfilter_get_rules()
 function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       $rule = dba::selectFirst('advancedcontentfilter_rules', [], ['id' => $args['id'], 'uid' => local_user()]);
+       $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => $args['id'], 'uid' => local_user()]);
 
        return json_encode($rule);
 }
@@ -311,11 +333,11 @@ function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, Res
 function advancedcontentfilter_post_rules(ServerRequestInterface $request)
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       if (!check_form_security_token()) {
-               throw new HTTPException\BadRequestException(L10n::t('Invalid form security token, please refresh the page.'));
+       if (!BaseModule::checkFormSecurityToken()) {
+               throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
        }
 
        $data = json_decode($request->getBody(), true);
@@ -323,37 +345,39 @@ function advancedcontentfilter_post_rules(ServerRequestInterface $request)
        try {
                $fields = advancedcontentfilter_build_fields($data);
        } catch (Exception $e) {
-               throw new HTTPException\BadRequestException($e->getMessage(), 0, $e);
+               throw new HTTPException\BadRequestException($e->getMessage(), $e);
        }
 
        if (empty($fields['name']) || empty($fields['expression'])) {
-               throw new HTTPException\BadRequestException(L10n::t('The rule name and expression are required.'));
+               throw new HTTPException\BadRequestException(DI::l10n()->t('The rule name and expression are required.'));
        }
 
        $fields['uid'] = local_user();
-       $fields['created'] = \Friendica\Util\DateTimeFormat::utcNow();
+       $fields['created'] = DateTimeFormat::utcNow();
 
-       if (!dba::insert('advancedcontentfilter_rules', $fields)) {
-               throw new HTTPException\ServiceUnavaiableException(dba::errorMessage());
+       if (!DBA::insert('advancedcontentfilter_rules', $fields)) {
+               throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
        }
 
-       $rule = dba::selectFirst('advancedcontentfilter_rules', [], ['id' => dba::lastInsertId()]);
+       $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => DBA::lastInsertId()]);
+
+       DI::cache()->delete('rules_' . local_user());
 
-       return json_encode(['message' => L10n::t('Rule successfully added'), 'rule' => $rule]);
+       return json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]);
 }
 
 function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       if (!check_form_security_token()) {
-               throw new HTTPException\BadRequestException(L10n::t('Invalid form security token, please refresh the page.'));
+       if (!BaseModule::checkFormSecurityToken()) {
+               throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
        }
 
-       if (!dba::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
-               throw new HTTPException\NotFoundException(L10n::t('Rule doesn\'t exist or doesn\'t belong to you.'));
+       if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
+               throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
        }
 
        $data = json_decode($request->getBody(), true);
@@ -361,63 +385,70 @@ function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, Res
        try {
                $fields = advancedcontentfilter_build_fields($data);
        } catch (Exception $e) {
-               throw new HTTPException\BadRequestException($e->getMessage(), 0, $e);
+               throw new HTTPException\BadRequestException($e->getMessage(), $e);
        }
 
-       if (!dba::update('advancedcontentfilter_rules', $fields, ['id' => $args['id']])) {
-               throw new HTTPException\ServiceUnavaiableException(dba::errorMessage());
+       if (!DBA::update('advancedcontentfilter_rules', $fields, ['id' => $args['id']])) {
+               throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
        }
 
-       return json_encode(['message' => L10n::t('Rule successfully updated')]);
+       DI::cache()->delete('rules_' . local_user());
+
+       return json_encode(['message' => DI::l10n()->t('Rule successfully updated')]);
 }
 
 function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       if (!check_form_security_token()) {
-               throw new HTTPException\BadRequestException(L10n::t('Invalid form security token, please refresh the page.'));
+       if (!BaseModule::checkFormSecurityToken()) {
+               throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
        }
 
-       if (!dba::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
-               throw new HTTPException\NotFoundException(L10n::t('Rule doesn\'t exist or doesn\'t belong to you.'));
+       if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
+               throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
        }
 
-       if (!dba::delete('advancedcontentfilter_rules', ['id' => $args['id']])) {
-               throw new HTTPException\ServiceUnavaiableException(dba::errorMessage());
+       if (!DBA::delete('advancedcontentfilter_rules', ['id' => $args['id']])) {
+               throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
        }
 
-       return json_encode(['message' => L10n::t('Rule successfully deleted')]);
+       DI::cache()->delete('rules_' . local_user());
+
+       return json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]);
 }
 
 function advancedcontentfilter_get_variables_guid(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
        if (!local_user()) {
-               throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this method'));
+               throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
        if (!isset($args['guid'])) {
-               throw new HTTPException\BadRequestException(L10n::t('Missing argument: guid.'));
+               throw new HTTPException\BadRequestException(DI::l10n()->t('Missing argument: guid.'));
        }
 
-       $item = dba::fetch_first(item_query() . " AND `item`.`guid` = ? AND (`item`.`uid` = ? OR `item`.`uid` = 0) ORDER BY `item`.`uid` DESC", $args['guid'], local_user());
+       $condition = ["`guid` = ? AND (`uid` = ? OR `uid` = 0)", $args['guid'], local_user()];
+       $params = ['order' => ['uid' => true]];
+       $item = Post::selectFirstForUser(local_user(), [], $condition, $params);
 
-       if (!\Friendica\Database\DBM::is_result($item)) {
-               throw new HTTPException\NotFoundException(L10n::t('Unknown post with guid: %s', $args['guid']));
+       if (!DBA::isResult($item)) {
+               throw new HTTPException\NotFoundException(DI::l10n()->t('Unknown post with guid: %s', $args['guid']));
        }
 
-       $tags = \Friendica\Model\Term::populateTagsFromItem($item);
+       $tags = Tag::populateFromItem($item);
 
        $item['tags'] = $tags['tags'];
        $item['hashtags'] = $tags['hashtags'];
        $item['mentions'] = $tags['mentions'];
 
-       $return = [];
-       foreach ($item as $key => $value) {
-               $return[str_replace('-', '_', $key)] = $value;
-       }
+       $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '');
+
+       $item['attachments'] = $attachments;
+
+       $return = advancedcontentfilter_get_filter_fields($item);
 
        return json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]);
-}
\ No newline at end of file
+}