4
0

importExportController.php 20 KB

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