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