]> git.wh0rd.org - tt-rss.git/blob - plugins/import_export/init.php
Merge branch 'master' of github.com:gothfox/Tiny-Tiny-RSS
[tt-rss.git] / plugins / import_export / init.php
1 <?php
2 class Import_Export extends Plugin implements IHandler {
3 private $host;
4
5 function init($host) {
6 $this->host = $host;
7
8 $host->add_hook($host::HOOK_PREFS_TAB, $this);
9 $host->add_command("xml-import", "import articles from XML", $this, ":", "FILE");
10 }
11
12 function about() {
13 return array(1.0,
14 "Imports and exports user data using neutral XML format",
15 "fox");
16 }
17
18 function xml_import($args) {
19
20 $filename = $args['xml_import'];
21
22 if (!is_file($filename)) {
23 print "error: input filename ($filename) doesn't exist.\n";
24 return;
25 }
26
27 _debug("please enter your username:");
28
29 $username = db_escape_string(trim(read_stdin()));
30
31 _debug("importing $filename for user $username...\n");
32
33 $result = db_query("SELECT id FROM ttrss_users WHERE login = '$username'");
34
35 if (db_num_rows($result) == 0) {
36 print "error: could not find user $username.\n";
37 return;
38 }
39
40 $owner_uid = db_fetch_result($result, 0, "id");
41
42 $this->perform_data_import($filename, $owner_uid);
43 }
44
45 function save() {
46 $example_value = db_escape_string($_POST["example_value"]);
47
48 echo "Value set to $example_value (not really)";
49 }
50
51 function get_prefs_js() {
52 return file_get_contents(dirname(__FILE__) . "/import_export.js");
53 }
54
55 function hook_prefs_tab($args) {
56 if ($args != "prefFeeds") return;
57
58 print "<div dojoType=\"dijit.layout.AccordionPane\" title=\"".__('Import and export')."\">";
59
60 print_notice(__("You can export and import your Starred and Archived articles for safekeeping or when migrating between tt-rss instances of same version."));
61
62 print "<p>";
63
64 print "<button dojoType=\"dijit.form.Button\" onclick=\"return exportData()\">".
65 __('Export my data')."</button> ";
66
67 print "<hr>";
68
69 print "<iframe id=\"data_upload_iframe\"
70 name=\"data_upload_iframe\" onload=\"dataImportComplete(this)\"
71 style=\"width: 400px; height: 100px; display: none;\"></iframe>";
72
73 print "<form name=\"import_form\" style='display : block' target=\"data_upload_iframe\"
74 enctype=\"multipart/form-data\" method=\"POST\"
75 action=\"backend.php\">
76 <input id=\"export_file\" name=\"export_file\" type=\"file\">&nbsp;
77 <input type=\"hidden\" name=\"op\" value=\"pluginhandler\">
78 <input type=\"hidden\" name=\"plugin\" value=\"import_export\">
79 <input type=\"hidden\" name=\"method\" value=\"dataimport\">
80 <button dojoType=\"dijit.form.Button\" onclick=\"return importData();\" type=\"submit\">" .
81 __('Import') . "</button>";
82
83 print "</form>";
84
85 print "</p>";
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($_REQUEST['offset']);
123 $exported = 0;
124 $limit = 250;
125
126 if ($offset < 10000 && is_writable(CACHE_DIR . "/export")) {
127 $result = db_query("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 $v = str_replace("]]>", "]]]]><![CDATA[>", $v);
166 fputs($fp, "<$k><![CDATA[$v]]></$k>");
167 }
168
169 fputs($fp, "</article>");
170 }
171
172 $exported = db_num_rows($result);
173
174 if ($exported < $limit && $exported > 0) {
175 fputs($fp, "</articles>");
176 }
177
178 fclose($fp);
179 }
180
181 }
182
183 print json_encode(array("exported" => $exported));
184 }
185
186 function perform_data_import($filename, $owner_uid) {
187
188 $num_imported = 0;
189 $num_processed = 0;
190 $num_feeds_created = 0;
191
192 libxml_disable_entity_loader(false);
193
194 $doc = @DOMDocument::load($filename);
195
196 if (!$doc) {
197 $contents = file_get_contents($filename);
198
199 if ($contents) {
200 $data = @gzuncompress($contents);
201 }
202
203 if (!$data) {
204 $data = @gzdecode($contents);
205 }
206
207 if ($data)
208 $doc = DOMDocument::loadXML($data);
209 }
210
211 libxml_disable_entity_loader(true);
212
213 if ($doc) {
214
215 $xpath = new DOMXpath($doc);
216
217 $container = $doc->firstChild;
218
219 if ($container && $container->hasAttribute('schema-version')) {
220 $schema_version = $container->getAttribute('schema-version');
221
222 if ($schema_version != SCHEMA_VERSION) {
223 print "<p>" .__("Could not import: incorrect schema version.") . "</p>";
224 return;
225 }
226
227 } else {
228 print "<p>" . __("Could not import: unrecognized document format.") . "</p>";
229 return;
230 }
231
232 $articles = $xpath->query("//article");
233
234 foreach ($articles as $article_node) {
235 if ($article_node->childNodes) {
236
237 $ref_id = 0;
238
239 $article = array();
240
241 foreach ($article_node->childNodes as $child) {
242 if ($child->nodeName != 'label_cache')
243 $article[$child->nodeName] = db_escape_string($child->nodeValue);
244 else
245 $article[$child->nodeName] = $child->nodeValue;
246 }
247
248 //print_r($article);
249
250 if ($article['guid']) {
251
252 ++$num_processed;
253
254 //db_query("BEGIN");
255
256 //print 'GUID:' . $article['guid'] . "\n";
257
258 $result = db_query("SELECT id FROM ttrss_entries
259 WHERE guid = '".$article['guid']."'");
260
261 if (db_num_rows($result) == 0) {
262
263 $result = db_query(
264 "INSERT INTO ttrss_entries
265 (title,
266 guid,
267 link,
268 updated,
269 content,
270 content_hash,
271 no_orig_date,
272 date_updated,
273 date_entered,
274 comments,
275 num_comments,
276 author)
277 VALUES
278 ('".$article['title']."',
279 '".$article['guid']."',
280 '".$article['link']."',
281 '".$article['updated']."',
282 '".$article['content']."',
283 '".sha1($article['content'])."',
284 false,
285 NOW(),
286 NOW(),
287 '',
288 '0',
289 '')");
290
291 $result = db_query("SELECT id FROM ttrss_entries
292 WHERE guid = '".$article['guid']."'");
293
294 if (db_num_rows($result) != 0) {
295 $ref_id = db_fetch_result($result, 0, "id");
296 }
297
298 } else {
299 $ref_id = db_fetch_result($result, 0, "id");
300 }
301
302 //print "Got ref ID: $ref_id\n";
303
304 if ($ref_id) {
305
306 $feed_url = $article['feed_url'];
307 $feed_title = $article['feed_title'];
308
309 $feed = 'NULL';
310
311 if ($feed_url && $feed_title) {
312 $result = db_query("SELECT id FROM ttrss_feeds
313 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
314
315 if (db_num_rows($result) != 0) {
316 $feed = db_fetch_result($result, 0, "id");
317 } else {
318 // try autocreating feed in Uncategorized...
319
320 $result = db_query("INSERT INTO ttrss_feeds (owner_uid,
321 feed_url, title) VALUES ($owner_uid, '$feed_url', '$feed_title')");
322
323 $result = db_query("SELECT id FROM ttrss_feeds
324 WHERE feed_url = '$feed_url' AND owner_uid = '$owner_uid'");
325
326 if (db_num_rows($result) != 0) {
327 ++$num_feeds_created;
328
329 $feed = db_fetch_result($result, 0, "id");
330 }
331 }
332 }
333
334 if ($feed != 'NULL')
335 $feed_qpart = "feed_id = $feed";
336 else
337 $feed_qpart = "feed_id IS NULL";
338
339 //print "$ref_id / $feed / " . $article['title'] . "\n";
340
341 $result = db_query("SELECT int_id FROM ttrss_user_entries
342 WHERE ref_id = '$ref_id' AND owner_uid = '$owner_uid' AND $feed_qpart");
343
344 if (db_num_rows($result) == 0) {
345
346 $marked = bool_to_sql_bool(sql_bool_to_bool($article['marked']));
347 $published = bool_to_sql_bool(sql_bool_to_bool($article['published']));
348 $score = (int) $article['score'];
349
350 $tag_cache = $article['tag_cache'];
351 $label_cache = db_escape_string($article['label_cache']);
352 $note = $article['note'];
353
354 //print "Importing " . $article['title'] . "<br/>";
355
356 ++$num_imported;
357
358 $result = db_query(
359 "INSERT INTO ttrss_user_entries
360 (ref_id, owner_uid, feed_id, unread, last_read, marked,
361 published, score, tag_cache, label_cache, uuid, note)
362 VALUES ($ref_id, $owner_uid, $feed, false,
363 NULL, $marked, $published, $score, '$tag_cache',
364 '$label_cache', '', '$note')");
365
366 $label_cache = json_decode($label_cache, true);
367
368 if (is_array($label_cache) && $label_cache["no-labels"] != 1) {
369 foreach ($label_cache as $label) {
370
371 label_create($label[1],
372 $label[2], $label[3], $owner_uid);
373
374 label_add_article($ref_id, $label[1], $owner_uid);
375
376 }
377 }
378
379 //db_query("COMMIT");
380 }
381 }
382 }
383 }
384 }
385
386 print "<p>" .
387 __("Finished: ").
388 vsprintf(_ngettext("%d article processed, ", "%d articles processed, ", $num_processed), $num_processed).
389 vsprintf(_ngettext("%d imported, ", "%d imported, ", $num_imported), $num_imported).
390 vsprintf(_ngettext("%d feed created.", "%d feeds created.", $num_feeds_created), $num_feeds_created).
391 "</p>";
392
393 } else {
394
395 print "<p>" . __("Could not load XML document.") . "</p>";
396
397 }
398 }
399
400 function exportData() {
401
402 print "<p style='text-align : center' id='export_status_message'>You need to prepare exported data first by clicking the button below.</p>";
403
404 print "<div align='center'>";
405 print "<button dojoType=\"dijit.form.Button\"
406 onclick=\"dijit.byId('dataExportDlg').prepare()\">".
407 __('Prepare data')."</button>";
408
409 print "<button dojoType=\"dijit.form.Button\"
410 onclick=\"dijit.byId('dataExportDlg').hide()\">".
411 __('Close this window')."</button>";
412
413 print "</div>";
414
415
416 }
417
418 function dataImport() {
419 header("Content-Type: text/html"); # required for iframe
420
421 print "<div style='text-align : center'>";
422
423 if ($_FILES['export_file']['error'] != 0) {
424 print_error(T_sprintf("Upload failed with error code %d",
425 $_FILES['export_file']['error']));
426 return;
427 }
428
429 $tmp_file = false;
430
431 if (is_uploaded_file($_FILES['export_file']['tmp_name'])) {
432 $tmp_file = tempnam(CACHE_DIR . '/upload', 'export');
433
434 $result = move_uploaded_file($_FILES['export_file']['tmp_name'],
435 $tmp_file);
436
437 if (!$result) {
438 print_error(__("Unable to move uploaded file."));
439 return;
440 }
441 } else {
442 print_error(__('Error: please upload OPML file.'));
443 return;
444 }
445
446 if (is_file($tmp_file)) {
447 $this->perform_data_import($tmp_file, $_SESSION['uid']);
448 unlink($tmp_file);
449 } else {
450 print_error(__('No file uploaded.'));
451 return;
452 }
453
454 print "<button dojoType=\"dijit.form.Button\"
455 onclick=\"dijit.byId('dataImportDlg').hide()\">".
456 __('Close this window')."</button>";
457
458 print "</div>";
459
460 }
461
462 function api_version() {
463 return 2;
464 }
465
466 }
467 ?>