importExportController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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. $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 (empty($item['id'])) {
  257. continue;
  258. }
  259. if (empty($item['origin'])) {
  260. $item['origin'] = [];
  261. }
  262. if (empty($item['origin']['title']) || trim($item['origin']['title']) === '') {
  263. $item['origin']['title'] = 'Import';
  264. }
  265. if (!empty($item['origin']['feedUrl'])) {
  266. $feedUrl = $item['origin']['feedUrl'];
  267. } elseif (!empty($item['origin']['streamId']) && strpos($item['origin']['streamId'], 'feed/') === 0) {
  268. $feedUrl = substr($item['origin']['streamId'], 5); //Google Reader
  269. $item['origin']['feedUrl'] = $feedUrl;
  270. } elseif (!empty($item['origin']['htmlUrl'])) {
  271. $feedUrl = $item['origin']['htmlUrl'];
  272. } else {
  273. $feedUrl = 'http://import.localhost/import.xml';
  274. $item['origin']['feedUrl'] = $feedUrl;
  275. $item['origin']['disable'] = true;
  276. }
  277. $feed = new FreshRSS_Feed($feedUrl);
  278. $feed = $this->feedDAO->searchByUrl($feed->url());
  279. if ($feed == null) {
  280. // Feed does not exist in DB,we should to try to add it.
  281. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  282. // Oops, no more place!
  283. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  284. } else {
  285. $feed = $this->addFeedJson($item['origin']);
  286. }
  287. if ($feed == null) {
  288. // Still null? It means something went wrong.
  289. $error = true;
  290. } else {
  291. $nb_feeds++;
  292. }
  293. }
  294. if ($feed != null) {
  295. $article_to_feed[$item['id']] = $feed->id();
  296. if (!isset($newFeedGuids['f_' . $feed->id()])) {
  297. $newFeedGuids['f_' . $feed->id()] = array();
  298. }
  299. $newFeedGuids['f_' . $feed->id()][] = safe_ascii($item['id']);
  300. }
  301. }
  302. $tagDAO = FreshRSS_Factory::createTagDao();
  303. $labels = $tagDAO->listTags();
  304. $knownLabels = array();
  305. foreach ($labels as $label) {
  306. $knownLabels[$label->name()]['id'] = $label->id();
  307. $knownLabels[$label->name()]['articles'] = array();
  308. }
  309. unset($labels);
  310. // For each feed, check existing GUIDs already in database.
  311. $existingHashForGuids = array();
  312. foreach ($newFeedGuids as $feedId => $newGuids) {
  313. $existingHashForGuids[$feedId] = $this->entryDAO->listHashForFeedGuids(substr($feedId, 2), $newGuids);
  314. }
  315. unset($newFeedGuids);
  316. // Then, articles are imported.
  317. $newGuids = array();
  318. $this->entryDAO->beginTransaction();
  319. foreach ($items as $item) {
  320. if (empty($item['id']) || empty($article_to_feed[$item['id']])) {
  321. // Related feed does not exist for this entry, do nothing.
  322. continue;
  323. }
  324. $feed_id = $article_to_feed[$item['id']];
  325. $author = isset($item['author']) ? $item['author'] : '';
  326. $is_starred = false;
  327. $is_read = null;
  328. $tags = empty($item['categories']) ? array() : $item['categories'];
  329. $labels = array();
  330. for ($i = count($tags) - 1; $i >= 0; $i--) {
  331. $tag = trim($tags[$i]);
  332. if (strpos($tag, 'user/-/') !== false) {
  333. if ($tag === 'user/-/state/com.google/starred') {
  334. $is_starred = true;
  335. } elseif ($tag === 'user/-/state/com.google/read') {
  336. $is_read = true;
  337. } elseif ($tag === 'user/-/state/com.google/unread') {
  338. $is_read = false;
  339. } elseif (strpos($tag, 'user/-/label/') === 0) {
  340. $tag = trim(substr($tag, 13));
  341. if ($tag != '') {
  342. $labels[] = $tag;
  343. }
  344. }
  345. unset($tags[$i]);
  346. }
  347. }
  348. if ($starred && !$is_starred) {
  349. //If the article has no label, mark it as starred (old format)
  350. $is_starred = empty($labels);
  351. }
  352. if ($is_read === null) {
  353. $is_read = $mark_as_read;
  354. }
  355. if (isset($item['alternate'][0]['href'])) {
  356. $url = $item['alternate'][0]['href'];
  357. } elseif (isset($item['url'])) {
  358. $url = $item['url']; //FeedBin
  359. } else {
  360. $url = '';
  361. }
  362. $title = empty($item['title']) ? $url : $item['title'];
  363. if (!empty($item['content']['content'])) {
  364. $content = $item['content']['content'];
  365. } elseif (!empty($item['summary']['content'])) {
  366. $content = $item['summary']['content'];
  367. } elseif (!empty($item['content'])) {
  368. $content = $item['content']; //FeedBin
  369. } else {
  370. $content = '';
  371. }
  372. $content = sanitizeHTML($content, $url);
  373. if (!empty($item['published'])) {
  374. $published = '' . $item['published'];
  375. } elseif (!empty($item['timestampUsec'])) {
  376. $published = substr('' . $item['timestampUsec'], 0, -6);
  377. } elseif (!empty($item['updated'])) {
  378. $published = '' . $item['updated'];
  379. } else {
  380. $published = '0';
  381. }
  382. if (!ctype_digit($published)) {
  383. $published = '' . strtotime($published);
  384. }
  385. if (strlen($published) > 10) { // Milliseconds, e.g. Feedly
  386. $published = substr($published, 0, -3);
  387. }
  388. $entry = new FreshRSS_Entry(
  389. $feed_id, $item['id'], $title, $author,
  390. $content, $url, $published, $is_read, $is_starred
  391. );
  392. $entry->_id(uTimeString());
  393. $entry->_tags($tags);
  394. if (isset($newGuids[$entry->guid()])) {
  395. continue; //Skip subsequent articles with same GUID
  396. }
  397. $newGuids[$entry->guid()] = true;
  398. /** @var FreshRSS_Entry|null */
  399. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  400. if ($entry == null) {
  401. // An extension has returned a null value, there is nothing to insert.
  402. continue;
  403. }
  404. $values = $entry->toArray();
  405. $ok = false;
  406. if (isset($existingHashForGuids['f_' . $feed_id][$entry->guid()])) {
  407. $ok = $this->entryDAO->updateEntry($values);
  408. } else {
  409. $ok = $this->entryDAO->addEntry($values);
  410. }
  411. foreach ($labels as $labelName) {
  412. if (empty($knownLabels[$labelName]['id'])) {
  413. $labelId = $tagDAO->addTag(array('name' => $labelName));
  414. $knownLabels[$labelName]['id'] = $labelId;
  415. $knownLabels[$labelName]['articles'] = array();
  416. }
  417. $knownLabels[$labelName]['articles'][] = array(
  418. //'id' => $entry->id(), //ID changes after commitNewEntries()
  419. 'id_feed' => $entry->feed(),
  420. 'guid' => $entry->guid(),
  421. );
  422. }
  423. $error |= ($ok === false);
  424. }
  425. $this->entryDAO->commit();
  426. $this->entryDAO->beginTransaction();
  427. $this->entryDAO->commitNewEntries();
  428. $this->feedDAO->updateCachedValues();
  429. $this->entryDAO->commit();
  430. $this->entryDAO->beginTransaction();
  431. foreach ($knownLabels as $labelName => $knownLabel) {
  432. $labelId = $knownLabel['id'];
  433. foreach ($knownLabel['articles'] as $article) {
  434. $entryId = $this->entryDAO->searchIdByGuid($article['id_feed'], $article['guid']);
  435. if ($entryId != null) {
  436. $tagDAO->tagEntry($labelId, $entryId);
  437. } else {
  438. Minz_Log::warning('Could not add label "' . $labelName . '" to entry "' . $article['guid'] . '" in feed ' . $article['id_feed']);
  439. }
  440. }
  441. }
  442. $this->entryDAO->commit();
  443. return !$error;
  444. }
  445. /**
  446. * This method import a JSON-based feed (Google Reader format).
  447. *
  448. * @param array<string,string> $origin represents a feed.
  449. * @return FreshRSS_Feed|null if feed is in database at the end of the process, else null.
  450. */
  451. private function addFeedJson($origin) {
  452. $return = null;
  453. if (!empty($origin['feedUrl'])) {
  454. $url = $origin['feedUrl'];
  455. } elseif (!empty($origin['htmlUrl'])) {
  456. $url = $origin['htmlUrl'];
  457. } else {
  458. return null;
  459. }
  460. if (!empty($origin['htmlUrl'])) {
  461. $website = $origin['htmlUrl'];
  462. } elseif (!empty($origin['feedUrl'])) {
  463. $website = $origin['feedUrl'];
  464. } else {
  465. $website = '';
  466. }
  467. $name = empty($origin['title']) ? $website : $origin['title'];
  468. try {
  469. // Create a Feed object and add it in database.
  470. $feed = new FreshRSS_Feed($url);
  471. $feed->_category(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  472. $feed->_name($name);
  473. $feed->_website($website);
  474. if (!empty($origin['disable'])) {
  475. $feed->_mute(true);
  476. }
  477. // Call the extension hook
  478. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  479. if ($feed != null) {
  480. // addFeedObject checks if feed is already in DB so nothing else to
  481. // check here.
  482. $id = $this->feedDAO->addFeedObject($feed);
  483. if ($id !== false) {
  484. $feed->_id($id);
  485. $return = $feed;
  486. }
  487. }
  488. } catch (FreshRSS_Feed_Exception $e) {
  489. if (FreshRSS_Context::$isCli) {
  490. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  491. } else {
  492. Minz_Log::warning($e->getMessage());
  493. }
  494. }
  495. return $return;
  496. }
  497. /**
  498. * This action handles export action.
  499. *
  500. * This action must be reached by a POST request.
  501. *
  502. * Parameters are:
  503. * - export_opml (default: false)
  504. * - export_starred (default: false)
  505. * - export_labelled (default: false)
  506. * - export_feeds (default: array()) a list of feed ids
  507. */
  508. public function exportAction() {
  509. if (!Minz_Request::isPost()) {
  510. return Minz_Request::forward(
  511. array('c' => 'importExport', 'a' => 'index'),
  512. true
  513. );
  514. }
  515. $username = Minz_Session::param('currentUser');
  516. $export_service = new FreshRSS_Export_Service($username);
  517. $export_opml = Minz_Request::param('export_opml', false);
  518. $export_starred = Minz_Request::param('export_starred', false);
  519. $export_labelled = Minz_Request::param('export_labelled', false);
  520. $export_feeds = Minz_Request::param('export_feeds', array());
  521. $max_number_entries = 50;
  522. $exported_files = [];
  523. if ($export_opml) {
  524. list($filename, $content) = $export_service->generateOpml();
  525. $exported_files[$filename] = $content;
  526. }
  527. // Starred and labelled entries are merged in the same `starred` file
  528. // to avoid duplication of content.
  529. if ($export_starred && $export_labelled) {
  530. list($filename, $content) = $export_service->generateStarredEntries('ST');
  531. $exported_files[$filename] = $content;
  532. } elseif ($export_starred) {
  533. list($filename, $content) = $export_service->generateStarredEntries('S');
  534. $exported_files[$filename] = $content;
  535. } elseif ($export_labelled) {
  536. list($filename, $content) = $export_service->generateStarredEntries('T');
  537. $exported_files[$filename] = $content;
  538. }
  539. foreach ($export_feeds as $feed_id) {
  540. $result = $export_service->generateFeedEntries($feed_id, $max_number_entries);
  541. if (!$result) {
  542. // It means the actual feed_id doesn’t correspond to any existing feed
  543. continue;
  544. }
  545. list($filename, $content) = $result;
  546. $exported_files[$filename] = $content;
  547. }
  548. $nb_files = count($exported_files);
  549. if ($nb_files <= 0) {
  550. // There’s nothing to do, there’re no files to export
  551. return Minz_Request::forward(
  552. array('c' => 'importExport', 'a' => 'index'),
  553. true
  554. );
  555. }
  556. if ($nb_files === 1) {
  557. // If we only have one file, we just export it as it is
  558. $filename = key($exported_files);
  559. $content = $exported_files[$filename];
  560. } else {
  561. // More files? Let’s compress them in a Zip archive
  562. if (!extension_loaded('zip')) {
  563. // Oops, there is no ZIP extension!
  564. return Minz_Request::bad(
  565. _t('feedback.import_export.export_no_zip_extension'),
  566. array('c' => 'importExport', 'a' => 'index')
  567. );
  568. }
  569. list($filename, $content) = $export_service->zip($exported_files);
  570. }
  571. $content_type = self::filenameToContentType($filename);
  572. header('Content-Type: ' . $content_type);
  573. header('Content-disposition: attachment; filename="' . $filename . '"');
  574. $this->view->_layout(false);
  575. $this->view->content = $content;
  576. }
  577. /**
  578. * Return the Content-Type corresponding to a filename.
  579. *
  580. * If the type of the filename is not supported, it returns
  581. * `application/octet-stream` by default.
  582. *
  583. * @param string $filename
  584. *
  585. * @return string
  586. */
  587. private static function filenameToContentType($filename) {
  588. $filetype = self::guessFileType($filename);
  589. switch ($filetype) {
  590. case 'zip':
  591. return 'application/zip';
  592. case 'opml':
  593. return 'application/xml; charset=utf-8';
  594. case 'json_starred':
  595. case 'json_feed':
  596. return 'application/json; charset=utf-8';
  597. default:
  598. return 'application/octet-stream';
  599. }
  600. }
  601. }