importExportController.php 20 KB

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