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