importExportController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <?php
  2. /**
  3. * Controller to handle every import and export actions.
  4. */
  5. class FreshRSS_importExport_Controller extends Minz_ActionController {
  6. /**
  7. * This action is called before every other action in that class. It is
  8. * the common boiler plate for every action. It is triggered by the
  9. * underlying framework.
  10. */
  11. public function firstAction() {
  12. if (!$this->view->loginOk) {
  13. Minz_Error::error(
  14. 403,
  15. array('error' => array(_t('access_denied')))
  16. );
  17. }
  18. require_once(LIB_PATH . '/lib_opml.php');
  19. $this->catDAO = new FreshRSS_CategoryDAO();
  20. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  21. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  22. }
  23. /**
  24. * This action displays the main page for import / export system.
  25. */
  26. public function indexAction() {
  27. $this->view->feeds = $this->feedDAO->listFeeds();
  28. Minz_View::prependTitle(_t('import_export') . ' · ');
  29. }
  30. /**
  31. * This action handles import action.
  32. *
  33. * It must be reached by a POST request.
  34. *
  35. * Parameter is:
  36. * - file (default: nothing!)
  37. * Available file types are: zip, json or xml.
  38. */
  39. public function importAction() {
  40. if (!Minz_Request::isPost()) {
  41. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  42. }
  43. $file = $_FILES['file'];
  44. $status_file = $file['error'];
  45. if ($status_file !== 0) {
  46. Minz_Log::error('File cannot be uploaded. Error code: ' . $status_file);
  47. Minz_Request::bad(_t('file_cannot_be_uploaded'),
  48. array('c' => 'importExport', 'a' => 'index'));
  49. }
  50. @set_time_limit(300);
  51. $type_file = $this->guessFileType($file['name']);
  52. $list_files = array(
  53. 'opml' => array(),
  54. 'json_starred' => array(),
  55. 'json_feed' => array()
  56. );
  57. // We try to list all files according to their type
  58. $list = array();
  59. if ($type_file === 'zip' && extension_loaded('zip')) {
  60. $zip = zip_open($file['tmp_name']);
  61. if (!is_resource($zip)) {
  62. // zip_open cannot open file: something is wrong
  63. Minz_Log::error('Zip archive cannot be imported. Error code: ' . $zip);
  64. Minz_Request::bad(_t('zip_error'),
  65. array('c' => 'importExport', 'a' => 'index'));
  66. }
  67. while (($zipfile = zip_read($zip)) !== false) {
  68. if (!is_resource($zipfile)) {
  69. // zip_entry() can also return an error code!
  70. Minz_Log::error('Zip file cannot be imported. Error code: ' . $zipfile);
  71. } else {
  72. $type_zipfile = $this->guessFileType(zip_entry_name($zipfile));
  73. if ($type_file !== 'unknown') {
  74. $list_files[$type_zipfile][] = zip_entry_read(
  75. $zipfile,
  76. zip_entry_filesize($zipfile)
  77. );
  78. }
  79. }
  80. }
  81. zip_close($zip);
  82. } elseif ($type_file === 'zip') {
  83. // Zip extension is not loaded
  84. Minz_Request::bad(_t('no_zip_extension'),
  85. array('c' => 'importExport', 'a' => 'index'));
  86. } elseif ($type_file !== 'unknown') {
  87. $list_files[$type_file][] = file_get_contents($file['tmp_name']);
  88. }
  89. // Import file contents.
  90. // OPML first(so categories and feeds are imported)
  91. // Starred articles then so the "favourite" status is already set
  92. // And finally all other files.
  93. $error = false;
  94. foreach ($list_files['opml'] as $opml_file) {
  95. $error = $this->importOpml($opml_file);
  96. }
  97. foreach ($list_files['json_starred'] as $article_file) {
  98. $error = $this->importJson($article_file, true);
  99. }
  100. foreach ($list_files['json_feed'] as $article_file) {
  101. $error = $this->importJson($article_file);
  102. }
  103. // And finally, we get import status and redirect to the home page
  104. Minz_Session::_param('actualize_feeds', true);
  105. $content_notif = $error === true ? _t('feeds_imported_with_errors') :
  106. _t('feeds_imported');
  107. Minz_Request::good($content_notif);
  108. }
  109. /**
  110. * This method tries to guess the file type based on its name.
  111. *
  112. * Itis a *very* basic guess file type function. Only based on filename.
  113. * That's could be improved but should be enough for what we have to do.
  114. *
  115. * @todo move into lib_rss.php
  116. */
  117. private function guessFileType($filename) {
  118. if (substr_compare($filename, '.zip', -4) === 0) {
  119. return 'zip';
  120. } elseif (substr_compare($filename, '.opml', -5) === 0 ||
  121. substr_compare($filename, '.xml', -4) === 0) {
  122. return 'opml';
  123. } elseif (substr_compare($filename, '.json', -5) === 0 &&
  124. strpos($filename, 'starred') !== false) {
  125. return 'json_starred';
  126. } elseif (substr_compare($filename, '.json', -5) === 0) {
  127. return 'json_feed';
  128. } else {
  129. return 'unknown';
  130. }
  131. }
  132. /**
  133. * This method parses and imports an OPML file.
  134. *
  135. * @param string $opml_file the OPML file content.
  136. * @return boolean true if an error occured, false else.
  137. */
  138. private function importOpml($opml_file) {
  139. $opml_array = array();
  140. try {
  141. $opml_array = libopml_parse_string($opml_file);
  142. } catch (LibOPML_Exception $e) {
  143. Minz_Log::warning($e->getMessage());
  144. return true;
  145. }
  146. $this->catDAO->checkDefault();
  147. return $this->addOpmlElements($opml_array['body']);
  148. }
  149. /**
  150. * This method imports an OPML file based on its body.
  151. *
  152. * @param array $opml_elements an OPML element (body or outline).
  153. * @param string $parent_cat the name of the parent category.
  154. * @return boolean true if an error occured, false else.
  155. */
  156. private function addOpmlElements($opml_elements, $parent_cat = null) {
  157. $error = false;
  158. foreach ($opml_elements as $elt) {
  159. $res = false;
  160. if (isset($elt['xmlUrl'])) {
  161. // If xmlUrl exists, it means it is a feed
  162. $res = $this->addFeedOpml($elt, $parent_cat);
  163. } else {
  164. // No xmlUrl? It should be a category!
  165. $res = $this->addCategoryOpml($elt, $parent_cat);
  166. }
  167. if (!$error && $res) {
  168. // oops: there is at least one error!
  169. $error = $res;
  170. }
  171. }
  172. return $error;
  173. }
  174. /**
  175. * This method imports an OPML feed element.
  176. *
  177. * @param array $feed_elt an OPML element (must be a feed element).
  178. * @param string $parent_cat the name of the parent category.
  179. * @return boolean true if an error occured, false else.
  180. */
  181. private function addFeedOpml($feed_elt, $parent_cat) {
  182. if (is_null($parent_cat)) {
  183. // This feed has no parent category so we get the default one
  184. $parent_cat = $this->catDAO->getDefault()->name();
  185. }
  186. $cat = $this->catDAO->searchByName($parent_cat);
  187. if (!$cat) {
  188. // If there is not $cat, it means parent category does not exist in
  189. // database. It should not happened!
  190. return true;
  191. }
  192. // We get different useful information
  193. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  194. $name = Minz_Helper::htmlspecialchars_utf8($feed_elt['text']);
  195. $website = '';
  196. if (isset($feed_elt['htmlUrl'])) {
  197. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl']);
  198. }
  199. $description = '';
  200. if (isset($feed_elt['description'])) {
  201. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description']);
  202. }
  203. $error = false;
  204. try {
  205. // Create a Feed object and add it in DB
  206. $feed = new FreshRSS_Feed($url);
  207. $feed->_category($cat->id());
  208. $feed->_name($name);
  209. $feed->_website($website);
  210. $feed->_description($description);
  211. // addFeedObject checks if feed is already in DB so nothing else to
  212. // check here
  213. $id = $this->feedDAO->addFeedObject($feed);
  214. $error = ($id === false);
  215. } catch (FreshRSS_Feed_Exception $e) {
  216. Minz_Log::warning($e->getMessage());
  217. $error = true;
  218. }
  219. return $error;
  220. }
  221. /**
  222. * This method imports an OPML category element.
  223. *
  224. * @param array $cat_elt an OPML element (must be a category element).
  225. * @param string $parent_cat the name of the parent category.
  226. * @return boolean true if an error occured, false else.
  227. */
  228. private function addCategoryOpml($cat_elt, $parent_cat) {
  229. // Create a new Category object
  230. $cat = new FreshRSS_Category(Minz_Helper::htmlspecialchars_utf8($cat_elt['text']));
  231. $id = $this->catDAO->addCategoryObject($cat);
  232. $error = ($id === false);
  233. if (isset($cat_elt['@outlines'])) {
  234. // Our cat_elt contains more categories or more feeds, so we
  235. // add them recursively.
  236. // Note: FreshRSS does not support yet category arborescence
  237. $res = $this->addOpmlElements($cat_elt['@outlines'], $cat->name());
  238. if (!$error && $res) {
  239. $error = true;
  240. }
  241. }
  242. return $error;
  243. }
  244. /**
  245. * This method import a JSON-based file (Google Reader format).
  246. *
  247. * @param string $article_file the JSON file content.
  248. * @param boolean $starred true if articles from the file must be starred.
  249. * @return boolean true if an error occured, false else.
  250. */
  251. private function importJson($article_file, $starred = false) {
  252. $article_object = json_decode($article_file, true);
  253. if (is_null($article_object)) {
  254. Minz_Log::warning('Try to import a non-JSON file');
  255. return true;
  256. }
  257. $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0;
  258. $google_compliant = strpos($article_object['id'], 'com.google') !== false;
  259. $error = false;
  260. $article_to_feed = array();
  261. // First, we check feeds of articles are in DB (and add them if needed).
  262. foreach ($article_object['items'] as $item) {
  263. $feed = $this->addFeedJson($item['origin'], $google_compliant);
  264. if (is_null($feed)) {
  265. $error = true;
  266. } else {
  267. $article_to_feed[$item['id']] = $feed->id();
  268. }
  269. }
  270. // Then, articles are imported.
  271. $prepared_statement = $this->entryDAO->addEntryPrepare();
  272. $this->entryDAO->beginTransaction();
  273. foreach ($article_object['items'] as $item) {
  274. if (!isset($article_to_feed[$item['id']])) {
  275. // Related feed does not exist for this entry, do nothing.
  276. continue;
  277. }
  278. $feed_id = $article_to_feed[$item['id']];
  279. $author = isset($item['author']) ? $item['author'] : '';
  280. $key_content = ($google_compliant && !isset($item['content'])) ?
  281. 'summary' : 'content';
  282. $tags = $item['categories'];
  283. if ($google_compliant) {
  284. // Remove tags containing "/state/com.google" which are useless.
  285. $tags = array_filter($tags, function($var) {
  286. return strpos($var, '/state/com.google') === false;
  287. });
  288. }
  289. $entry = new FreshRSS_Entry(
  290. $feed_id, $item['id'], $item['title'], $author,
  291. $item[$key_content]['content'], $item['alternate'][0]['href'],
  292. $item['published'], $is_read, $starred
  293. );
  294. $entry->_id(min(time(), $entry->date(true)) . uSecString());
  295. $entry->_tags($tags);
  296. $values = $entry->toArray();
  297. $id = $this->entryDAO->addEntry($values, $prepared_statement);
  298. if (!$error && ($id === false)) {
  299. $error = true;
  300. }
  301. }
  302. $this->entryDAO->commit();
  303. return $error;
  304. }
  305. /**
  306. * This method import a JSON-based feed (Google Reader format).
  307. *
  308. * @param array $origin represents a feed.
  309. * @param boolean $google_compliant takes care of some specific values if true.
  310. * @return FreshRSS_Feed if feed is in database at the end of the process,
  311. * else null.
  312. */
  313. private function addFeedJson($origin, $google_compliant) {
  314. $default_cat = $this->catDAO->getDefault();
  315. $return = null;
  316. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  317. $url = $origin[$key];
  318. $name = $origin['title'];
  319. $website = $origin['htmlUrl'];
  320. try {
  321. // Create a Feed object and add it in database.
  322. $feed = new FreshRSS_Feed($url);
  323. $feed->_category($default_cat->id());
  324. $feed->_name($name);
  325. $feed->_website($website);
  326. // addFeedObject checks if feed is already in DB so nothing else to
  327. // check here.
  328. $id = $this->feedDAO->addFeedObject($feed);
  329. if ($id !== false) {
  330. $feed->_id($id);
  331. $return = $feed;
  332. }
  333. } catch (FreshRSS_Feed_Exception $e) {
  334. Minz_Log::warning($e->getMessage());
  335. }
  336. return $return;
  337. }
  338. /**
  339. * This action handles export action.
  340. *
  341. * This action must be reached by a POST request.
  342. *
  343. * Parameters are:
  344. * - export_opml (default: false)
  345. * - export_starred (default: false)
  346. * - export_feeds (default: array()) a list of feed ids
  347. */
  348. public function exportAction() {
  349. if (!Minz_Request::isPost()) {
  350. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  351. }
  352. $this->view->_useLayout(false);
  353. $export_opml = Minz_Request::param('export_opml', false);
  354. $export_starred = Minz_Request::param('export_starred', false);
  355. $export_feeds = Minz_Request::param('export_feeds', array());
  356. $export_files = array();
  357. if ($export_opml) {
  358. $export_files['feeds.opml'] = $this->generateOpml();
  359. }
  360. if ($export_starred) {
  361. $export_files['starred.json'] = $this->generateEntries('starred');
  362. }
  363. foreach ($export_feeds as $feed_id) {
  364. $feed = $this->feedDAO->searchById($feed_id);
  365. if ($feed) {
  366. $filename = 'feed_' . $feed->category() . '_'
  367. . $feed->id() . '.json';
  368. $export_files[$filename] = $this->generateEntries('feed', $feed);
  369. }
  370. }
  371. $nb_files = count($export_files);
  372. if ($nb_files > 1) {
  373. // If there are more than 1 file to export, we need a zip archive.
  374. try {
  375. $this->exportZip($export_files);
  376. } catch (Exception $e) {
  377. # Oops, there is no Zip extension!
  378. Minz_Request::bad(_t('export_no_zip_extension'),
  379. array('c' => 'importExport', 'a' => 'index'));
  380. }
  381. } elseif ($nb_files === 1) {
  382. // Only one file? Guess its type and export it.
  383. $filename = key($export_files);
  384. $type = $this->guessFileType($filename);
  385. $this->exportFile('freshrss_' . $filename, $export_files[$filename], $type);
  386. } else {
  387. // Nothing to do...
  388. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  389. }
  390. }
  391. /**
  392. * This method returns the OPML file based on user subscriptions.
  393. *
  394. * @return string the OPML file content.
  395. */
  396. private function generateOpml() {
  397. $list = array();
  398. foreach ($this->catDAO->listCategories() as $key => $cat) {
  399. $list[$key]['name'] = $cat->name();
  400. $list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id());
  401. }
  402. $this->view->categories = $list;
  403. return $this->view->helperToString('export/opml');
  404. }
  405. /**
  406. * This method returns a JSON file content.
  407. *
  408. * @param string $type must be "starred" or "feed"
  409. * @param FreshRSS_Feed $feed feed of which we want to get entries.
  410. * @return string the JSON file content.
  411. */
  412. private function generateEntries($type, $feed = NULL) {
  413. $this->view->categories = $this->catDAO->listCategories();
  414. if ($type == 'starred') {
  415. $this->view->list_title = _t('starred_list');
  416. $this->view->type = 'starred';
  417. $unread_fav = $this->entryDAO->countUnreadReadFavorites();
  418. $this->view->entries = $this->entryDAO->listWhere(
  419. 's', '', FreshRSS_Entry::STATE_ALL, 'ASC', $unread_fav['all']
  420. );
  421. } elseif ($type == 'feed' && !is_null($feed)) {
  422. $this->view->list_title = _t('feed_list', $feed->name());
  423. $this->view->type = 'feed/' . $feed->id();
  424. $this->view->entries = $this->entryDAO->listWhere(
  425. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, 'ASC',
  426. $this->view->conf->posts_per_page
  427. );
  428. $this->view->feed = $feed;
  429. }
  430. return $this->view->helperToString('export/articles');
  431. }
  432. /**
  433. * This method zips a list of files and returns it by HTTP.
  434. *
  435. * @param array $files list of files where key is filename and value the content.
  436. * @throws Exception if Zip extension is not loaded.
  437. */
  438. private function exportZip($files) {
  439. if (!extension_loaded('zip')) {
  440. throw new Exception();
  441. }
  442. // From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
  443. $zip_file = tempnam('tmp', 'zip');
  444. $zip = new ZipArchive();
  445. $zip->open($zip_file, ZipArchive::OVERWRITE);
  446. foreach ($files as $filename => $content) {
  447. $zip->addFromString($filename, $content);
  448. }
  449. // Close and send to user
  450. $zip->close();
  451. header('Content-Type: application/zip');
  452. header('Content-Length: ' . filesize($zip_file));
  453. header('Content-Disposition: attachment; filename="freshrss_export.zip"');
  454. readfile($zip_file);
  455. unlink($zip_file);
  456. }
  457. /**
  458. * This method returns a single file (OPML or JSON) by HTTP.
  459. *
  460. * @param string $filename
  461. * @param string $content
  462. * @param string $type the file type (opml, json_feed or json_starred).
  463. * If equals to unknown, nothing happens.
  464. */
  465. private function exportFile($filename, $content, $type) {
  466. if ($type === 'unknown') {
  467. return;
  468. }
  469. $content_type = '';
  470. if ($type === 'opml') {
  471. $content_type = "text/opml";
  472. } elseif ($type === 'json_feed' || $type === 'json_starred') {
  473. $content_type = "text/json";
  474. }
  475. header('Content-Type: ' . $content_type . '; charset=utf-8');
  476. header('Content-disposition: attachment; filename=' . $filename);
  477. print($content);
  478. }
  479. }