importExportController.php 10 KB

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