importExportController.php 13 KB

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