importExportController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. class FreshRSS_importExport_Controller extends Minz_ActionController {
  3. public function firstAction() {
  4. if (!$this->view->loginOk) {
  5. Minz_Error::error(
  6. 403,
  7. array('error' => array(Minz_Translate::t('access_denied')))
  8. );
  9. }
  10. require_once(LIB_PATH . '/lib_opml.php');
  11. $this->catDAO = new FreshRSS_CategoryDAO();
  12. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  13. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  14. }
  15. public function indexAction() {
  16. $this->view->categories = $this->catDAO->listCategories();
  17. $this->view->feeds = $this->feedDAO->listFeeds();
  18. Minz_View::prependTitle(Minz_Translate::t('import_export') . ' · ');
  19. }
  20. public function importAction() {
  21. if (Minz_Request::isPost() && $_FILES['file']['error'] == 0) {
  22. @set_time_limit(300);
  23. $file = $_FILES['file'];
  24. $type_file = $this->guessFileType($file['name']);
  25. $list_files = array(
  26. 'opml' => array(),
  27. 'json_starred' => array(),
  28. 'json_feed' => array()
  29. );
  30. // We try to list all files according to their type
  31. // A zip file is first opened and then its files are listed
  32. $list = array();
  33. if ($type_file === 'zip' && extension_loaded('zip')) {
  34. $zip = zip_open($file['tmp_name']);
  35. if (!is_resource($zip)) {
  36. Minz_Log::error(
  37. 'Zip file cannot be imported. Error code: ' . $zip
  38. );
  39. // zip_open cannot open file: something is wrong
  40. Minz_Session::_param('notification', array(
  41. 'type' => 'bad',
  42. 'content' => _t('zip_error')
  43. ));
  44. Minz_Request::forward(array('c' => 'importExport'), true);
  45. }
  46. while (($zipfile = zip_read($zip)) !== false) {
  47. $type_zipfile = $this->guessFileType(
  48. zip_entry_name($zipfile)
  49. );
  50. if ($type_file !== 'unknown') {
  51. $list_files[$type_zipfile][] = zip_entry_read(
  52. $zipfile,
  53. zip_entry_filesize($zipfile)
  54. );
  55. }
  56. }
  57. zip_close($zip);
  58. } elseif ($type_file === 'zip') {
  59. // Zip extension is not loaded
  60. Minz_Session::_param('notification', array(
  61. 'type' => 'bad',
  62. 'content' => _t('no_zip_extension')
  63. ));
  64. Minz_Request::forward(array('c' => 'importExport'), true);
  65. } elseif ($type_file !== 'unknown') {
  66. $list_files[$type_file][] = file_get_contents(
  67. $file['tmp_name']
  68. );
  69. }
  70. // Import different files.
  71. // OPML first(so categories and feeds are imported)
  72. // Starred articles then so the "favourite" status is already set
  73. // And finally all other files.
  74. $error = false;
  75. foreach ($list_files['opml'] as $opml_file) {
  76. $error = $this->importOpml($opml_file);
  77. }
  78. foreach ($list_files['json_starred'] as $article_file) {
  79. $error = $this->importArticles($article_file, true);
  80. }
  81. foreach ($list_files['json_feed'] as $article_file) {
  82. $error = $this->importArticles($article_file);
  83. }
  84. // And finally, we get import status and redirect to the home page
  85. $notif = null;
  86. if ($error === true) {
  87. $content_notif = Minz_Translate::t(
  88. 'feeds_imported_with_errors'
  89. );
  90. } else {
  91. $content_notif = Minz_Translate::t(
  92. 'feeds_imported'
  93. );
  94. }
  95. Minz_Session::_param('notification', array(
  96. 'type' => 'good',
  97. 'content' => $content_notif
  98. ));
  99. Minz_Session::_param('actualize_feeds', true);
  100. Minz_Request::forward(array(
  101. 'c' => 'index',
  102. 'a' => 'index'
  103. ), true);
  104. }
  105. // What are you doing? you have to call this controller
  106. // with a POST request!
  107. Minz_Request::forward(array(
  108. 'c' => 'importExport',
  109. 'a' => 'index'
  110. ));
  111. }
  112. private function guessFileType($filename) {
  113. // A *very* basic guess file type function. Only based on filename
  114. // That's could be improved but should be enough, at least for a first
  115. // implementation.
  116. // TODO: improve this function?
  117. if (substr_compare($filename, '.zip', -4) === 0) {
  118. return 'zip';
  119. } elseif (substr_compare($filename, '.opml', -5) === 0 ||
  120. substr_compare($filename, '.xml', -4) === 0) {
  121. return 'opml';
  122. } elseif (strcmp($filename, 'starred.json') === 0) {
  123. return 'json_starred';
  124. } elseif (substr_compare($filename, '.json', -5) === 0 &&
  125. strpos($filename, 'feed_') === 0) {
  126. return 'json_feed';
  127. } else {
  128. return 'unknown';
  129. }
  130. }
  131. private function importOpml($opml_file) {
  132. $opml_array = array();
  133. try {
  134. $opml_array = libopml_parse_string($opml_file);
  135. } catch (LibOPML_Exception $e) {
  136. Minz_Log::warning($e->getMessage());
  137. return true;
  138. }
  139. $this->catDAO->checkDefault();
  140. return $this->addOpmlElements($opml_array['body']);
  141. }
  142. private function addOpmlElements($opml_elements, $parent_cat = null) {
  143. $error = false;
  144. foreach ($opml_elements as $elt) {
  145. $res = false;
  146. if (isset($elt['xmlUrl'])) {
  147. $res = $this->addFeedOpml($elt, $parent_cat);
  148. } else {
  149. $res = $this->addCategoryOpml($elt, $parent_cat);
  150. }
  151. if (!$error && $res) {
  152. // oops: there is at least one error!
  153. $error = $res;
  154. }
  155. }
  156. return $error;
  157. }
  158. private function addFeedOpml($feed_elt, $parent_cat) {
  159. if (is_null($parent_cat)) {
  160. // This feed has no parent category so we get the default one
  161. $parent_cat = $this->catDAO->getDefault()->name();
  162. }
  163. $cat = $this->catDAO->searchByName($parent_cat);
  164. if (!$cat) {
  165. return true;
  166. }
  167. // We get different useful information
  168. $url = html_chars_utf8($feed_elt['xmlUrl']);
  169. $name = html_chars_utf8($feed_elt['text']);
  170. $website = '';
  171. if (isset($feed_elt['htmlUrl'])) {
  172. $website = html_chars_utf8($feed_elt['htmlUrl']);
  173. }
  174. $description = '';
  175. if (isset($feed_elt['description'])) {
  176. $description = html_chars_utf8($feed_elt['description']);
  177. }
  178. $error = false;
  179. try {
  180. // Create a Feed object and add it in DB
  181. $feed = new FreshRSS_Feed($url);
  182. $feed->_category($cat->id());
  183. $feed->_name($name);
  184. $feed->_website($website);
  185. $feed->_description($description);
  186. // addFeedObject checks if feed is already in DB so nothing else to
  187. // check here
  188. $id = $this->feedDAO->addFeedObject($feed);
  189. $error = ($id === false);
  190. } catch (FreshRSS_Feed_Exception $e) {
  191. Minz_Log::warning($e->getMessage());
  192. $error = true;
  193. }
  194. return $error;
  195. }
  196. private function addCategoryOpml($cat_elt, $parent_cat) {
  197. // Create a new Category object
  198. $cat = new FreshRSS_Category(html_chars_utf8($cat_elt['text']));
  199. $id = $this->catDAO->addCategoryObject($cat);
  200. $error = ($id === false);
  201. if (isset($cat_elt['@outlines'])) {
  202. // Our cat_elt contains more categories or more feeds, so we
  203. // add them recursively.
  204. // Note: FreshRSS does not support yet category arborescence
  205. $res = $this->addOpmlElements($cat_elt['@outlines'], $cat->name());
  206. if (!$error && $res) {
  207. $error = true;
  208. }
  209. }
  210. return $error;
  211. }
  212. private function importArticles($article_file, $starred = false) {
  213. $article_object = json_decode($article_file, true);
  214. if (is_null($article_object)) {
  215. Minz_Log::warning('Try to import a non-JSON file');
  216. return true;
  217. }
  218. $is_read = $this->view->conf->mark_when['reception'] ? 1 : 0;
  219. $google_compliant = (
  220. strpos($article_object['id'], 'com.google') !== false
  221. );
  222. $error = false;
  223. foreach ($article_object['items'] as $item) {
  224. $feed = $this->addFeedArticles($item['origin'], $google_compliant);
  225. if (is_null($feed)) {
  226. $error = true;
  227. continue;
  228. }
  229. $author = isset($item['author']) ? $item['author'] : '';
  230. $key_content = ($google_compliant && !isset($item['content'])) ?
  231. 'summary' : 'content';
  232. $tags = $item['categories'];
  233. if ($google_compliant) {
  234. $tags = array_filter($tags, function($var) {
  235. return strpos($var, '/state/com.google') === false;
  236. });
  237. }
  238. $entry = new FreshRSS_Entry(
  239. $feed->id(), $item['id'], $item['title'], $author,
  240. $item[$key_content]['content'], $item['alternate'][0]['href'],
  241. $item['published'], $is_read, $starred
  242. );
  243. $entry->_tags($tags);
  244. //FIME: Use entryDAO->addEntryPrepare(). Do not call entryDAO->listLastGuidsByFeed() for each entry. Consider using a transaction.
  245. $id = $this->entryDAO->addEntryObject(
  246. $entry, $this->view->conf, $feed->keepHistory()
  247. );
  248. if (!$error && ($id === false)) {
  249. $error = true;
  250. }
  251. }
  252. return $error;
  253. }
  254. private function addFeedArticles($origin, $google_compliant) {
  255. $default_cat = $this->catDAO->getDefault();
  256. $return = null;
  257. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  258. $url = $origin[$key];
  259. $name = $origin['title'];
  260. $website = $origin['htmlUrl'];
  261. $error = false;
  262. try {
  263. // Create a Feed object and add it in DB
  264. $feed = new FreshRSS_Feed($url);
  265. $feed->_category($default_cat->id());
  266. $feed->_name($name);
  267. $feed->_website($website);
  268. // addFeedObject checks if feed is already in DB so nothing else to
  269. // check here
  270. $id = $this->feedDAO->addFeedObject($feed);
  271. if ($id !== false) {
  272. $feed->_id($id);
  273. $return = $feed;
  274. }
  275. } catch (FreshRSS_Feed_Exception $e) {
  276. Minz_Log::warning($e->getMessage());
  277. }
  278. return $return;
  279. }
  280. public function exportAction() {
  281. if (Minz_Request::isPost()) {
  282. $this->view->_useLayout(false);
  283. $export_opml = Minz_Request::param('export_opml', false);
  284. $export_starred = Minz_Request::param('export_starred', false);
  285. $export_feeds = Minz_Request::param('export_feeds', array ());
  286. $export_files = array ();
  287. if ($export_opml) {
  288. $export_files['feeds.opml'] = $this->generateOpml();
  289. }
  290. if ($export_starred) {
  291. $export_files['starred.json'] = $this->generateArticles('starred');
  292. }
  293. foreach ($export_feeds as $feed_id) {
  294. $feed = $this->feedDAO->searchById($feed_id);
  295. if ($feed) {
  296. $filename = 'feed_' . $feed->category() . '_'
  297. . $feed->id() . '.json';
  298. $export_files[$filename] = $this->generateArticles(
  299. 'feed', $feed
  300. );
  301. }
  302. }
  303. $nb_files = count($export_files);
  304. if ($nb_files > 1) {
  305. // If there are more than 1 file to export, we need an .zip
  306. try {
  307. $this->exportZip($export_files);
  308. } catch (Exception $e) {
  309. # Oops, there is no Zip extension!
  310. $notif = array(
  311. 'type' => 'bad',
  312. 'content' => _t('export_no_zip_extension')
  313. );
  314. Minz_Session::_param('notification', $notif);
  315. Minz_Request::forward(array('c' => 'importExport'), true);
  316. }
  317. } elseif ($nb_files === 1) {
  318. // Only one file? Guess its type and export it.
  319. $filename = key($export_files);
  320. $type = null;
  321. if (substr_compare($filename, '.opml', -5) === 0) {
  322. $type = "text/xml";
  323. } elseif (substr_compare($filename, '.json', -5) === 0) {
  324. $type = "text/json";
  325. }
  326. $this->exportFile($filename, $export_files[$filename], $type);
  327. } else {
  328. Minz_Request::forward(array('c' => 'importExport'), true);
  329. }
  330. }
  331. }
  332. private function generateOpml() {
  333. $list = array();
  334. foreach ($this->catDAO->listCategories() as $key => $cat) {
  335. $list[$key]['name'] = $cat->name();
  336. $list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id());
  337. }
  338. $this->view->categories = $list;
  339. return $this->view->helperToString('export/opml');
  340. }
  341. private function generateArticles($type, $feed = NULL) {
  342. $this->view->categories = $this->catDAO->listCategories();
  343. if ($type == 'starred') {
  344. $this->view->list_title = Minz_Translate::t('starred_list');
  345. $this->view->type = 'starred';
  346. $unread_fav = $this->entryDAO->countUnreadReadFavorites();
  347. $this->view->entries = $this->entryDAO->listWhere(
  348. 's', '', FreshRSS_Entry::STATE_ALL, 'ASC',
  349. $unread_fav['all']
  350. );
  351. } elseif ($type == 'feed' && !is_null($feed)) {
  352. $this->view->list_title = Minz_Translate::t(
  353. 'feed_list', $feed->name()
  354. );
  355. $this->view->type = 'feed/' . $feed->id();
  356. $this->view->entries = $this->entryDAO->listWhere(
  357. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, 'ASC',
  358. $this->view->conf->posts_per_page
  359. );
  360. $this->view->feed = $feed;
  361. }
  362. return $this->view->helperToString('export/articles');
  363. }
  364. private function exportZip($files) {
  365. if (!extension_loaded('zip')) {
  366. throw new Exception();
  367. }
  368. // From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
  369. $zip_file = tempnam('tmp', 'zip');
  370. $zip = new ZipArchive();
  371. $zip->open($zip_file, ZipArchive::OVERWRITE);
  372. foreach ($files as $filename => $content) {
  373. $zip->addFromString($filename, $content);
  374. }
  375. // Close and send to user
  376. $zip->close();
  377. header('Content-Type: application/zip');
  378. header('Content-Length: ' . filesize($zip_file));
  379. header('Content-Disposition: attachment; filename="freshrss_export.zip"');
  380. readfile($zip_file);
  381. unlink($zip_file);
  382. }
  383. private function exportFile($filename, $content, $type) {
  384. if (is_null($type)) {
  385. return;
  386. }
  387. header('Content-Type: ' . $type . '; charset=utf-8');
  388. header('Content-disposition: attachment; filename=' . $filename);
  389. print($content);
  390. }
  391. }