importExportController.php 21 KB

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