importExportController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. <?php
  2. /**
  3. * Controller to handle every import and export actions.
  4. */
  5. class FreshRSS_importExport_Controller extends Minz_ActionController {
  6. /**
  7. * This action is called before every other action in that class. It is
  8. * the common boiler plate for every action. It is triggered by the
  9. * underlying framework.
  10. */
  11. public function firstAction() {
  12. if (!FreshRSS_Auth::hasAccess()) {
  13. Minz_Error::error(403);
  14. }
  15. require_once(LIB_PATH . '/lib_opml.php');
  16. $this->catDAO = new FreshRSS_CategoryDAO();
  17. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  18. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  19. }
  20. /**
  21. * This action displays the main page for import / export system.
  22. */
  23. public function indexAction() {
  24. $this->view->feeds = $this->feedDAO->listFeeds();
  25. Minz_View::prependTitle(_t('sub.import_export.title') . ' · ');
  26. }
  27. public function importFile($name, $path, $username = null) {
  28. require_once(LIB_PATH . '/lib_opml.php');
  29. $this->catDAO = new FreshRSS_CategoryDAO($username);
  30. $this->entryDAO = FreshRSS_Factory::createEntryDao($username);
  31. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  32. $type_file = self::guessFileType($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($path);
  42. if (!is_resource($zip)) {
  43. // zip_open cannot open file: something is wrong
  44. throw new FreshRSS_Zip_Exception($zip);
  45. }
  46. while (($zipfile = zip_read($zip)) !== false) {
  47. if (!is_resource($zipfile)) {
  48. // zip_entry() can also return an error code!
  49. throw new FreshRSS_Zip_Exception($zipfile);
  50. } else {
  51. $type_zipfile = self::guessFileType(zip_entry_name($zipfile));
  52. if ($type_file !== 'unknown') {
  53. $list_files[$type_zipfile][] = zip_entry_read(
  54. $zipfile,
  55. zip_entry_filesize($zipfile)
  56. );
  57. }
  58. }
  59. }
  60. zip_close($zip);
  61. } elseif ($type_file === 'zip') {
  62. // ZIP extension is not loaded
  63. throw new FreshRSS_ZipMissing_Exception();
  64. } elseif ($type_file !== 'unknown') {
  65. $list_files[$type_file][] = file_get_contents($path);
  66. }
  67. // Import file contents.
  68. // OPML first(so categories and feeds are imported)
  69. // Starred articles then so the "favourite" status is already set
  70. // And finally all other files.
  71. $ok = true;
  72. foreach ($list_files['opml'] as $opml_file) {
  73. if (!$this->importOpml($opml_file)) {
  74. $ok = false;
  75. if (FreshRSS_Context::$isCli) {
  76. fwrite(STDERR, 'FreshRSS error during OPML import' . "\n");
  77. }
  78. }
  79. }
  80. foreach ($list_files['json_starred'] as $article_file) {
  81. if (!$this->importJson($article_file, true)) {
  82. $ok = false;
  83. if (FreshRSS_Context::$isCli) {
  84. fwrite(STDERR, 'FreshRSS error during JSON stars import' . "\n");
  85. }
  86. }
  87. }
  88. foreach ($list_files['json_feed'] as $article_file) {
  89. if (!$this->importJson($article_file)) {
  90. $ok = false;
  91. if (FreshRSS_Context::$isCli) {
  92. fwrite(STDERR, 'FreshRSS error during JSON feeds import' . "\n");
  93. }
  94. }
  95. }
  96. return $ok;
  97. }
  98. /**
  99. * This action handles import action.
  100. *
  101. * It must be reached by a POST request.
  102. *
  103. * Parameter is:
  104. * - file (default: nothing!)
  105. * Available file types are: zip, json or xml.
  106. */
  107. public function importAction() {
  108. if (!Minz_Request::isPost()) {
  109. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  110. }
  111. $file = $_FILES['file'];
  112. $status_file = $file['error'];
  113. if ($status_file !== 0) {
  114. Minz_Log::warning('File cannot be uploaded. Error code: ' . $status_file);
  115. Minz_Request::bad(_t('feedback.import_export.file_cannot_be_uploaded'),
  116. array('c' => 'importExport', 'a' => 'index'));
  117. }
  118. @set_time_limit(300);
  119. $error = false;
  120. try {
  121. $error = !$this->importFile($file['name'], $file['tmp_name']);
  122. } catch (FreshRSS_ZipMissing_Exception $zme) {
  123. Minz_Request::bad(_t('feedback.import_export.no_zip_extension'),
  124. array('c' => 'importExport', 'a' => 'index'));
  125. } catch (FreshRSS_Zip_Exception $ze) {
  126. Minz_Log::warning('ZIP archive cannot be imported. Error code: ' . $ze->zipErrorCode());
  127. Minz_Request::bad(_t('feedback.import_export.zip_error'),
  128. array('c' => 'importExport', 'a' => 'index'));
  129. }
  130. // And finally, we get import status and redirect to the home page
  131. Minz_Session::_param('actualize_feeds', true);
  132. $content_notif = $error === true ? _t('feedback.import_export.feeds_imported_with_errors') :
  133. _t('feedback.import_export.feeds_imported');
  134. Minz_Request::good($content_notif);
  135. }
  136. /**
  137. * This method tries to guess the file type based on its name.
  138. *
  139. * Itis a *very* basic guess file type function. Only based on filename.
  140. * That's could be improved but should be enough for what we have to do.
  141. */
  142. private static function guessFileType($filename) {
  143. if (substr_compare($filename, '.zip', -4) === 0) {
  144. return 'zip';
  145. } elseif (substr_compare($filename, '.opml', -5) === 0 ||
  146. substr_compare($filename, '.xml', -4) === 0) {
  147. return 'opml';
  148. } elseif (substr_compare($filename, '.json', -5) === 0 &&
  149. strpos($filename, 'starred') !== false) {
  150. return 'json_starred';
  151. } elseif (substr_compare($filename, '.json', -5) === 0) {
  152. return 'json_feed';
  153. } else {
  154. return 'unknown';
  155. }
  156. }
  157. /**
  158. * This method parses and imports an OPML file.
  159. *
  160. * @param string $opml_file the OPML file content.
  161. * @return boolean false if an error occured, true otherwise.
  162. */
  163. private function importOpml($opml_file) {
  164. $opml_array = array();
  165. try {
  166. $opml_array = libopml_parse_string($opml_file, false);
  167. } catch (LibOPML_Exception $e) {
  168. if (FreshRSS_Context::$isCli) {
  169. fwrite(STDERR, 'FreshRSS error during OPML parsing: ' . $e->getMessage() . "\n");
  170. } else {
  171. Minz_Log::warning($e->getMessage());
  172. }
  173. return false;
  174. }
  175. $this->catDAO->checkDefault();
  176. return $this->addOpmlElements($opml_array['body']);
  177. }
  178. /**
  179. * This method imports an OPML file based on its body.
  180. *
  181. * @param array $opml_elements an OPML element (body or outline).
  182. * @param string $parent_cat the name of the parent category.
  183. * @return boolean false if an error occured, true otherwise.
  184. */
  185. private function addOpmlElements($opml_elements, $parent_cat = null) {
  186. $ok = true;
  187. $nb_feeds = count($this->feedDAO->listFeeds());
  188. $nb_cats = count($this->catDAO->listCategories(false));
  189. $limits = FreshRSS_Context::$system_conf->limits;
  190. foreach ($opml_elements as $elt) {
  191. if (isset($elt['xmlUrl'])) {
  192. // If xmlUrl exists, it means it is a feed
  193. if (!FreshRSS_Context::$isCli) {
  194. if ($nb_feeds >= $limits['max_feeds']) {
  195. Minz_Log::warning(_t('feedback.sub.feed.over_max',
  196. $limits['max_feeds']));
  197. $ok = false;
  198. continue;
  199. }
  200. }
  201. if ($this->addFeedOpml($elt, $parent_cat)) {
  202. $nb_feeds++;
  203. } else {
  204. $ok = false;
  205. }
  206. } else {
  207. // No xmlUrl? It should be a category!
  208. $limit_reached = ($nb_cats >= $limits['max_categories']);
  209. if (!FreshRSS_Context::$isCli) {
  210. if ($limit_reached) {
  211. Minz_Log::warning(_t('feedback.sub.category.over_max',
  212. $limits['max_categories']));
  213. }
  214. $ok = false;
  215. continue;
  216. }
  217. if ($this->addCategoryOpml($elt, $parent_cat, $limit_reached)) {
  218. $nb_cats++;
  219. } else {
  220. $ok = false;
  221. }
  222. }
  223. }
  224. return $ok;
  225. }
  226. /**
  227. * This method imports an OPML feed element.
  228. *
  229. * @param array $feed_elt an OPML element (must be a feed element).
  230. * @param string $parent_cat the name of the parent category.
  231. * @return boolean false if an error occured, true otherwise.
  232. */
  233. private function addFeedOpml($feed_elt, $parent_cat) {
  234. if ($parent_cat == null) {
  235. // This feed has no parent category so we get the default one
  236. $this->catDAO->checkDefault();
  237. $default_cat = $this->catDAO->getDefault();
  238. $parent_cat = $default_cat->name();
  239. }
  240. $cat = $this->catDAO->searchByName($parent_cat);
  241. if ($cat == null) {
  242. // If there is not $cat, it means parent category does not exist in
  243. // database.
  244. // If it happens, take the default category.
  245. $this->catDAO->checkDefault();
  246. $cat = $this->catDAO->getDefault();
  247. }
  248. // We get different useful information
  249. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  250. $name = Minz_Helper::htmlspecialchars_utf8($feed_elt['text']);
  251. $website = '';
  252. if (isset($feed_elt['htmlUrl'])) {
  253. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl']);
  254. }
  255. $description = '';
  256. if (isset($feed_elt['description'])) {
  257. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description']);
  258. }
  259. $error = false;
  260. try {
  261. // Create a Feed object and add it in DB
  262. $feed = new FreshRSS_Feed($url);
  263. $feed->_category($cat->id());
  264. $feed->_name($name);
  265. $feed->_website($website);
  266. $feed->_description($description);
  267. // Call the extension hook
  268. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  269. if ($feed != null) {
  270. // addFeedObject checks if feed is already in DB so nothing else to
  271. // check here
  272. $id = $this->feedDAO->addFeedObject($feed);
  273. $error = ($id === false);
  274. } else {
  275. $error = true;
  276. }
  277. } catch (FreshRSS_Feed_Exception $e) {
  278. if (FreshRSS_Context::$isCli) {
  279. fwrite(STDERR, 'FreshRSS error during OPML feed import: ' . $e->getMessage() . "\n");
  280. } else {
  281. Minz_Log::warning($e->getMessage());
  282. }
  283. $error = true;
  284. }
  285. if ($error) {
  286. if (FreshRSS_Context::$isCli) {
  287. fwrite(STDERR, 'FreshRSS error during OPML feed import from URL: ' . $url . ' in category ' . $cat->id() . "\n");
  288. } else {
  289. Minz_Log::warning('Error during OPML feed import from URL: ' . $url . ' in category ' . $cat->id());
  290. }
  291. }
  292. return !$error;
  293. }
  294. /**
  295. * This method imports an OPML category element.
  296. *
  297. * @param array $cat_elt an OPML element (must be a category element).
  298. * @param string $parent_cat the name of the parent category.
  299. * @param boolean $cat_limit_reached indicates if category limit has been reached.
  300. * if yes, category is not added (but we try for feeds!)
  301. * @return boolean false if an error occured, true otherwise.
  302. */
  303. private function addCategoryOpml($cat_elt, $parent_cat, $cat_limit_reached) {
  304. // Create a new Category object
  305. $catName = Minz_Helper::htmlspecialchars_utf8($cat_elt['text']);
  306. $cat = new FreshRSS_Category($catName);
  307. $error = true;
  308. if (FreshRSS_Context::$isCli || !$cat_limit_reached) {
  309. $id = $this->catDAO->addCategoryObject($cat);
  310. $error = ($id === false);
  311. }
  312. if ($error) {
  313. if (FreshRSS_Context::$isCli) {
  314. fwrite(STDERR, 'FreshRSS error during OPML category import from URL: ' . $catName . "\n");
  315. } else {
  316. Minz_Log::warning('Error during OPML category import from URL: ' . $catName);
  317. }
  318. }
  319. if (isset($cat_elt['@outlines'])) {
  320. // Our cat_elt contains more categories or more feeds, so we
  321. // add them recursively.
  322. // Note: FreshRSS does not support yet category arborescence
  323. $error &= !$this->addOpmlElements($cat_elt['@outlines'], $catName);
  324. }
  325. return !$error;
  326. }
  327. /**
  328. * This method import a JSON-based file (Google Reader format).
  329. *
  330. * @param string $article_file the JSON file content.
  331. * @param boolean $starred true if articles from the file must be starred.
  332. * @return boolean false if an error occured, true otherwise.
  333. */
  334. private function importJson($article_file, $starred = false) {
  335. $article_object = json_decode($article_file, true);
  336. if ($article_object == null) {
  337. if (FreshRSS_Context::$isCli) {
  338. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  339. } else {
  340. Minz_Log::warning('Try to import a non-JSON file');
  341. }
  342. return false;
  343. }
  344. $is_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  345. $google_compliant = strpos($article_object['id'], 'com.google') !== false;
  346. $error = false;
  347. $article_to_feed = array();
  348. $nb_feeds = count($this->feedDAO->listFeeds());
  349. $limits = FreshRSS_Context::$system_conf->limits;
  350. // First, we check feeds of articles are in DB (and add them if needed).
  351. foreach ($article_object['items'] as $item) {
  352. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  353. $feed = new FreshRSS_Feed($item['origin'][$key]);
  354. $feed = $this->feedDAO->searchByUrl($feed->url());
  355. if ($feed == null) {
  356. // Feed does not exist in DB,we should to try to add it.
  357. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  358. // Oops, no more place!
  359. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  360. } else {
  361. $feed = $this->addFeedJson($item['origin'], $google_compliant);
  362. }
  363. if ($feed == null) {
  364. // Still null? It means something went wrong.
  365. $error = true;
  366. } else {
  367. $nb_feeds++;
  368. }
  369. }
  370. if ($feed != null) {
  371. $article_to_feed[$item['id']] = $feed->id();
  372. }
  373. }
  374. $newGuids = array();
  375. foreach ($article_object['items'] as $item) {
  376. $newGuids[] = safe_ascii($item['id']);
  377. }
  378. // For this feed, check existing GUIDs already in database.
  379. $existingHashForGuids = $this->entryDAO->listHashForFeedGuids($feed->id(), $newGuids);
  380. unset($newGuids);
  381. // Then, articles are imported.
  382. $this->entryDAO->beginTransaction();
  383. foreach ($article_object['items'] as $item) {
  384. if (!isset($article_to_feed[$item['id']])) {
  385. // Related feed does not exist for this entry, do nothing.
  386. continue;
  387. }
  388. $feed_id = $article_to_feed[$item['id']];
  389. $author = isset($item['author']) ? $item['author'] : '';
  390. $key_content = ($google_compliant && !isset($item['content'])) ?
  391. 'summary' : 'content';
  392. $tags = $item['categories'];
  393. if ($google_compliant) {
  394. // Remove tags containing "/state/com.google" which are useless.
  395. $tags = array_filter($tags, function($var) {
  396. return strpos($var, '/state/com.google') !== false;
  397. });
  398. }
  399. $entry = new FreshRSS_Entry(
  400. $feed_id, $item['id'], $item['title'], $author,
  401. $item[$key_content]['content'], $item['alternate'][0]['href'],
  402. $item['published'], $is_read, $starred
  403. );
  404. $entry->_id(min(time(), $entry->date(true)) . uSecString());
  405. $entry->_tags($tags);
  406. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  407. if ($entry == null) {
  408. // An extension has returned a null value, there is nothing to insert.
  409. continue;
  410. }
  411. $values = $entry->toArray();
  412. if (isset($existingHashForGuids[$entry->guid()])) {
  413. $id = $this->entryDAO->updateEntry($values);
  414. } else {
  415. $id = $this->entryDAO->addEntry($values);
  416. }
  417. if (!$error && ($id === false)) {
  418. $error = true;
  419. }
  420. }
  421. $this->entryDAO->commit();
  422. return !$error;
  423. }
  424. /**
  425. * This method import a JSON-based feed (Google Reader format).
  426. *
  427. * @param array $origin represents a feed.
  428. * @param boolean $google_compliant takes care of some specific values if true.
  429. * @return FreshRSS_Feed if feed is in database at the end of the process,
  430. * else null.
  431. */
  432. private function addFeedJson($origin, $google_compliant) {
  433. $return = null;
  434. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  435. $url = $origin[$key];
  436. $name = $origin['title'];
  437. $website = $origin['htmlUrl'];
  438. try {
  439. // Create a Feed object and add it in database.
  440. $feed = new FreshRSS_Feed($url);
  441. $feed->_category(FreshRSS_CategoryDAO::defaultCategoryId);
  442. $feed->_name($name);
  443. $feed->_website($website);
  444. // Call the extension hook
  445. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  446. if ($feed != null) {
  447. // addFeedObject checks if feed is already in DB so nothing else to
  448. // check here.
  449. $id = $this->feedDAO->addFeedObject($feed);
  450. if ($id !== false) {
  451. $feed->_id($id);
  452. $return = $feed;
  453. }
  454. }
  455. } catch (FreshRSS_Feed_Exception $e) {
  456. if (FreshRSS_Context::$isCli) {
  457. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  458. } else {
  459. Minz_Log::warning($e->getMessage());
  460. }
  461. }
  462. return $return;
  463. }
  464. public function exportFile($export_opml = true, $export_starred = false, $export_feeds = array(), $maxFeedEntries = 50, $username = null) {
  465. require_once(LIB_PATH . '/lib_opml.php');
  466. $this->catDAO = new FreshRSS_CategoryDAO($username);
  467. $this->entryDAO = FreshRSS_Factory::createEntryDao($username);
  468. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  469. if ($export_feeds === true) {
  470. //All feeds
  471. $export_feeds = $this->feedDAO->listFeedsIds();
  472. }
  473. if (!is_array($export_feeds)) {
  474. $export_feeds = array();
  475. }
  476. $day = date('Y-m-d');
  477. $export_files = array();
  478. if ($export_opml) {
  479. $export_files["feeds_${day}.opml.xml"] = $this->generateOpml();
  480. }
  481. if ($export_starred) {
  482. $export_files["starred_${day}.json"] = $this->generateEntries('starred');
  483. }
  484. foreach ($export_feeds as $feed_id) {
  485. $feed = $this->feedDAO->searchById($feed_id);
  486. if ($feed) {
  487. $filename = "feed_${day}_" . $feed->category() . '_'
  488. . $feed->id() . '.json';
  489. $export_files[$filename] = $this->generateEntries('feed', $feed, $maxFeedEntries);
  490. }
  491. }
  492. $nb_files = count($export_files);
  493. if ($nb_files > 1) {
  494. // If there are more than 1 file to export, we need a ZIP archive.
  495. try {
  496. $this->sendZip($export_files);
  497. } catch (Exception $e) {
  498. throw new FreshRSS_ZipMissing_Exception($e);
  499. }
  500. } elseif ($nb_files === 1) {
  501. // Only one file? Guess its type and export it.
  502. $filename = key($export_files);
  503. $type = self::guessFileType($filename);
  504. $this->sendFile('freshrss_' . $filename, $export_files[$filename], $type);
  505. }
  506. return $nb_files;
  507. }
  508. /**
  509. * This action handles export action.
  510. *
  511. * This action must be reached by a POST request.
  512. *
  513. * Parameters are:
  514. * - export_opml (default: false)
  515. * - export_starred (default: false)
  516. * - export_feeds (default: array()) a list of feed ids
  517. */
  518. public function exportAction() {
  519. if (!Minz_Request::isPost()) {
  520. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  521. }
  522. $this->view->_useLayout(false);
  523. $nb_files = 0;
  524. try {
  525. $nb_files = $this->exportFile(
  526. Minz_Request::param('export_opml', false),
  527. Minz_Request::param('export_starred', false),
  528. Minz_Request::param('export_feeds', array())
  529. );
  530. } catch (FreshRSS_ZipMissing_Exception $zme) {
  531. # Oops, there is no ZIP extension!
  532. Minz_Request::bad(_t('feedback.import_export.export_no_zip_extension'),
  533. array('c' => 'importExport', 'a' => 'index'));
  534. }
  535. if ($nb_files < 1) {
  536. // Nothing to do...
  537. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  538. }
  539. }
  540. /**
  541. * This method returns the OPML file based on user subscriptions.
  542. *
  543. * @return string the OPML file content.
  544. */
  545. private function generateOpml() {
  546. $list = array();
  547. foreach ($this->catDAO->listCategories() as $key => $cat) {
  548. $list[$key]['name'] = $cat->name();
  549. $list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id());
  550. }
  551. $this->view->categories = $list;
  552. return $this->view->helperToString('export/opml');
  553. }
  554. /**
  555. * This method returns a JSON file content.
  556. *
  557. * @param string $type must be "starred" or "feed"
  558. * @param FreshRSS_Feed $feed feed of which we want to get entries.
  559. * @return string the JSON file content.
  560. */
  561. private function generateEntries($type, $feed = NULL, $maxFeedEntries = 50) {
  562. $this->view->categories = $this->catDAO->listCategories();
  563. if ($type == 'starred') {
  564. $this->view->list_title = _t('sub.import_export.starred_list');
  565. $this->view->type = 'starred';
  566. $unread_fav = $this->entryDAO->countUnreadReadFavorites();
  567. $this->view->entries = $this->entryDAO->listWhere(
  568. 's', '', FreshRSS_Entry::STATE_ALL, 'ASC', $unread_fav['all']
  569. );
  570. } elseif ($type === 'feed' && $feed != null) {
  571. $this->view->list_title = _t('sub.import_export.feed_list', $feed->name());
  572. $this->view->type = 'feed/' . $feed->id();
  573. $this->view->entries = $this->entryDAO->listWhere(
  574. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, 'ASC',
  575. $maxFeedEntries
  576. );
  577. $this->view->feed = $feed;
  578. }
  579. return $this->view->helperToString('export/articles');
  580. }
  581. /**
  582. * This method zips a list of files and returns it by HTTP.
  583. *
  584. * @param array $files list of files where key is filename and value the content.
  585. * @throws Exception if Zip extension is not loaded.
  586. */
  587. private function sendZip($files) {
  588. if (!extension_loaded('zip')) {
  589. throw new Exception();
  590. }
  591. // From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
  592. $zip_file = tempnam('tmp', 'zip');
  593. $zip = new ZipArchive();
  594. $zip->open($zip_file, ZipArchive::OVERWRITE);
  595. foreach ($files as $filename => $content) {
  596. $zip->addFromString($filename, $content);
  597. }
  598. // Close and send to user
  599. $zip->close();
  600. header('Content-Type: application/zip');
  601. header('Content-Length: ' . filesize($zip_file));
  602. $day = date('Y-m-d');
  603. header('Content-Disposition: attachment; filename="freshrss_' . $day . '_export.zip"');
  604. readfile($zip_file);
  605. unlink($zip_file);
  606. }
  607. /**
  608. * This method returns a single file (OPML or JSON) by HTTP.
  609. *
  610. * @param string $filename
  611. * @param string $content
  612. * @param string $type the file type (opml, json_feed or json_starred).
  613. * If equals to unknown, nothing happens.
  614. */
  615. private function sendFile($filename, $content, $type) {
  616. if ($type === 'unknown') {
  617. return;
  618. }
  619. $content_type = '';
  620. if ($type === 'opml') {
  621. $content_type = 'application/xml';
  622. } elseif ($type === 'json_feed' || $type === 'json_starred') {
  623. $content_type = 'application/json';
  624. }
  625. header('Content-Type: ' . $content_type . '; charset=utf-8');
  626. header('Content-disposition: attachment; filename=' . $filename);
  627. print($content);
  628. }
  629. }