importExportController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. <?php
  2. /**
  3. * Controller to handle every import and export actions.
  4. */
  5. class FreshRSS_importExport_Controller extends FreshRSS_ActionController {
  6. /** @var FreshRSS_EntryDAO */
  7. private $entryDAO;
  8. /** @var FreshRSS_FeedDAO */
  9. private $feedDAO;
  10. /**
  11. * This action is called before every other action in that class. It is
  12. * the common boiler plate for every action. It is triggered by the
  13. * underlying framework.
  14. */
  15. public function firstAction() {
  16. if (!FreshRSS_Auth::hasAccess()) {
  17. Minz_Error::error(403);
  18. }
  19. require_once(LIB_PATH . '/lib_opml.php');
  20. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  21. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  22. }
  23. /**
  24. * This action displays the main page for import / export system.
  25. */
  26. public function indexAction() {
  27. $this->view->feeds = $this->feedDAO->listFeeds();
  28. FreshRSS_View::prependTitle(_t('sub.import_export.title') . ' · ');
  29. }
  30. private static function megabytes($size_str) {
  31. switch (substr($size_str, -1)) {
  32. case 'M': case 'm': return (int)$size_str;
  33. case 'K': case 'k': return (int)$size_str / 1024;
  34. case 'G': case 'g': return (int)$size_str * 1024;
  35. }
  36. return $size_str;
  37. }
  38. private static function minimumMemory($mb) {
  39. $mb = (int)$mb;
  40. $ini = self::megabytes(ini_get('memory_limit'));
  41. if ($ini < $mb) {
  42. ini_set('memory_limit', $mb . 'M');
  43. }
  44. }
  45. public function importFile($name, $path, $username = null) {
  46. self::minimumMemory(256);
  47. $this->entryDAO = FreshRSS_Factory::createEntryDao($username);
  48. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  49. $type_file = self::guessFileType($name);
  50. $list_files = array(
  51. 'opml' => array(),
  52. 'json_starred' => array(),
  53. 'json_feed' => array(),
  54. 'ttrss_starred' => array(),
  55. );
  56. // We try to list all files according to their type
  57. $list = array();
  58. if ('zip' === $type_file && extension_loaded('zip')) {
  59. $zip = new ZipArchive();
  60. $result = $zip->open($path);
  61. if (true !== $result) {
  62. // zip_open cannot open file: something is wrong
  63. throw new FreshRSS_Zip_Exception($result);
  64. }
  65. for ($i = 0; $i < $zip->numFiles; $i++) {
  66. $type_zipfile = self::guessFileType($zip->getNameIndex($i));
  67. if ('unknown' !== $type_zipfile) {
  68. $list_files[$type_zipfile][] = $zip->getFromIndex($i);
  69. }
  70. }
  71. $zip->close();
  72. } elseif ('zip' === $type_file) {
  73. // ZIP extension is not loaded
  74. throw new FreshRSS_ZipMissing_Exception();
  75. } elseif ('unknown' !== $type_file) {
  76. $list_files[$type_file][] = file_get_contents($path);
  77. }
  78. // Import file contents.
  79. // OPML first(so categories and feeds are imported)
  80. // Starred articles then so the "favourite" status is already set
  81. // And finally all other files.
  82. $ok = true;
  83. $importService = new FreshRSS_Import_Service($username);
  84. foreach ($list_files['opml'] as $opml_file) {
  85. $importService->importOpml($opml_file);
  86. if (!$importService->lastStatus()) {
  87. $ok = false;
  88. if (FreshRSS_Context::$isCli) {
  89. fwrite(STDERR, 'FreshRSS error during OPML import' . "\n");
  90. } else {
  91. Minz_Log::warning('Error during OPML import');
  92. }
  93. }
  94. }
  95. foreach ($list_files['json_starred'] as $article_file) {
  96. if (!$this->importJson($article_file, true)) {
  97. $ok = false;
  98. if (FreshRSS_Context::$isCli) {
  99. fwrite(STDERR, 'FreshRSS error during JSON stars import' . "\n");
  100. } else {
  101. Minz_Log::warning('Error during JSON stars import');
  102. }
  103. }
  104. }
  105. foreach ($list_files['json_feed'] as $article_file) {
  106. if (!$this->importJson($article_file)) {
  107. $ok = false;
  108. if (FreshRSS_Context::$isCli) {
  109. fwrite(STDERR, 'FreshRSS error during JSON feeds import' . "\n");
  110. } else {
  111. Minz_Log::warning('Error during JSON feeds import');
  112. }
  113. }
  114. }
  115. foreach ($list_files['ttrss_starred'] as $article_file) {
  116. $json = $this->ttrssXmlToJson($article_file);
  117. if (!$this->importJson($json, true)) {
  118. $ok = false;
  119. if (FreshRSS_Context::$isCli) {
  120. fwrite(STDERR, 'FreshRSS error during TT-RSS articles import' . "\n");
  121. } else {
  122. Minz_Log::warning('Error during TT-RSS articles import');
  123. }
  124. }
  125. }
  126. return $ok;
  127. }
  128. /**
  129. * This action handles import action.
  130. *
  131. * It must be reached by a POST request.
  132. *
  133. * Parameter is:
  134. * - file (default: nothing!)
  135. * Available file types are: zip, json or xml.
  136. */
  137. public function importAction() {
  138. if (!Minz_Request::isPost()) {
  139. Minz_Request::forward(array('c' => 'importExport', 'a' => 'index'), true);
  140. }
  141. $file = $_FILES['file'];
  142. $status_file = $file['error'];
  143. if ($status_file !== 0) {
  144. Minz_Log::warning('File cannot be uploaded. Error code: ' . $status_file);
  145. Minz_Request::bad(_t('feedback.import_export.file_cannot_be_uploaded'), [ 'c' => 'importExport', 'a' => 'index' ]);
  146. }
  147. @set_time_limit(300);
  148. $error = false;
  149. try {
  150. $error = !$this->importFile($file['name'], $file['tmp_name']);
  151. } catch (FreshRSS_ZipMissing_Exception $zme) {
  152. Minz_Request::bad(_t('feedback.import_export.no_zip_extension'),
  153. array('c' => 'importExport', 'a' => 'index'));
  154. } catch (FreshRSS_Zip_Exception $ze) {
  155. Minz_Log::warning('ZIP archive cannot be imported. Error code: ' . $ze->zipErrorCode());
  156. Minz_Request::bad(_t('feedback.import_export.zip_error'),
  157. array('c' => 'importExport', 'a' => 'index'));
  158. }
  159. // And finally, we get import status and redirect to the home page
  160. Minz_Session::_param('actualize_feeds', true);
  161. $content_notif = $error === true ? _t('feedback.import_export.feeds_imported_with_errors') : _t('feedback.import_export.feeds_imported');
  162. Minz_Request::good($content_notif);
  163. }
  164. /**
  165. * This method tries to guess the file type based on its name.
  166. *
  167. * It is a *very* basic guess file type function. Only based on filename.
  168. * That could be improved but should be enough for what we have to do.
  169. */
  170. private static function guessFileType($filename) {
  171. if (substr_compare($filename, '.zip', -4) === 0) {
  172. return 'zip';
  173. } elseif (stripos($filename, 'opml') !== false) {
  174. return 'opml';
  175. } elseif (substr_compare($filename, '.json', -5) === 0) {
  176. if (strpos($filename, 'starred') !== false) {
  177. return 'json_starred';
  178. } else {
  179. return 'json_feed';
  180. }
  181. } elseif (substr_compare($filename, '.xml', -4) === 0) {
  182. if (preg_match('/Tiny|tt-?rss/i', $filename)) {
  183. return 'ttrss_starred';
  184. } else {
  185. return 'opml';
  186. }
  187. }
  188. return 'unknown';
  189. }
  190. private function ttrssXmlToJson(string $xml) {
  191. $table = (array)simplexml_load_string($xml, null, LIBXML_NOBLANKS | LIBXML_NOCDATA);
  192. $table['items'] = isset($table['article']) ? $table['article'] : array();
  193. unset($table['article']);
  194. for ($i = count($table['items']) - 1; $i >= 0; $i--) {
  195. $item = (array)($table['items'][$i]);
  196. $item = array_filter($item, function ($v) {
  197. // Filter out empty properties, potentially reported as empty objects
  198. return (is_string($v) && trim($v) !== '') || !empty($v);
  199. });
  200. $item['updated'] = isset($item['updated']) ? strtotime($item['updated']) : '';
  201. $item['published'] = $item['updated'];
  202. $item['content'] = array('content' => isset($item['content']) ? $item['content'] : '');
  203. $item['categories'] = isset($item['tag_cache']) ? array($item['tag_cache']) : array();
  204. if (!empty($item['marked'])) {
  205. $item['categories'][] = 'user/-/state/com.google/starred';
  206. }
  207. if (!empty($item['published'])) {
  208. $item['categories'][] = 'user/-/state/com.google/broadcast';
  209. }
  210. if (!empty($item['label_cache'])) {
  211. $labels_cache = json_decode($item['label_cache'], true);
  212. if (is_array($labels_cache)) {
  213. foreach ($labels_cache as $label_cache) {
  214. if (!empty($label_cache[1])) {
  215. $item['categories'][] = 'user/-/label/' . trim($label_cache[1]);
  216. }
  217. }
  218. }
  219. }
  220. $item['alternate'][0]['href'] = isset($item['link']) ? $item['link'] : '';
  221. $item['origin'] = array(
  222. 'title' => isset($item['feed_title']) ? $item['feed_title'] : '',
  223. 'feedUrl' => isset($item['feed_url']) ? $item['feed_url'] : '',
  224. );
  225. $item['id'] = isset($item['guid']) ? $item['guid'] : (isset($item['feed_url']) ? $item['feed_url'] : $item['published']);
  226. $item['guid'] = $item['id'];
  227. $table['items'][$i] = $item;
  228. }
  229. return json_encode($table);
  230. }
  231. /**
  232. * This method import a JSON-based file (Google Reader format).
  233. *
  234. * @param string $article_file the JSON file content.
  235. * @param boolean $starred true if articles from the file must be starred.
  236. * @return boolean false if an error occurred, true otherwise.
  237. */
  238. private function importJson($article_file, $starred = false) {
  239. $article_object = json_decode($article_file, true);
  240. if ($article_object == null) {
  241. if (FreshRSS_Context::$isCli) {
  242. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  243. } else {
  244. Minz_Log::warning('Try to import a non-JSON file');
  245. }
  246. return false;
  247. }
  248. $items = isset($article_object['items']) ? $article_object['items'] : $article_object;
  249. $mark_as_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  250. $error = false;
  251. $article_to_feed = array();
  252. $nb_feeds = count($this->feedDAO->listFeeds());
  253. $newFeedGuids = array();
  254. $limits = FreshRSS_Context::$system_conf->limits;
  255. // First, we check feeds of articles are in DB (and add them if needed).
  256. foreach ($items as $item) {
  257. if (!isset($item['guid']) && isset($item['id'])) {
  258. $item['guid'] = $item['id'];
  259. }
  260. if (empty($item['guid'])) {
  261. continue;
  262. }
  263. if (empty($item['origin'])) {
  264. $item['origin'] = [];
  265. }
  266. if (empty($item['origin']['title']) || trim($item['origin']['title']) === '') {
  267. $item['origin']['title'] = 'Import';
  268. }
  269. if (!empty($item['origin']['feedUrl'])) {
  270. $feedUrl = $item['origin']['feedUrl'];
  271. } elseif (!empty($item['origin']['streamId']) && strpos($item['origin']['streamId'], 'feed/') === 0) {
  272. $feedUrl = substr($item['origin']['streamId'], 5); //Google Reader
  273. $item['origin']['feedUrl'] = $feedUrl;
  274. } elseif (!empty($item['origin']['htmlUrl'])) {
  275. $feedUrl = $item['origin']['htmlUrl'];
  276. } else {
  277. $feedUrl = 'http://import.localhost/import.xml';
  278. $item['origin']['feedUrl'] = $feedUrl;
  279. $item['origin']['disable'] = true;
  280. }
  281. $feed = new FreshRSS_Feed($feedUrl);
  282. $feed = $this->feedDAO->searchByUrl($feed->url());
  283. if ($feed == null) {
  284. // Feed does not exist in DB,we should to try to add it.
  285. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  286. // Oops, no more place!
  287. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  288. } else {
  289. $feed = $this->addFeedJson($item['origin']);
  290. }
  291. if ($feed == null) {
  292. // Still null? It means something went wrong.
  293. $error = true;
  294. } else {
  295. $nb_feeds++;
  296. }
  297. }
  298. if ($feed != null) {
  299. $article_to_feed[$item['guid']] = $feed->id();
  300. if (!isset($newFeedGuids['f_' . $feed->id()])) {
  301. $newFeedGuids['f_' . $feed->id()] = array();
  302. }
  303. $newFeedGuids['f_' . $feed->id()][] = safe_ascii($item['guid']);
  304. }
  305. }
  306. $tagDAO = FreshRSS_Factory::createTagDao();
  307. $labels = $tagDAO->listTags();
  308. $knownLabels = array();
  309. foreach ($labels as $label) {
  310. $knownLabels[$label->name()]['id'] = $label->id();
  311. $knownLabels[$label->name()]['articles'] = array();
  312. }
  313. unset($labels);
  314. // For each feed, check existing GUIDs already in database.
  315. $existingHashForGuids = array();
  316. foreach ($newFeedGuids as $feedId => $newGuids) {
  317. $existingHashForGuids[$feedId] = $this->entryDAO->listHashForFeedGuids(substr($feedId, 2), $newGuids);
  318. }
  319. unset($newFeedGuids);
  320. // Then, articles are imported.
  321. $newGuids = array();
  322. $this->entryDAO->beginTransaction();
  323. foreach ($items as $item) {
  324. if (empty($item['guid']) || empty($article_to_feed[$item['guid']])) {
  325. // Related feed does not exist for this entry, do nothing.
  326. continue;
  327. }
  328. $feed_id = $article_to_feed[$item['guid']];
  329. $author = isset($item['author']) ? $item['author'] : '';
  330. $is_starred = null; // null is used to preserve the current state if that item exists and is already starred
  331. $is_read = null;
  332. $tags = empty($item['categories']) ? array() : $item['categories'];
  333. $labels = array();
  334. for ($i = count($tags) - 1; $i >= 0; $i--) {
  335. $tag = trim($tags[$i]);
  336. if (strpos($tag, 'user/-/') !== false) {
  337. if ($tag === 'user/-/state/com.google/starred') {
  338. $is_starred = true;
  339. } elseif ($tag === 'user/-/state/com.google/read') {
  340. $is_read = true;
  341. } elseif ($tag === 'user/-/state/com.google/unread') {
  342. $is_read = false;
  343. } elseif (strpos($tag, 'user/-/label/') === 0) {
  344. $tag = trim(substr($tag, 13));
  345. if ($tag != '') {
  346. $labels[] = $tag;
  347. }
  348. }
  349. unset($tags[$i]);
  350. }
  351. }
  352. if ($starred && !$is_starred) {
  353. //If the article has no label, mark it as starred (old format)
  354. $is_starred = empty($labels);
  355. }
  356. if ($is_read === null) {
  357. $is_read = $mark_as_read;
  358. }
  359. if (isset($item['alternate'][0]['href'])) {
  360. $url = $item['alternate'][0]['href'];
  361. } elseif (isset($item['url'])) {
  362. $url = $item['url']; //FeedBin
  363. } else {
  364. $url = '';
  365. }
  366. $title = empty($item['title']) ? $url : $item['title'];
  367. if (!empty($item['content']['content'])) {
  368. $content = $item['content']['content'];
  369. } elseif (!empty($item['summary']['content'])) {
  370. $content = $item['summary']['content'];
  371. } elseif (!empty($item['content'])) {
  372. $content = $item['content']; //FeedBin
  373. } else {
  374. $content = '';
  375. }
  376. $content = sanitizeHTML($content, $url);
  377. if (!empty($item['published'])) {
  378. $published = '' . $item['published'];
  379. } elseif (!empty($item['timestampUsec'])) {
  380. $published = substr('' . $item['timestampUsec'], 0, -6);
  381. } elseif (!empty($item['updated'])) {
  382. $published = '' . $item['updated'];
  383. } else {
  384. $published = '0';
  385. }
  386. if (!ctype_digit($published)) {
  387. $published = '' . strtotime($published);
  388. }
  389. if (strlen($published) > 10) { // Milliseconds, e.g. Feedly
  390. $published = substr($published, 0, -3);
  391. }
  392. $entry = new FreshRSS_Entry(
  393. $feed_id, $item['guid'], $title, $author,
  394. $content, $url, $published, $is_read, $is_starred
  395. );
  396. $entry->_id(uTimeString());
  397. $entry->_tags($tags);
  398. if (isset($newGuids[$entry->guid()])) {
  399. continue; //Skip subsequent articles with same GUID
  400. }
  401. $newGuids[$entry->guid()] = true;
  402. /** @var FreshRSS_Entry|null */
  403. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  404. if ($entry == null) {
  405. // An extension has returned a null value, there is nothing to insert.
  406. continue;
  407. }
  408. $values = $entry->toArray();
  409. $ok = false;
  410. if (isset($existingHashForGuids['f_' . $feed_id][$entry->guid()])) {
  411. $ok = $this->entryDAO->updateEntry($values);
  412. } else {
  413. $ok = $this->entryDAO->addEntry($values);
  414. }
  415. foreach ($labels as $labelName) {
  416. if (empty($knownLabels[$labelName]['id'])) {
  417. $labelId = $tagDAO->addTag(array('name' => $labelName));
  418. $knownLabels[$labelName]['id'] = $labelId;
  419. $knownLabels[$labelName]['articles'] = array();
  420. }
  421. $knownLabels[$labelName]['articles'][] = array(
  422. //'id' => $entry->id(), //ID changes after commitNewEntries()
  423. 'id_feed' => $entry->feedId(),
  424. 'guid' => $entry->guid(),
  425. );
  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. $this->entryDAO->beginTransaction();
  435. foreach ($knownLabels as $labelName => $knownLabel) {
  436. $labelId = $knownLabel['id'];
  437. if (!$labelId) {
  438. continue;
  439. }
  440. foreach ($knownLabel['articles'] as $article) {
  441. $entryId = $this->entryDAO->searchIdByGuid($article['id_feed'], $article['guid']);
  442. if ($entryId != null) {
  443. $tagDAO->tagEntry($labelId, $entryId);
  444. } else {
  445. Minz_Log::warning('Could not add label "' . $labelName . '" to entry "' . $article['guid'] . '" in feed ' . $article['id_feed']);
  446. }
  447. }
  448. }
  449. $this->entryDAO->commit();
  450. return !$error;
  451. }
  452. /**
  453. * This method import a JSON-based feed (Google Reader format).
  454. *
  455. * @param array<string,string> $origin represents a feed.
  456. * @return FreshRSS_Feed|null if feed is in database at the end of the process, else null.
  457. */
  458. private function addFeedJson($origin) {
  459. $return = null;
  460. if (!empty($origin['feedUrl'])) {
  461. $url = $origin['feedUrl'];
  462. } elseif (!empty($origin['htmlUrl'])) {
  463. $url = $origin['htmlUrl'];
  464. } else {
  465. return null;
  466. }
  467. if (!empty($origin['htmlUrl'])) {
  468. $website = $origin['htmlUrl'];
  469. } elseif (!empty($origin['feedUrl'])) {
  470. $website = $origin['feedUrl'];
  471. } else {
  472. $website = '';
  473. }
  474. $name = empty($origin['title']) ? $website : $origin['title'];
  475. try {
  476. // Create a Feed object and add it in database.
  477. $feed = new FreshRSS_Feed($url);
  478. $feed->_categoryId(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  479. $feed->_name($name);
  480. $feed->_website($website);
  481. if (!empty($origin['disable'])) {
  482. $feed->_mute(true);
  483. }
  484. // Call the extension hook
  485. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  486. if ($feed != null) {
  487. // addFeedObject checks if feed is already in DB so nothing else to
  488. // check here.
  489. $id = $this->feedDAO->addFeedObject($feed);
  490. if ($id !== false) {
  491. $feed->_id($id);
  492. $return = $feed;
  493. }
  494. }
  495. } catch (FreshRSS_Feed_Exception $e) {
  496. if (FreshRSS_Context::$isCli) {
  497. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  498. } else {
  499. Minz_Log::warning($e->getMessage());
  500. }
  501. }
  502. return $return;
  503. }
  504. /**
  505. * This action handles export action.
  506. *
  507. * This action must be reached by a POST request.
  508. *
  509. * Parameters are:
  510. * - export_opml (default: false)
  511. * - export_starred (default: false)
  512. * - export_labelled (default: false)
  513. * - export_feeds (default: array()) a list of feed ids
  514. */
  515. public function exportAction() {
  516. if (!Minz_Request::isPost()) {
  517. return Minz_Request::forward(
  518. array('c' => 'importExport', 'a' => 'index'),
  519. true
  520. );
  521. }
  522. $username = Minz_Session::param('currentUser');
  523. $export_service = new FreshRSS_Export_Service($username);
  524. $export_opml = Minz_Request::param('export_opml', false);
  525. $export_starred = Minz_Request::param('export_starred', false);
  526. $export_labelled = Minz_Request::param('export_labelled', false);
  527. $export_feeds = Minz_Request::param('export_feeds', array());
  528. $max_number_entries = 50;
  529. $exported_files = [];
  530. if ($export_opml) {
  531. list($filename, $content) = $export_service->generateOpml();
  532. $exported_files[$filename] = $content;
  533. }
  534. // Starred and labelled entries are merged in the same `starred` file
  535. // to avoid duplication of content.
  536. if ($export_starred && $export_labelled) {
  537. list($filename, $content) = $export_service->generateStarredEntries('ST');
  538. $exported_files[$filename] = $content;
  539. } elseif ($export_starred) {
  540. list($filename, $content) = $export_service->generateStarredEntries('S');
  541. $exported_files[$filename] = $content;
  542. } elseif ($export_labelled) {
  543. list($filename, $content) = $export_service->generateStarredEntries('T');
  544. $exported_files[$filename] = $content;
  545. }
  546. foreach ($export_feeds as $feed_id) {
  547. $result = $export_service->generateFeedEntries($feed_id, $max_number_entries);
  548. if (!$result) {
  549. // It means the actual feed_id doesn’t correspond to any existing feed
  550. continue;
  551. }
  552. list($filename, $content) = $result;
  553. $exported_files[$filename] = $content;
  554. }
  555. $nb_files = count($exported_files);
  556. if ($nb_files <= 0) {
  557. // There’s nothing to do, there’re no files to export
  558. return Minz_Request::forward(
  559. array('c' => 'importExport', 'a' => 'index'),
  560. true
  561. );
  562. }
  563. if ($nb_files === 1) {
  564. // If we only have one file, we just export it as it is
  565. $filename = key($exported_files);
  566. $content = $exported_files[$filename];
  567. } else {
  568. // More files? Let’s compress them in a Zip archive
  569. if (!extension_loaded('zip')) {
  570. // Oops, there is no ZIP extension!
  571. return Minz_Request::bad(
  572. _t('feedback.import_export.export_no_zip_extension'),
  573. array('c' => 'importExport', 'a' => 'index')
  574. );
  575. }
  576. list($filename, $content) = $export_service->zip($exported_files);
  577. }
  578. $content_type = self::filenameToContentType($filename);
  579. header('Content-Type: ' . $content_type);
  580. header('Content-disposition: attachment; filename="' . $filename . '"');
  581. $this->view->_layout(false);
  582. $this->view->content = $content;
  583. }
  584. /**
  585. * Return the Content-Type corresponding to a filename.
  586. *
  587. * If the type of the filename is not supported, it returns
  588. * `application/octet-stream` by default.
  589. *
  590. * @param string $filename
  591. *
  592. * @return string
  593. */
  594. private static function filenameToContentType($filename) {
  595. $filetype = self::guessFileType($filename);
  596. switch ($filetype) {
  597. case 'zip':
  598. return 'application/zip';
  599. case 'opml':
  600. return 'application/xml; charset=utf-8';
  601. case 'json_starred':
  602. case 'json_feed':
  603. return 'application/json; charset=utf-8';
  604. default:
  605. return 'application/octet-stream';
  606. }
  607. }
  608. }