importExportController.php 21 KB

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