importExportController.php 21 KB

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