importExportController.php 21 KB

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