importExportController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. $ok = false;
  415. if (isset($existingHashForGuids[$entry->guid()])) {
  416. $ok = $this->entryDAO->updateEntry($values);
  417. } else {
  418. $ok = $this->entryDAO->addEntry($values);
  419. }
  420. $error |= ($ok === false);
  421. }
  422. $this->entryDAO->commit();
  423. $this->entryDAO->beginTransaction();
  424. $this->entryDAO->commitNewEntries();
  425. $this->feedDAO->updateCachedValues();
  426. $this->entryDAO->commit();
  427. return !$error;
  428. }
  429. /**
  430. * This method import a JSON-based feed (Google Reader format).
  431. *
  432. * @param array $origin represents a feed.
  433. * @param boolean $google_compliant takes care of some specific values if true.
  434. * @return FreshRSS_Feed if feed is in database at the end of the process,
  435. * else null.
  436. */
  437. private function addFeedJson($origin, $google_compliant) {
  438. $return = null;
  439. $key = $google_compliant ? 'htmlUrl' : 'feedUrl';
  440. $url = $origin[$key];
  441. $name = $origin['title'];
  442. $website = $origin['htmlUrl'];
  443. try {
  444. // Create a Feed object and add it in database.
  445. $feed = new FreshRSS_Feed($url);
  446. $feed->_category(FreshRSS_CategoryDAO::defaultCategoryId);
  447. $feed->_name($name);
  448. $feed->_website($website);
  449. // Call the extension hook
  450. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  451. if ($feed != null) {
  452. // addFeedObject checks if feed is already in DB so nothing else to
  453. // check here.
  454. $id = $this->feedDAO->addFeedObject($feed);
  455. if ($id !== false) {
  456. $feed->_id($id);
  457. $return = $feed;
  458. }
  459. }
  460. } catch (FreshRSS_Feed_Exception $e) {
  461. if (FreshRSS_Context::$isCli) {
  462. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  463. } else {
  464. Minz_Log::warning($e->getMessage());
  465. }
  466. }
  467. return $return;
  468. }
  469. public function exportFile($export_opml = true, $export_starred = false, $export_feeds = array(), $maxFeedEntries = 50, $username = null) {
  470. require_once(LIB_PATH . '/lib_opml.php');
  471. $this->catDAO = new FreshRSS_CategoryDAO($username);
  472. $this->entryDAO = FreshRSS_Factory::createEntryDao($username);
  473. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  474. $this->entryDAO->disableBuffering();
  475. if ($export_feeds === true) {
  476. //All feeds
  477. $export_feeds = $this->feedDAO->listFeedsIds();
  478. }
  479. if (!is_array($export_feeds)) {
  480. $export_feeds = array();
  481. }
  482. $day = date('Y-m-d');
  483. $export_files = array();
  484. if ($export_opml) {
  485. $export_files["feeds_${day}.opml.xml"] = $this->generateOpml();
  486. }
  487. if ($export_starred) {
  488. $export_files["starred_${day}.json"] = $this->generateEntries('starred');
  489. }
  490. foreach ($export_feeds as $feed_id) {
  491. $feed = $this->feedDAO->searchById($feed_id);
  492. if ($feed) {
  493. $filename = "feed_${day}_" . $feed->category() . '_'
  494. . $feed->id() . '.json';
  495. $export_files[$filename] = $this->generateEntries('feed', $feed, $maxFeedEntries);
  496. }
  497. }
  498. $nb_files = count($export_files);
  499. if ($nb_files > 1) {
  500. // If there are more than 1 file to export, we need a ZIP archive.
  501. try {
  502. $this->sendZip($export_files);
  503. } catch (Exception $e) {
  504. throw new FreshRSS_ZipMissing_Exception($e);
  505. }
  506. } elseif ($nb_files === 1) {
  507. // Only one file? Guess its type and export it.
  508. $filename = key($export_files);
  509. $type = self::guessFileType($filename);
  510. $this->sendFile('freshrss_' . $filename, $export_files[$filename], $type);
  511. }
  512. return $nb_files;
  513. }
  514. /**
  515. * This action handles export action.
  516. *
  517. * This action must be reached by a POST request.
  518. *
  519. * Parameters are:
  520. * - export_opml (default: false)
  521. * - export_starred (default: false)
  522. * - export_feeds (default: array()) a list of feed ids
  523. */
  524. public function exportAction() {
  525. if (!Minz_Request::isPost()) {
  526. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  527. }
  528. $this->view->_useLayout(false);
  529. $nb_files = 0;
  530. try {
  531. $nb_files = $this->exportFile(
  532. Minz_Request::param('export_opml', false),
  533. Minz_Request::param('export_starred', false),
  534. Minz_Request::param('export_feeds', array())
  535. );
  536. } catch (FreshRSS_ZipMissing_Exception $zme) {
  537. # Oops, there is no ZIP extension!
  538. Minz_Request::bad(_t('feedback.import_export.export_no_zip_extension'),
  539. array('c' => 'importExport', 'a' => 'index'));
  540. }
  541. if ($nb_files < 1) {
  542. // Nothing to do...
  543. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  544. }
  545. }
  546. /**
  547. * This method returns the OPML file based on user subscriptions.
  548. *
  549. * @return string the OPML file content.
  550. */
  551. private function generateOpml() {
  552. $list = array();
  553. foreach ($this->catDAO->listCategories() as $key => $cat) {
  554. $list[$key]['name'] = $cat->name();
  555. $list[$key]['feeds'] = $this->feedDAO->listByCategory($cat->id());
  556. }
  557. $this->view->categories = $list;
  558. return $this->view->helperToString('export/opml');
  559. }
  560. /**
  561. * This method returns a JSON file content.
  562. *
  563. * @param string $type must be "starred" or "feed"
  564. * @param FreshRSS_Feed $feed feed of which we want to get entries.
  565. * @return string the JSON file content.
  566. */
  567. private function generateEntries($type, $feed = NULL, $maxFeedEntries = 50) {
  568. $this->view->categories = $this->catDAO->listCategories();
  569. if ($type == 'starred') {
  570. $this->view->list_title = _t('sub.import_export.starred_list');
  571. $this->view->type = 'starred';
  572. $unread_fav = $this->entryDAO->countUnreadReadFavorites();
  573. $this->view->entriesRaw = $this->entryDAO->listWhereRaw(
  574. 's', '', FreshRSS_Entry::STATE_ALL, 'ASC', $unread_fav['all']
  575. );
  576. } elseif ($type === 'feed' && $feed != null) {
  577. $this->view->list_title = _t('sub.import_export.feed_list', $feed->name());
  578. $this->view->type = 'feed/' . $feed->id();
  579. $this->view->entriesRaw = $this->entryDAO->listWhereRaw(
  580. 'f', $feed->id(), FreshRSS_Entry::STATE_ALL, 'ASC',
  581. $maxFeedEntries
  582. );
  583. $this->view->feed = $feed;
  584. }
  585. return $this->view->helperToString('export/articles');
  586. }
  587. /**
  588. * This method zips a list of files and returns it by HTTP.
  589. *
  590. * @param array $files list of files where key is filename and value the content.
  591. * @throws Exception if Zip extension is not loaded.
  592. */
  593. private function sendZip($files) {
  594. if (!extension_loaded('zip')) {
  595. throw new Exception();
  596. }
  597. // From https://stackoverflow.com/questions/1061710/php-zip-files-on-the-fly
  598. $zip_file = tempnam('tmp', 'zip');
  599. $zip = new ZipArchive();
  600. $zip->open($zip_file, ZipArchive::OVERWRITE);
  601. foreach ($files as $filename => $content) {
  602. $zip->addFromString($filename, $content);
  603. }
  604. // Close and send to user
  605. $zip->close();
  606. header('Content-Type: application/zip');
  607. header('Content-Length: ' . filesize($zip_file));
  608. $day = date('Y-m-d');
  609. header('Content-Disposition: attachment; filename="freshrss_' . $day . '_export.zip"');
  610. readfile($zip_file);
  611. unlink($zip_file);
  612. }
  613. /**
  614. * This method returns a single file (OPML or JSON) by HTTP.
  615. *
  616. * @param string $filename
  617. * @param string $content
  618. * @param string $type the file type (opml, json_feed or json_starred).
  619. * If equals to unknown, nothing happens.
  620. */
  621. private function sendFile($filename, $content, $type) {
  622. if ($type === 'unknown') {
  623. return;
  624. }
  625. $content_type = '';
  626. if ($type === 'opml') {
  627. $content_type = 'application/xml';
  628. } elseif ($type === 'json_feed' || $type === 'json_starred') {
  629. $content_type = 'application/json';
  630. }
  631. header('Content-Type: ' . $content_type . '; charset=utf-8');
  632. header('Content-disposition: attachment; filename=' . $filename);
  633. print($content);
  634. }
  635. }