]> git.mxchange.org Git - friendica-addons.git/blob - advancedcontentfilter/advancedcontentfilter.php
aedd6e8c908ef898e741f488cecdd37a82a668b7
[friendica-addons.git] / advancedcontentfilter / advancedcontentfilter.php
1 <?php
2 /**
3  * Name: Advanced content Filter
4  * Description: Expression-based content filter
5  * Version: 1.0
6  * Author: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
7  * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
8  *
9  * Copyright (c) 2018 Hypolite Petovan
10  * All rights reserved.
11  *
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.
22  *
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.
33  *
34  */
35
36 use Friendica\App;
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;
44 use Friendica\DI;
45 use Friendica\Model\Item;
46 use Friendica\Model\Post;
47 use Friendica\Model\Tag;
48 use Friendica\Module\Security\Login;
49 use Friendica\Network\HTTPException;
50 use Friendica\Util\DateTimeFormat;
51 use Psr\Http\Message\ResponseInterface;
52 use Psr\Http\Message\ServerRequestInterface;
53 use Symfony\Component\ExpressionLanguage;
54
55 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
56
57 function advancedcontentfilter_install(App $a)
58 {
59         Hook::register('dbstructure_definition'     , __FILE__, 'advancedcontentfilter_dbstructure_definition');
60         Hook::register('prepare_body_content_filter', __FILE__, 'advancedcontentfilter_prepare_body_content_filter');
61         Hook::register('addon_settings'             , __FILE__, 'advancedcontentfilter_addon_settings');
62
63         Hook::add('dbstructure_definition'          , __FILE__, 'advancedcontentfilter_dbstructure_definition');
64         DBStructure::performUpdate();
65
66         Logger::log("installed advancedcontentfilter");
67 }
68
69 /*
70  * Hooks
71  */
72
73 function advancedcontentfilter_dbstructure_definition(App $a, &$database)
74 {
75         $database["advancedcontentfilter_rules"] = [
76                 "comment" => "Advancedcontentfilter addon rules",
77                 "fields" => [
78                         "id"         => ["type" => "int unsigned", "not null" => "1", "extra" => "auto_increment", "primary" => "1", "comment" => "Auto incremented rule id"],
79                         "uid"        => ["type" => "int unsigned", "not null" => "1", "comment" => "Owner user id"],
80                         "name"       => ["type" => "varchar(255)", "not null" => "1", "comment" => "Rule name"],
81                         "expression" => ["type" => "mediumtext"  , "not null" => "1", "comment" => "Expression text"],
82                         "serialized" => ["type" => "mediumtext"  , "not null" => "1", "comment" => "Serialized parsed expression"],
83                         "active"     => ["type" => "boolean"     , "not null" => "1", "default" => "1", "comment" => "Whether the rule is active or not"],
84                         "created"    => ["type" => "datetime"    , "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => "Creation date"],
85                 ],
86                 "indexes" => [
87                         "PRIMARY" => ["id"],
88                         "uid_active" => ["uid", "active"],
89                 ]
90         ];
91 }
92
93 function advancedcontentfilter_get_filter_fields(array $item)
94 {
95         $vars = [];
96
97         // Convert the language JSON text into a filterable format
98         if (!empty($item['language']) && ($languages = json_decode($item['language'], true))) {
99                 foreach ($languages as $key => $value) {
100                         $vars['language_' . strtolower($key)] = $value;
101                 }
102         }
103
104         foreach ($item as $key => $value) {
105                 $vars[str_replace('-', '_', $key)] = $value;
106         }
107
108         ksort($vars);
109
110         return $vars;
111 }
112
113 function advancedcontentfilter_prepare_body_content_filter(App $a, &$hook_data)
114 {
115         static $expressionLanguage;
116
117         if (is_null($expressionLanguage)) {
118                 $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
119         }
120
121         if (!local_user()) {
122                 return;
123         }
124
125         $vars = advancedcontentfilter_get_filter_fields($hook_data['item']);
126
127         $rules = DI::cache()->get('rules_' . local_user());
128         if (!isset($rules)) {
129                 $rules = DBA::toArray(DBA::select(
130                         'advancedcontentfilter_rules',
131                         ['name', 'expression', 'serialized'],
132                         ['uid' => local_user(), 'active' => true]
133                 ));
134
135                 DI::cache()->set('rules_' . local_user(), $rules);
136         }
137
138         if ($rules) {
139                 foreach($rules as $rule) {
140                         try {
141                                 $serializedParsedExpression = new ExpressionLanguage\SerializedParsedExpression(
142                                         $rule['expression'],
143                                         $rule['serialized']
144                                 );
145
146                                 // The error suppression operator is used because of potentially broken user-supplied regular expressions
147                                 $found = (bool) @$expressionLanguage->evaluate($serializedParsedExpression, $vars);
148                         } catch (Exception $e) {
149                                 $found = false;
150                         }
151
152                         if ($found) {
153                                 $hook_data['filter_reasons'][] = DI::l10n()->t('Filtered by rule: %s', $rule['name']);
154                                 break;
155                         }
156                 }
157         }
158 }
159
160
161 function advancedcontentfilter_addon_settings(App $a, &$s)
162 {
163         if (!local_user()) {
164                 return;
165         }
166
167         $advancedcontentfilter = DI::l10n()->t('Advanced Content Filter');
168
169         $s .= <<<HTML
170                 <span class="settings-block fakelink" style="display: block;"><h3><a href="advancedcontentfilter">$advancedcontentfilter <i class="glyphicon glyphicon-share"></i></a></h3></span>
171 HTML;
172
173         return;
174 }
175
176 /*
177  * Module
178  */
179
180 function advancedcontentfilter_module() {}
181
182 function advancedcontentfilter_init(App $a)
183 {
184         if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'api') {
185                 $slim = new \Slim\App();
186
187                 require __DIR__ . '/src/middlewares.php';
188
189                 require __DIR__ . '/src/routes.php';
190                 $slim->run();
191
192                 exit;
193         }
194 }
195
196 function advancedcontentfilter_content(App $a)
197 {
198         if (!local_user()) {
199                 return Login::form('/' . implode('/', DI::args()->getArgv()));
200         }
201
202         if (DI::args()->getArgc() > 1 && DI::args()->getArgv()[1] == 'help') {
203                 $lang = $a->getUserValue('language');
204
205                 $default_dir = 'addon/advancedcontentfilter/doc/';
206                 $help_file = 'advancedcontentfilter.md';
207                 $help_path = $default_dir . $help_file;
208                 if (file_exists($default_dir . $lang . '/' . $help_file)) {
209                         $help_path = $default_dir . $lang . '/' . $help_file;
210                 }
211
212                 $content = file_get_contents($help_path);
213
214                 $html = Markdown::convert($content, false);
215
216                 $html = str_replace('code>', 'key>', $html);
217
218                 return $html;
219         } else {
220                 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/advancedcontentfilter/');
221                 return Renderer::replaceMacros($t, [
222                         '$messages' => [
223                                 'backtosettings'    => DI::l10n()->t('Back to Addon Settings'),
224                                 'title'             => DI::l10n()->t('Advanced Content Filter'),
225                                 'add_a_rule'        => DI::l10n()->t('Add a Rule'),
226                                 'help'              => DI::l10n()->t('Help'),
227                                 '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.'),
228                                 'your_rules'        => DI::l10n()->t('Your rules'),
229                                 'no_rules'          => DI::l10n()->t('You have no rules yet! Start adding one by clicking on the button above next to the title.'),
230                                 'disabled'          => DI::l10n()->t('Disabled'),
231                                 'enabled'           => DI::l10n()->t('Enabled'),
232                                 'disable_this_rule' => DI::l10n()->t('Disable this rule'),
233                                 'enable_this_rule'  => DI::l10n()->t('Enable this rule'),
234                                 'edit_this_rule'    => DI::l10n()->t('Edit this rule'),
235                                 'edit_the_rule'     => DI::l10n()->t('Edit the rule'),
236                                 'save_this_rule'    => DI::l10n()->t('Save this rule'),
237                                 'delete_this_rule'  => DI::l10n()->t('Delete this rule'),
238                                 'rule'              => DI::l10n()->t('Rule'),
239                                 'close'             => DI::l10n()->t('Close'),
240                                 'addtitle'          => DI::l10n()->t('Add new rule'),
241                                 'rule_name'         => DI::l10n()->t('Rule Name'),
242                                 'rule_expression'   => DI::l10n()->t('Rule Expression'),
243                                 'cancel'            => DI::l10n()->t('Cancel'),
244                         ],
245                         '$current_theme' => $a->getCurrentTheme(),
246                         '$rules' => advancedcontentfilter_get_rules(),
247                         '$form_security_token' => BaseModule::getFormSecurityToken()
248                 ]);
249         }
250 }
251
252 /*
253  * Common functions
254  */
255 function advancedcontentfilter_build_fields($data)
256 {
257         $fields = [];
258
259         if (!empty($data['name'])) {
260                 $fields['name'] = $data['name'];
261         }
262
263         if (!empty($data['expression'])) {
264                 $allowed_keys = [
265                         'author_id', 'author_link', 'author_name', 'author_avatar',
266                         'owner_id', 'owner_link', 'owner_name', 'owner_avatar',
267                         'contact_id', 'uid', 'id', 'parent', 'uri',
268                         'thr_parent', 'parent_uri',
269                         'content_warning',
270                         'commented', 'created', 'edited', 'received',
271                         'verb', 'object_type', 'postopts', 'plink', 'guid', 'wall', 'private', 'starred',
272                         'title', 'body',
273                         'file', 'event_id', 'location', 'coord', 'app', 'attach',
274                         'rendered_hash', 'rendered_html', 'object',
275                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
276                         'item_id', 'item_network', 'author_thumb', 'owner_thumb',
277                         'network', 'url', 'name', 'writable', 'self',
278                         'cid', 'alias',
279                         'event_created', 'event_edited', 'event_start', 'event_finish', 'event_summary',
280                         'event_desc', 'event_location', 'event_type', 'event_nofinish', 'event_adjust', 'event_ignore',
281                         'children', 'pagedrop', 'tags', 'hashtags', 'mentions',
282                 ];
283
284                 $expressionLanguage = new ExpressionLanguage\ExpressionLanguage();
285
286                 $parsedExpression = $expressionLanguage->parse($data['expression'], $allowed_keys);
287
288                 $serialized = serialize($parsedExpression->getNodes());
289
290                 $fields['expression'] = $data['expression'];
291                 $fields['serialized'] = $serialized;
292         }
293
294         if (isset($data['active'])) {
295                 $fields['active'] = intval($data['active']);
296         } else {
297                 $fields['active'] = 1;
298         }
299
300         return $fields;
301 }
302
303 /*
304  * API
305  */
306
307 function advancedcontentfilter_get_rules()
308 {
309         if (!local_user()) {
310                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
311         }
312
313         $rules = DBA::toArray(DBA::select('advancedcontentfilter_rules', [], ['uid' => local_user()]));
314
315         return json_encode($rules);
316 }
317
318 function advancedcontentfilter_get_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
319 {
320         if (!local_user()) {
321                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
322         }
323
324         $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => $args['id'], 'uid' => local_user()]);
325
326         return json_encode($rule);
327 }
328
329 function advancedcontentfilter_post_rules(ServerRequestInterface $request)
330 {
331         if (!local_user()) {
332                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
333         }
334
335         if (!BaseModule::checkFormSecurityToken()) {
336                 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
337         }
338
339         $data = json_decode($request->getBody(), true);
340
341         try {
342                 $fields = advancedcontentfilter_build_fields($data);
343         } catch (Exception $e) {
344                 throw new HTTPException\BadRequestException($e->getMessage(), $e);
345         }
346
347         if (empty($fields['name']) || empty($fields['expression'])) {
348                 throw new HTTPException\BadRequestException(DI::l10n()->t('The rule name and expression are required.'));
349         }
350
351         $fields['uid'] = local_user();
352         $fields['created'] = DateTimeFormat::utcNow();
353
354         if (!DBA::insert('advancedcontentfilter_rules', $fields)) {
355                 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
356         }
357
358         $rule = DBA::selectFirst('advancedcontentfilter_rules', [], ['id' => DBA::lastInsertId()]);
359
360         return json_encode(['message' => DI::l10n()->t('Rule successfully added'), 'rule' => $rule]);
361 }
362
363 function advancedcontentfilter_put_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
364 {
365         if (!local_user()) {
366                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
367         }
368
369         if (!BaseModule::checkFormSecurityToken()) {
370                 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
371         }
372
373         if (!DBA::exists('advancedcontentfilter_rules', ['id' => $args['id'], 'uid' => local_user()])) {
374                 throw new HTTPException\NotFoundException(DI::l10n()->t('Rule doesn\'t exist or doesn\'t belong to you.'));
375         }
376
377         $data = json_decode($request->getBody(), true);
378
379         try {
380                 $fields = advancedcontentfilter_build_fields($data);
381         } catch (Exception $e) {
382                 throw new HTTPException\BadRequestException($e->getMessage(), $e);
383         }
384
385         if (!DBA::update('advancedcontentfilter_rules', $fields, ['id' => $args['id']])) {
386                 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
387         }
388
389         return json_encode(['message' => DI::l10n()->t('Rule successfully updated')]);
390 }
391
392 function advancedcontentfilter_delete_rules_id(ServerRequestInterface $request, ResponseInterface $response, $args)
393 {
394         if (!local_user()) {
395                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
396         }
397
398         if (!BaseModule::checkFormSecurityToken()) {
399                 throw new HTTPException\BadRequestException(DI::l10n()->t('Invalid form security token, please refresh the page.'));
400         }
401
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.'));
404         }
405
406         if (!DBA::delete('advancedcontentfilter_rules', ['id' => $args['id']])) {
407                 throw new HTTPException\ServiceUnavailableException(DBA::errorMessage());
408         }
409
410         return json_encode(['message' => DI::l10n()->t('Rule successfully deleted')]);
411 }
412
413 function advancedcontentfilter_get_variables_guid(ServerRequestInterface $request, ResponseInterface $response, $args)
414 {
415         if (!local_user()) {
416                 throw new HTTPException\UnauthorizedException(DI::l10n()->t('You must be logged in to use this method'));
417         }
418
419         if (!isset($args['guid'])) {
420                 throw new HTTPException\BadRequestException(DI::l10n()->t('Missing argument: guid.'));
421         }
422
423         $condition = ["`guid` = ? AND (`uid` = ? OR `uid` = 0)", $args['guid'], local_user()];
424         $params = ['order' => ['uid' => true]];
425         $item = Post::selectFirstForUser(local_user(), [], $condition, $params);
426
427         if (!DBA::isResult($item)) {
428                 throw new HTTPException\NotFoundException(DI::l10n()->t('Unknown post with guid: %s', $args['guid']));
429         }
430
431         $tags = Tag::populateFromItem($item);
432
433         $item['tags'] = $tags['tags'];
434         $item['hashtags'] = $tags['hashtags'];
435         $item['mentions'] = $tags['mentions'];
436
437         $return = advancedcontentfilter_get_filter_fields($item);
438
439         return json_encode(['variables' => str_replace('\\\'', '\'', var_export($return, true))]);
440 }