importExportController.php 21 KB

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