init.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. <?php
  2. class Import_Export extends Plugin implements IHandler {
  3. private $host;
  4. function init($host) {
  5. $this->host = $host;
  6. $host->add_hook($host::HOOK_PREFS_TAB, $this);
  7. $host->add_command("xml-import", "import articles from XML", $this, ":", "FILE");
  8. }
  9. function about() {
  10. return array(1.0,
  11. "Imports and exports user data using neutral XML format",
  12. "fox");
  13. }
  14. private function bool_to_sql_bool($s) {
  15. return $s ? 'true' : 'false';
  16. }
  17. function xml_import($args) {
  18. $filename = $args['xml_import'];
  19. if (!is_file($filename)) {
  20. print "error: input filename ($filename) doesn't exist.\n";
  21. return;
  22. }
  23. _debug("please enter your username:");
  24. $username = db_escape_string(trim(read_stdin()));
  25. _debug("importing $filename for user $username...\n");
  26. $result = db_query("SELECT id FROM ttrss_users WHERE login = '$username'");
  27. if (db_num_rows($result) == 0) {
  28. print "error: could not find user $username.\n";
  29. return;
  30. }
  31. $owner_uid = db_fetch_result($result, 0, "id");
  32. $this->perform_data_import($filename, $owner_uid);
  33. }
  34. function save() {
  35. $example_value = db_escape_string($_POST["example_value"]);
  36. echo "Value set to $example_value (not really)";
  37. }
  38. function get_prefs_js() {
  39. return file_get_contents(dirname(__FILE__) . "/import_export.js");
  40. }
  41. function hook_prefs_tab($args) {
  42. if ($args != "prefFeeds") return;
  43. print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Import and export')."\">";
  44. print_notice(__("You can export and import your Starred and Archived articles for safekeeping or when migrating between tt-rss instances of same version."));
  45. print "<p>";
  46. print "<button dojoType=\"dijit.form.Button\" onclick=\"return exportData()\">".
  47. __('Export my data')."</button> ";
  48. print "<hr>";
  49. print "<iframe id=\"data_upload_iframe\"
  50. name=\"data_upload_iframe\" onload=\"dataImportComplete(this)\"
  51. style=\"width: 400px; height: 100px; display: none;\"></iframe>";
  52. print "<form name=\"import_form\" style='display : block' target=\"data_upload_iframe\"
  53. enctype=\"multipart/form-data\" method=\"POST\"
  54. action=\"backend.php\">
  55. <input id=\"export_file\" name=\"export_file\" type=\"file\">&nbsp;
  56. <input type=\"hidden\" name=\"op\" value=\"pluginhandler\">
  57. <input type=\"hidden\" name=\"plugin\" value=\"import_export\">
  58. <input type=\"hidden\" name=\"method\" value=\"dataimport\">
  59. <button dojoType=\"dijit.form.Button\" onclick=\"return importData();\" type=\"submit\">" .
  60. __('Import') . "</button>";
  61. print "</form>";
  62. print "</p>";
  63. print "</div>"; # pane
  64. }
  65. function csrf_ignore($method) {
  66. return in_array($method, array("exportget"));
  67. }
  68. /**
  69. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  70. */
  71. function before($method) {
  72. return $_SESSION["uid"] != false;
  73. }
  74. function after() {
  75. return true;
  76. }
  77. /**
  78. * @SuppressWarnings(unused)
  79. */
  80. function exportget() {
  81. $exportname = CACHE_DIR . "/export/" .
  82. sha1($_SESSION['uid'] . $_SESSION['login']) . ".xml";
  83. if (file_exists($exportname)) {
  84. header("Content-type: text/xml");
  85. $timestamp_suffix = date("Y-m-d", filemtime($exportname));
  86. if (function_exists('gzencode')) {
  87. header("Content-Disposition: attachment; filename=TinyTinyRSS_exported_${timestamp_suffix}.xml.gz");
  88. echo gzencode(file_get_contents($exportname));
  89. } else {
  90. header("Content-Disposition: attachment; filename=TinyTinyRSS_exported_${timestamp_suffix}.xml");
  91. echo file_get_contents($exportname);
  92. }
  93. } else {
  94. echo "File not found.";
  95. }
  96. }
  97. function exportrun() {
  98. $offset = (int) db_escape_string($_REQUEST['offset']);
  99. $exported = 0;
  100. $limit = 250;
  101. if ($offset < 10000 && is_writable(CACHE_DIR . "/export")) {
  102. $result = db_query("SELECT
  103. ttrss_entries.guid,
  104. ttrss_entries.title,
  105. content,
  106. marked,
  107. published,
  108. score,
  109. note,
  110. link,
  111. tag_cache,
  112. label_cache,
  113. ttrss_feeds.title AS feed_title,
  114. ttrss_feeds.feed_url AS feed_url,
  115. ttrss_entries.updated
  116. FROM
  117. ttrss_user_entries LEFT JOIN ttrss_feeds ON (ttrss_feeds.id = feed_id),
  118. ttrss_entries
  119. WHERE
  120. (marked = true OR feed_id IS NULL) AND
  121. ref_id = ttrss_entries.id AND
  122. ttrss_user_entries.owner_uid = " . $_SESSION['uid'] . "
  123. ORDER BY ttrss_entries.id LIMIT $limit OFFSET $offset");
  124. $exportname = sha1($_SESSION['uid'] . $_SESSION['login']);
  125. if ($offset == 0) {
  126. $fp = fopen(CACHE_DIR . "/export/$exportname.xml", "w");
  127. fputs($fp, "<articles schema-version=\"".SCHEMA_VERSION."\">");
  128. } else {
  129. $fp = fopen(CACHE_DIR . "/export/$exportname.xml", "a");
  130. }
  131. if ($fp) {
  132. while ($line = db_fetch_assoc($result)) {
  133. fputs($fp, "<article>");
  134. foreach ($line as $k => $v) {
  135. $v = str_replace("]]>", "]]]]><![CDATA[>", $v);
  136. fputs($fp, "<$k><![CDATA[$v]]></$k>");
  137. }
  138. fputs($fp, "</article>");
  139. }
  140. $exported = db_num_rows($result);
  141. if ($exported < $limit && $exported > 0) {
  142. fputs($fp, "</articles>");
  143. }
  144. fclose($fp);
  145. }
  146. }
  147. print json_encode(array("exported" => $exported));
  148. }
  149. function perform_data_import($filename, $owner_uid) {
  150. $num_imported = 0;
  151. $num_processed = 0;
  152. $num_feeds_created = 0;
  153. libxml_disable_entity_loader(false);
  154. $doc = @DOMDocument::load($filename);
  155. if (!$doc) {
  156. $contents = file_get_contents($filename);
  157. if ($contents) {
  158. $data = @gzuncompress($contents);
  159. }
  160. if (!$data) {
  161. $data = @gzdecode($contents);
  162. }
  163. if ($data)
  164. $doc = DOMDocument::loadXML($data);
  165. }
  166. libxml_disable_entity_loader(true);
  167. if ($doc) {
  168. $xpath = new DOMXpath($doc);
  169. $container = $doc->firstChild;
  170. if ($container && $container->hasAttribute('schema-version')) {
  171. $schema_version = $container->getAttribute('schema-version');
  172. if ($schema_version != SCHEMA_VERSION) {
  173. print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
  174. return;
  175. }
  176. } else {
  177. print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
  178. return;
  179. }
  180. $articles = $xpath->query("//article");
  181. foreach ($articles as $article_node) {
  182. if ($article_node->childNodes) {
  183. $ref_id = 0;
  184. $article = array();
  185. foreach ($article_node->childNodes as $child) {
  186. if ($child->nodeName == 'content') {
  187. $article[$child->nodeName] = db_escape_string($child->nodeValue, false);
  188. } else if ($child->nodeName == 'label_cache') {
  189. $article[$child->nodeName] = $child->nodeValue;
  190. } else {
  191. $article[$child->nodeName] = db_escape_string($child->nodeValue);
  192. }
  193. }
  194. //print_r($article);
  195. if ($article['guid']) {
  196. ++$num_processed;
  197. //db_query("BEGIN");
  198. //print 'GUID:' . $article['guid'] . "\n";
  199. $result = db_query("SELECT id FROM ttrss_entries
  200. WHERE guid = '".$article['guid']."'");
  201. if (db_num_rows($result) == 0) {
  202. $result = db_query(
  203. "INSERT INTO ttrss_entries
  204. (title,
  205. guid,
  206. link,
  207. updated,
  208. content,
  209. content_hash,
  210. no_orig_date,
  211. date_updated,
  212. date_entered,
  213. comments,
  214. num_comments,
  215. author)
  216. VALUES
  217. ('".$article['title']."',
  218. '".$article['guid']."',
  219. '".$article['link']."',
  220. '".$article['updated']."',
  221. '".$article['content']."',
  222. '".sha1($article['content'])."',
  223. false,
  224. NOW(),
  225. NOW(),
  226. '',
  227. '0',
  228. '')");
  229. $result = db_query("SELECT id FROM ttrss_entries
  230. WHERE guid = '".$article['guid']."'");
  231. if (db_num_rows($result) != 0) {
  232. $ref_id = db_fetch_result($result, 0, "id");
  233. }
  234. } else {
  235. $ref_id = db_fetch_result($result, 0, "id");
  236. }
  237. //print "Got ref ID: $ref_id\n";
  238. if ($ref_id) {
  239. $feed_url = $article['feed_url'];
  240. $feed_title = $article['feed_title'];
  241. $feed = 'NULL';
  242. if ($feed_url && $feed_title) {
  243. $result = db_query("SELECT id FROM ttrss_feeds
  244. WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
  245. if (db_num_rows($result) != 0) {
  246. $feed = db_fetch_result($result, 0, "id");
  247. } else {
  248. // try autocreating feed in Uncategorized...
  249. $result = db_query("INSERT INTO ttrss_feeds (owner_uid,
  250. feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
  251. $result = db_query("SELECT id FROM ttrss_feeds
  252. WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
  253. if (db_num_rows($result) != 0) {
  254. ++$num_feeds_created;
  255. $feed = db_fetch_result($result, 0, "id");
  256. }
  257. }
  258. }
  259. if ($feed != 'NULL')
  260. $feed_qpart = "feed_id = $feed";
  261. else
  262. $feed_qpart = "feed_id IS NULL";
  263. //print "$ref_id / $feed / " . $article['title'] . "\n";
  264. $result = db_query("SELECT int_id FROM ttrss_user_entries
  265. WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
  266. if (db_num_rows($result) == 0) {
  267. $marked = $this->bool_to_sql_bool(sql_bool_to_bool($article['marked']));
  268. $published = $this->bool_to_sql_bool(sql_bool_to_bool($article['published']));
  269. $score = (int) $article['score'];
  270. $tag_cache = $article['tag_cache'];
  271. $note = $article['note'];
  272. //print "Importing " . $article['title'] . "<br/>";
  273. ++$num_imported;
  274. $result = db_query(
  275. "INSERT INTO ttrss_user_entries
  276. (ref_id, owner_uid, feed_id, unread, last_read, marked,
  277. published, score, tag_cache, label_cache, uuid, note)
  278. VALUES ($ref_id, $owner_uid, $feed, false,
  279. NULL, $marked, $published, $score, '$tag_cache',
  280. '', '', '$note')");
  281. $label_cache = json_decode($article['label_cache'], true);
  282. if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
  283. foreach ($label_cache as $label) {
  284. Labels::create($label[1],
  285. $label[2], $label[3], $owner_uid);
  286. Labels::add_article($ref_id, $label[1], $owner_uid);
  287. }
  288. }
  289. //db_query("COMMIT");
  290. }
  291. }
  292. }
  293. }
  294. }
  295. print "<p>" .
  296. __("Finished: ").
  297. vsprintf(_ngettext("%d article processed, ", "%d articles processed, ", $num_processed), $num_processed).
  298. vsprintf(_ngettext("%d imported, ", "%d imported, ", $num_imported), $num_imported).
  299. vsprintf(_ngettext("%d feed created.", "%d feeds created.", $num_feeds_created), $num_feeds_created).
  300. "</p>";
  301. } else {
  302. print "<p>" . __("Could not load XML document.") . "</p>";
  303. }
  304. }
  305. function exportData() {
  306. print "<p style='text-align : center' id='export_status_message'>You need to prepare exported data first by clicking the button below.</p>";
  307. print "<div align='center'>";
  308. print "<button dojoType=\"dijit.form.Button\"
  309. onclick=\"dijit.byId('dataExportDlg').prepare()\">".
  310. __('Prepare data')."</button>";
  311. print "<button dojoType=\"dijit.form.Button\"
  312. onclick=\"dijit.byId('dataExportDlg').hide()\">".
  313. __('Close this window')."</button>";
  314. print "</div>";
  315. }
  316. function dataImport() {
  317. header("Content-Type: text/html"); # required for iframe
  318. print "<div style='text-align : center'>";
  319. if ($_FILES['export_file']['error'] != 0) {
  320. print_error(T_sprintf("Upload failed with error code %d (%s)",
  321. $_FILES['export_file']['error'],
  322. get_upload_error_message($_FILES['export_file']['error'])));
  323. } else {
  324. $tmp_file = false;
  325. if (is_uploaded_file($_FILES['export_file']['tmp_name'])) {
  326. $tmp_file = tempnam(CACHE_DIR . '/upload', 'export');
  327. $result = move_uploaded_file($_FILES['export_file']['tmp_name'],
  328. $tmp_file);
  329. if (!$result) {
  330. print_error(__("Unable to move uploaded file."));
  331. return;
  332. }
  333. } else {
  334. print_error(__('Error: please upload OPML file.'));
  335. return;
  336. }
  337. if (is_file($tmp_file)) {
  338. $this->perform_data_import($tmp_file, $_SESSION['uid']);
  339. unlink($tmp_file);
  340. } else {
  341. print_error(__('No file uploaded.'));
  342. return;
  343. }
  344. }
  345. print "<button dojoType=\"dijit.form.Button\"
  346. onclick=\"dijit.byId('dataImportDlg').hide()\">".
  347. __('Close this window')."</button>";
  348. print "</div>";
  349. }
  350. function api_version() {
  351. return 2;
  352. }
  353. }