init.php 12 KB

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