importExportController.php 22 KB

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