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