importExportController.php 13 KB

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