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