4
0

importExportController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. <?php
  2. /**
  3. * Controller to handle every import and export actions.
  4. */
  5. class FreshRSS_importExport_Controller extends FreshRSS_ActionController {
  6. private $entryDAO;
  7. private $feedDAO;
  8. /**
  9. * This action is called before every other action in that class. It is
  10. * the common boiler plate for every action. It is triggered by the
  11. * underlying framework.
  12. */
  13. public function firstAction() {
  14. if (!FreshRSS_Auth::hasAccess()) {
  15. Minz_Error::error(403);
  16. }
  17. require_once(LIB_PATH . '/lib_opml.php');
  18. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  19. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  20. }
  21. /**
  22. * This action displays the main page for import / export system.
  23. */
  24. public function indexAction() {
  25. $this->view->feeds = $this->feedDAO->listFeeds();
  26. FreshRSS_View::prependTitle(_t('sub.import_export.title') . ' · ');
  27. }
  28. private static function megabytes($size_str) {
  29. switch (substr($size_str, -1)) {
  30. case 'M': case 'm': return (int)$size_str;
  31. case 'K': case 'k': return (int)$size_str / 1024;
  32. case 'G': case 'g': return (int)$size_str * 1024;
  33. }
  34. return $size_str;
  35. }
  36. private static function minimumMemory($mb) {
  37. $mb = (int)$mb;
  38. $ini = self::megabytes(ini_get('memory_limit'));
  39. if ($ini < $mb) {
  40. ini_set('memory_limit', $mb . 'M');
  41. }
  42. }
  43. public function importFile($name, $path, $username = null) {
  44. self::minimumMemory(256);
  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. * It is a *very* basic guess file type function. Only based on filename.
  165. * That 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 (stripos($filename, 'opml') !== false) {
  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(string $xml) {
  188. $table = (array)simplexml_load_string($xml, null, LIBXML_NOBLANKS | 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 = array_filter($item, function ($v) {
  194. // Filter out empty properties, potentially reported as empty objects
  195. return (is_string($v) && trim($v) !== '') || !empty($v);
  196. });
  197. $item['updated'] = isset($item['updated']) ? strtotime($item['updated']) : '';
  198. $item['published'] = $item['updated'];
  199. $item['content'] = array('content' => isset($item['content']) ? $item['content'] : '');
  200. $item['categories'] = isset($item['tag_cache']) ? array($item['tag_cache']) : array();
  201. if (!empty($item['marked'])) {
  202. $item['categories'][] = 'user/-/state/com.google/starred';
  203. }
  204. if (!empty($item['published'])) {
  205. $item['categories'][] = 'user/-/state/com.google/broadcast';
  206. }
  207. if (!empty($item['label_cache'])) {
  208. $labels_cache = json_decode($item['label_cache'], true);
  209. if (is_array($labels_cache)) {
  210. foreach ($labels_cache as $label_cache) {
  211. if (!empty($label_cache[1])) {
  212. $item['categories'][] = 'user/-/label/' . trim($label_cache[1]);
  213. }
  214. }
  215. }
  216. }
  217. $item['alternate'][0]['href'] = isset($item['link']) ? $item['link'] : '';
  218. $item['origin'] = array(
  219. 'title' => isset($item['feed_title']) ? $item['feed_title'] : '',
  220. 'feedUrl' => isset($item['feed_url']) ? $item['feed_url'] : '',
  221. );
  222. $item['id'] = isset($item['guid']) ? $item['guid'] : (isset($item['feed_url']) ? $item['feed_url'] : $item['published']);
  223. $table['items'][$i] = $item;
  224. }
  225. return json_encode($table);
  226. }
  227. /**
  228. * This method import a JSON-based file (Google Reader format).
  229. *
  230. * @param string $article_file the JSON file content.
  231. * @param boolean $starred true if articles from the file must be starred.
  232. * @return boolean false if an error occurred, true otherwise.
  233. */
  234. private function importJson($article_file, $starred = false) {
  235. $article_object = json_decode($article_file, true);
  236. if ($article_object == null) {
  237. if (FreshRSS_Context::$isCli) {
  238. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  239. } else {
  240. Minz_Log::warning('Try to import a non-JSON file');
  241. }
  242. return false;
  243. }
  244. $items = isset($article_object['items']) ? $article_object['items'] : $article_object;
  245. $mark_as_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0;
  246. $error = false;
  247. $article_to_feed = array();
  248. $nb_feeds = count($this->feedDAO->listFeeds());
  249. $newFeedGuids = array();
  250. $limits = FreshRSS_Context::$system_conf->limits;
  251. // First, we check feeds of articles are in DB (and add them if needed).
  252. foreach ($items as $item) {
  253. if (empty($item['id'])) {
  254. continue;
  255. }
  256. if (empty($item['origin'])) {
  257. $item['origin'] = [];
  258. }
  259. if (empty($item['origin']['title']) || trim($item['origin']['title']) === '') {
  260. $item['origin']['title'] = 'Import';
  261. }
  262. if (!empty($item['origin']['feedUrl'])) {
  263. $feedUrl = $item['origin']['feedUrl'];
  264. } elseif (!empty($item['origin']['streamId']) && strpos($item['origin']['streamId'], 'feed/') === 0) {
  265. $feedUrl = substr($item['origin']['streamId'], 5); //Google Reader
  266. $item['origin']['feedUrl'] = $feedUrl;
  267. } elseif (!empty($item['origin']['htmlUrl'])) {
  268. $feedUrl = $item['origin']['htmlUrl'];
  269. } else {
  270. $feedUrl = 'http://import.localhost/import.xml';
  271. $item['origin']['feedUrl'] = $feedUrl;
  272. $item['origin']['disable'] = true;
  273. }
  274. $feed = new FreshRSS_Feed($feedUrl);
  275. $feed = $this->feedDAO->searchByUrl($feed->url());
  276. if ($feed == null) {
  277. // Feed does not exist in DB,we should to try to add it.
  278. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  279. // Oops, no more place!
  280. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  281. } else {
  282. $feed = $this->addFeedJson($item['origin']);
  283. }
  284. if ($feed == null) {
  285. // Still null? It means something went wrong.
  286. $error = true;
  287. } else {
  288. $nb_feeds++;
  289. }
  290. }
  291. if ($feed != null) {
  292. $article_to_feed[$item['id']] = $feed->id();
  293. if (!isset($newFeedGuids['f_' . $feed->id()])) {
  294. $newFeedGuids['f_' . $feed->id()] = array();
  295. }
  296. $newFeedGuids['f_' . $feed->id()][] = safe_ascii($item['id']);
  297. }
  298. }
  299. $tagDAO = FreshRSS_Factory::createTagDao();
  300. $labels = $tagDAO->listTags();
  301. $knownLabels = array();
  302. foreach ($labels as $label) {
  303. $knownLabels[$label->name()]['id'] = $label->id();
  304. $knownLabels[$label->name()]['articles'] = array();
  305. }
  306. unset($labels);
  307. // For each feed, check existing GUIDs already in database.
  308. $existingHashForGuids = array();
  309. foreach ($newFeedGuids as $feedId => $newGuids) {
  310. $existingHashForGuids[$feedId] = $this->entryDAO->listHashForFeedGuids(substr($feedId, 2), $newGuids);
  311. }
  312. unset($newFeedGuids);
  313. // Then, articles are imported.
  314. $newGuids = array();
  315. $this->entryDAO->beginTransaction();
  316. foreach ($items as $item) {
  317. if (empty($item['id']) || empty($article_to_feed[$item['id']])) {
  318. // Related feed does not exist for this entry, do nothing.
  319. continue;
  320. }
  321. $feed_id = $article_to_feed[$item['id']];
  322. $author = isset($item['author']) ? $item['author'] : '';
  323. $is_starred = false;
  324. $is_read = null;
  325. $tags = empty($item['categories']) ? array() : $item['categories'];
  326. $labels = array();
  327. for ($i = count($tags) - 1; $i >= 0; $i--) {
  328. $tag = trim($tags[$i]);
  329. if (strpos($tag, 'user/-/') !== false) {
  330. if ($tag === 'user/-/state/com.google/starred') {
  331. $is_starred = true;
  332. } elseif ($tag === 'user/-/state/com.google/read') {
  333. $is_read = true;
  334. } elseif ($tag === 'user/-/state/com.google/unread') {
  335. $is_read = false;
  336. } elseif (strpos($tag, 'user/-/label/') === 0) {
  337. $tag = trim(substr($tag, 13));
  338. if ($tag != '') {
  339. $labels[] = $tag;
  340. }
  341. }
  342. unset($tags[$i]);
  343. }
  344. }
  345. if ($starred && !$is_starred) {
  346. //If the article has no label, mark it as starred (old format)
  347. $is_starred = empty($labels);
  348. }
  349. if ($is_read === null) {
  350. $is_read = $mark_as_read;
  351. }
  352. if (isset($item['alternate'][0]['href'])) {
  353. $url = $item['alternate'][0]['href'];
  354. } elseif (isset($item['url'])) {
  355. $url = $item['url']; //FeedBin
  356. } else {
  357. $url = '';
  358. }
  359. $title = empty($item['title']) ? $url : $item['title'];
  360. if (!empty($item['content']['content'])) {
  361. $content = $item['content']['content'];
  362. } elseif (!empty($item['summary']['content'])) {
  363. $content = $item['summary']['content'];
  364. } elseif (!empty($item['content'])) {
  365. $content = $item['content']; //FeedBin
  366. } else {
  367. $content = '';
  368. }
  369. $content = sanitizeHTML($content, $url);
  370. if (!empty($item['published'])) {
  371. $published = '' . $item['published'];
  372. } elseif (!empty($item['timestampUsec'])) {
  373. $published = substr('' . $item['timestampUsec'], 0, -6);
  374. } elseif (!empty($item['updated'])) {
  375. $published = '' . $item['updated'];
  376. } else {
  377. $published = '0';
  378. }
  379. if (!ctype_digit($published)) {
  380. $published = '' . strtotime($published);
  381. }
  382. if (strlen($published) > 10) { // Milliseconds, e.g. Feedly
  383. $published = substr($published, 0, -3);
  384. }
  385. $entry = new FreshRSS_Entry(
  386. $feed_id, $item['id'], $title, $author,
  387. $content, $url, $published, $is_read, $is_starred
  388. );
  389. $entry->_id(uTimeString());
  390. $entry->_tags($tags);
  391. if (isset($newGuids[$entry->guid()])) {
  392. continue; //Skip subsequent articles with same GUID
  393. }
  394. $newGuids[$entry->guid()] = true;
  395. $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
  396. if ($entry == null) {
  397. // An extension has returned a null value, there is nothing to insert.
  398. continue;
  399. }
  400. $values = $entry->toArray();
  401. $ok = false;
  402. if (isset($existingHashForGuids['f_' . $feed_id][$entry->guid()])) {
  403. $ok = $this->entryDAO->updateEntry($values);
  404. } else {
  405. $ok = $this->entryDAO->addEntry($values);
  406. }
  407. foreach ($labels as $labelName) {
  408. if (empty($knownLabels[$labelName]['id'])) {
  409. $labelId = $tagDAO->addTag(array('name' => $labelName));
  410. $knownLabels[$labelName]['id'] = $labelId;
  411. $knownLabels[$labelName]['articles'] = array();
  412. }
  413. $knownLabels[$labelName]['articles'][] = array(
  414. //'id' => $entry->id(), //ID changes after commitNewEntries()
  415. 'id_feed' => $entry->feed(),
  416. 'guid' => $entry->guid(),
  417. );
  418. }
  419. $error |= ($ok === false);
  420. }
  421. $this->entryDAO->commit();
  422. $this->entryDAO->beginTransaction();
  423. $this->entryDAO->commitNewEntries();
  424. $this->feedDAO->updateCachedValues();
  425. $this->entryDAO->commit();
  426. $this->entryDAO->beginTransaction();
  427. foreach ($knownLabels as $labelName => $knownLabel) {
  428. $labelId = $knownLabel['id'];
  429. foreach ($knownLabel['articles'] as $article) {
  430. $entryId = $this->entryDAO->searchIdByGuid($article['id_feed'], $article['guid']);
  431. if ($entryId != null) {
  432. $tagDAO->tagEntry($labelId, $entryId);
  433. } else {
  434. Minz_Log::warning('Could not add label "' . $labelName . '" to entry "' . $article['guid'] . '" in feed ' . $article['id_feed']);
  435. }
  436. }
  437. }
  438. $this->entryDAO->commit();
  439. return !$error;
  440. }
  441. /**
  442. * This method import a JSON-based feed (Google Reader format).
  443. *
  444. * @param array<string,string> $origin represents a feed.
  445. * @return FreshRSS_Feed|null if feed is in database at the end of the process, else null.
  446. */
  447. private function addFeedJson($origin) {
  448. $return = null;
  449. if (!empty($origin['feedUrl'])) {
  450. $url = $origin['feedUrl'];
  451. } elseif (!empty($origin['htmlUrl'])) {
  452. $url = $origin['htmlUrl'];
  453. } else {
  454. return null;
  455. }
  456. if (!empty($origin['htmlUrl'])) {
  457. $website = $origin['htmlUrl'];
  458. } elseif (!empty($origin['feedUrl'])) {
  459. $website = $origin['feedUrl'];
  460. } else {
  461. $website = '';
  462. }
  463. $name = empty($origin['title']) ? $website : $origin['title'];
  464. try {
  465. // Create a Feed object and add it in database.
  466. $feed = new FreshRSS_Feed($url);
  467. $feed->_category(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  468. $feed->_name($name);
  469. $feed->_website($website);
  470. if (!empty($origin['disable'])) {
  471. $feed->_ttl(-1 * FreshRSS_Context::$user_conf->ttl_default);
  472. }
  473. // Call the extension hook
  474. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  475. if ($feed != null) {
  476. // addFeedObject checks if feed is already in DB so nothing else to
  477. // check here.
  478. $id = $this->feedDAO->addFeedObject($feed);
  479. if ($id !== false) {
  480. $feed->_id($id);
  481. $return = $feed;
  482. }
  483. }
  484. } catch (FreshRSS_Feed_Exception $e) {
  485. if (FreshRSS_Context::$isCli) {
  486. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  487. } else {
  488. Minz_Log::warning($e->getMessage());
  489. }
  490. }
  491. return $return;
  492. }
  493. /**
  494. * This action handles export action.
  495. *
  496. * This action must be reached by a POST request.
  497. *
  498. * Parameters are:
  499. * - export_opml (default: false)
  500. * - export_starred (default: false)
  501. * - export_labelled (default: false)
  502. * - export_feeds (default: array()) a list of feed ids
  503. */
  504. public function exportAction() {
  505. if (!Minz_Request::isPost()) {
  506. return Minz_Request::forward(
  507. array('c' => 'importExport', 'a' => 'index'),
  508. true
  509. );
  510. }
  511. $username = Minz_Session::param('currentUser');
  512. $export_service = new FreshRSS_Export_Service($username);
  513. $export_opml = Minz_Request::param('export_opml', false);
  514. $export_starred = Minz_Request::param('export_starred', false);
  515. $export_labelled = Minz_Request::param('export_labelled', false);
  516. $export_feeds = Minz_Request::param('export_feeds', array());
  517. $max_number_entries = 50;
  518. $exported_files = [];
  519. if ($export_opml) {
  520. list($filename, $content) = $export_service->generateOpml();
  521. $exported_files[$filename] = $content;
  522. }
  523. // Starred and labelled entries are merged in the same `starred` file
  524. // to avoid duplication of content.
  525. if ($export_starred && $export_labelled) {
  526. list($filename, $content) = $export_service->generateStarredEntries('ST');
  527. $exported_files[$filename] = $content;
  528. } elseif ($export_starred) {
  529. list($filename, $content) = $export_service->generateStarredEntries('S');
  530. $exported_files[$filename] = $content;
  531. } elseif ($export_labelled) {
  532. list($filename, $content) = $export_service->generateStarredEntries('T');
  533. $exported_files[$filename] = $content;
  534. }
  535. foreach ($export_feeds as $feed_id) {
  536. $result = $export_service->generateFeedEntries($feed_id, $max_number_entries);
  537. if (!$result) {
  538. // It means the actual feed_id doesn’t correspond to any existing feed
  539. continue;
  540. }
  541. list($filename, $content) = $result;
  542. $exported_files[$filename] = $content;
  543. }
  544. $nb_files = count($exported_files);
  545. if ($nb_files <= 0) {
  546. // There’s nothing to do, there’re no files to export
  547. return Minz_Request::forward(
  548. array('c' => 'importExport', 'a' => 'index'),
  549. true
  550. );
  551. }
  552. if ($nb_files === 1) {
  553. // If we only have one file, we just export it as it is
  554. $filename = key($exported_files);
  555. $content = $exported_files[$filename];
  556. } else {
  557. // More files? Let’s compress them in a Zip archive
  558. if (!extension_loaded('zip')) {
  559. // Oops, there is no ZIP extension!
  560. return Minz_Request::bad(
  561. _t('feedback.import_export.export_no_zip_extension'),
  562. array('c' => 'importExport', 'a' => 'index')
  563. );
  564. }
  565. list($filename, $content) = $export_service->zip($exported_files);
  566. }
  567. $content_type = self::filenameToContentType($filename);
  568. header('Content-Type: ' . $content_type);
  569. header('Content-disposition: attachment; filename="' . $filename . '"');
  570. $this->view->_layout(false);
  571. $this->view->content = $content;
  572. }
  573. /**
  574. * Return the Content-Type corresponding to a filename.
  575. *
  576. * If the type of the filename is not supported, it returns
  577. * `application/octet-stream` by default.
  578. *
  579. * @param string $filename
  580. *
  581. * @return string
  582. */
  583. private static function filenameToContentType($filename) {
  584. $filetype = self::guessFileType($filename);
  585. switch ($filetype) {
  586. case 'zip':
  587. return 'application/zip';
  588. case 'opml':
  589. return 'application/xml; charset=utf-8';
  590. case 'json_starred':
  591. case 'json_feed':
  592. return 'application/json; charset=utf-8';
  593. default:
  594. return 'application/octet-stream';
  595. }
  596. }
  597. }