importExportController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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(
  181. $content_notif,
  182. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  183. );
  184. }
  185. /**
  186. * This method tries to guess the file type based on its name.
  187. *
  188. * It is a *very* basic guess file type function. Only based on filename.
  189. * That could be improved but should be enough for what we have to do.
  190. */
  191. private static function guessFileType(string $filename): string {
  192. if (str_ends_with($filename, '.zip')) {
  193. return 'zip';
  194. } elseif (stripos($filename, 'opml') !== false) {
  195. return 'opml';
  196. } elseif (str_ends_with($filename, '.json')) {
  197. if (str_contains($filename, 'starred')) {
  198. return 'json_starred';
  199. } else {
  200. return 'json_feed';
  201. }
  202. } elseif (str_ends_with($filename, '.xml')) {
  203. if (preg_match('/Tiny|tt-?rss/i', $filename)) {
  204. return 'ttrss_starred';
  205. } else {
  206. return 'opml';
  207. }
  208. }
  209. return 'unknown';
  210. }
  211. private function ttrssXmlToJson(string $xml): string|false {
  212. $table = (array)simplexml_load_string($xml, options: LIBXML_NOBLANKS | LIBXML_NOCDATA);
  213. $table['items'] = $table['article'] ?? [];
  214. if (!is_array($table['items'])) {
  215. $table['items'] = [];
  216. }
  217. unset($table['article']);
  218. for ($i = count($table['items']) - 1; $i >= 0; $i--) {
  219. $item = (array)($table['items'][$i]);
  220. $item = array_filter($item, static fn($v) =>
  221. // Filter out empty properties, potentially reported as empty objects
  222. (is_string($v) && trim($v) !== '') || !empty($v));
  223. $item['updated'] = is_string($item['updated'] ?? null) ? strtotime($item['updated']) : '';
  224. $item['published'] = $item['updated'];
  225. $item['content'] = ['content' => $item['content'] ?? ''];
  226. $item['categories'] = is_string($item['tag_cache'] ?? null) ? [$item['tag_cache']] : [];
  227. if (!empty($item['marked'])) {
  228. $item['categories'][] = 'user/-/state/com.google/starred';
  229. }
  230. if (!empty($item['published'])) {
  231. $item['categories'][] = 'user/-/state/com.google/broadcast';
  232. }
  233. if (is_string($item['label_cache'] ?? null)) {
  234. $labels_cache = json_decode($item['label_cache'], true);
  235. if (is_array($labels_cache)) {
  236. foreach ($labels_cache as $label_cache) {
  237. if (is_array($label_cache) && !empty($label_cache[1]) && is_string($label_cache[1])) {
  238. $item['categories'][] = 'user/-/label/' . trim($label_cache[1]);
  239. }
  240. }
  241. }
  242. }
  243. $item['alternate'] = [['href' => $item['link'] ?? '']];
  244. $item['origin'] = [
  245. 'title' => $item['feed_title'] ?? '',
  246. 'feedUrl' => $item['feed_url'] ?? '',
  247. ];
  248. $item['id'] = $item['guid'] ?? ($item['feed_url'] ?? $item['published']);
  249. $item['guid'] = $item['id'];
  250. $table['items'][$i] = $item;
  251. }
  252. return json_encode($table);
  253. }
  254. /**
  255. * This method import a JSON-based file (Google Reader format).
  256. *
  257. * $article_file the JSON file content.
  258. * true if articles from the file must be starred.
  259. * @return bool false if an error occurred, true otherwise.
  260. * @throws Minz_ConfigurationNamespaceException
  261. * @throws Minz_PDOConnectionException
  262. */
  263. private function importJson(string $article_file, bool $starred = false): bool {
  264. $article_object = json_decode($article_file, true);
  265. if (!is_array($article_object)) {
  266. if (FreshRSS_Context::$isCli) {
  267. fwrite(STDERR, 'FreshRSS error trying to import a non-JSON file' . "\n");
  268. } else {
  269. Minz_Log::warning('Try to import a non-JSON file');
  270. }
  271. return false;
  272. }
  273. $items = $article_object['items'] ?? $article_object;
  274. if (!is_array($items)) {
  275. $items = [];
  276. }
  277. $mark_as_read = FreshRSS_Context::userConf()->mark_when['reception'] ? 1 : 0;
  278. $error = false;
  279. $article_to_feed = [];
  280. $nb_feeds = count($this->feedDAO->listFeeds());
  281. $newFeedGuids = [];
  282. $limits = FreshRSS_Context::systemConf()->limits;
  283. // First, we check feeds of articles are in DB (and add them if needed).
  284. foreach ($items as &$item) {
  285. if (!is_array($item)) {
  286. continue;
  287. }
  288. if (!is_string($item['guid'] ?? null) && is_string($item['id'] ?? null)) {
  289. $item['guid'] = $item['id'];
  290. }
  291. if (!is_string($item['guid'] ?? null)) {
  292. continue;
  293. }
  294. if (!is_array($item['origin'] ?? null)) {
  295. $item['origin'] = [];
  296. }
  297. if (!is_string($item['origin']['title'] ?? null) || trim($item['origin']['title']) === '') {
  298. $item['origin']['title'] = 'Import';
  299. }
  300. if (is_string($item['origin']['feedUrl'] ?? null)) {
  301. $feedUrl = $item['origin']['feedUrl'];
  302. } elseif (is_string($item['origin']['streamId'] ?? null) && str_starts_with($item['origin']['streamId'], 'feed/')) {
  303. $feedUrl = substr($item['origin']['streamId'], 5); //Google Reader
  304. $item['origin']['feedUrl'] = $feedUrl;
  305. } elseif (is_string($item['origin']['htmlUrl'] ?? null)) {
  306. $feedUrl = $item['origin']['htmlUrl'];
  307. } else {
  308. $feedUrl = 'http://import.localhost/import.xml';
  309. $item['origin']['feedUrl'] = $feedUrl;
  310. $item['origin']['disable'] = 'true';
  311. }
  312. $feed = new FreshRSS_Feed($feedUrl);
  313. $feed = $this->feedDAO->searchByUrl($feed->url());
  314. if ($feed === null) {
  315. // Feed does not exist in DB,we should to try to add it.
  316. if ((!FreshRSS_Context::$isCli) && ($nb_feeds >= $limits['max_feeds'])) {
  317. // Oops, no more place!
  318. Minz_Log::warning(_t('feedback.sub.feed.over_max', $limits['max_feeds']));
  319. } else {
  320. $origin = array_filter($item['origin'], fn($value, $key): bool => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  321. $feed = $this->addFeedJson($origin);
  322. }
  323. if ($feed === null) {
  324. // Still null? It means something went wrong.
  325. $error = true;
  326. } else {
  327. $nb_feeds++;
  328. }
  329. }
  330. if ($feed !== null) {
  331. $article_to_feed[$item['guid']] = $feed->id();
  332. if (!isset($newFeedGuids['f_' . $feed->id()])) {
  333. $newFeedGuids['f_' . $feed->id()] = [];
  334. }
  335. $newFeedGuids['f_' . $feed->id()][] = safe_ascii($item['guid']);
  336. }
  337. }
  338. $tagDAO = FreshRSS_Factory::createTagDao();
  339. $labels = FreshRSS_Context::labels();
  340. $knownLabels = [];
  341. foreach ($labels as $label) {
  342. $knownLabels[$label->name()]['id'] = $label->id();
  343. $knownLabels[$label->name()]['articles'] = [];
  344. }
  345. unset($labels);
  346. // For each feed, check existing GUIDs already in database.
  347. $existingHashForGuids = [];
  348. foreach ($newFeedGuids as $feedId => $newGuids) {
  349. $existingHashForGuids[$feedId] = $this->entryDAO->listHashForFeedGuids((int)substr($feedId, 2), $newGuids);
  350. }
  351. unset($newFeedGuids);
  352. // Then, articles are imported.
  353. $newGuids = [];
  354. $this->entryDAO->beginTransaction();
  355. foreach ($items as &$item) {
  356. if (!is_array($item) || empty($item['guid']) || !is_string($item['guid']) || empty($article_to_feed[$item['guid']])) {
  357. // Related feed does not exist for this entry, do nothing.
  358. continue;
  359. }
  360. $feed_id = $article_to_feed[$item['guid']];
  361. $author = is_string($item['author'] ?? null) ? $item['author'] : '';
  362. $is_starred = null; // null is used to preserve the current state if that item exists and is already starred
  363. $is_read = null;
  364. $tags = is_array($item['categories'] ?? null) ? $item['categories'] : [];
  365. $labels = [];
  366. for ($i = count($tags) - 1; $i >= 0; $i--) {
  367. $tag = $tags[$i];
  368. if (!is_string($tag)) {
  369. unset($tags[$i]);
  370. continue;
  371. }
  372. $tag = trim($tag);
  373. if (preg_match('%^user/[A-Za-z0-9_-]+/%', $tag)) {
  374. if (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/starred$%', $tag)) {
  375. $is_starred = true;
  376. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/read$%', $tag)) {
  377. $is_read = true;
  378. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/state/com.google/unread$%', $tag)) {
  379. $is_read = false;
  380. } elseif (preg_match('%^user/[A-Za-z0-9_-]+/label/\s*(?P<tag>.+?)\s*$%', $tag, $matches)) {
  381. $labels[] = $matches['tag'];
  382. }
  383. unset($tags[$i]);
  384. }
  385. }
  386. $tags = array_values(array_filter($tags, 'is_string'));
  387. if ($starred && !$is_starred) {
  388. //If the article has no label, mark it as starred (old format)
  389. $is_starred = empty($labels);
  390. }
  391. if ($is_read === null) {
  392. $is_read = $mark_as_read;
  393. }
  394. if (is_array($item['alternate']) && is_array($item['alternate'][0] ?? null) && is_string($item['alternate'][0]['href'] ?? null)) {
  395. $url = $item['alternate'][0]['href'];
  396. } elseif (is_string($item['url'] ?? null)) {
  397. $url = $item['url']; //FeedBin
  398. } else {
  399. $url = '';
  400. }
  401. $title = is_string($item['title'] ?? null) ? $item['title'] : $url;
  402. if (is_array($item['content'] ?? null) && is_string($item['content']['content'] ?? null)) {
  403. $content = $item['content']['content'];
  404. } elseif (is_array($item['summary']) && is_string($item['summary']['content'] ?? null)) {
  405. $content = $item['summary']['content'];
  406. } elseif (is_string($item['content'] ?? null)) {
  407. $content = $item['content']; //FeedBin
  408. } else {
  409. $content = '';
  410. }
  411. $content = sanitizeHTML($content, $url);
  412. if (is_int($item['published'] ?? null) || is_string($item['published'] ?? null)) {
  413. $published = (string)$item['published'];
  414. } elseif (is_int($item['timestampUsec'] ?? null) || is_string($item['timestampUsec'] ?? null)) {
  415. $published = substr((string)$item['timestampUsec'], 0, -6);
  416. } elseif (is_int($item['updated'] ?? null) || is_string($item['updated'] ?? null)) {
  417. $published = (string)$item['updated'];
  418. } else {
  419. $published = '0';
  420. }
  421. if (!ctype_digit($published)) {
  422. $published = (string)(strtotime($published) ?: 0);
  423. }
  424. if (strlen($published) > 10) { // Milliseconds, e.g. Feedly
  425. $published = substr($published, 0, -3);
  426. if (!is_numeric($published)) {
  427. $published = '0'; // For PHPStan
  428. }
  429. }
  430. $entry = new FreshRSS_Entry(
  431. $feed_id, $item['guid'], $title, $author,
  432. $content, $url, $published, $is_read, $is_starred
  433. );
  434. $entry->_id(uTimeString());
  435. $entry->_tags($tags);
  436. if (isset($newGuids[$entry->guid()])) {
  437. continue; //Skip subsequent articles with same GUID
  438. }
  439. $newGuids[$entry->guid()] = true;
  440. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeInsert, $entry);
  441. if (!($entry instanceof FreshRSS_Entry)) {
  442. // An extension has returned a null value, there is nothing to insert.
  443. continue;
  444. }
  445. if (isset($existingHashForGuids['f_' . $feed_id][$entry->guid()])) {
  446. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeUpdate, $entry);
  447. if (!($entry instanceof FreshRSS_Entry)) {
  448. // An extension has returned a null value, there is nothing to insert.
  449. continue;
  450. }
  451. $ok = $this->entryDAO->updateEntry($entry->toArray());
  452. } else {
  453. $entry->_lastSeen(time());
  454. $entry = Minz_ExtensionManager::callHook(Minz_HookType::EntryBeforeAdd, $entry);
  455. if (!($entry instanceof FreshRSS_Entry)) {
  456. // An extension has returned a null value, there is nothing to insert.
  457. continue;
  458. }
  459. $ok = $this->entryDAO->addEntry($entry->toArray());
  460. }
  461. foreach ($labels as $labelName) {
  462. if (empty($knownLabels[$labelName]['id'])) {
  463. $labelId = $tagDAO->addTag(['name' => $labelName]);
  464. $knownLabels[$labelName]['id'] = $labelId;
  465. $knownLabels[$labelName]['articles'] = [];
  466. }
  467. $knownLabels[$labelName]['articles'][] = [
  468. //'id' => $entry->id(), //ID changes after commitNewEntries()
  469. 'id_feed' => $entry->feedId(),
  470. 'guid' => $entry->guid(),
  471. ];
  472. }
  473. $error |= ($ok === false);
  474. }
  475. $this->entryDAO->commit();
  476. $this->entryDAO->beginTransaction();
  477. $this->entryDAO->commitNewEntries();
  478. $this->feedDAO->updateCachedValues();
  479. $this->entryDAO->commit();
  480. $this->entryDAO->beginTransaction();
  481. foreach ($knownLabels as $labelName => $knownLabel) {
  482. $labelId = $knownLabel['id'];
  483. if (!$labelId) {
  484. continue;
  485. }
  486. foreach ($knownLabel['articles'] as $article) {
  487. $entryId = $this->entryDAO->searchIdByGuid($article['id_feed'], $article['guid']);
  488. if ($entryId != null) {
  489. $tagDAO->tagEntry($labelId, $entryId);
  490. } else {
  491. Minz_Log::warning('Could not add label "' . $labelName . '" to entry "' . $article['guid'] . '" in feed ' . $article['id_feed']);
  492. }
  493. }
  494. }
  495. $this->entryDAO->commit();
  496. return !$error;
  497. }
  498. /**
  499. * This method import a JSON-based feed (Google Reader format).
  500. *
  501. * @param array<string,string> $origin represents a feed.
  502. * @return FreshRSS_Feed|null if feed is in database at the end of the process, else null.
  503. */
  504. private function addFeedJson(array $origin): ?FreshRSS_Feed {
  505. $return = null;
  506. if (!empty($origin['feedUrl'])) {
  507. $url = $origin['feedUrl'];
  508. } elseif (!empty($origin['htmlUrl'])) {
  509. $url = $origin['htmlUrl'];
  510. } else {
  511. return null;
  512. }
  513. if (!empty($origin['htmlUrl'])) {
  514. $website = $origin['htmlUrl'];
  515. } elseif (!empty($origin['feedUrl'])) {
  516. $website = $origin['feedUrl'];
  517. } else {
  518. $website = '';
  519. }
  520. $name = empty($origin['title']) ? $website : $origin['title'];
  521. try {
  522. // Create a Feed object and add it in database.
  523. $feed = new FreshRSS_Feed($url);
  524. $feed->_categoryId(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
  525. $feed->_name($name);
  526. $feed->_website($website);
  527. if (!empty($origin['disable'])) {
  528. $feed->_mute(true);
  529. }
  530. // Call the extension hook
  531. $feed = Minz_ExtensionManager::callHook(Minz_HookType::FeedBeforeInsert, $feed);
  532. if ($feed instanceof FreshRSS_Feed) {
  533. // addFeedObject checks if feed is already in DB so nothing else to
  534. // check here.
  535. $id = $this->feedDAO->addFeedObject($feed);
  536. if ($id !== false) {
  537. $feed->_id($id);
  538. $return = $feed;
  539. }
  540. }
  541. } catch (FreshRSS_Feed_Exception $e) {
  542. if (FreshRSS_Context::$isCli) {
  543. fwrite(STDERR, 'FreshRSS error during JSON feed import: ' . $e->getMessage() . "\n");
  544. } else {
  545. Minz_Log::warning($e->getMessage());
  546. }
  547. }
  548. return $return;
  549. }
  550. /**
  551. * This action handles export action.
  552. *
  553. * This action must be reached by a POST request.
  554. *
  555. * Parameters are:
  556. * - export_opml (default: false)
  557. * - export_starred (default: false)
  558. * - export_labelled (default: false)
  559. * - export_feeds (default: []) a list of feed ids
  560. */
  561. public function exportAction(): void {
  562. if (!Minz_Request::isPost()) {
  563. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  564. return;
  565. }
  566. $username = Minz_User::name() ?? '_';
  567. $export_service = new FreshRSS_Export_Service($username);
  568. $export_opml = Minz_Request::paramBoolean('export_opml');
  569. $export_starred = Minz_Request::paramBoolean('export_starred');
  570. $export_labelled = Minz_Request::paramBoolean('export_labelled');
  571. /** @var array<numeric-string> */
  572. $export_feeds = Minz_Request::paramArray('export_feeds');
  573. $max_number_entries = 50;
  574. $exported_files = [];
  575. if ($export_opml) {
  576. [$filename, $content] = $export_service->generateOpml();
  577. $exported_files[$filename] = $content;
  578. }
  579. // Starred and labelled entries are merged in the same `starred` file
  580. // to avoid duplication of content.
  581. if ($export_starred && $export_labelled) {
  582. [$filename, $content] = $export_service->generateStarredEntries('ST');
  583. $exported_files[$filename] = $content;
  584. } elseif ($export_starred) {
  585. [$filename, $content] = $export_service->generateStarredEntries('S');
  586. $exported_files[$filename] = $content;
  587. } elseif ($export_labelled) {
  588. [$filename, $content] = $export_service->generateStarredEntries('T');
  589. $exported_files[$filename] = $content;
  590. }
  591. foreach ($export_feeds as $feed_id) {
  592. $result = $export_service->generateFeedEntries((int)$feed_id, $max_number_entries);
  593. if ($result === null) {
  594. // It means the actual feed_id doesn’t correspond to any existing feed
  595. continue;
  596. }
  597. [$filename, $content] = $result;
  598. $exported_files[$filename] = $content;
  599. }
  600. $nb_files = count($exported_files);
  601. if ($nb_files <= 0) {
  602. // There’s nothing to do, there are no files to export
  603. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  604. return;
  605. }
  606. if ($nb_files === 1) {
  607. // If we only have one file, we just export it as it is
  608. $filename = key($exported_files);
  609. $content = $exported_files[$filename];
  610. } else {
  611. // More files? Let’s compress them in a Zip archive
  612. if (!extension_loaded('zip')) {
  613. // Oops, there is no ZIP extension!
  614. Minz_Request::bad(
  615. _t('feedback.import_export.export_no_zip_extension'),
  616. ['c' => 'importExport', 'a' => 'index']
  617. );
  618. return;
  619. }
  620. [$filename, $content] = $export_service->zip($exported_files);
  621. }
  622. if (!is_string($content)) {
  623. Minz_Request::bad(_t('feedback.import_export.zip_error'), ['c' => 'importExport', 'a' => 'index']);
  624. return;
  625. }
  626. $content_type = self::filenameToContentType($filename);
  627. header('Content-Type: ' . $content_type);
  628. header('Content-disposition: attachment; filename="' . $filename . '"');
  629. $this->view->_layout(null);
  630. $this->view->content = $content;
  631. }
  632. /**
  633. * Return the Content-Type corresponding to a filename.
  634. *
  635. * If the type of the filename is not supported, it returns
  636. * `application/octet-stream` by default.
  637. */
  638. private static function filenameToContentType(string $filename): string {
  639. $filetype = self::guessFileType($filename);
  640. return match ($filetype) {
  641. 'zip' => 'application/zip',
  642. 'opml' => 'application/xml; charset=utf-8',
  643. 'json_starred', 'json_feed' => 'application/json; charset=utf-8',
  644. default => 'application/octet-stream',
  645. };
  646. }
  647. private const REGEX_SQLITE_FILENAME = '/^(?![.-])[0-9a-zA-Z_.@ #&()~\-]{1,128}\.sqlite$/';
  648. private function listSqliteArchives(): void {
  649. $this->view->sqliteArchives = [];
  650. $files = glob(USERS_PATH . '/' . Minz_User::name() . '/*.sqlite', GLOB_NOSORT) ?: [];
  651. foreach ($files as $file) {
  652. $archive = [
  653. 'name' => basename($file),
  654. 'size' => @filesize($file),
  655. 'mtime' => @filemtime($file),
  656. ];
  657. if ($archive['size'] != false && $archive['mtime'] != false && preg_match(self::REGEX_SQLITE_FILENAME, $archive['name'])) {
  658. $this->view->sqliteArchives[] = $archive;
  659. }
  660. }
  661. // Sort by time, newest first:
  662. usort($this->view->sqliteArchives, static fn(array $a, array $b): int => $b['mtime'] <=> $a['mtime']);
  663. }
  664. public function sqliteAction(): void {
  665. if (!Minz_Request::isPost()) {
  666. Minz_Request::forward(['c' => 'importExport', 'a' => 'index'], true);
  667. }
  668. $sqlite = Minz_Request::paramString('sqlite');
  669. if (!preg_match(self::REGEX_SQLITE_FILENAME, $sqlite)) {
  670. Minz_Error::error(404);
  671. return;
  672. }
  673. $path = USERS_PATH . '/' . Minz_User::name() . '/' . $sqlite;
  674. if (!file_exists($path) || @filesize($path) == false || @filemtime($path) == false) {
  675. Minz_Error::error(404);
  676. return;
  677. }
  678. $this->view->sqlitePath = $path;
  679. $this->view->sqliteName = basename($path);
  680. if ($this->view->sqliteName === 'db.sqlite') {
  681. $username = Minz_User::name() ?? '_';
  682. $date = date('Y-m-d_H-i-s', filemtime($path) ?: time());
  683. $this->view->sqliteName = 'freshrss_' . $username . '_' . $date . '_db.sqlite';
  684. }
  685. $this->view->_layout(null);
  686. }
  687. }