importExportController.php 21 KB

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