importExportController.php 20 KB

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