importExportController.php 12 KB

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