importExportController.php 21 KB

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