[advancedcontentfilter] Stop using advancedcontentfilter_get_rules() outside of route...
[friendica-addons.git/.git] / advancedcontentfilter / advancedcontentfilter.php
index 99c8683..418b253 100644 (file)
@@ -55,7 +55,7 @@ use Symfony\Component\ExpressionLanguage;
 
 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
 
-function advancedcontentfilter_install(App $a)
+function advancedcontentfilter_install()
 {
        Hook::register('dbstructure_definition'     , __FILE__, 'advancedcontentfilter_dbstructure_definition');
        Hook::register('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
@@ -64,33 +64,37 @@ function advancedcontentfilter_install(App $a)
        Hook::add('dbstructure_definition'          , __FILE__, 'advancedcontentfilter_dbstructure_definition');
        DBStructure::performUpdate();
 
-       Logger::log("installed advancedcontentfilter");
+       Logger::notice('installed advancedcontentfilter');
 }
 
 /*
  * Hooks
  */
 
-function advancedcontentfilter_dbstructure_definition(App $a, &$database)
+function advancedcontentfilter_dbstructure_definition(&$database)
 {
-       $database["advancedcontentfilter_rules"] = [
-               "comment" => "Advancedcontentfilter addon rules",
-               "fields" => [
-                       "id"         => ["type" => "int unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1", "comment" => "Auto incremented rule id"],
-                       "uid"        => ["type" => "int unsigned", "not null" => "1", "comment" => "Owner user id"],
-                       "name"       => ["type" => "varchar(255)", "not null" => "1", "comment" => "Rule name"],
-                       "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" => DBA::NULL_DATETIME, "comment" => "Creation date"],
+       $database['advancedcontentfilter_rules'] = [
+               'comment' => 'Advancedcontentfilter addon rules',
+               'fields' => [
+                       'id'         => ['type' => 'int unsigned', 'not null' => '1', 'extra' => 'auto_increment', 'primary' => '1', 'comment' => 'Auto incremented rule id'],
+                       'uid'        => ['type' => 'int unsigned', 'not null' => '1', 'comment' => 'Owner user id'],
+                       'name'       => ['type' => 'varchar(255)', 'not null' => '1', 'comment' => 'Rule name'],
+                       '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' => DBA::NULL_DATETIME, 'comment' => 'Creation date'],
                ],
-               "indexes" => [
-                       "PRIMARY" => ["id"],
-                       "uid_active" => ["uid", "active"],
+               'indexes' => [
+                       'PRIMARY' => ['id'],
+                       'uid_active' => ['uid', 'active'],
                ]
        ];
 }
 
+/**
+ * @param array $item Prepared by either Model\Item::prepareBody or advancedcontentfilter_prepare_item_row
+ * @return array
+ */
 function advancedcontentfilter_get_filter_fields(array $item)
 {
        $vars = [];
@@ -111,7 +115,7 @@ function advancedcontentfilter_get_filter_fields(array $item)
        return $vars;
 }
 
-function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
+function advancedcontentfilter_prepare_body_content_filter(&$hook_data)
 {
        static $expressionLanguage;
 
@@ -119,21 +123,21 @@ function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
                $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
        }
 
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                return;
        }
 
        $vars = advancedcontentfilter_get_filter_fields($hook_data['item']);
 
-       $rules = DI::cache()->get('rules_' . local_user());
+       $rules = DI::cache()->get('rules_' . DI::userSession()->getLocalUserId());
        if (!isset($rules)) {
                $rules = DBA::toArray(DBA::select(
                        'advancedcontentfilter_rules',
                        ['name', 'expression', 'serialized'],
-                       ['uid' => local_user(), 'active' => true]
+                       ['uid' => DI::userSession()->getLocalUserId(), 'active' => true]
                ));
 
-               DI::cache()->set('rules_' . local_user(), $rules);
+               DI::cache()->set('rules_' . DI::userSession()->getLocalUserId(), $rules);
        }
 
        if ($rules) {
@@ -159,31 +163,34 @@ function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
 }
 
 
-function advancedcontentfilter_addon_settings(App $a, &$s)
+function advancedcontentfilter_addon_settings(array &$data)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                return;
        }
 
-       $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>
-HTML;
-
-       return;
+       $data = [
+               'addon' => 'advancedcontentfilter',
+               'title' => DI::l10n()->t('Advanced Content Filter'),
+               'href'  => 'advancedcontentfilter',
+       ];
 }
 
 /*
  * Module
  */
 
+/**
+ * This is a statement rather than an actual function definition. The simple
+ * existence of this method is checked to figure out if the addon offers a
+ * module.
+ */
 function advancedcontentfilter_module() {}
 
-function advancedcontentfilter_init(App $a)
+function advancedcontentfilter_init()
 {
        if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'api') {
-               $slim = new \Slim\App();
+               $slim = \Slim\Factory\AppFactory::create();
 
                require __DIR__ . '/src/middlewares.php';
 
@@ -194,14 +201,14 @@ function advancedcontentfilter_init(App $a)
        }
 }
 
-function advancedcontentfilter_content(App $a)
+function advancedcontentfilter_content()
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                return Login::form('/' . implode('/', DI::args()->getArgv()));
        }
 
        if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'help') {
-               $user = User::getById(local_user());
+               $user = User::getById(DI::userSession()->getLocalUserId());
 
                $lang = $user['language'];
 
@@ -245,8 +252,8 @@ function advancedcontentfilter_content(App $a)
                                'rule_expression'   => DI::l10n()->t('Rule Expression'),
                                'cancel'            => DI::l10n()->t('Cancel'),
                        ],
-                       '$current_theme' => $a->getCurrentTheme(),
-                       '$rules' => advancedcontentfilter_get_rules(),
+                       '$current_theme' => DI::app()->getCurrentTheme(),
+                       '$rules' => DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => DI::userSession()->getLocalUserId()])),
                        '$form_security_token' => BaseModule::getFormSecurityToken()
                ]);
        }
@@ -264,30 +271,20 @@ function advancedcontentfilter_build_fields($data)
        }
 
        if (!empty($data['expression'])) {
-               $allowed_keys = [
-                       'author_id', 'author_link', 'author_name', 'author_avatar',
-                       'owner_id', 'owner_link', 'owner_name', 'owner_avatar',
-                       'contact_id', 'uid', 'id', 'parent', 'uri',
-                       'thr_parent', 'parent_uri',
-                       'content_warning',
-                       'commented', 'created', 'edited', 'received',
-                       'verb', 'object_type', 'postopts', 'plink', 'guid', 'wall', 'private', 'starred',
-                       'title', 'body',
-                       'file', 'event_id', 'location', 'coord', 'app', 'attach',
-                       'rendered_hash', 'rendered_html', 'object',
-                       'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
-                       'item_id', 'item_network', 'author_thumb', 'owner_thumb',
-                       'network', 'url', 'name', 'writable', 'self',
-                       'cid', 'alias',
-                       'event_created', 'event_edited', 'event_start', 'event_finish', 'event_summary',
-                       'event_desc', 'event_location', 'event_type', 'event_nofinish', 'event_ignore',
-                       'children', 'pagedrop', 'tags', 'hashtags', 'mentions',
-                       'attachments',
-               ];
+               // Using a dummy item to validate the field existence
+               $condition = ["(`uid` = ? OR `uid` = 0)", DI::userSession()->getLocalUserId()];
+               $params = ['order' => ['uid' => true]];
+               $item_row = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), [], $condition, $params);
 
-               $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
+               if (!DBA::isResult($item_row)) {
+                       throw new HTTPException\NotFoundException(DI::l10n()->t('This addon requires this node having at least one post'));
+               }
 
-               $parsedExpression = $expressionLanguage->parse($data['expression'], $allowed_keys);
+               $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
+               $parsedExpression = $expressionLanguage->parse(
+                       $data['expression'],
+                       array_keys(advancedcontentfilter_get_filter_fields(advancedcontentfilter_prepare_item_row($item_row)))
+               );
 
                $serialized = serialize($parsedExpression->getNodes());
 
@@ -308,31 +305,33 @@ function advancedcontentfilter_build_fields($data)
  * API
  */
 
-function advancedcontentfilter_get_rules()
+function advancedcontentfilter_get_rules(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
-       $rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => local_user()]));
+       $rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => DI::userSession()->getLocalUserId()]));
 
-       return json_encode($rules);
+       $response->getBody()->write(json_encode($rules));
+       return $response->withHeader('Content-Type', 'application/json');
 }
 
 function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                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' => DI::userSession()->getLocalUserId()]);
 
-       return json_encode($rule);
+       $response->getBody()->write(json_encode($rule));
+       return $response->withHeader('Content-Type', 'application/json');
 }
 
-function advancedcontentfilter_post_rules(ServerRequestInterface $request)
+function advancedcontentfilter_post_rules(ServerRequestInterface $request, ResponseInterface $response)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
@@ -352,7 +351,7 @@ function advancedcontentfilter_post_rules(ServerRequestInterface $request)
                throw new HTTPException\BadRequestException(DI::l10n()->t('The rule name and expression are required.'));
        }
 
-       $fields['uid'] = local_user();
+       $fields['uid'] = DI::userSession()->getLocalUserId();
        $fields['created'] = DateTimeFormat::utcNow();
 
        if (!DBA::insert('advancedcontentfilter_rules', $fields)) {
@@ -361,14 +360,15 @@ function advancedcontentfilter_post_rules(ServerRequestInterface $request)
 
        $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => DBA::lastInsertId()]);
 
-       DI::cache()->delete('rules_' . local_user());
+       DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
 
-       return json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]);
+       $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]));
+       return $response->withHeader('Content-Type', 'application/json');
 }
 
 function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
@@ -376,7 +376,7 @@ function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, Res
                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()])) {
+       if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => DI::userSession()->getLocalUserId()])) {
                throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
        }
 
@@ -392,14 +392,15 @@ function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, Res
                throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
        }
 
-       DI::cache()->delete('rules_' . local_user());
+       DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
 
-       return json_encode(['message' => DI::l10n()->t('Rule successfully updated')]);
+       $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully updated')]));
+       return $response->withHeader('Content-Type', 'application/json');
 }
 
 function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
@@ -407,7 +408,7 @@ function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request,
                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()])) {
+       if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => DI::userSession()->getLocalUserId()])) {
                throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
        }
 
@@ -415,14 +416,15 @@ function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request,
                throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
        }
 
-       DI::cache()->delete('rules_' . local_user());
+       DI::cache()->delete('rules_' . DI::userSession()->getLocalUserId());
 
-       return json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]);
+       $response->getBody()->write(json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]));
+       return $response->withHeader('Content-Type', 'application/json');
 }
 
 function advancedcontentfilter_get_variables_guid(ServerRequestInterface $request, ResponseInterface $response, $args)
 {
-       if (!local_user()) {
+       if (!DI::userSession()->getLocalUserId()) {
                throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
        }
 
@@ -430,25 +432,36 @@ function advancedcontentfilter_get_variables_guid(ServerRequestInterface $reques
                throw new HTTPException\BadRequestException(DI::l10n()->t('Missing argument: guid.'));
        }
 
-       $condition = ["`guid` = ? AND (`uid` = ? OR `uid` = 0)", $args['guid'], local_user()];
+       $condition = ["`guid` = ? AND (`uid` = ? OR `uid` = 0)", $args['guid'], DI::userSession()->getLocalUserId()];
        $params = ['order' => ['uid' => true]];
-       $item = Post::selectFirstForUser(local_user(), [], $condition, $params);
+       $item_row = Post::selectFirstForUser(DI::userSession()->getLocalUserId(), [], $condition, $params);
 
-       if (!DBA::isResult($item)) {
+       if (!DBA::isResult($item_row)) {
                throw new HTTPException\NotFoundException(DI::l10n()->t('Unknown post with guid: %s', $args['guid']));
        }
 
-       $tags = Tag::populateFromItem($item);
+       $return = advancedcontentfilter_get_filter_fields(advancedcontentfilter_prepare_item_row($item_row));
 
-       $item['tags'] = $tags['tags'];
-       $item['hashtags'] = $tags['hashtags'];
-       $item['mentions'] = $tags['mentions'];
-
-       $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '');
+       $response->getBody()->write(json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]));
+       return $response->withHeader('Content-Type', 'application/json');
+}
 
-       $item['attachments'] = $attachments;
+/**
+ * This mimimcs the processing performed in Model\Item::prepareBody
+ *
+ * @param array $item_row
+ * @return array
+ * @throws HTTPException\InternalServerErrorException
+ * @throws ImagickException
+ */
+function advancedcontentfilter_prepare_item_row(array $item_row): array
+{
+       $tags = Tag::populateFromItem($item_row);
 
-       $return = advancedcontentfilter_get_filter_fields($item);
+       $item_row['tags'] = $tags['tags'];
+       $item_row['hashtags'] = $tags['hashtags'];
+       $item_row['mentions'] = $tags['mentions'];
+       $item_row['attachments'] = DI::postMediaRepository()->splitAttachments($item_row['uri-id']);
 
-       return json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]);
+       return $item_row;
 }