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