importExportController.php 24 KB

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