importExportController.php 27 KB

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