opml.php 19 KB

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