importExportController.php 22 KB

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