init.php 12 KB

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