importExportController.php 20 KB

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