]> git.wh0rd.org Git - tt-rss.git/blob - classes/opml.php
further stylesheet simplification related 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                                 ".stylesheet_tag("css/default.css")."
31                                 <title>".__("OPML Utility")."</title>
32                                 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
33                         </head>
34                         <body class='claro ttrss_utility'>
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                                 $line["rules"] = array();
177                                 $line["actions"] = array();
178
179                                 $tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_rules
180                                         WHERE filter_id = ?");
181                                 $tmph->execute([$line['id']]);
182
183                                 while ($tmp_line = $tmph->fetch()) {
184                                         unset($tmp_line["id"]);
185                                         unset($tmp_line["filter_id"]);
186
187                                         $cat_filter = $tmp_line["cat_filter"];
188
189                                         if (!$tmp_line["match_on"]) {
190                         if ($cat_filter && $tmp_line["cat_id"] || $tmp_line["feed_id"]) {
191                             $tmp_line["feed"] = Feeds::getFeedTitle(
192                                 $cat_filter ? $tmp_line["cat_id"] : $tmp_line["feed_id"],
193                                 $cat_filter);
194                         } else {
195                             $tmp_line["feed"] = "";
196                         }
197                     } else {
198                                             $match = [];
199                                             foreach (json_decode($tmp_line["match_on"], true) as $feed_id) {
200
201                             if (strpos($feed_id, "CAT:") === 0) {
202                                 $feed_id = (int)substr($feed_id, 4);
203                                 if ($feed_id) {
204                                     array_push($match, [Feeds::getCategoryTitle($feed_id), true, false]);
205                                 } else {
206                                     array_push($match, [0, true, true]);
207                                 }
208                             } else {
209                                 if ($feed_id) {
210                                     array_push($match, [Feeds::getFeedTitle((int)$feed_id), false, false]);
211                                 } else {
212                                     array_push($match, [0, false, true]);
213                                 }
214                             }
215                         }
216
217                         $tmp_line["match"] = $match;
218                                             unset($tmp_line["match_on"]);
219                     }
220
221                                         unset($tmp_line["feed_id"]);
222                                         unset($tmp_line["cat_id"]);
223
224                                         array_push($line["rules"], $tmp_line);
225                                 }
226
227                                 $tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_actions
228                                         WHERE filter_id = ?");
229                                 $tmph->execute([$line['id']]);
230
231                                 while ($tmp_line = $tmph->fetch()) {
232                                         unset($tmp_line["id"]);
233                                         unset($tmp_line["filter_id"]);
234
235                                         array_push($line["actions"], $tmp_line);
236                                 }
237
238                                 unset($line["id"]);
239                                 unset($line["owner_uid"]);
240                                 $filter = json_encode($line);
241
242                                 $out .= "<outline filter-type=\"2\"><![CDATA[$filter]]></outline>";
243
244                         }
245
246
247                         $out .= "</outline>";
248                 }
249
250                 $out .= "</body></opml>";
251
252                 // Format output.
253                 $doc = new DOMDocument();
254                 $doc->formatOutput = true;
255                 $doc->preserveWhiteSpace = false;
256                 $doc->loadXML($out);
257
258                 $xpath = new DOMXpath($doc);
259                 $outlines = $xpath->query("//outline[@title]");
260
261                 // cleanup empty categories
262                 foreach ($outlines as $node) {
263                         if ($node->getElementsByTagName('outline')->length == 0)
264                                 $node->parentNode->removeChild($node);
265                 }
266
267                 $res = $doc->saveXML();
268
269 /*              // saveXML uses a two-space indent.  Change to tabs.
270                 $res = preg_replace_callback('/^(?:  )+/mu',
271                         create_function(
272                                 '$matches',
273                                 'return str_repeat("\t", intval(strlen($matches[0])/2));'),
274                         $res); */
275
276                 print $res;
277         }
278
279         // Import
280
281         private function opml_import_feed($node, $cat_id, $owner_uid) {
282                 $attrs = $node->attributes;
283
284                 $feed_title = mb_substr($attrs->getNamedItem('text')->nodeValue, 0, 250);
285                 if (!$feed_title) $feed_title = mb_substr($attrs->getNamedItem('title')->nodeValue, 0, 250);
286
287                 $feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
288                 if (!$feed_url) $feed_url = $attrs->getNamedItem('xmlURL')->nodeValue;
289
290                 $site_url = mb_substr($attrs->getNamedItem('htmlUrl')->nodeValue, 0, 250);
291
292                 if ($feed_url && $feed_title) {
293                         $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
294                                 feed_url = ? AND owner_uid = ?");
295                         $sth->execute([$feed_url, $owner_uid]);
296
297                         if (!$sth->fetch()) {
298                                 #$this->opml_notice("[FEED] [$feed_title/$feed_url] dst_CAT=$cat_id");
299                                 $this->opml_notice(T_sprintf("Adding feed: %s", $feed_title));
300
301                                 if (!$cat_id) $cat_id = null;
302
303                                 $sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
304                                         (title, feed_url, owner_uid, cat_id, site_url, order_id) VALUES
305                                         (?, ?, ?, ?, ?, 0)");
306
307                                 $sth->execute([$feed_title, $feed_url, $owner_uid, $cat_id, $site_url]);
308
309                         } else {
310                                 $this->opml_notice(T_sprintf("Duplicate feed: %s", $feed_title));
311                         }
312                 }
313         }
314
315         private function opml_import_label($node, $owner_uid) {
316                 $attrs = $node->attributes;
317                 $label_name = $attrs->getNamedItem('label-name')->nodeValue;
318
319                 if ($label_name) {
320                         $fg_color = $attrs->getNamedItem('label-fg-color')->nodeValue;
321                         $bg_color = $attrs->getNamedItem('label-bg-color')->nodeValue;
322
323                         if (!Labels::find_id($label_name, $_SESSION['uid'])) {
324                                 $this->opml_notice(T_sprintf("Adding label %s", htmlspecialchars($label_name)));
325                                 Labels::create($label_name, $fg_color, $bg_color, $owner_uid);
326                         } else {
327                                 $this->opml_notice(T_sprintf("Duplicate label: %s", htmlspecialchars($label_name)));
328                         }
329                 }
330         }
331
332         private function opml_import_preference($node) {
333                 $attrs = $node->attributes;
334                 $pref_name = $attrs->getNamedItem('pref-name')->nodeValue;
335
336                 if ($pref_name) {
337                         $pref_value = $attrs->getNamedItem('value')->nodeValue;
338
339                         $this->opml_notice(T_sprintf("Setting preference key %s to %s",
340                                 $pref_name, $pref_value));
341
342                         set_pref($pref_name, $pref_value);
343                 }
344         }
345
346         private function opml_import_filter($node) {
347                 $attrs = $node->attributes;
348
349                 $filter_type = $attrs->getNamedItem('filter-type')->nodeValue;
350
351                 if ($filter_type == '2') {
352                         $filter = json_decode($node->nodeValue, true);
353
354                         if ($filter) {
355                                 $match_any_rule = bool_to_sql_bool($filter["match_any_rule"]);
356                                 $enabled = bool_to_sql_bool($filter["enabled"]);
357                                 $inverse = bool_to_sql_bool($filter["inverse"]);
358                                 $title = $filter["title"];
359
360                                 print "F: $title, $inverse, $enabled, $match_any_rule";
361
362                                 $sth = $this->pdo->prepare("INSERT INTO ttrss_filters2 (match_any_rule,enabled,inverse,title,owner_uid)
363                                         VALUES (?, ?, ?, ?, ?)");
364
365                                 $sth->execute([$match_any_rule, $enabled, $inverse, $title, $_SESSION['uid']]);
366
367                                 $sth = $this->pdo->prepare("SELECT MAX(id) AS id FROM ttrss_filters2 WHERE
368                                         owner_uid = ?");
369                                 $sth->execute([$_SESSION['uid']]);
370
371                                 $row = $sth->fetch();
372                                 $filter_id = $row['id'];
373
374                                 if ($filter_id) {
375                                         $this->opml_notice(T_sprintf("Adding filter..."));
376
377                                         foreach ($filter["rules"] as $rule) {
378                                                 $feed_id = null;
379                                                 $cat_id = null;
380
381                                                 if ($rule["match"]) {
382
383                             $match_on = [];
384
385                                                     foreach ($rule["match"] as $match) {
386                                                         list ($name, $is_cat, $is_id) = $match;
387
388                                                         if ($is_id) {
389                                                             array_push($match_on, ($is_cat ? "CAT:" : "") . $name);
390                                 } else {
391
392                                                             $match_id = false;
393
394                                     if (!$is_cat) {
395                                         $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
396                                                 WHERE title = ? AND owner_uid = ?");
397
398                                         $tsth->execute([$name, $_SESSION['uid']]);
399
400                                         if ($row = $tsth->fetch()) {
401                                             $match_id = $row['id'];
402                                         }
403                                     } else {
404                                         $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
405                                                 WHERE title = ? AND owner_uid = ?");
406                                                                                 $tsth->execute([$name, $_SESSION['uid']]);
407
408                                                                                 if ($row = $tsth->fetch()) {
409                                                                                         $match_id = $row['id'];
410                                                                                 }
411                                     }
412
413                                     if ($match_id) array_push($match_on, $match_id);
414                                 }
415                             }
416
417                             $reg_exp = $rule["reg_exp"];
418                             $filter_type = (int)$rule["filter_type"];
419                             $inverse = bool_to_sql_bool($rule["inverse"]);
420                             $match_on = json_encode($match_on);
421
422                             $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules 
423                                                                 (feed_id,cat_id,match_on,filter_id,filter_type,reg_exp,cat_filter,inverse)
424                                 VALUES 
425                                 (NULL, NULL, ?, ?, ?, ?, false, ?)");
426                             $usth->execute([$match_on, $filter_id, $filter_type, $reg_exp, $inverse]);
427
428                         } else {
429
430                             if (!$rule["cat_filter"]) {
431                                 $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
432                                     WHERE title = ? AND owner_uid = ?");
433
434                                 $tsth->execute([$rule['feed'], $_SESSION['uid']]);
435
436                                 if ($row = $tsth->fetch()) {
437                                     $feed_id = $row['id'];
438                                 }
439                             } else {
440                                                                 $tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
441                                     WHERE title = ? AND owner_uid = ?");
442
443                                                                 $tsth->execute([$rule['feed'], $_SESSION['uid']]);
444
445                                                                 if ($row = $tsth->fetch()) {
446                                                                         $feed_id = $row['id'];
447                                                                 }
448                             }
449
450                             $cat_filter = bool_to_sql_bool($rule["cat_filter"]);
451                             $reg_exp = $rule["reg_exp"];
452                             $filter_type = (int)$rule["filter_type"];
453                             $inverse = bool_to_sql_bool($rule["inverse"]);
454
455                             $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules 
456                                                                 (feed_id,cat_id,filter_id,filter_type,reg_exp,cat_filter,inverse)
457                                 VALUES 
458                                 (?, ?, ?, ?, ?, ?, ?)");
459                             $usth->execute([$feed_id, $cat_id, $filter_id, $filter_type, $reg_exp, $cat_filter, $inverse]);
460                         }
461                                         }
462
463                                         foreach ($filter["actions"] as $action) {
464
465                                                 $action_id = (int)$action["action_id"];
466                                                 $action_param = $action["action_param"];
467
468                                                 $usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_actions 
469                                                         (filter_id,action_id,action_param)
470                                                         VALUES 
471                                                         (?, ?, ?)");
472                                                 $usth->execute([$filter_id, $action_id, $action_param]);
473                                         }
474                                 }
475                         }
476                 }
477         }
478
479         private function opml_import_category($doc, $root_node, $owner_uid, $parent_id) {
480                 $default_cat_id = (int) $this->get_feed_category('Imported feeds', false);
481
482                 if ($root_node) {
483                         $cat_title = mb_substr($root_node->attributes->getNamedItem('text')->nodeValue, 0, 250);
484
485                         if (!$cat_title)
486                                 $cat_title = mb_substr($root_node->attributes->getNamedItem('title')->nodeValue, 0, 250);
487
488                         if (!in_array($cat_title, array("tt-rss-filters", "tt-rss-labels", "tt-rss-prefs"))) {
489                                 $cat_id = $this->get_feed_category($cat_title, $parent_id);
490
491                                 if ($cat_id === false) {
492                                         add_feed_category($cat_title, $parent_id);
493                                         $cat_id = $this->get_feed_category($cat_title, $parent_id);
494                                 }
495
496                         } else {
497                                 $cat_id = 0;
498                         }
499
500                         $outlines = $root_node->childNodes;
501
502                 } else {
503                         $xpath = new DOMXpath($doc);
504                         $outlines = $xpath->query("//opml/body/outline");
505
506                         $cat_id = 0;
507                 }
508
509                 #$this->opml_notice("[CAT] $cat_title id: $cat_id P_id: $parent_id");
510                 $this->opml_notice(T_sprintf("Processing category: %s", $cat_title ? $cat_title : __("Uncategorized")));
511
512                 foreach ($outlines as $node) {
513                         if ($node->hasAttributes() && strtolower($node->tagName) == "outline") {
514                                 $attrs = $node->attributes;
515                                 $node_cat_title = $attrs->getNamedItem('text')->nodeValue;
516
517                                 if (!$node_cat_title)
518                                         $node_cat_title = $attrs->getNamedItem('title')->nodeValue;
519
520                                 $node_feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
521
522                                 if ($node_cat_title && !$node_feed_url) {
523                                         $this->opml_import_category($doc, $node, $owner_uid, $cat_id);
524                                 } else {
525
526                                         if (!$cat_id) {
527                                                 $dst_cat_id = $default_cat_id;
528                                         } else {
529                                                 $dst_cat_id = $cat_id;
530                                         }
531
532                                         switch ($cat_title) {
533                                         case "tt-rss-prefs":
534                                                 $this->opml_import_preference($node);
535                                                 break;
536                                         case "tt-rss-labels":
537                                                 $this->opml_import_label($node, $owner_uid);
538                                                 break;
539                                         case "tt-rss-filters":
540                                                 $this->opml_import_filter($node);
541                                                 break;
542                                         default:
543                                                 $this->opml_import_feed($node, $dst_cat_id, $owner_uid);
544                                         }
545                                 }
546                         }
547                 }
548         }
549
550         function opml_import($owner_uid) {
551                 if (!$owner_uid) return;
552
553                 $doc = false;
554
555                 if ($_FILES['opml_file']['error'] != 0) {
556                         print_error(T_sprintf("Upload failed with error code %d",
557                                 $_FILES['opml_file']['error']));
558                         return;
559                 }
560
561                 if (is_uploaded_file($_FILES['opml_file']['tmp_name'])) {
562                         $tmp_file = tempnam(CACHE_DIR . '/upload', 'opml');
563
564                         $result = move_uploaded_file($_FILES['opml_file']['tmp_name'],
565                                 $tmp_file);
566
567                         if (!$result) {
568                                 print_error(__("Unable to move uploaded file."));
569                                 return;
570                         }
571                 } else {
572                         print_error(__('Error: please upload OPML file.'));
573                         return;
574                 }
575
576                 if (is_file($tmp_file)) {
577                         $doc = new DOMDocument();
578                         libxml_disable_entity_loader(false);
579                         $doc->load($tmp_file);
580                         libxml_disable_entity_loader(true);
581                         unlink($tmp_file);
582                 } else if (!$doc) {
583                         print_error(__('Error: unable to find moved OPML file.'));
584                         return;
585                 }
586
587                 if ($doc) {
588                         $this->pdo->beginTransaction();
589                         $this->opml_import_category($doc, false, $owner_uid, false);
590                         $this->pdo->commit();
591                 } else {
592                         print_error(__('Error while parsing document.'));
593                 }
594         }
595
596         private function opml_notice($msg) {
597                 print "$msg<br/>";
598         }
599
600         static function opml_publish_url(){
601
602                 $url_path = get_self_url_prefix();
603                 $url_path .= "/opml.php?op=publish&key=" .
604                         get_feed_access_key('OPML:Publish', false, $_SESSION["uid"]);
605
606                 return $url_path;
607         }
608
609         function get_feed_category($feed_cat, $parent_cat_id = false) {
610
611                 $parent_cat_id = (int) $parent_cat_id;
612
613                 $sth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
614                         WHERE title = :title 
615                         AND (parent_cat = :parent OR (:parent = 0 AND parent_cat IS NULL))
616                         AND owner_uid = :uid");
617
618                 $sth->execute([':title' => $feed_cat, ':parent' => $parent_cat_id, ':uid' => $_SESSION['uid']]);
619
620                 if ($row = $sth->fetch()) {
621                         return $row['id'];
622                 } else {
623                         return false;
624                 }
625         }
626
627
628 }