]> git.wh0rd.org Git - tt-rss.git/blob - classes/pref/filters.php
reinstate wrongfully renamed archived feed; properly fix prefs filtertree labels...
[tt-rss.git] / classes / pref / filters.php
1 <?php
2 class Pref_Filters extends Handler_Protected {
3
4         function csrf_ignore($method) {
5                 $csrf_ignored = array("index", "getfiltertree", "edit", "newfilter", "newrule",
6                         "newaction", "savefilterorder");
7
8                 return array_search($method, $csrf_ignored) !== false;
9         }
10
11         function filtersortreset() {
12                 $this->dbh->query("UPDATE ttrss_filters2
13                                 SET order_id = 0 WHERE owner_uid = " . $_SESSION["uid"]);
14                 return;
15         }
16
17         function savefilterorder() {
18                 $data = json_decode($_POST['payload'], true);
19
20                 #file_put_contents("/tmp/saveorder.json", $_POST['payload']);
21                 #$data = json_decode(file_get_contents("/tmp/saveorder.json"), true);
22
23                 if (!is_array($data['items']))
24                         $data['items'] = json_decode($data['items'], true);
25
26                 $index = 0;
27
28                 if (is_array($data) && is_array($data['items'])) {
29                         foreach ($data['items'][0]['items'] as $item) {
30                                 $filter_id = (int) str_replace("FILTER:", "", $item['_reference']);
31
32                                 if ($filter_id > 0) {
33
34                                         $this->dbh->query("UPDATE ttrss_filters2 SET
35                                                 order_id = $index WHERE id = '$filter_id' AND
36                                                 owner_uid = " .$_SESSION["uid"]);
37
38                                         ++$index;
39                                 }
40                         }
41                 }
42
43                 return;
44         }
45
46
47         function testFilter() {
48                 $filter = array();
49
50                 $filter["enabled"] = true;
51                 $filter["match_any_rule"] = sql_bool_to_bool(
52                         checkbox_to_sql_bool($this->dbh->escape_string($_REQUEST["match_any_rule"])));
53                 $filter["inverse"] = sql_bool_to_bool(
54                         checkbox_to_sql_bool($this->dbh->escape_string($_REQUEST["inverse"])));
55
56                 $filter["rules"] = array();
57
58                 $result = $this->dbh->query("SELECT id,name FROM ttrss_filter_types");
59
60                 $filter_types = array();
61                 while ($line = $this->dbh->fetch_assoc($result)) {
62                         $filter_types[$line["id"]] = $line["name"];
63                 }
64
65                 $rctr = 0;
66                 foreach ($_REQUEST["rule"] AS $r) {
67                         $rule = json_decode($r, true);
68
69                         if ($rule && $rctr < 5) {
70                                 $rule["type"] = $filter_types[$rule["filter_type"]];
71                                 unset($rule["filter_type"]);
72
73                                 if (strpos($rule["feed_id"], "CAT:") === 0) {
74                                         $rule["cat_id"] = (int) substr($rule["feed_id"], 4);
75                                         unset($rule["feed_id"]);
76                                 }
77
78                                 array_push($filter["rules"], $rule);
79
80                                 ++$rctr;
81                         } else {
82                                 break;
83                         }
84                 }
85
86                 $qfh_ret = queryFeedHeadlines(-4, 30, "", false, false, false,
87                         "date_entered DESC", 0, $_SESSION["uid"], $filter);
88
89                 $result = $qfh_ret[0];
90
91                 $found = 0;
92
93                 print __("Articles matching this filter:");
94
95                 print "<div class=\"filterTestHolder\">";
96                 print "<table width=\"100%\" cellspacing=\"0\" id=\"prefErrorFeedList\">";
97
98                 while ($line = $this->dbh->fetch_assoc($result)) {
99                         $line["content_preview"] = truncate_string(strip_tags($line["content"]), 100, '...');
100
101                         foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) {
102                                         $line = $p->hook_query_headlines($line, 100);
103                                 }
104
105                         $content_preview = $line["content_preview"];
106
107                         if ($line["feed_title"])
108                                 $feed_title = $line["feed_title"];
109
110                         print "<tr>";
111
112                         print "<td width='5%' align='center'><input
113                                 dojoType=\"dijit.form.CheckBox\" checked=\"1\"
114                                 disabled=\"1\" type=\"checkbox\"></td>";
115                         print "<td>";
116
117                         print $line["title"];
118                         print "&nbsp;(";
119                         print "<b>" . $feed_title . "</b>";
120                         print "):&nbsp;";
121                         print "<span class=\"insensitive\">" . $content_preview . "</span>";
122                         print " " . mb_substr($line["date_entered"], 0, 16);
123
124                         print "</td></tr>";
125
126                         $found++;
127                 }
128
129                 if ($found == 0) {
130                         print "<tr><td align='center'>" .
131                                 __("No recent articles matching this filter have been found.");
132
133                         print "</td></tr><tr><td class='insensitive' align='center'>";
134
135                         print __("Complex expressions might not give results while testing due to issues with database server regexp implementation.");
136
137                         print "</td></tr>";
138
139                 }
140
141                 print "</table></div>";
142
143                 print "<div style='text-align : center'>";
144                 print "<button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('filterTestDlg').hide()\">".
145                         __('Close this window')."</button>";
146                 print "</div>";
147
148         }
149
150         private function getfilterrules_concise($filter_id) {
151                 $result = $this->dbh->query("SELECT reg_exp,
152                         inverse,
153                         feed_id,
154                         cat_id,
155                         cat_filter,
156                         ttrss_filter_types.description AS field
157                         FROM
158                                 ttrss_filters2_rules, ttrss_filter_types
159                         WHERE
160                                 filter_id = '$filter_id' AND filter_type = ttrss_filter_types.id");
161
162                 $rv = "";
163
164                 while ($line = $this->dbh->fetch_assoc($result)) {
165
166                         $where = sql_bool_to_bool($line["cat_filter"]) ?
167                                 getCategoryTitle($line["cat_id"]) :
168                                 ($line["feed_id"] ?
169                                         getFeedTitle($line["feed_id"]) : __("All feeds"));
170
171 #                       $where = $line["cat_id"] . "/" . $line["feed_id"];
172
173                         $inverse = sql_bool_to_bool($line["inverse"]) ? "inverse" : "";
174
175                         $rv .= "<span class='$inverse'>" . T_sprintf("%s on %s in %s %s",
176                                 strip_tags($line["reg_exp"]),
177                                 $line["field"],
178                                 $where,
179                                 sql_bool_to_bool($line["inverse"]) ? __("(inverse)") : "") . "</span>";
180                 }
181
182                 return $rv;
183         }
184
185         function getfiltertree() {
186                 $root = array();
187                 $root['id'] = 'root';
188                 $root['name'] = __('Filters');
189                 $root['items'] = array();
190
191                 $filter_search = $_SESSION["prefs_filter_search"];
192
193                 $result = $this->dbh->query("SELECT *,
194                         (SELECT action_param FROM ttrss_filters2_actions
195                                 WHERE filter_id = ttrss_filters2.id ORDER BY id LIMIT 1) AS action_param,
196                         (SELECT action_id FROM ttrss_filters2_actions
197                                 WHERE filter_id = ttrss_filters2.id ORDER BY id LIMIT 1) AS action_id,
198                         (SELECT description FROM ttrss_filter_actions
199                                 WHERE id = (SELECT action_id FROM ttrss_filters2_actions
200                                         WHERE filter_id = ttrss_filters2.id ORDER BY id LIMIT 1)) AS action_name,
201                         (SELECT reg_exp FROM ttrss_filters2_rules
202                                 WHERE filter_id = ttrss_filters2.id ORDER BY id LIMIT 1) AS reg_exp
203                         FROM ttrss_filters2 WHERE
204                         owner_uid = ".$_SESSION["uid"]." ORDER BY order_id, title");
205
206
207                 $folder = array();
208                 $folder['items'] = array();
209
210                 while ($line = $this->dbh->fetch_assoc($result)) {
211
212                         $name = $this->getFilterName($line["id"]);
213
214                         $match_ok = false;
215                         if ($filter_search) {
216                                 $rules_result = $this->dbh->query(
217                                         "SELECT reg_exp FROM ttrss_filters2_rules WHERE filter_id = ".$line["id"]);
218
219                                 while ($rule_line = $this->dbh->fetch_assoc($rules_result)) {
220                                         if (mb_strpos($rule_line['reg_exp'], $filter_search) !== false) {
221                                                 $match_ok = true;
222                                                 break;
223                                         }
224                                 }
225                         }
226
227                         if ($line['action_id'] == 7) {
228                                 $label_result = $this->dbh->query("SELECT fg_color, bg_color
229                                         FROM ttrss_labels2 WHERE caption = '".$this->dbh->escape_string($line['action_param'])."' AND
230                                                 owner_uid = " . $_SESSION["uid"]);
231
232                                 if ($this->dbh->num_rows($label_result) > 0) {
233                                         $fg_color = $this->dbh->fetch_result($label_result, 0, "fg_color");
234                                         $bg_color = $this->dbh->fetch_result($label_result, 0, "bg_color");
235
236                                         $name[1] = "<span class=\"labelColorIndicator\" id=\"label-editor-indicator\" style='color : $fg_color; background-color : $bg_color; margin-right : 4px'>&alpha;</span>" . $name[1];
237                                 }
238                         }
239
240                         $filter = array();
241                         $filter['id'] = 'FILTER:' . $line['id'];
242                         $filter['bare_id'] = $line['id'];
243                         $filter['name'] = $name[0];
244                         $filter['param'] = $name[1];
245                         $filter['checkbox'] = false;
246                         $filter['enabled'] = sql_bool_to_bool($line["enabled"]);
247                         $filter['rules'] = $this->getfilterrules_concise($line['id']);
248
249                         if (!$filter_search || $match_ok) {
250                                 array_push($folder['items'], $filter);
251                         }
252                 }
253
254                 /* if (count($folder['items']) > 0) {
255                         array_push($root['items'], $folder);
256                 } */
257
258                 $root['items'] = $folder['items'];
259
260                 $fl = array();
261                 $fl['identifier'] = 'id';
262                 $fl['label'] = 'name';
263                 $fl['items'] = array($root);
264
265                 print json_encode($fl);
266                 return;
267         }
268
269         function edit() {
270
271                 $filter_id = $this->dbh->escape_string($_REQUEST["id"]);
272
273                 $result = $this->dbh->query(
274                         "SELECT * FROM ttrss_filters2 WHERE id = '$filter_id' AND owner_uid = " . $_SESSION["uid"]);
275
276                 $enabled = sql_bool_to_bool($this->dbh->fetch_result($result, 0, "enabled"));
277                 $match_any_rule = sql_bool_to_bool($this->dbh->fetch_result($result, 0, "match_any_rule"));
278                 $inverse = sql_bool_to_bool($this->dbh->fetch_result($result, 0, "inverse"));
279                 $title = htmlspecialchars($this->dbh->fetch_result($result, 0, "title"));
280
281                 print "<form id=\"filter_edit_form\" onsubmit='return false'>";
282
283                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-filters\">";
284                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"id\" value=\"$filter_id\">";
285                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"editSave\">";
286                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"csrf_token\" value=\"".$_SESSION['csrf_token']."\">";
287
288                 print "<div class=\"dlgSec\">".__("Caption")."</div>";
289
290                 print "<input required=\"true\" dojoType=\"dijit.form.ValidationTextBox\" style=\"width : 20em;\" name=\"title\" value=\"$title\">";
291
292                 print "</div>";
293
294                 print "<div class=\"dlgSec\">".__("Match")."</div>";
295
296                 print "<div dojoType=\"dijit.Toolbar\">";
297
298                 print "<div dojoType=\"dijit.form.DropDownButton\">".
299                                 "<span>" . __('Select')."</span>";
300                 print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
301                 print "<div onclick=\"dijit.byId('filterEditDlg').selectRules(true)\"
302                         dojoType=\"dijit.MenuItem\">".__('All')."</div>";
303                 print "<div onclick=\"dijit.byId('filterEditDlg').selectRules(false)\"
304                         dojoType=\"dijit.MenuItem\">".__('None')."</div>";
305                 print "</div></div>";
306
307                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').addRule()\">".
308                         __('Add')."</button> ";
309
310                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').deleteRule()\">".
311                         __('Delete')."</button> ";
312
313                 print "</div>";
314
315                 print "<ul id='filterDlg_Matches'>";
316
317                 $rules_result = $this->dbh->query("SELECT * FROM ttrss_filters2_rules
318                         WHERE filter_id = '$filter_id' ORDER BY reg_exp, id");
319
320                 while ($line = $this->dbh->fetch_assoc($rules_result)) {
321                         if (sql_bool_to_bool($line["cat_filter"])) {
322                                 $line["feed_id"] = "CAT:" . (int)$line["cat_id"];
323                         }
324
325                         unset($line["cat_filter"]);
326                         unset($line["cat_id"]);
327                         unset($line["filter_id"]);
328                         unset($line["id"]);
329                         if (!sql_bool_to_bool($line["inverse"])) unset($line["inverse"]);
330
331                         $data = htmlspecialchars(json_encode($line));
332
333                         print "<li><input dojoType='dijit.form.CheckBox' type='checkbox' onclick='toggleSelectListRow2(this)'>".
334                                 "<span onclick=\"dijit.byId('filterEditDlg').editRule(this)\">".$this->getRuleName($line)."</span>".
335                                 "<input type='hidden' name='rule[]' value=\"$data\"/></li>";
336                 }
337
338                 print "</ul>";
339
340                 print "</div>";
341
342                 print "<div class=\"dlgSec\">".__("Apply actions")."</div>";
343
344                 print "<div dojoType=\"dijit.Toolbar\">";
345
346                 print "<div dojoType=\"dijit.form.DropDownButton\">".
347                                 "<span>" . __('Select')."</span>";
348                 print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
349                 print "<div onclick=\"dijit.byId('filterEditDlg').selectActions(true)\"
350                         dojoType=\"dijit.MenuItem\">".__('All')."</div>";
351                 print "<div onclick=\"dijit.byId('filterEditDlg').selectActions(false)\"
352                         dojoType=\"dijit.MenuItem\">".__('None')."</div>";
353                 print "</div></div>";
354
355                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').addAction()\">".
356                         __('Add')."</button> ";
357
358                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').deleteAction()\">".
359                         __('Delete')."</button> ";
360
361                 print "</div>";
362
363                 print "<ul id='filterDlg_Actions'>";
364
365                 $actions_result = $this->dbh->query("SELECT * FROM ttrss_filters2_actions
366                         WHERE filter_id = '$filter_id' ORDER BY id");
367
368                 while ($line = $this->dbh->fetch_assoc($actions_result)) {
369                         $line["action_param_label"] = $line["action_param"];
370
371                         unset($line["filter_id"]);
372                         unset($line["id"]);
373
374                         $data = htmlspecialchars(json_encode($line));
375
376                         print "<li><input dojoType='dijit.form.CheckBox' type='checkbox' onclick='toggleSelectListRow2(this)'>".
377                                 "<span onclick=\"dijit.byId('filterEditDlg').editAction(this)\">".$this->getActionName($line)."</span>".
378                                 "<input type='hidden' name='action[]' value=\"$data\"/></li>";
379                 }
380
381                 print "</ul>";
382
383                 print "</div>";
384
385                 if ($enabled) {
386                         $checked = "checked=\"1\"";
387                 } else {
388                         $checked = "";
389                 }
390
391                 print "<input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"enabled\" id=\"enabled\" $checked>
392                                 <label for=\"enabled\">".__('Enabled')."</label>";
393
394                 if ($match_any_rule) {
395                         $checked = "checked=\"1\"";
396                 } else {
397                         $checked = "";
398                 }
399
400                 print "<br/><input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"match_any_rule\" id=\"match_any_rule\" $checked>
401                                 <label for=\"match_any_rule\">".__('Match any rule')."</label>";
402
403                 if ($inverse) {
404                         $checked = "checked=\"1\"";
405                 } else {
406                         $checked = "";
407                 }
408
409                 print "<br/><input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"inverse\" id=\"inverse\" $checked>
410                                 <label for=\"inverse\">".__('Inverse matching')."</label>";
411
412                 print "<p/>";
413
414                 print "<div class=\"dlgButtons\">";
415
416                 print "<div style=\"float : left\">";
417                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').removeFilter()\">".
418                         __('Remove')."</button>";
419                 print "</div>";
420
421                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').test()\">".
422                         __('Test')."</button> ";
423
424                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').execute()\">".
425                         __('Save')."</button> ";
426
427                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').hide()\">".
428                         __('Cancel')."</button>";
429
430                 print "</div>";
431         }
432
433         private function getRuleName($rule) {
434                 if (!$rule) $rule = json_decode($_REQUEST["rule"], true);
435
436                 $feed_id = $rule["feed_id"];
437
438                 if (strpos($feed_id, "CAT:") === 0) {
439                         $feed_id = (int) substr($feed_id, 4);
440                         $feed = getCategoryTitle($feed_id);
441                 } else {
442                         $feed_id = (int) $feed_id;
443
444                         if ($rule["feed_id"])
445                                 $feed = getFeedTitle((int)$rule["feed_id"]);
446                         else
447                                 $feed = __("All feeds");
448                 }
449
450                 $result = $this->dbh->query("SELECT description FROM ttrss_filter_types
451                         WHERE id = ".(int)$rule["filter_type"]);
452                 $filter_type = $this->dbh->fetch_result($result, 0, "description");
453
454                 $inverse = isset($rule["inverse"]) ? "inverse" : "";
455
456                 return "<span class='filterRule $inverse'>" .
457                         T_sprintf("%s on %s in %s %s", strip_tags($rule["reg_exp"]),
458                         $filter_type, $feed, isset($rule["inverse"]) ? __("(inverse)") : "") . "</span>";
459         }
460
461         function printRuleName() {
462                 print $this->getRuleName(json_decode($_REQUEST["rule"], true));
463         }
464
465         private function getActionName($action) {
466                 $result = $this->dbh->query("SELECT description FROM
467                         ttrss_filter_actions WHERE id = " .(int)$action["action_id"]);
468
469                 $title = __($this->dbh->fetch_result($result, 0, "description"));
470
471                 if ($action["action_id"] == 4 || $action["action_id"] == 6 ||
472                         $action["action_id"] == 7)
473                                 $title .= ": " . $action["action_param"];
474
475                 return $title;
476         }
477
478         function printActionName() {
479                 print $this->getActionName(json_decode($_REQUEST["action"], true));
480         }
481
482         function editSave() {
483                 if ($_REQUEST["savemode"] && $_REQUEST["savemode"] == "test") {
484                         return $this->testFilter();
485                 }
486
487 #               print_r($_REQUEST);
488
489                 $filter_id = $this->dbh->escape_string($_REQUEST["id"]);
490                 $enabled = checkbox_to_sql_bool($this->dbh->escape_string($_REQUEST["enabled"]));
491                 $match_any_rule = checkbox_to_sql_bool($this->dbh->escape_string($_REQUEST["match_any_rule"]));
492                 $inverse = checkbox_to_sql_bool($this->dbh->escape_string($_REQUEST["inverse"]));
493                 $title = $this->dbh->escape_string($_REQUEST["title"]);
494
495                 $this->dbh->query("UPDATE ttrss_filters2 SET enabled = $enabled,
496                         match_any_rule = $match_any_rule,
497                         inverse = $inverse,
498                         title = '$title'
499                         WHERE id = '$filter_id'
500                         AND owner_uid = ". $_SESSION["uid"]);
501
502                 $this->saveRulesAndActions($filter_id);
503
504         }
505
506         function remove() {
507
508                 $ids = explode(",", $this->dbh->escape_string($_REQUEST["ids"]));
509
510                 foreach ($ids as $id) {
511                         $this->dbh->query("DELETE FROM ttrss_filters2 WHERE id = '$id' AND owner_uid = ". $_SESSION["uid"]);
512                 }
513         }
514
515         private function saveRulesAndActions($filter_id) {
516
517                 $this->dbh->query("DELETE FROM ttrss_filters2_rules WHERE filter_id = '$filter_id'");
518                 $this->dbh->query("DELETE FROM ttrss_filters2_actions WHERE filter_id = '$filter_id'");
519
520                 if ($filter_id) {
521                         /* create rules */
522
523                         $rules = array();
524                         $actions = array();
525
526                         foreach ($_REQUEST["rule"] as $rule) {
527                                 $rule = json_decode($rule, true);
528                                 unset($rule["id"]);
529
530                                 if (array_search($rule, $rules) === false) {
531                                         array_push($rules, $rule);
532                                 }
533                         }
534
535                         foreach ($_REQUEST["action"] as $action) {
536                                 $action = json_decode($action, true);
537                                 unset($action["id"]);
538
539                                 if (array_search($action, $actions) === false) {
540                                         array_push($actions, $action);
541                                 }
542                         }
543
544                         foreach ($rules as $rule) {
545                                 if ($rule) {
546
547                                         $reg_exp = strip_tags($this->dbh->escape_string(trim($rule["reg_exp"])));
548                                         $inverse = isset($rule["inverse"]) ? "true" : "false";
549
550                                         $filter_type = (int) $this->dbh->escape_string(trim($rule["filter_type"]));
551                                         $feed_id = $this->dbh->escape_string(trim($rule["feed_id"]));
552
553                                         if (strpos($feed_id, "CAT:") === 0) {
554
555                                                 $cat_filter = bool_to_sql_bool(true);
556                                                 $cat_id = (int) substr($feed_id, 4);
557                                                 $feed_id = "NULL";
558
559                                                 if (!$cat_id) $cat_id = "NULL"; // Uncategorized
560                                         } else {
561                                                 $cat_filter = bool_to_sql_bool(false);
562                                                 $feed_id = (int) $feed_id;
563                                                 $cat_id = "NULL";
564
565                                                 if (!$feed_id) $feed_id = "NULL"; // Uncategorized
566                                         }
567
568                                         $query = "INSERT INTO ttrss_filters2_rules
569                                                 (filter_id, reg_exp,filter_type,feed_id,cat_id,cat_filter,inverse) VALUES
570                                                 ('$filter_id', '$reg_exp', '$filter_type', $feed_id, $cat_id, $cat_filter, $inverse)";
571
572                                         $this->dbh->query($query);
573                                 }
574                         }
575
576                         foreach ($actions as $action) {
577                                 if ($action) {
578
579                                         $action_id = (int) $this->dbh->escape_string($action["action_id"]);
580                                         $action_param = $this->dbh->escape_string($action["action_param"]);
581                                         $action_param_label = $this->dbh->escape_string($action["action_param_label"]);
582
583                                         if ($action_id == 7) {
584                                                 $action_param = $action_param_label;
585                                         }
586
587                                         if ($action_id == 6) {
588                                                 $action_param = (int) str_replace("+", "", $action_param);
589                                         }
590
591                                         $query = "INSERT INTO ttrss_filters2_actions
592                                                 (filter_id, action_id, action_param) VALUES
593                                                 ('$filter_id', '$action_id', '$action_param')";
594
595                                         $this->dbh->query($query);
596                                 }
597                         }
598                 }
599
600
601         }
602
603         function add() {
604                 if ($_REQUEST["savemode"] && $_REQUEST["savemode"] == "test") {
605                         return $this->testFilter();
606                 }
607
608 #               print_r($_REQUEST);
609
610                 $enabled = checkbox_to_sql_bool($_REQUEST["enabled"]);
611                 $match_any_rule = checkbox_to_sql_bool($_REQUEST["match_any_rule"]);
612                 $title = $this->dbh->escape_string($_REQUEST["title"]);
613                 $inverse = checkbox_to_sql_bool($_REQUEST["inverse"]);
614
615                 $this->dbh->query("BEGIN");
616
617                 /* create base filter */
618
619                 $result = $this->dbh->query("INSERT INTO ttrss_filters2
620                         (owner_uid, match_any_rule, enabled, title, inverse) VALUES
621                         (".$_SESSION["uid"].",$match_any_rule,$enabled, '$title', $inverse)");
622
623                 $result = $this->dbh->query("SELECT MAX(id) AS id FROM ttrss_filters2
624                         WHERE owner_uid = ".$_SESSION["uid"]);
625
626                 $filter_id = $this->dbh->fetch_result($result, 0, "id");
627
628                 $this->saveRulesAndActions($filter_id);
629
630                 $this->dbh->query("COMMIT");
631         }
632
633         function index() {
634
635                 $sort = $this->dbh->escape_string($_REQUEST["sort"]);
636
637                 if (!$sort || $sort == "undefined") {
638                         $sort = "reg_exp";
639                 }
640
641                 $filter_search = $this->dbh->escape_string($_REQUEST["search"]);
642
643                 if (array_key_exists("search", $_REQUEST)) {
644                         $_SESSION["prefs_filter_search"] = $filter_search;
645                 } else {
646                         $filter_search = $_SESSION["prefs_filter_search"];
647                 }
648
649                 print "<div id=\"pref-filter-wrap\" dojoType=\"dijit.layout.BorderContainer\" gutters=\"false\">";
650                 print "<div id=\"pref-filter-header\" dojoType=\"dijit.layout.ContentPane\" region=\"top\">";
651                 print "<div id=\"pref-filter-toolbar\" dojoType=\"dijit.Toolbar\">";
652
653                 $filter_search = $this->dbh->escape_string($_REQUEST["search"]);
654
655                 if (array_key_exists("search", $_REQUEST)) {
656                         $_SESSION["prefs_filter_search"] = $filter_search;
657                 } else {
658                         $filter_search = $_SESSION["prefs_filter_search"];
659                 }
660
661                 print "<div style='float : right; padding-right : 4px;'>
662                         <input dojoType=\"dijit.form.TextBox\" id=\"filter_search\" size=\"20\" type=\"search\"
663                                 value=\"$filter_search\">
664                         <button dojoType=\"dijit.form.Button\" onclick=\"updateFilterList()\">".
665                                 __('Search')."</button>
666                         </div>";
667
668                 print "<div dojoType=\"dijit.form.DropDownButton\">".
669                                 "<span>" . __('Select')."</span>";
670                 print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
671                 print "<div onclick=\"dijit.byId('filterTree').model.setAllChecked(true)\"
672                         dojoType=\"dijit.MenuItem\">".__('All')."</div>";
673                 print "<div onclick=\"dijit.byId('filterTree').model.setAllChecked(false)\"
674                         dojoType=\"dijit.MenuItem\">".__('None')."</div>";
675                 print "</div></div>";
676
677                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return quickAddFilter()\">".
678                         __('Create filter')."</button> ";
679
680                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return joinSelectedFilters()\">".
681                         __('Combine')."</button> ";
682
683                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return editSelectedFilter()\">".
684                         __('Edit')."</button> ";
685
686                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return resetFilterOrder()\">".
687                         __('Reset sort order')."</button> ";
688
689
690                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return removeSelectedFilters()\">".
691                         __('Remove')."</button> ";
692
693                 if (defined('_ENABLE_FEED_DEBUGGING')) {
694                         print "<button dojoType=\"dijit.form.Button\" onclick=\"rescore_all_feeds()\">".
695                                 __('Rescore articles')."</button> ";
696                 }
697
698                 print "</div>"; # toolbar
699                 print "</div>"; # toolbar-frame
700                 print "<div id=\"pref-filter-content\" dojoType=\"dijit.layout.ContentPane\" region=\"center\">";
701
702                 print "<div id=\"filterlistLoading\">
703                 <img src='images/indicator_tiny.gif'>".
704                  __("Loading, please wait...")."</div>";
705
706                 print "<div dojoType=\"fox.PrefFilterStore\" jsId=\"filterStore\"
707                         url=\"backend.php?op=pref-filters&method=getfiltertree\">
708                 </div>
709                 <div dojoType=\"lib.CheckBoxStoreModel\" jsId=\"filterModel\" store=\"filterStore\"
710                         query=\"{id:'root'}\" rootId=\"root\" rootLabel=\"Filters\"
711                         childrenAttrs=\"items\" checkboxStrict=\"false\" checkboxAll=\"false\">
712                 </div>
713                 <div dojoType=\"fox.PrefFilterTree\" id=\"filterTree\"
714                         dndController=\"dijit.tree.dndSource\"
715                         betweenThreshold=\"5\"
716                         model=\"filterModel\" openOnClick=\"true\">
717                 <script type=\"dojo/method\" event=\"onLoad\" args=\"item\">
718                         Element.hide(\"filterlistLoading\");
719                 </script>
720                 <script type=\"dojo/method\" event=\"onClick\" args=\"item\">
721                         var id = String(item.id);
722                         var bare_id = id.substr(id.indexOf(':')+1);
723
724                         if (id.match('FILTER:')) {
725                                 editFilter(bare_id);
726                         }
727                 </script>
728
729                 </div>";
730
731                 print "</div>"; #pane
732
733                 PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB,
734                         "hook_prefs_tab", "prefFilters");
735
736                 print "</div>"; #container
737
738         }
739
740         function newfilter() {
741
742                 print "<form name='filter_new_form' id='filter_new_form'>";
743
744                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"op\" value=\"pref-filters\">";
745                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"method\" value=\"add\">";
746                 print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"csrf_token\" value=\"".$_SESSION['csrf_token']."\">";
747
748                 print "<div class=\"dlgSec\">".__("Caption")."</div>";
749
750                 print "<input required=\"true\" dojoType=\"dijit.form.ValidationTextBox\" style=\"width : 20em;\" name=\"title\" value=\"\">";
751
752                 print "<div class=\"dlgSec\">".__("Match")."</div>";
753
754                 print "<div dojoType=\"dijit.Toolbar\">";
755
756                 print "<div dojoType=\"dijit.form.DropDownButton\">".
757                                 "<span>" . __('Select')."</span>";
758                 print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
759                 print "<div onclick=\"dijit.byId('filterEditDlg').selectRules(true)\"
760                         dojoType=\"dijit.MenuItem\">".__('All')."</div>";
761                 print "<div onclick=\"dijit.byId('filterEditDlg').selectRules(false)\"
762                         dojoType=\"dijit.MenuItem\">".__('None')."</div>";
763                 print "</div></div>";
764
765                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').addRule()\">".
766                         __('Add')."</button> ";
767
768                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').deleteRule()\">".
769                         __('Delete')."</button> ";
770
771                 print "</div>";
772
773                 print "<ul id='filterDlg_Matches'>";
774 #               print "<li>No rules</li>";
775                 print "</ul>";
776
777                 print "</div>";
778
779                 print "<div class=\"dlgSec\">".__("Apply actions")."</div>";
780
781                 print "<div dojoType=\"dijit.Toolbar\">";
782
783                 print "<div dojoType=\"dijit.form.DropDownButton\">".
784                                 "<span>" . __('Select')."</span>";
785                 print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
786                 print "<div onclick=\"dijit.byId('filterEditDlg').selectActions(true)\"
787                         dojoType=\"dijit.MenuItem\">".__('All')."</div>";
788                 print "<div onclick=\"dijit.byId('filterEditDlg').selectActions(false)\"
789                         dojoType=\"dijit.MenuItem\">".__('None')."</div>";
790                 print "</div></div>";
791
792                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').addAction()\">".
793                         __('Add')."</button> ";
794
795                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').deleteAction()\">".
796                         __('Delete')."</button> ";
797
798                 print "</div>";
799
800                 print "<ul id='filterDlg_Actions'>";
801 #               print "<li>No actions</li>";
802                 print "</ul>";
803
804 /*              print "<div class=\"dlgSec\">".__("Options")."</div>";
805                 print "<div class=\"dlgSecCont\">"; */
806
807                 print "<input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"enabled\" id=\"enabled\" checked=\"1\">
808                                 <label for=\"enabled\">".__('Enabled')."</label>";
809
810                 print "<br/><input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"match_any_rule\" id=\"match_any_rule\">
811                                 <label for=\"match_any_rule\">".__('Match any rule')."</label>";
812
813                 print "<br/><input dojoType=\"dijit.form.CheckBox\" type=\"checkbox\" name=\"inverse\" id=\"inverse\">
814                                 <label for=\"inverse\">".__('Inverse matching')."</label>";
815
816 //              print "</div>";
817
818                 print "<div class=\"dlgButtons\">";
819
820                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').test()\">".
821                         __('Test')."</button> ";
822
823                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').execute()\">".
824                         __('Create')."</button> ";
825
826                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterEditDlg').hide()\">".
827                         __('Cancel')."</button>";
828
829                 print "</div>";
830
831         }
832
833         function newrule() {
834                 $rule = json_decode($_REQUEST["rule"], true);
835
836                 if ($rule) {
837                         $reg_exp = htmlspecialchars($rule["reg_exp"]);
838                         $filter_type = $rule["filter_type"];
839                         $feed_id = $rule["feed_id"];
840                         $inverse_checked = isset($rule["inverse"]) ? "checked" : "";
841                 } else {
842                         $reg_exp = "";
843                         $filter_type = 1;
844                         $feed_id = 0;
845                         $inverse_checked = "";
846                 }
847
848                 if (strpos($feed_id, "CAT:") === 0) {
849                         $feed_id = substr($feed_id, 4);
850                         $cat_filter = true;
851                 } else {
852                         $cat_filter = false;
853                 }
854
855
856                 print "<form name='filter_new_rule_form' id='filter_new_rule_form'>";
857
858                 $result = $this->dbh->query("SELECT id,description
859                         FROM ttrss_filter_types WHERE id != 5 ORDER BY description");
860
861                 $filter_types = array();
862
863                 while ($line = $this->dbh->fetch_assoc($result)) {
864                         $filter_types[$line["id"]] = __($line["description"]);
865                 }
866
867                 print "<div class=\"dlgSec\">".__("Match")."</div>";
868
869                 print "<div class=\"dlgSecCont\">";
870
871                 print "<input dojoType=\"dijit.form.ValidationTextBox\"
872                          required=\"true\" id=\"filterDlg_regExp\"
873                          style=\"font-size : 16px; width : 20em;\"
874                          name=\"reg_exp\" value=\"$reg_exp\"/>";
875
876                 print "<hr/>";
877                 print "<input id=\"filterDlg_inverse\" dojoType=\"dijit.form.CheckBox\"
878                          name=\"inverse\" $inverse_checked/>";
879                 print "<label for=\"filterDlg_inverse\">".__("Inverse regular expression matching")."</label>";
880
881                 print "<hr/>" .  __("on field") . " ";
882                 print_select_hash("filter_type", $filter_type, $filter_types,
883                         'dojoType="dijit.form.Select"');
884
885                 print "<hr/>";
886
887                 print __("in") . " ";
888
889                 print "<span id='filterDlg_feeds'>";
890                 print_feed_select("feed_id",
891                         $cat_filter ? "CAT:$feed_id" : $feed_id,
892                         'dojoType="dijit.form.FilteringSelect"');
893                 print "</span>";
894
895                 print "</div>";
896
897                 print "<div class=\"dlgButtons\">";
898
899                 print "<div style=\"float : left\">
900                         <a class=\"visibleLink\" target=\"_blank\" href=\"http://tt-rss.org/wiki/ContentFilters\">".__("Wiki: Filters")."</a>
901                 </div>";
902
903
904                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterNewRuleDlg').execute()\">".
905                         ($rule ? __("Save rule") : __('Add rule'))."</button> ";
906
907                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterNewRuleDlg').hide()\">".
908                         __('Cancel')."</button>";
909
910                 print "</div>";
911
912                 print "</form>";
913         }
914
915         function newaction() {
916                 $action = json_decode($_REQUEST["action"], true);
917
918                 if ($action) {
919                         $action_param = $this->dbh->escape_string($action["action_param"]);
920                         $action_id = (int)$action["action_id"];
921                 } else {
922                         $action_param = "";
923                         $action_id = 0;
924                 }
925
926                 print "<form name='filter_new_action_form' id='filter_new_action_form'>";
927
928                 print "<div class=\"dlgSec\">".__("Perform Action")."</div>";
929
930                 print "<div class=\"dlgSecCont\">";
931
932                 print "<select name=\"action_id\" dojoType=\"dijit.form.Select\"
933                         onchange=\"filterDlgCheckAction(this)\">";
934
935                 $result = $this->dbh->query("SELECT id,description FROM ttrss_filter_actions
936                         ORDER BY name");
937
938                 while ($line = $this->dbh->fetch_assoc($result)) {
939                         $is_selected = ($line["id"] == $action_id) ? "selected='1'" : "";
940                         printf("<option $is_selected value='%d'>%s</option>", $line["id"], __($line["description"]));
941                 }
942
943                 print "</select>";
944
945                 $param_box_hidden = ($action_id == 7 || $action_id == 4 || $action_id == 6) ?
946                         "" : "display : none";
947
948                 $param_hidden = ($action_id == 4 || $action_id == 6) ?
949                         "" : "display : none";
950
951                 $label_param_hidden = ($action_id == 7) ?       "" : "display : none";
952
953                 print "<span id=\"filterDlg_paramBox\" style=\"$param_box_hidden\">";
954                 print " " . __("with parameters:") . " ";
955                 print "<input dojoType=\"dijit.form.TextBox\"
956                         id=\"filterDlg_actionParam\" style=\"$param_hidden\"
957                         name=\"action_param\" value=\"$action_param\">";
958
959                 print_label_select("action_param_label", $action_param,
960                         "id=\"filterDlg_actionParamLabel\" style=\"$label_param_hidden\"
961                         dojoType=\"dijit.form.Select\"");
962
963                 print "</span>";
964
965                 print "&nbsp;"; // tiny layout hack
966
967                 print "</div>";
968
969                 print "<div class=\"dlgButtons\">";
970
971                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterNewActionDlg').execute()\">".
972                         ($action ? __("Save action") : __('Add action'))."</button> ";
973
974                 print "<button dojoType=\"dijit.form.Button\" onclick=\"return dijit.byId('filterNewActionDlg').hide()\">".
975                         __('Cancel')."</button>";
976
977                 print "</div>";
978
979                 print "</form>";
980         }
981
982         private function getFilterName($id) {
983
984                 $result = $this->dbh->query(
985                         "SELECT title,COUNT(DISTINCT r.id) AS num_rules,COUNT(DISTINCT a.id) AS num_actions
986                                 FROM ttrss_filters2 AS f LEFT JOIN ttrss_filters2_rules AS r
987                                         ON (r.filter_id = f.id)
988                                                 LEFT JOIN ttrss_filters2_actions AS a
989                                                         ON (a.filter_id = f.id) WHERE f.id = '$id' GROUP BY f.title");
990
991                 $title = $this->dbh->fetch_result($result, 0, "title");
992                 $num_rules = $this->dbh->fetch_result($result, 0, "num_rules");
993                 $num_actions = $this->dbh->fetch_result($result, 0, "num_actions");
994
995                 if (!$title) $title = __("[No caption]");
996
997                 $title = sprintf(_ngettext("%s (%d rule)", "%s (%d rules)", $num_rules), $title, $num_rules);
998
999                 $result = $this->dbh->query(
1000                         "SELECT * FROM ttrss_filters2_actions WHERE filter_id = '$id' ORDER BY id LIMIT 1");
1001
1002                 $actions = "";
1003
1004                 if ($this->dbh->num_rows($result) > 0) {
1005                         $line = $this->dbh->fetch_assoc($result);
1006                         $actions = $this->getActionName($line);
1007
1008                         $num_actions -= 1;
1009                 }
1010
1011                 if ($num_actions > 0)
1012                         $actions = sprintf(_ngettext("%s (+%d action)", "%s (+%d actions)", $num_actions), $actions, $num_actions);
1013
1014                 return array($title, $actions);
1015         }
1016
1017         function join() {
1018                 $ids = explode(",", $this->dbh->escape_string($_REQUEST["ids"]));
1019
1020                 if (count($ids) > 1) {
1021                         $base_id = array_shift($ids);
1022                         $ids_str = join(",", $ids);
1023
1024                         $this->dbh->query("BEGIN");
1025                         $this->dbh->query("UPDATE ttrss_filters2_rules
1026                                 SET filter_id = '$base_id' WHERE filter_id IN ($ids_str)");
1027                         $this->dbh->query("UPDATE ttrss_filters2_actions
1028                                 SET filter_id = '$base_id' WHERE filter_id IN ($ids_str)");
1029
1030                         $this->dbh->query("DELETE FROM ttrss_filters2 WHERE id IN ($ids_str)");
1031                         $this->dbh->query("UPDATE ttrss_filters2 SET match_any_rule = true WHERE id = '$base_id'");
1032
1033                         $this->dbh->query("COMMIT");
1034
1035                         $this->optimizeFilter($base_id);
1036
1037                 }
1038         }
1039
1040         private function optimizeFilter($id) {
1041                 $this->dbh->query("BEGIN");
1042                 $result = $this->dbh->query("SELECT * FROM ttrss_filters2_actions
1043                         WHERE filter_id = '$id'");
1044
1045                 $tmp = array();
1046                 $dupe_ids = array();
1047
1048                 while ($line = $this->dbh->fetch_assoc($result)) {
1049                         $id = $line["id"];
1050                         unset($line["id"]);
1051
1052                         if (array_search($line, $tmp) === false) {
1053                                 array_push($tmp, $line);
1054                         } else {
1055                                 array_push($dupe_ids, $id);
1056                         }
1057                 }
1058
1059                 if (count($dupe_ids) > 0) {
1060                         $ids_str = join(",", $dupe_ids);
1061                         $this->dbh->query("DELETE FROM ttrss_filters2_actions
1062                                 WHERE id IN ($ids_str)");
1063                 }
1064
1065                 $result = $this->dbh->query("SELECT * FROM ttrss_filters2_rules
1066                         WHERE filter_id = '$id'");
1067
1068                 $tmp = array();
1069                 $dupe_ids = array();
1070
1071                 while ($line = $this->dbh->fetch_assoc($result)) {
1072                         $id = $line["id"];
1073                         unset($line["id"]);
1074
1075                         if (array_search($line, $tmp) === false) {
1076                                 array_push($tmp, $line);
1077                         } else {
1078                                 array_push($dupe_ids, $id);
1079                         }
1080                 }
1081
1082                 if (count($dupe_ids) > 0) {
1083                         $ids_str = join(",", $dupe_ids);
1084                         $this->dbh->query("DELETE FROM ttrss_filters2_rules
1085                                 WHERE id IN ($ids_str)");
1086                 }
1087
1088                 $this->dbh->query("COMMIT");
1089         }
1090 }
1091 ?>