init.php 12 KB

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