importExportController.php 22 KB

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