4
0

importExportController.php 25 KB

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