importExportController.php 21 KB

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