importExportController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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') : _t('feedback.import_export.feeds_imported');
  139. Minz_Request::good($content_notif);
  140. }
  141. /**
  142. * This method tries to guess the file type based on its name.
  143. *
  144. * Itis a *very* basic guess file type function. Only based on filename.
  145. * That's could be improved but should be enough for what we have to do.
  146. */
  147. private static function guessFileType($filename) {
  148. if (substr_compare($filename, '.zip', -4) === 0) {
  149. return 'zip';
  150. } elseif (substr_compare($filename, '.opml', -5) === 0 ||
  151. substr_compare($filename, '.xml', -4) === 0) {
  152. return 'opml';
  153. } elseif (substr_compare($filename, '.json', -5) === 0 &&
  154. strpos($filename, 'starred') !== false) {
  155. return 'json_starred';
  156. } elseif (substr_compare($filename, '.json', -5) === 0) {
  157. return 'json_feed';
  158. } else {
  159. return 'unknown';
  160. }
  161. }
  162. /**
  163. * This method parses and imports an OPML file.
  164. *
  165. * @param string $opml_file the OPML file content.
  166. * @return boolean false if an error occured, true otherwise.
  167. */
  168. private function importOpml($opml_file) {
  169. $opml_array = array();
  170. try {
  171. $opml_array = libopml_parse_string($opml_file, false);
  172. } catch (LibOPML_Exception $e) {
  173. if (FreshRSS_Context::$isCli) {
  174. fwrite(STDERR, 'FreshRSS error during OPML parsing: ' . $e->getMessage() . "\n");
  175. } else {
  176. Minz_Log::warning($e->getMessage());
  177. }
  178. return false;
  179. }
  180. $this->catDAO->checkDefault();
  181. return $this->addOpmlElements($opml_array['body']);
  182. }
  183. /**
  184. * This method imports an OPML file based on its body.
  185. *
  186. * @param array $opml_elements an OPML element (body or outline).
  187. * @param string $parent_cat the name of the parent category.
  188. * @return boolean false if an error occured, true otherwise.
  189. */
  190. private function addOpmlElements($opml_elements, $parent_cat = null) {
  191. $ok = true;
  192. $nb_feeds = count($this->feedDAO->listFeeds());
  193. $nb_cats = count($this->catDAO->listCategories(false));
  194. $limits = FreshRSS_Context::$system_conf->limits;
  195. foreach ($opml_elements as $elt) {
  196. if (isset($elt['xmlUrl'])) {
  197. // If xmlUrl exists, it means it is a feed
  198. if (FreshRSS_Context::$isCli && $nb_feeds >= $limits['max_feeds']) {
  199. Minz_Log::warning(_t('feedback.sub.feed.over_max',
  200. $limits['max_feeds']));
  201. $ok = false;
  202. continue;
  203. }
  204. if ($this->addFeedOpml($elt, $parent_cat)) {
  205. $nb_feeds++;
  206. } else {
  207. $ok = false;
  208. }
  209. } else {
  210. // No xmlUrl? It should be a category!
  211. $limit_reached = ($nb_cats >= $limits['max_categories']);
  212. if (!FreshRSS_Context::$isCli && $limit_reached) {
  213. Minz_Log::warning(_t('feedback.sub.category.over_max',
  214. $limits['max_categories']));
  215. $ok = false;
  216. continue;
  217. }
  218. if ($this->addCategoryOpml($elt, $parent_cat, $limit_reached)) {
  219. $nb_cats++;
  220. } else {
  221. $ok = false;
  222. }
  223. }
  224. }
  225. return $ok;
  226. }
  227. /**
  228. * This method imports an OPML feed element.
  229. *
  230. * @param array $feed_elt an OPML element (must be a feed element).
  231. * @param string $parent_cat the name of the parent category.
  232. * @return boolean false if an error occured, true otherwise.
  233. */
  234. private function addFeedOpml($feed_elt, $parent_cat) {
  235. if ($parent_cat == null) {
  236. // This feed has no parent category so we get the default one
  237. $this->catDAO->checkDefault();
  238. $default_cat = $this->catDAO->getDefault();
  239. $parent_cat = $default_cat->name();
  240. }
  241. $cat = $this->catDAO->searchByName($parent_cat);
  242. if ($cat == null) {
  243. // If there is not $cat, it means parent category does not exist in
  244. // database.
  245. // If it happens, take the default category.
  246. $this->catDAO->checkDefault();
  247. $cat = $this->catDAO->getDefault();
  248. }
  249. // We get different useful information
  250. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  251. $name = Minz_Helper::htmlspecialchars_utf8($feed_elt['text']);
  252. $website = '';
  253. if (isset($feed_elt['htmlUrl'])) {
  254. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl']);
  255. }
  256. $description = '';
  257. if (isset($feed_elt['description'])) {
  258. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description']);
  259. }
  260. $error = false;
  261. try {
  262. // Create a Feed object and add it in DB
  263. $feed = new FreshRSS_Feed($url);
  264. $feed->_category($cat->id());
  265. $feed->_name($name);
  266. $feed->_website($website);
  267. $feed->_description($description);
  268. // Call the extension hook
  269. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  270. if ($feed != null) {
  271. // addFeedObject checks if feed is already in DB so nothing else to
  272. // check here
  273. $id = $this->feedDAO->addFeedObject($feed);
  274. $error = ($id === false);
  275. } else {
  276. $error = true;
  277. }
  278. } catch (FreshRSS_Feed_Exception $e) {
  279. if (FreshRSS_Context::$isCli) {
  280. fwrite(STDERR, 'FreshRSS error during OPML feed import: ' . $e->getMessage() . "\n");
  281. } else {
  282. Minz_Log::warning($e->getMessage());
  283. }
  284. $error = true;
  285. }
  286. if ($error) {
  287. if (FreshRSS_Context::$isCli) {
  288. fwrite(STDERR, 'FreshRSS error during OPML feed import from URL: ' . $url . ' in category ' . $cat->id() . "\n");
  289. } else {
  290. Minz_Log::warning('Error during OPML feed import from URL: ' . $url . ' in category ' . $cat->id());
  291. }
  292. }
  293. return !$error;
  294. }
  295. /**
  296. * This method imports an OPML category element.
  297. *
  298. * @param array $cat_elt an OPML element (must be a category element).
  299. * @param string $parent_cat the name of the parent category.
  300. * @param boolean $cat_limit_reached indicates if category limit has been reached.
  301. * if yes, category is not added (but we try for feeds!)
  302. * @return boolean false if an error occured, true otherwise.
  303. */
  304. private function addCategoryOpml($cat_elt, $parent_cat, $cat_limit_reached) {
  305. // Create a new Category object
  306. $catName = Minz_Helper::htmlspecialchars_utf8($cat_elt['text']);
  307. $cat = new FreshRSS_Category($catName);
  308. $error = true;
  309. if (FreshRSS_Context::$isCli || !$cat_limit_reached) {
  310. $id = $this->catDAO->addCategoryObject($cat);
  311. $error = ($id === false);
  312. }
  313. if ($error) {
  314. if (FreshRSS_Context::$isCli) {
  315. fwrite(STDERR, 'FreshRSS error during OPML category import from URL: ' . $catName . "\n");
  316. } else {
  317. Minz_Log::warning('Error during OPML category import from URL: ' . $catName);
  318. }
  319. }
  320. if (isset($cat_elt['@outlines'])) {
  321. // Our cat_elt contains more categories or more feeds, so we
  322. // add them recursively.
  323. // Note: FreshRSS does not support yet category arborescence
  324. $error &= !$this->addOpmlElements($cat_elt['@outlines'], $catName);
  325. }
  326. return !$error;
  327. }
  328. /**
  329. * This method import a JSON-based file (Google Reader format).
  330. *
  331. * @param string $article_file the JSON file content.
  332. * @param boolean $starred true if articles from the file must be starred.
  333. * @return boolean false if an error occured, true otherwise.
  334. */
  335. private function importJson($article_file, $starred = false) {
  336. $article_object = json_decode($article_file, true);
  337. if ($article_object == null) {
  338. if (FreshRSS_Context::$isCli) {
  339. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  340. } else {
  341. Minz_Log::warning('Try to import a non-JSON file');
  342. }
  343. return false;
  344. }
  345. $is_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  346. $google_compliant = strpos($article_object['id'], 'com.google') !== false;
  347. $error = false;
  348. $article_to_feed = array();
  349. $nb_feeds = count($this->feedDAO->listFeeds());
  350. $limits = FreshRSS_Context::$system_conf->limits;
  351. // First, we check feeds of articles are in DB (and add them if needed).
  352. foreach ($article_object['items'] as $item) {
  353. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  354. $feed = new FreshRSS_Feed($item['origin'][$key]);
  355. $feed = $this->feedDAO->searchByUrl($feed->url());
  356. if ($feed == null) {
  357. // Feed does not exist in DB,we should to try to add it.
  358. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  359. // Oops, no more place!
  360. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  361. } else {
  362. $feed = $this->addFeedJson($item['origin'], $google_compliant);
  363. }
  364. if ($feed == null) {
  365. // Still null? It means something went wrong.
  366. $error = true;
  367. } else {
  368. $nb_feeds++;
  369. }
  370. }
  371. if ($feed != null) {
  372. $article_to_feed[$item['id']] = $feed->id();
  373. }
  374. }
  375. $newGuids = array();
  376. foreach ($article_object['items'] as $item) {
  377. $newGuids[] = safe_ascii($item['id']);
  378. }
  379. // For this feed, check existing GUIDs already in database.
  380. $existingHashForGuids = $this->entryDAO->listHashForFeedGuids($feed->id(), $newGuids);
  381. unset($newGuids);
  382. // Then, articles are imported.
  383. $this->entryDAO->beginTransaction();
  384. foreach ($article_object['items'] as $item) {
  385. if (!isset($article_to_feed[$item['id']])) {
  386. // Related feed does not exist for this entry, do nothing.
  387. continue;
  388. }
  389. $feed_id = $article_to_feed[$item['id']];
  390. $author = isset($item['author']) ? $item['author'] : '';
  391. $key_content = ($google_compliant && !isset($item['content'])) ? '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. $ok = false;
  413. if (isset($existingHashForGuids[$entry->guid()])) {
  414. $ok = $this->entryDAO->updateEntry($values);
  415. } else {
  416. $ok = $this->entryDAO->addEntry($values);
  417. }
  418. $error |= ($ok === false);
  419. }
  420. $this->entryDAO->commit();
  421. $this->entryDAO->beginTransaction();
  422. $this->entryDAO->commitNewEntries();
  423. $this->feedDAO->updateCachedValues();
  424. $this->entryDAO->commit();
  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. }