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