]> git.wh0rd.org Git - tt-rss.git/blob - classes/opml.php
OPML: use PDO; minor fixes
[tt-rss.git] / classes / opml.php
1 <?php
2 class Opml extends Handler_Protected {
3
4         function csrf_ignore($method) {
5                 $csrf_ignored = array("export", "import");
6
7                 return array_search($method, $csrf_ignored) !== false;
8         }
9
10         function export() {
11                 $output_name = $_REQUEST["filename"];
12                 if (!$output_name) $output_name = "TinyTinyRSS.opml";
13
14                 $show_settings = $_REQUEST["settings"];
15
16                 $owner_uid = $_SESSION["uid"];
17
18                 $rc = $this->opml_export($output_name, $owner_uid, false, ($show_settings == 1));
19
20                 return $rc;
21         }
22
23         function import() {
24                 $owner_uid = $_SESSION["uid"];
25
26                 header('Content-Type: text/html; charset=utf-8');
27
28                 print "<html>
29                         <head>
30                                 <link rel=\"stylesheet\" href=\"css/utility.css\" type=\"text/css\">
31                                 <title>".__("OPML Utility")."</title>
32                                 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
33                         </head>
34                         <body>
35                         <div class=\"floatingLogo\"><img src=\"images/logo_small.png\"></div>
36                         <h1>".__('OPML Utility')."</h1><div class='content'>";
37
38                 add_feed_category("Imported feeds");
39
40                 $this->opml_notice(__("Importing OPML..."));
41
42                 $this->opml_import($owner_uid);
43
44                 print "<br><form method=\"GET\" action=\"prefs.php\">
45                         <input type=\"submit\" value=\"".__("Return to preferences")."\">
46                         </form>";
47
48                 print "</div></body></html>";
49
50
51         }
52
53         // Export
54
55         private function opml_export_category($owner_uid, $cat_id, $hide_private_feeds=false) {
56
57                 $cat_id = (int) $cat_id;
58
59                 if ($hide_private_feeds)
60                         $hide_qpart = "(private IS false AND auth_login = '' AND auth_pass = '')";
61                 else
62                         $hide_qpart = "true";
63
64                 $out = "";
65
66                 if ($cat_id) {
67                         $sth = $this->pdo->prepare("SELECT title FROM ttrss_feed_categories WHERE id = ?
68                                 AND owner_uid = ?");
69                         $sth->execute([$cat_id, $owner_uid]);
70                         $row = $sth->fetch();
71                         $cat_title = htmlspecialchars($row['title']);
72                 }
73
74                 if ($cat_title) $out .= "<outline text=\"$cat_title\">\n";
75
76                 $sth = $this->pdo->prepare("SELECT id,title
77                         FROM ttrss_feed_categories WHERE
78                                 (parent_cat = :cat OR (:cat = 0 AND parent_cat IS NULL)) AND 
79                                 owner_uid = :uid ORDER BY order_id, title");
80
81                 $sth->execute([':cat' => $cat_id, ':uid' => $owner_uid]);
82
83                 while ($line = $sth->fetch()) {
84                         $out .= $this->opml_export_category($owner_uid, $line["id"], $hide_private_feeds);
85                 }
86
87                 $fsth = $this->pdo->prepare("select title, feed_url, site_url
88                                 FROM ttrss_feeds WHERE 
89                                         (cat_id = :cat OR (:cat = 0 AND cat_id IS NULL)) AND owner_uid = :uid AND $hide_qpart
90                                 ORDER BY order_id, title");
91
92                 $fsth->execute([':cat' => $cat_id, ':uid' => $owner_uid]);
93
94                 while ($fline = $fsth->fetch()) {
95                         $title = htmlspecialchars($fline["title"]);
96                         $url = htmlspecialchars($fline["feed_url"]);
97                         $site_url = htmlspecialchars($fline["site_url"]);
98
99                         if ($site_url) {
100                                 $html_url_qpart = "htmlUrl=\"$site_url\"";
101                         } else {
102                                 $html_url_qpart = "";
103                         }
104
105                         $out .= "<outline type=\"rss\" text=\"$title\" xmlUrl=\"$url\" $html_url_qpart/>\n";
106                 }
107
108                 if ($cat_title) $out .= "</outline>\n";
109
110                 return $out;
111         }
112
113         function opml_export($name, $owner_uid, $hide_private_feeds=false, $include_settings=true) {
114                 if (!$owner_uid) return;
115
116                 if (!isset($_REQUEST["debug"])) {
117                         header("Content-type: application/xml+opml");
118                         header("Content-Disposition: attachment; filename=" . $name );
119                 } else {
120                         header("Content-type: text/xml");
121                 }
122
123                 $out = "<?xml version=\"1.0\" encoding=\"utf-8\"?".">";
124
125                 $out .= "<opml version=\"1.0\">";
126                 $out .= "<head>
127                         <dateCreated>" . date("r", time()) . "</dateCreated>
128                         <title>Tiny Tiny RSS Feed Export</title>
129                 </head>";
130                 $out .= "<body>";
131
132                 $out .= $this->opml_export_category($owner_uid, 0, $hide_private_feeds);
133
134                 # export tt-rss settings
135
136                 if ($include_settings) {
137                         $out .= "<outline text=\"tt-rss-prefs\" schema-version=\"".SCHEMA_VERSION."\">";
138
139                         $sth = $this->pdo->prepare("SELECT pref_name, value FROM ttrss_user_prefs WHERE
140                            profile IS NULL AND owner_uid = ? ORDER BY pref_name");
141                         $sth->execute([$owner_uid]);
142
143                         while ($line = $sth->fetch()) {
144                                 $name = $line["pref_name"];
145                                 $value = htmlspecialchars($line["value"]);
146
147                                 $out .= "<outline pref-name=\"$name\" value=\"$value\"/>";
148                         }
149
150                         $out .= "</outline>";
151
152                         $out .= "<outline text=\"tt-rss-labels\" schema-version=\"".SCHEMA_VERSION."\">";
153
154                         $sth = $this->pdo->prepare("SELECT * FROM ttrss_labels2 WHERE
155                                 owner_uid = ?");
156                         $sth->execute([$owner_uid]);
157
158                         while ($line = $sth->fetch()) {
159                                 $name = htmlspecialchars($line['caption']);
160                                 $fg_color = htmlspecialchars($line['fg_color']);
161                                 $bg_color = htmlspecialchars($line['bg_color']);
162
163                                 $out .= "<outline label-name=\"$name\" label-fg-color=\"$fg_color\" label-bg-color=\"$bg_color\"/>";
164
165                         }
166
167                         $out .= "</outline>";
168
169                         $out .= "<outline text=\"tt-rss-filters\" schema-version=\"".SCHEMA_VERSION."\">";
170
171                         $sth = $this->pdo->prepare("SELECT * FROM ttrss_filters2
172                                 WHERE owner_uid = ? ORDER BY id");
173                         $sth->execute([$owner_uid]);
174
175                         while ($line = $sth->fetch()) {
176                                 foreach (array('enabled', 'match_any_rule', 'inverse') as $b) {
177                                         $line[$b] = sql_bool_to_bool($line[$b]);
178                                 }
179
180                                 $line["rules"] = array();
181                                 $line["actions"] = array();
182
183                                 $tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_rules
184                                         WHERE filter_id = ?");
185                                 $tmph->execute([$line['id']]);
186
187                                 while ($tmp_line = $tmph->fetch()) {
188                                         unset($tmp_line["id"]);
189                                         unset($tmp_line["filter_id"]);
190
191                                         $cat_filter = sql_bool_to_bool($tmp_line["cat_filter"]);
192
193                                         if (!$tmp_line["match_on"]) {
194                         if ($cat_filter && $tmp_line["cat_id"] || $tmp_line["feed_id"]) {
195                             $tmp_line["feed"] = Feeds::getFeedTitle(
196                                 $cat_filter ? $tmp_line["cat_id"] : $tmp_line["feed_id"],
197                                 $cat_filter);
198                         } else {
199                             $tmp_line["feed"] = "";
200                         }
201                     } else {
202                                             $match = [];
203                                             foreach (json_decode($tmp_line["match_on"], true) as $feed_id) {
204
205                             if (strpos($feed_id, "CAT:") === 0) {
206                                 $feed_id = (int)substr($feed_id, 4);
207                                 if ($feed_id) {
208                                     array_push($match, [Feeds::getCategoryTitle($feed_id), true, false]);
209                                 } else {
210                                     array_push($match, [0, true, true]);
211                                 }
212                             } else {
213                                 if ($feed_id) {
214                                     array_push($match, [Feeds::getFeedTitle((int)$feed_id), false, false]);
215                                 } else {
216                                     array_push($match, [0, false, true]);
217                                 }
218                             }
219                         }
220
221                         $tmp_line["match"] = $match;
222                                             unset($tmp_line["match_on"]);
223                     }
224
225                                         $tmp_line["cat_filter"] = sql_bool_to_bool($tmp_line["cat_filter"]);
226                                         $tmp_line["inverse"] = sql_bool_to_bool($tmp_line["inverse"]);
227
228                                         unset($tmp_line["feed_id"]);
229                                         unset($tmp_line["cat_id"]);
230
231                                         array_push($line["rules"], $tmp_line);
232                                 }
233
234                                 $tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_actions
235                                         WHERE filter_id = ?");
236                                 $tmph->execute([$line['id']]);
237
238                                 while ($tmp_line = $tmph->fetch()) {
239                                         unset($tmp_line["id"]);
240                                         unset($tmp_line["filter_id"]);
241
242                                         array_push($line["actions"], $tmp_line);
243                                 }
244
245                                 unset($line["id"]);
246                                 unset($line["owner_uid"]);
247                                 $filter = json_encode($line);
248
249                                 $out .= "<outline filter-type=\"2\"><![CDATA[$filter]]></outline>";
250
251                         }
252
253
254                         $out .= "</outline>";
255                 }
256
257                 $out .= "</body></opml>";
258
259                 // Format output.
260                 $doc = new DOMDocument();
261                 $doc->formatOutput = true;
262                 $doc->preserveWhiteSpace = false;
263                 $doc->loadXML($out);
264
265                 $xpath = new DOMXpath($doc);
266                 $outlines = $xpath->query("//outline[@title]");
267
268                 // cleanup empty categories
269                 foreach ($outlines as $node) {
270                         if ($node->getElementsByTagName('outline')->length == 0)
271                                 $node->parentNode->removeChild($node);
272                 }
273
274                 $res = $doc->saveXML();
275
276 /*              // saveXML uses a two-space indent.  Change to tabs.
277                 $res = preg_replace_callback('/^(?:  )+/mu',
278                         create_function(
279                                 '$matches',
280                                 'return str_repeat("\t", intval(strlen($matches[0])/2));'),
281                         $res); */
282
283                 print $res;
284         }
285
286         // Import
287
288         private function opml_import_feed($node, $cat_id, $owner_uid) {
289                 $attrs = $node->attributes;
290
291                 $feed_title = mb_substr($attrs->getNamedItem('text')->nodeValue, 0, 250);
292                 if (!$feed_title) $feed_title = mb_substr($attrs->getNamedItem('title')->nodeValue, 0, 250);
293
294                 $feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
295                 if (!$feed_url) $feed_url = $attrs->getNamedItem('xmlURL')->nodeValue;
296
297                 $site_url = mb_substr($attrs->getNamedItem('htmlUrl')->nodeValue, 0, 250);
298
299                 if ($feed_url && $feed_title) {
300                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
301                                 feed_url = ? AND owner_uid = ?");
302                         $sth->execute([$feed_url, $owner_uid]);
303
304                         if (!$sth->fetch()) {
305                                 #$this->opml_notice("[FEED] [$feed_title/$feed_url] dst_CAT=$cat_id");
306                                 $this->opml_notice(T_sprintf("Adding feed: %s", $feed_title));
307
308                                 if (!$cat_id) $cat_id = null;
309
310                                 $sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
311                                         (title, feed_url, owner_uid, cat_id, site_url, order_id) VALUES
312                                         (?, ?, ?, ?, ?, 0)");
313
314                                 $sth->execute([$feed_title, $feed_url, $owner_uid, $cat_id, $site_url]);
315
316                         } else {
317                                 $this->opml_notice(T_sprintf("Duplicate feed: %s", $feed_title));
318                         }
319                 }
320         }
321
322         private function opml_import_label($node, $owner_uid) {
323                 $attrs = $node->attributes;
324                 $label_name = $attrs->getNamedItem('label-name')->nodeValue;
325
326                 if ($label_name) {
327                         $fg_color = $attrs->getNamedItem('label-fg-color')->nodeValue;
328                         $bg_color = $attrs->getNamedItem('label-bg-color')->nodeValue;
329
330                         if (!Labels::find_id($label_name, $_SESSION['uid'])) {
331                                 $this->opml_notice(T_sprintf("Adding label %s", htmlspecialchars($label_name)));
332                                 Labels::create($label_name, $fg_color, $bg_color, $owner_uid);
333                         } else {
334                                 $this->opml_notice(T_sprintf("Duplicate label: %s", htmlspecialchars($label_name)));
335                         }
336                 }
337         }
338
339         private function opml_import_preference($node) {
340                 $attrs = $node->attributes;
341                 $pref_name = $attrs->getNamedItem('pref-name')->nodeValue;
342
343                 if ($pref_name) {
344                         $pref_value = $attrs->getNamedItem('value')->nodeValue;
345
346                         $this->opml_notice(T_sprintf("Setting preference key %s to %s",
347                                 $pref_name, $pref_value));
348
349                         set_pref($pref_name, $pref_value);
350                 }
351         }
352
353         private function opml_import_filter($node) {
354                 $attrs = $node->attributes;
355
356                 $filter_type = $attrs->getNamedItem('filter-type')->nodeValue;
357
358                 if ($filter_type == '2') {
359                         $filter = json_decode($node->nodeValue, true);
360
361                         if ($filter) {
362                                 $match_any_rule = bool_to_sql_bool($filter["match_any_rule"]);
363                                 $enabled = bool_to_sql_bool($filter["enabled"]);
364                                 $inverse = bool_to_sql_bool($filter["inverse"]);
365                                 $title = $filter["title"];
366
367                                 $sth = $this->pdo->prepare("INSERT INTO ttrss_filters2 (match_any_rule,enabled,inverse,title,owner_uid)
368                                         VALUES (?, ?, ?, ?, ?)");
369
370                                 $sth->execute([$match_any_rule, $enabled, $inverse, $title, $_SESSION['uid']]);
371
372                                 $sth = $this->pdo->prepare("SELECT MAX(id) AS id FROM ttrss_filters2 WHERE
373                                         owner_uid = ?");
374                                 $sth->execute([$_SESSION['uid']]);
375
376                                 $row = $sth->fetch();
377                                 $filter_id = $row['id'];
378
379                                 if ($filter_id) {
380                                         $this->opml_notice(T_sprintf("Adding filter..."));
381
382                                         foreach ($filter["rules"] as $rule) {
383                                                 $feed_id = null;
384                                                 $cat_id = null;
385
386                                                 if ($rule["match"]) {
387
388                             $match_on = [];
389
390                                                     foreach ($rule["match"] as $match) {
391                                                         list ($name, $is_cat, $is_id) = $match;
392
393                                                         if ($is_id) {
394                                                             array_push($match_on, ($is_cat ? "CAT:" : "") . $name);
395                                 } else {
396
397                                                             $match_id = false;
398
399                                     if (!$is_cat) {
400                                         $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
401                                                 WHERE title = ? AND owner_uid = ?");
402
403                                         $tsth->execute([$name, $_SESSION['uid']]);
404
405                                         if ($row = $tsth->fetch()) {
406                                             $match_id = $row['id'];
407                                         }
408                                     } else {
409                                         $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
410                                                 WHERE title = ? AND owner_uid = ?");
411                                                                                 $tsth->execute([$name, $_SESSION['uid']]);
412
413                                                                                 if ($row = $tsth->fetch()) {
414                                                                                         $match_id = $row['id'];
415                                                                                 }
416                                     }
417
418                                     if ($match_id) array_push($match_on, $match_id);
419                                 }
420                             }
421
422                             $reg_exp = $rule["reg_exp"];
423                             $filter_type = (int)$rule["filter_type"];
424                             $inverse = bool_to_sql_bool($rule["inverse"]);
425                             $match_on = json_encode($match_on);
426
427                             $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules 
428                                                                 (feed_id,cat_id,match_on,filter_id,filter_type,reg_exp,cat_filter,inverse)
429                                 VALUES 
430                                 (NULL, NULL, ?, ?, ?, ?, false, ?)");
431                             $usth->execute([$match_on, $filter_id, $filter_type, $reg_exp, $inverse]);
432
433                         } else {
434
435                             if (!$rule["cat_filter"]) {
436                                 $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
437                                     WHERE title = ? AND owner_uid = ?");
438
439                                 $tsth->execute([$rule['feed'], $_SESSION['uid']]);
440
441                                 if ($row = $tsth->fetch()) {
442                                     $feed_id = $row['id'];
443                                 }
444                             } else {
445                                                                 $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
446                                     WHERE title = ? AND owner_uid = ?");
447
448                                                                 $tsth->execute([$rule['feed'], $_SESSION['uid']]);
449
450                                                                 if ($row = $tsth->fetch()) {
451                                                                         $feed_id = $row['id'];
452                                                                 }
453                             }
454
455                             $cat_filter = bool_to_sql_bool($rule["cat_filter"]);
456                             $reg_exp = $rule["reg_exp"];
457                             $filter_type = (int)$rule["filter_type"];
458                             $inverse = bool_to_sql_bool($rule["inverse"]);
459
460                             $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules 
461                                                                 (feed_id,cat_id,filter_id,filter_type,reg_exp,cat_filter,inverse)
462                                 VALUES 
463                                 (?, ?, ?, ?, ?, ?, ?)");
464                             $usth->execute([$feed_id, $cat_id, $filter_id, $filter_type, $reg_exp, $cat_filter, $inverse]);
465                         }
466                                         }
467
468                                         foreach ($filter["actions"] as $action) {
469
470                                                 $action_id = (int)$action["action_id"];
471                                                 $action_param = $action["action_param"];
472
473                                                 $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_actions 
474                                                         (filter_id,action_id,action_param)
475                                                         VALUES 
476                                                         (?, ?, ?)");
477                                                 $usth->execute([$filter_id, $action_id, $action_param]);
478                                         }
479                                 }
480                         }
481                 }
482         }
483
484         private function opml_import_category($doc, $root_node, $owner_uid, $parent_id) {
485                 $default_cat_id = (int) $this->get_feed_category('Imported feeds', false);
486
487                 if ($root_node) {
488                         $cat_title = mb_substr($root_node->attributes->getNamedItem('text')->nodeValue, 0, 250);
489
490                         if (!$cat_title)
491                                 $cat_title = mb_substr($root_node->attributes->getNamedItem('title')->nodeValue, 0, 250);
492
493                         if (!in_array($cat_title, array("tt-rss-filters", "tt-rss-labels", "tt-rss-prefs"))) {
494                                 $cat_id = $this->get_feed_category($cat_title, $parent_id);
495
496                                 if ($cat_id === false) {
497                                         add_feed_category($cat_title, $parent_id);
498                                         $cat_id = $this->get_feed_category($cat_title, $parent_id);
499                                 }
500
501                         } else {
502                                 $cat_id = 0;
503                         }
504
505                         $outlines = $root_node->childNodes;
506
507                 } else {
508                         $xpath = new DOMXpath($doc);
509                         $outlines = $xpath->query("//opml/body/outline");
510
511                         $cat_id = 0;
512                 }
513
514                 #$this->opml_notice("[CAT] $cat_title id: $cat_id P_id: $parent_id");
515                 $this->opml_notice(T_sprintf("Processing category: %s", $cat_title ? $cat_title : __("Uncategorized")));
516
517                 foreach ($outlines as $node) {
518                         if ($node->hasAttributes() && strtolower($node->tagName) == "outline") {
519                                 $attrs = $node->attributes;
520                                 $node_cat_title = $attrs->getNamedItem('text')->nodeValue;
521
522                                 if (!$node_cat_title)
523                                         $node_cat_title = $attrs->getNamedItem('title')->nodeValue;
524
525                                 $node_feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
526
527                                 if ($node_cat_title && !$node_feed_url) {
528                                         $this->opml_import_category($doc, $node, $owner_uid, $cat_id);
529                                 } else {
530
531                                         if (!$cat_id) {
532                                                 $dst_cat_id = $default_cat_id;
533                                         } else {
534                                                 $dst_cat_id = $cat_id;
535                                         }
536
537                                         switch ($cat_title) {
538                                         case "tt-rss-prefs":
539                                                 $this->opml_import_preference($node);
540                                                 break;
541                                         case "tt-rss-labels":
542                                                 $this->opml_import_label($node, $owner_uid);
543                                                 break;
544                                         case "tt-rss-filters":
545                                                 $this->opml_import_filter($node);
546                                                 break;
547                                         default:
548                                                 $this->opml_import_feed($node, $dst_cat_id, $owner_uid);
549                                         }
550                                 }
551                         }
552                 }
553         }
554
555         function opml_import($owner_uid) {
556                 if (!$owner_uid) return;
557
558                 $doc = false;
559
560                 if ($_FILES['opml_file']['error'] != 0) {
561                         print_error(T_sprintf("Upload failed with error code %d",
562                                 $_FILES['opml_file']['error']));
563                         return;
564                 }
565
566                 if (is_uploaded_file($_FILES['opml_file']['tmp_name'])) {
567                         $tmp_file = tempnam(CACHE_DIR . '/upload', 'opml');
568
569                         $result = move_uploaded_file($_FILES['opml_file']['tmp_name'],
570                                 $tmp_file);
571
572                         if (!$result) {
573                                 print_error(__("Unable to move uploaded file."));
574                                 return;
575                         }
576                 } else {
577                         print_error(__('Error: please upload OPML file.'));
578                         return;
579                 }
580
581                 if (is_file($tmp_file)) {
582                         $doc = new DOMDocument();
583                         libxml_disable_entity_loader(false);
584                         $doc->load($tmp_file);
585                         libxml_disable_entity_loader(true);
586                         unlink($tmp_file);
587                 } else if (!$doc) {
588                         print_error(__('Error: unable to find moved OPML file.'));
589                         return;
590                 }
591
592                 if ($doc) {
593                         $this->pdo->beginTransaction();
594                         $this->opml_import_category($doc, false, $owner_uid, false);
595                         $this->pdo->commit();
596                 } else {
597                         print_error(__('Error while parsing document.'));
598                 }
599         }
600
601         private function opml_notice($msg) {
602                 print "$msg<br/>";
603         }
604
605         static function opml_publish_url(){
606
607                 $url_path = get_self_url_prefix();
608                 $url_path .= "/opml.php?op=publish&key=" .
609                         get_feed_access_key('OPML:Publish', false, $_SESSION["uid"]);
610
611                 return $url_path;
612         }
613
614         function get_feed_category($feed_cat, $parent_cat_id = false) {
615
616                 $parent_cat_id = (int) $parent_cat_id;
617
618                 $sth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
619                         WHERE title = :title 
620                         AND (parent_cat = :parent OR (:parent = 0 AND parent_cat IS NULL))
621                         AND owner_uid = :uid");
622
623                 $sth->execute([':title' => $feed_cat, ':parent' => $parent_cat_id, ':uid' => $_SESSION['uid']]);
624
625                 if ($row = $sth->fetch()) {
626                         return $row['id'];
627                 } else {
628                         return false;
629                 }
630         }
631
632
633 }