importExportController.php 21 KB

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