4
0

importExportController.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. private FreshRSS_CategoryDAO $categoryDAO;
  10. /**
  11. * ZIP import safety limits (defence against ZIP bombs / decompression DoS).
  12. * A legitimate export is an OPML plus a handful of JSON files, so these ceilings
  13. * sit far above any realistic export while keeping import memory bounded.
  14. */
  15. private const IMPORT_ZIP_MAX_MEMBERS = 100;
  16. private const IMPORT_ZIP_MEMBER_MAX_SIZE = 64 * 1024 * 1024;
  17. private const IMPORT_ZIP_TOTAL_MAX_SIZE = 128 * 1024 * 1024;
  18. private const IMPORT_ZIP_MAX_RATIO = 100;
  19. /**
  20. * Read a ZIP member by name through a stream, aborting once the decompressed
  21. * content exceeds $maxBytes. Returns null on read error or when the cap is
  22. * exceeded, so a forged/under-reported uncompressed size in the archive
  23. * metadata cannot be used to force unbounded memory allocation.
  24. */
  25. private static function readZipMemberCapped(ZipArchive $zip, string $name, int $maxBytes): ?string {
  26. $stream = $zip->getStream($name);
  27. if ($stream === false) {
  28. return null;
  29. }
  30. $content = '';
  31. try {
  32. while (!feof($stream)) {
  33. $chunk = fread($stream, 1 << 16);
  34. if ($chunk === false) {
  35. return null;
  36. }
  37. $content .= $chunk;
  38. if (strlen($content) > $maxBytes) {
  39. return null;
  40. }
  41. }
  42. } finally {
  43. fclose($stream);
  44. }
  45. return $content;
  46. }
  47. /**
  48. * This action is called before every other action in that class. It is
  49. * the common boilerplate for every action. It is triggered by the
  50. * underlying framework.
  51. */
  52. #[\Override]
  53. public function firstAction(): void {
  54. if (!FreshRSS_Auth::hasAccess()) {
  55. Minz_Error::error(403);
  56. }
  57. $this->entryDAO = FreshRSS_Factory::createEntryDao();
  58. $this->feedDAO = FreshRSS_Factory::createFeedDao();
  59. $this->categoryDAO = FreshRSS_Factory::createCategoryDao();
  60. }
  61. /**
  62. * This action displays the main page for import / export system.
  63. */
  64. public function indexAction(): void {
  65. $this->view->categories = array_filter(
  66. $this->categoryDAO->listCategories(),
  67. static fn(FreshRSS_Category $category): bool => !empty($category->feeds()),
  68. );
  69. $this->view->feedCount = array_sum(array_map(static fn(FreshRSS_Category $category): int => count($category->feeds()), $this->view->categories));
  70. FreshRSS_View::prependTitle(_t('sub.import_export.title') . ' · ');
  71. $this->listSqliteArchives();
  72. }
  73. private static function megabytes(string $size_str): float|int|string {
  74. return match (substr($size_str, -1)) {
  75. 'M', 'm' => (int)$size_str,
  76. 'K', 'k' => (int)$size_str / 1024,
  77. 'G', 'g' => (int)$size_str * 1024,
  78. default => $size_str,
  79. };
  80. }
  81. private static function minimumMemory(int|string $mb): void {
  82. $mb = (int)$mb;
  83. $ini = self::megabytes(ini_get('memory_limit') ?: '0');
  84. if ($ini < $mb) {
  85. ini_set('memory_limit', $mb . 'M');
  86. }
  87. }
  88. /**
  89. * @throws FreshRSS_Zip_Exception
  90. * @throws FreshRSS_ZipMissing_Exception
  91. * @throws Minz_ConfigurationNamespaceException
  92. * @throws Minz_PDOConnectionException
  93. */
  94. public function importFile(string $name, string $path, ?string $username = null): bool {
  95. self::minimumMemory(256);
  96. $this->entryDAO = FreshRSS_Factory::createEntryDao($username);
  97. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  98. $this->categoryDAO = FreshRSS_Factory::createCategoryDao($username);
  99. $type_file = self::guessFileType($name);
  100. $list_files = [
  101. 'opml' => [],
  102. 'json_starred' => [],
  103. 'json_feed' => [],
  104. 'ttrss_starred' => [],
  105. ];
  106. // We try to list all files according to their type
  107. $skipped = false;
  108. if ('zip' === $type_file && extension_loaded('zip')) {
  109. $zip = new ZipArchive();
  110. $result = $zip->open($path);
  111. if (true !== $result) {
  112. // zip_open cannot open file: something is wrong
  113. throw new FreshRSS_Zip_Exception($result);
  114. }
  115. $accepted = 0;
  116. $totalUncompressed = 0;
  117. for ($i = 0; $i < $zip->numFiles; $i++) {
  118. $entryName = $zip->getNameIndex($i);
  119. if ($entryName === false) {
  120. continue;
  121. }
  122. $type_zipfile = self::guessFileType($entryName);
  123. if ('unknown' === $type_zipfile) {
  124. continue;
  125. }
  126. if ($zip->locateName($entryName) !== $i) {
  127. // Duplicate entry name: keep only the first occurrence
  128. continue;
  129. }
  130. // Reject obvious ZIP bombs cheaply from the central-directory metadata...
  131. $stat = $zip->statIndex($i);
  132. $declaredSize = is_array($stat) ? (int)($stat['size'] ?? 0) : 0;
  133. $compSize = is_array($stat) ? (int)($stat['comp_size'] ?? 0) : 0;
  134. if ($declaredSize > self::IMPORT_ZIP_MEMBER_MAX_SIZE
  135. || ($compSize > 0 && $declaredSize / $compSize > self::IMPORT_ZIP_MAX_RATIO)) {
  136. Minz_Log::warning('Import: skipping oversized/over-compressed ZIP member: ' . $entryName);
  137. $skipped = true;
  138. continue;
  139. }
  140. if ($accepted >= self::IMPORT_ZIP_MAX_MEMBERS) {
  141. Minz_Log::warning('Import: ZIP member budget reached, remaining members skipped');
  142. break;
  143. }
  144. // ...then enforce the real decompressed size while streaming, since the
  145. // declared metadata above is attacker-controlled and can under-report.
  146. $content = self::readZipMemberCapped($zip, $entryName, self::IMPORT_ZIP_MEMBER_MAX_SIZE);
  147. if ($content === null) {
  148. Minz_Log::warning('Import: skipping unreadable/over-limit ZIP member: ' . $entryName);
  149. $skipped = true;
  150. continue;
  151. }
  152. $totalUncompressed += strlen($content);
  153. if ($totalUncompressed > self::IMPORT_ZIP_TOTAL_MAX_SIZE) {
  154. Minz_Log::warning('Import: ZIP total size reached, remaining members skipped');
  155. $skipped = true;
  156. break;
  157. }
  158. $list_files[$type_zipfile][] = $content;
  159. $accepted++;
  160. }
  161. $zip->close();
  162. } elseif ('zip' === $type_file) {
  163. // ZIP extension is not loaded
  164. throw new FreshRSS_ZipMissing_Exception();
  165. } elseif ('txt' === $type_file) {
  166. $contents = file_get_contents($path);
  167. if (is_string($contents)) {
  168. $list_files['opml'][] = self::txtToOpml($contents);
  169. }
  170. } elseif ('unknown' !== $type_file) {
  171. $list_files[$type_file][] = file_get_contents($path);
  172. }
  173. // Import file contents.
  174. // OPML first(so categories and feeds are imported)
  175. // Starred articles then so the "favourite" status is already set
  176. // And finally all other files.
  177. $ok = !$skipped;
  178. $importService = new FreshRSS_Import_Service($username);
  179. foreach ($list_files['opml'] as $opml_file) {
  180. if ($opml_file === false) {
  181. continue;
  182. }
  183. $importService->importOpml($opml_file, trusted_source: true);
  184. if (!$importService->lastStatus()) {
  185. $ok = false;
  186. if (FreshRSS_Context::$isCli) {
  187. fwrite(STDERR, 'FreshRSS error during OPML import' . "\n");
  188. } else {
  189. Minz_Log::warning('Error during OPML import');
  190. }
  191. }
  192. }
  193. foreach ($list_files['json_starred'] as $article_file) {
  194. if (!is_string($article_file) || !$this->importJson($article_file, true)) {
  195. $ok = false;
  196. if (FreshRSS_Context::$isCli) {
  197. fwrite(STDERR, 'FreshRSS error during JSON stars import' . "\n");
  198. } else {
  199. Minz_Log::warning('Error during JSON stars import');
  200. }
  201. }
  202. }
  203. foreach ($list_files['json_feed'] as $article_file) {
  204. if (!is_string($article_file) || !$this->importJson($article_file)) {
  205. $ok = false;
  206. if (FreshRSS_Context::$isCli) {
  207. fwrite(STDERR, 'FreshRSS error during JSON feeds import' . "\n");
  208. } else {
  209. Minz_Log::warning('Error during JSON feeds import');
  210. }
  211. }
  212. }
  213. foreach ($list_files['ttrss_starred'] as $article_file) {
  214. $json = is_string($article_file) ? $this->ttrssXmlToJson($article_file) : false;
  215. if ($json === false || !$this->importJson($json, true)) {
  216. $ok = false;
  217. if (FreshRSS_Context::$isCli) {
  218. fwrite(STDERR, 'FreshRSS error during TT-RSS articles import' . "\n");
  219. } else {
  220. Minz_Log::warning('Error during TT-RSS articles import');
  221. }
  222. }
  223. }
  224. return $ok;
  225. }
  226. /**
  227. * This action handles import action.
  228. *
  229. * It must be reached by a POST request.
  230. *
  231. * Parameter is:
  232. * - file (default: nothing!)
  233. * Available file types are: zip, json or xml.
  234. */
  235. public function importAction(): void {
  236. if (!Minz_Request::isPost()) {
  237. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  238. }
  239. $file = $_FILES['file'] ?? null;
  240. $status_file = is_array($file) ? $file['error'] ?? -1 : -1;
  241. if (!is_array($file) || $status_file !== 0 || !is_string($file['name'] ?? null) || !is_string($file['tmp_name'] ?? null)) {
  242. Minz_Log::warning('File cannot be uploaded. Error code: ' . (is_numeric($status_file) ? $status_file : -1));
  243. Minz_Request::bad(_t('feedback.import_export.file_cannot_be_uploaded'), [ 'c' => 'importExport', 'a' => 'index' ]);
  244. return;
  245. }
  246. if (function_exists('set_time_limit')) {
  247. @set_time_limit(300);
  248. }
  249. $error = false;
  250. try {
  251. $error = !$this->importFile($file['name'], $file['tmp_name']);
  252. } catch (FreshRSS_ZipMissing_Exception) {
  253. Minz_Request::bad(
  254. _t('feedback.import_export.no_zip_extension'),
  255. ['c' => 'importExport', 'a' => 'index']
  256. );
  257. } catch (FreshRSS_Zip_Exception $ze) {
  258. Minz_Log::warning('ZIP archive cannot be imported. Error code: ' . $ze->zipErrorCode());
  259. Minz_Request::bad(
  260. _t('feedback.import_export.zip_error'),
  261. ['c' => 'importExport', 'a' => 'index']
  262. );
  263. }
  264. // And finally, we get import status and redirect to the home page
  265. $content_notif = $error === true ? _t('feedback.import_export.feeds_imported_with_errors') : _t('feedback.import_export.feeds_imported');
  266. Minz_Request::good(
  267. $content_notif,
  268. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  269. );
  270. }
  271. /**
  272. * This method tries to guess the file type based on its name.
  273. *
  274. * It is a *very* basic guess file type function. Only based on filename.
  275. * That could be improved but should be enough for what we have to do.
  276. */
  277. private static function guessFileType(string $filename): string {
  278. if (str_ends_with($filename, '.zip')) {
  279. return 'zip';
  280. } elseif (str_ends_with($filename, '.txt')) {
  281. return 'txt';
  282. } elseif (stripos($filename, 'opml') !== false) {
  283. return 'opml';
  284. } elseif (str_ends_with($filename, '.json')) {
  285. if (str_contains($filename, 'starred')) {
  286. return 'json_starred';
  287. } else {
  288. return 'json_feed';
  289. }
  290. } elseif (str_ends_with($filename, '.xml')) {
  291. if (preg_match('/Tiny|tt-?rss/i', $filename)) {
  292. return 'ttrss_starred';
  293. } else {
  294. return 'opml';
  295. }
  296. }
  297. return 'unknown';
  298. }
  299. /**
  300. * Wraps a newline-separated list of feed URLs into a minimal OPML document
  301. * so it can be imported through the existing OPML pipeline.
  302. */
  303. private static function txtToOpml(string $contents): string {
  304. $utf8BOM = "\xEF\xBB\xBF";
  305. $contents = preg_replace('/^' . $utf8BOM . '/', '', $contents) ?? $contents;
  306. $outlines = '';
  307. foreach (preg_split('/\R/', $contents) ?: [] as $line) {
  308. $url = trim($line);
  309. if ($url === '' || str_starts_with($url, '#') || str_starts_with($url, '<')) {
  310. continue;
  311. }
  312. if (filter_var($url, FILTER_VALIDATE_URL) === false) {
  313. $message = 'TXT import: skipping invalid URL “' . \SimplePie\Misc::url_remove_credentials($url) . '”';
  314. if (FreshRSS_Context::$isCli) {
  315. fwrite(STDERR, $message . "\n");
  316. } else {
  317. Minz_Log::warning($message);
  318. }
  319. continue;
  320. }
  321. $escaped = htmlspecialchars($url, ENT_COMPAT | ENT_XML1, 'UTF-8');
  322. $outlines .= '<outline type="rss" text="' . $escaped . '" xmlUrl="' . $escaped . '" />' . "\n";
  323. }
  324. return '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
  325. . '<opml version="2.0"><body>' . "\n"
  326. . $outlines
  327. . '</body></opml>' . "\n";
  328. }
  329. private function ttrssXmlToJson(string $xml): string|false {
  330. $table = (array)simplexml_load_string($xml, options: LIBXML_NOBLANKS | LIBXML_NOCDATA);
  331. $table['items'] = $table['article'] ?? [];
  332. if (!is_array($table['items'])) {
  333. $table['items'] = [];
  334. }
  335. unset($table['article']);
  336. for ($i = count($table['items']) - 1; $i >= 0; $i--) {
  337. $item = (array)($table['items'][$i]);
  338. $item = array_filter($item, static fn($v) =>
  339. // Filter out empty properties, potentially reported as empty objects
  340. (is_string($v) && trim($v) !== '') || !empty($v));
  341. $item['updated'] = is_string($item['updated'] ?? null) ? strtotime($item['updated']) : '';
  342. $item['published'] = $item['updated'];
  343. $item['content'] = ['content' => $item['content'] ?? ''];
  344. $item['categories'] = is_string($item['tag_cache'] ?? null) ? [$item['tag_cache']] : [];
  345. if (!empty($item['marked'])) {
  346. $item['categories'][] = 'user/-/state/com.google/starred';
  347. }
  348. if (!empty($item['published'])) {
  349. $item['categories'][] = 'user/-/state/com.google/broadcast';
  350. }
  351. if (is_string($item['label_cache'] ?? null)) {
  352. $labels_cache = json_decode($item['label_cache'], true);
  353. if (is_array($labels_cache)) {
  354. foreach ($labels_cache as $label_cache) {
  355. if (is_array($label_cache) && !empty($label_cache[1]) && is_string($label_cache[1])) {
  356. $item['categories'][] = 'user/-/label/' . trim($label_cache[1]);
  357. }
  358. }
  359. }
  360. }
  361. $item['alternate'] = [['href' => $item['link'] ?? '']];
  362. $item['origin'] = [
  363. 'title' => $item['feed_title'] ?? '',
  364. 'feedUrl' => $item['feed_url'] ?? '',
  365. ];
  366. $item['id'] = $item['guid'] ?? ($item['feed_url'] ?? $item['published']);
  367. $item['guid'] = $item['id'];
  368. $table['items'][$i] = $item;
  369. }
  370. return json_encode($table);
  371. }
  372. /**
  373. * This method import a JSON-based file (Google Reader format).
  374. *
  375. * $article_file the JSON file content.
  376. * true if articles from the file must be starred.
  377. * @return bool false if an error occurred, true otherwise.
  378. * @throws Minz_ConfigurationNamespaceException
  379. * @throws Minz_PDOConnectionException
  380. */
  381. private function importJson(string $article_file, bool $starred = false): bool {
  382. $article_object = json_decode($article_file, true);
  383. if (!is_array($article_object)) {
  384. if (FreshRSS_Context::$isCli) {
  385. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  386. } else {
  387. Minz_Log::warning('Try to import a non-JSON file');
  388. }
  389. return false;
  390. }
  391. $items = $article_object['items'] ?? $article_object;
  392. if (!is_array($items)) {
  393. $items = [];
  394. }
  395. $mark_as_read = FreshRSS_Context::userConf()->mark_when['reception'] ? 1 : 0;
  396. $error = false;
  397. $article_to_feed = [];
  398. $nb_feeds = count($this->feedDAO->listFeeds());
  399. $newFeedGuids = [];
  400. $limits = FreshRSS_Context::systemConf()->limits;
  401. // First, we check feeds of articles are in DB (and add them if needed).
  402. foreach ($items as &$item) {
  403. if (!is_array($item)) {
  404. continue;
  405. }
  406. if (!is_string($item['guid'] ?? null) && is_string($item['id'] ?? null)) {
  407. $item['guid'] = $item['id'];
  408. }
  409. if (!is_string($item['guid'] ?? null)) {
  410. continue;
  411. }
  412. if (!is_array($item['origin'] ?? null)) {
  413. $item['origin'] = [];
  414. }
  415. if (!is_string($item['origin']['title'] ?? null) || trim($item['origin']['title']) === '') {
  416. $item['origin']['title'] = 'Import';
  417. }
  418. if (is_string($item['origin']['feedUrl'] ?? null)) {
  419. $feedUrl = $item['origin']['feedUrl'];
  420. } elseif (is_string($item['origin']['streamId'] ?? null) && str_starts_with($item['origin']['streamId'], 'feed/')) {
  421. $feedUrl = substr($item['origin']['streamId'], 5); //Google Reader
  422. $item['origin']['feedUrl'] = $feedUrl;
  423. } elseif (is_string($item['origin']['htmlUrl'] ?? null)) {
  424. $feedUrl = $item['origin']['htmlUrl'];
  425. } else {
  426. $feedUrl = 'http://import.localhost/import.xml';
  427. $item['origin']['feedUrl'] = $feedUrl;
  428. $item['origin']['disable'] = 'true';
  429. }
  430. $feedUrlOriginal = $feedUrl;
  431. $feedUrl = Minz_Helper::htmlspecialchars_utf8(FreshRSS_http_Util::checkUrl($feedUrl) ?: '');
  432. try {
  433. $feed = new FreshRSS_Feed($feedUrl);
  434. } catch (FreshRSS_BadUrl_Exception) {
  435. Minz_Log::warning('Could not add feed with invalid URL "' . \SimplePie\Misc::url_remove_credentials($feedUrlOriginal) . '" during JSON import');
  436. continue;
  437. }
  438. $feed = $this->feedDAO->searchByUrl($feed->url());
  439. if ($feed === null) {
  440. // Feed does not exist in DB,we should to try to add it.
  441. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  442. // Oops, no more place!
  443. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  444. } else {
  445. $origin = array_filter($item['origin'], fn($value, $key): bool => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  446. $feed = $this->addFeedJson($origin);
  447. }
  448. if ($feed === null) {
  449. // Still null? It means something went wrong.
  450. $error = true;
  451. } else {
  452. $nb_feeds++;
  453. }
  454. }
  455. if ($feed !== null) {
  456. $article_to_feed[$item['guid']] = $feed->id();
  457. if (!isset($newFeedGuids['f_' . $feed->id()])) {
  458. $newFeedGuids['f_' . $feed->id()] = [];
  459. }
  460. $newFeedGuids['f_' . $feed->id()][] = safe_ascii($item['guid']);
  461. }
  462. }
  463. $tagDAO = FreshRSS_Factory::createTagDao();
  464. $labels = FreshRSS_Context::labels();
  465. $knownLabels = [];
  466. foreach ($labels as $label) {
  467. $knownLabels[$label->name()]['id'] = $label->id();
  468. $knownLabels[$label->name()]['articles'] = [];
  469. }
  470. unset($labels);
  471. // For each feed, check existing GUIDs already in database.
  472. $existingHashForGuids = [];
  473. foreach ($newFeedGuids as $feedId => $newGuids) {
  474. $existingHashForGuids[$feedId] = $this->entryDAO->listHashForFeedGuids((int)substr($feedId, 2), $newGuids);
  475. }
  476. unset($newFeedGuids);
  477. // Then, articles are imported.
  478. $newGuids = [];
  479. $this->entryDAO->beginTransaction();
  480. foreach ($items as &$item) {
  481. if (!is_array($item) || empty($item['guid']) || !is_string($item['guid']) || empty($article_to_feed[$item['guid']])) {
  482. // Related feed does not exist for this entry, do nothing.
  483. continue;
  484. }
  485. $feed_id = $article_to_feed[$item['guid']];
  486. $author = is_string($item['author'] ?? null) ? Minz_Helper::htmlspecialchars_utf8($item['author']) : '';
  487. $is_starred = null; // null is used to preserve the current state if that item exists and is already starred
  488. $is_read = null;
  489. $tags = is_array($item['categories'] ?? null) ? $item['categories'] : [];
  490. $labels = [];
  491. for ($i = count($tags) - 1; $i >= 0; $i--) {
  492. $tag = $tags[$i];
  493. if (!is_string($tag)) {
  494. unset($tags[$i]);
  495. continue;
  496. }
  497. $tag = trim($tag);
  498. if (preg_match('%^user/[A-Za-z0-9_-]+/%', $tag)) {
  499. if (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/starred$%', $tag)) {
  500. $is_starred = true;
  501. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/read$%', $tag)) {
  502. $is_read = true;
  503. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/unread$%', $tag)) {
  504. $is_read = false;
  505. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/label/\s*(?P<tag>.+?)\s*$%', $tag, $matches)) {
  506. $labels[] = $matches['tag'];
  507. }
  508. unset($tags[$i]);
  509. }
  510. }
  511. $tags = Minz_Helper::htmlspecialchars_utf8(array_values(array_filter($tags, 'is_string')));
  512. if ($starred && !$is_starred) {
  513. //If the article has no label, mark it as starred (old format)
  514. $is_starred = empty($labels);
  515. }
  516. if ($is_read === null) {
  517. $is_read = $mark_as_read;
  518. }
  519. if (is_array($item['alternate']) && is_array($item['alternate'][0] ?? null) && is_string($item['alternate'][0]['href'] ?? null)) {
  520. $url = $item['alternate'][0]['href'];
  521. } elseif (is_string($item['url'] ?? null)) {
  522. $url = $item['url']; //FeedBin
  523. } else {
  524. $url = '';
  525. }
  526. $url = Minz_Helper::htmlspecialchars_utf8(FreshRSS_http_Util::checkUrl($url) ?: '');
  527. $title = is_string($item['title'] ?? null) ? $item['title'] : $url;
  528. $title = Minz_Helper::htmlspecialchars_utf8($title);
  529. if (is_array($item['content'] ?? null) && is_string($item['content']['content'] ?? null)) {
  530. $content = $item['content']['content'];
  531. } elseif (is_array($item['summary']) && is_string($item['summary']['content'] ?? null)) {
  532. $content = $item['summary']['content'];
  533. } elseif (is_string($item['content'] ?? null)) {
  534. $content = $item['content']; //FeedBin
  535. } else {
  536. $content = '';
  537. }
  538. $content = FreshRSS_SimplePieCustom::sanitizeHTML($content, $url);
  539. if (is_int($item['published'] ?? null) || is_string($item['published'] ?? null)) {
  540. $published = (string)$item['published'];
  541. } elseif (is_int($item['timestampUsec'] ?? null) || is_string($item['timestampUsec'] ?? null)) {
  542. $published = substr((string)$item['timestampUsec'], 0, -6);
  543. } elseif (is_int($item['updated'] ?? null) || is_string($item['updated'] ?? null)) {
  544. $published = (string)$item['updated'];
  545. } else {
  546. $published = '0';
  547. }
  548. if (!ctype_digit($published)) {
  549. $published = (string)(strtotime($published) ?: 0);
  550. }
  551. if (strlen($published) > 10) { // Milliseconds, e.g. Feedly
  552. $published = substr($published, 0, -3);
  553. if (!is_numeric($published)) {
  554. $published = '0'; // For PHPStan
  555. }
  556. }
  557. $entry = new FreshRSS_Entry(
  558. $feed_id, $item['guid'], $title, $author,
  559. $content, $url, $published, $is_read, $is_starred
  560. );
  561. $entry->_id(uTimeString());
  562. $entry->_tags($tags);
  563. if (isset($newGuids[$entry->guid()])) {
  564. continue; //Skip subsequent articles with same GUID
  565. }
  566. $newGuids[$entry->guid()] = true;
  567. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeInsert, $entry);
  568. if (!($entry instanceof FreshRSS_Entry)) {
  569. // An extension has returned a null value, there is nothing to insert.
  570. continue;
  571. }
  572. if (isset($existingHashForGuids['f_' . $feed_id][$entry->guid()])) {
  573. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeUpdate, $entry);
  574. if (!($entry instanceof FreshRSS_Entry)) {
  575. // An extension has returned a null value, there is nothing to insert.
  576. continue;
  577. }
  578. $ok = $this->entryDAO->updateEntry($entry->toArray());
  579. } else {
  580. $entry->_lastSeen(time());
  581. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeAdd, $entry);
  582. if (!($entry instanceof FreshRSS_Entry)) {
  583. // An extension has returned a null value, there is nothing to insert.
  584. continue;
  585. }
  586. $ok = $this->entryDAO->addEntry($entry->toArray());
  587. }
  588. foreach ($labels as $labelName) {
  589. if (empty($knownLabels[$labelName]['id'])) {
  590. $labelId = $tagDAO->addTag(['name' => $labelName]);
  591. $knownLabels[$labelName]['id'] = $labelId;
  592. $knownLabels[$labelName]['articles'] = [];
  593. }
  594. $knownLabels[$labelName]['articles'][] = [
  595. //'id' => $entry->id(), //ID changes after commitNewEntries()
  596. 'id_feed' => $entry->feedId(),
  597. 'guid' => $entry->guid(),
  598. ];
  599. }
  600. $error |= ($ok === false);
  601. }
  602. $this->entryDAO->commit();
  603. $this->entryDAO->beginTransaction();
  604. $this->entryDAO->commitNewEntries();
  605. $this->feedDAO->updateCachedValues();
  606. $this->entryDAO->commit();
  607. $this->entryDAO->beginTransaction();
  608. foreach ($knownLabels as $labelName => $knownLabel) {
  609. $labelId = $knownLabel['id'];
  610. if (!$labelId) {
  611. continue;
  612. }
  613. foreach ($knownLabel['articles'] as $article) {
  614. $entryId = $this->entryDAO->searchIdByGuid($article['id_feed'], $article['guid']);
  615. if ($entryId != null) {
  616. $tagDAO->tagEntry($labelId, $entryId);
  617. } else {
  618. Minz_Log::warning('Could not add label "' . $labelName . '" to entry "' . $article['guid'] . '" in feed ' . $article['id_feed']);
  619. }
  620. }
  621. }
  622. $this->entryDAO->commit();
  623. return !$error;
  624. }
  625. /**
  626. * This method import a JSON-based feed (Google Reader format).
  627. *
  628. * @param array<string,string> $origin represents a feed.
  629. * @return FreshRSS_Feed|null if feed is in database at the end of the process, else null.
  630. */
  631. private function addFeedJson(array $origin): ?FreshRSS_Feed {
  632. $return = null;
  633. if (!empty($origin['feedUrl'])) {
  634. $url = $origin['feedUrl'];
  635. } elseif (!empty($origin['htmlUrl'])) {
  636. $url = $origin['htmlUrl'];
  637. } else {
  638. return null;
  639. }
  640. $url = Minz_Helper::htmlspecialchars_utf8(FreshRSS_http_Util::checkUrl($url) ?: '');
  641. if (!empty($origin['htmlUrl'])) {
  642. $website = $origin['htmlUrl'];
  643. } elseif (!empty($origin['feedUrl'])) {
  644. $website = $origin['feedUrl'];
  645. } else {
  646. $website = '';
  647. }
  648. $website = Minz_Helper::htmlspecialchars_utf8(FreshRSS_http_Util::checkUrl($website) ?: '');
  649. $name = empty($origin['title']) ? $website : $origin['title'];
  650. $name = Minz_Helper::htmlspecialchars_utf8($name);
  651. $cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  652. $cat_name = Minz_Helper::htmlspecialchars_utf8(trim($origin['category'] ?? ''));
  653. if ($cat_name !== '') {
  654. $new_cat = $this->categoryDAO->searchByName($cat_name);
  655. $cat_id = $new_cat?->id() ?: $this->categoryDAO->addCategory(['name' => $cat_name]) ?: FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  656. }
  657. try {
  658. // Create a Feed object and add it in database.
  659. $feed = new FreshRSS_Feed($url);
  660. $feed->_categoryId($cat_id);
  661. $feed->_name($name);
  662. $feed->_website($website);
  663. if (!empty($origin['disable'])) {
  664. $feed->_mute(true);
  665. }
  666. // Call the extension hook
  667. $feed = Minz_ExtensionManager::callHook(Minz_HookType::FeedBeforeInsert, $feed);
  668. if ($feed instanceof FreshRSS_Feed) {
  669. // addFeedObject checks if feed is already in DB so nothing else to
  670. // check here.
  671. $id = $this->feedDAO->addFeedObject($feed);
  672. if ($id !== false) {
  673. $feed->_id($id);
  674. $return = $feed;
  675. }
  676. }
  677. } catch (FreshRSS_Feed_Exception $e) {
  678. if (FreshRSS_Context::$isCli) {
  679. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  680. } else {
  681. Minz_Log::warning($e->getMessage());
  682. }
  683. }
  684. return $return;
  685. }
  686. /**
  687. * This action handles export action.
  688. *
  689. * This action must be reached by a POST request.
  690. *
  691. * Parameters are:
  692. * - export_opml (default: false)
  693. * - export_starred (default: false)
  694. * - export_labelled (default: false)
  695. * - export_feeds (default: []) a list of feed ids
  696. */
  697. public function exportAction(): void {
  698. if (!Minz_Request::isPost()) {
  699. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  700. return;
  701. }
  702. $username = Minz_User::name() ?? '_';
  703. $export_service = new FreshRSS_Export_Service($username);
  704. $export_opml = Minz_Request::paramBoolean('export_opml');
  705. $export_starred = Minz_Request::paramBoolean('export_starred');
  706. $export_labelled = Minz_Request::paramBoolean('export_labelled');
  707. /** @var array<numeric-string> */
  708. $export_feeds = Minz_Request::paramArray('export_feeds');
  709. $max_number_entries = 50;
  710. $exported_files = [];
  711. if ($export_opml) {
  712. [$filename, $content] = $export_service->generateOpml();
  713. $exported_files[$filename] = $content;
  714. }
  715. // Starred and labelled entries are merged in the same `starred` file
  716. // to avoid duplication of content.
  717. if ($export_starred && $export_labelled) {
  718. [$filename, $content] = $export_service->generateStarredEntries('ST');
  719. $exported_files[$filename] = $content;
  720. } elseif ($export_starred) {
  721. [$filename, $content] = $export_service->generateStarredEntries('S');
  722. $exported_files[$filename] = $content;
  723. } elseif ($export_labelled) {
  724. [$filename, $content] = $export_service->generateStarredEntries('T');
  725. $exported_files[$filename] = $content;
  726. }
  727. foreach ($export_feeds as $feed_id) {
  728. $result = $export_service->generateFeedEntries((int)$feed_id, $max_number_entries);
  729. if ($result === null) {
  730. // It means the actual feed_id doesn’t correspond to any existing feed
  731. continue;
  732. }
  733. [$filename, $content] = $result;
  734. $exported_files[$filename] = $content;
  735. }
  736. $nb_files = count($exported_files);
  737. if ($nb_files <= 0) {
  738. // There’s nothing to do, there are no files to export
  739. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  740. return;
  741. }
  742. if ($nb_files === 1) {
  743. // If we only have one file, we just export it as it is
  744. $filename = key($exported_files);
  745. $content = $exported_files[$filename];
  746. } else {
  747. // More files? Let’s compress them in a Zip archive
  748. if (!extension_loaded('zip')) {
  749. // Oops, there is no ZIP extension!
  750. Minz_Request::bad(
  751. _t('feedback.import_export.export_no_zip_extension'),
  752. ['c' => 'importExport', 'a' => 'index']
  753. );
  754. return;
  755. }
  756. [$filename, $content] = $export_service->zip($exported_files);
  757. }
  758. if (!is_string($content)) {
  759. Minz_Request::bad(_t('feedback.import_export.zip_error'), ['c' => 'importExport', 'a' => 'index']);
  760. return;
  761. }
  762. $content_type = self::filenameToContentType($filename);
  763. header('Content-Type: ' . $content_type);
  764. header('Content-disposition: attachment; filename="' . $filename . '"');
  765. $this->view->_layout(null);
  766. $this->view->content = $content;
  767. }
  768. /**
  769. * Return the Content-Type corresponding to a filename.
  770. *
  771. * If the type of the filename is not supported, it returns
  772. * `application/octet-stream` by default.
  773. */
  774. private static function filenameToContentType(string $filename): string {
  775. $filetype = self::guessFileType($filename);
  776. return match ($filetype) {
  777. 'zip' => 'application/zip',
  778. 'opml' => 'application/xml; charset=utf-8',
  779. 'json_starred', 'json_feed' => 'application/json; charset=utf-8',
  780. default => 'application/octet-stream',
  781. };
  782. }
  783. private const REGEX_SQLITE_FILENAME = '/^(?![.-])[0-9a-zA-Z_.@ #&()~\-]{1,128}\.sqlite$/';
  784. private function listSqliteArchives(): void {
  785. $this->view->sqliteArchives = [];
  786. $files = glob(USERS_PATH . '/' . Minz_User::name() . '/*.sqlite', GLOB_NOSORT) ?: [];
  787. foreach ($files as $file) {
  788. $archive = [
  789. 'name' => basename($file),
  790. 'size' => @filesize($file),
  791. 'mtime' => @filemtime($file),
  792. ];
  793. if ($archive['size'] != false && $archive['mtime'] != false && preg_match(self::REGEX_SQLITE_FILENAME, $archive['name'])) {
  794. $this->view->sqliteArchives[] = $archive;
  795. }
  796. }
  797. // Sort by time, newest first:
  798. usort($this->view->sqliteArchives, static fn(array $a, array $b): int => $b['mtime'] <=> $a['mtime']);
  799. }
  800. public function sqliteAction(): void {
  801. if (!Minz_Request::isPost()) {
  802. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  803. }
  804. $sqlite = Minz_Request::paramString('sqlite');
  805. if (!preg_match(self::REGEX_SQLITE_FILENAME, $sqlite)) {
  806. Minz_Error::error(404);
  807. return;
  808. }
  809. $path = USERS_PATH . '/' . Minz_User::name() . '/' . $sqlite;
  810. if (!file_exists($path) || @filesize($path) == false || @filemtime($path) == false) {
  811. Minz_Error::error(404);
  812. return;
  813. }
  814. $this->view->sqlitePath = $path;
  815. $this->view->sqliteName = basename($path);
  816. if ($this->view->sqliteName === 'db.sqlite') {
  817. $username = Minz_User::name() ?? '_';
  818. $date = date('Y-m-d_H-i-s', filemtime($path) ?: time()); // @phpstan-ignore ternary.alwaysTrue (for additional safety)
  819. $this->view->sqliteName = 'freshrss_' . $username . '_' . $date . '_db.sqlite';
  820. }
  821. $this->view->_layout(null);
  822. }
  823. }