ImportService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Provide methods to import files.
  5. */
  6. class FreshRSS_Import_Service {
  7. private readonly FreshRSS_CategoryDAO $catDAO;
  8. private readonly FreshRSS_FeedDAO $feedDAO;
  9. /** true if success, false otherwise */
  10. private bool $lastStatus;
  11. /**
  12. * Initialize the service for the given user.
  13. */
  14. public function __construct(?string $username = null) {
  15. $this->catDAO = FreshRSS_Factory::createCategoryDao($username);
  16. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  17. }
  18. /** @return bool true if success, false otherwise */
  19. public function lastStatus(): bool {
  20. return $this->lastStatus;
  21. }
  22. /**
  23. * This method parses and imports an OPML file.
  24. *
  25. * @param string $opml_file the OPML file content.
  26. * @param FreshRSS_Category|null $forced_category force the feeds to be associated to this category.
  27. * @param bool $dry_run true to not create categories and feeds in database.
  28. */
  29. public function importOpml(string $opml_file, ?FreshRSS_Category $forced_category = null, bool $dry_run = false): void {
  30. if (function_exists('set_time_limit')) {
  31. @set_time_limit(300);
  32. }
  33. $this->lastStatus = true;
  34. $opml_array = [];
  35. try {
  36. $libopml = new \marienfressinaud\LibOpml\LibOpml(false);
  37. /** @var array{body:array<array<mixed>>} $opml_array */
  38. $opml_array = $libopml->parseString($opml_file);
  39. } catch (\marienfressinaud\LibOpml\Exception $e) {
  40. self::log($e->getMessage());
  41. $this->lastStatus = false;
  42. return;
  43. }
  44. $this->catDAO->checkDefault();
  45. $default_category = $this->catDAO->getDefault();
  46. if ($default_category === null) {
  47. self::log('Cannot get the default category');
  48. $this->lastStatus = false;
  49. return;
  50. }
  51. // Get the categories by names so we can use this array to retrieve
  52. // existing categories later.
  53. $categories = $this->catDAO->listCategories(prePopulateFeeds: false);
  54. $categories_by_names = [];
  55. foreach ($categories as $category) {
  56. $categories_by_names[$category->name()] = $category;
  57. }
  58. // Get current numbers of categories and feeds, and the limits to
  59. // verify the user can import its categories/feeds.
  60. $nb_categories = count($categories);
  61. $nb_feeds = count($this->feedDAO->listFeeds());
  62. $limits = FreshRSS_Context::systemConf()->limits;
  63. // Process the OPML outlines to get a list of categories and a list of
  64. // feeds elements indexed by their categories names.
  65. [$categories_elements, $categories_to_feeds] = $this->loadFromOutlines($opml_array['body'], '');
  66. foreach ($categories_to_feeds as $category_name => $feeds_elements) {
  67. $category_element = $categories_elements[$category_name] ?? null;
  68. $category = null;
  69. if ($forced_category !== null) {
  70. // If the category is forced, ignore the actual category name
  71. $category = $forced_category;
  72. } elseif (isset($categories_by_names[$category_name])) {
  73. // If the category already exists, get it from $categories_by_names
  74. $category = $categories_by_names[$category_name];
  75. } elseif (is_array($category_element)) {
  76. // Otherwise, create the category (if possible)
  77. $limit_reached = $nb_categories >= $limits['max_categories'];
  78. $can_create_category = FreshRSS_Context::$isCli || !$limit_reached;
  79. if ($can_create_category) {
  80. $category = $this->createCategory($category_element, $dry_run);
  81. if ($category !== null) {
  82. $categories_by_names[$category->name()] = $category;
  83. $nb_categories++;
  84. }
  85. } else {
  86. Minz_Log::warning(
  87. _t('feedback.sub.category.over_max', $limits['max_categories'])
  88. );
  89. }
  90. }
  91. if ($category === null) {
  92. // Category can be null if the feeds weren't in a category
  93. // outline, or if we weren't able to create the category.
  94. $category = $default_category;
  95. }
  96. // Then, create the feeds one by one and attach them to the
  97. // category we just got.
  98. foreach ($feeds_elements as $feed_element) {
  99. $limit_reached = $nb_feeds >= $limits['max_feeds'];
  100. $can_create_feed = FreshRSS_Context::$isCli || !$limit_reached;
  101. if (!$can_create_feed) {
  102. Minz_Log::warning(
  103. _t('feedback.sub.feed.over_max', $limits['max_feeds'])
  104. );
  105. $this->lastStatus = false;
  106. break;
  107. }
  108. if ($this->createFeed($feed_element, $category, $dry_run) !== null) {
  109. // TODO what if the feed already exists in the database?
  110. $nb_feeds++;
  111. } else {
  112. $this->lastStatus = false;
  113. }
  114. }
  115. }
  116. }
  117. /**
  118. * Create a feed from a feed element (i.e. OPML outline).
  119. *
  120. * @param array<string,string> $feed_elt An OPML element (must be a feed element).
  121. * @param FreshRSS_Category $category The category to associate to the feed.
  122. * @param bool $dry_run true to not create the feed in database.
  123. * @return FreshRSS_Feed|null The created feed, or null if it failed.
  124. */
  125. private function createFeed(array $feed_elt, FreshRSS_Category $category, bool $dry_run): ?FreshRSS_Feed {
  126. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  127. $name = $feed_elt['text'] ?? $feed_elt['title'] ?? '';
  128. $name = Minz_Helper::htmlspecialchars_utf8($name);
  129. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl'] ?? '');
  130. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description'] ?? '');
  131. try {
  132. // Create a Feed object and add it in DB
  133. $feed = new FreshRSS_Feed($url);
  134. $feed->_category($category);
  135. $feed->_name($name);
  136. $feed->_website($website);
  137. $feed->_description($description);
  138. switch (strtolower($feed_elt['type'] ?? '')) {
  139. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH):
  140. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH);
  141. break;
  142. case strtolower(FreshRSS_Export_Service::TYPE_XML_XPATH):
  143. $feed->_kind(FreshRSS_Feed::KIND_XML_XPATH);
  144. break;
  145. case strtolower(FreshRSS_Export_Service::TYPE_JSON_DOTNOTATION):
  146. case strtolower(FreshRSS_Export_Service::TYPE_JSON_DOTPATH):
  147. $feed->_kind(FreshRSS_Feed::KIND_JSON_DOTNOTATION);
  148. break;
  149. case strtolower(FreshRSS_Export_Service::TYPE_JSONFEED):
  150. $feed->_kind(FreshRSS_Feed::KIND_JSONFEED);
  151. break;
  152. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH_JSON_DOTNOTATION):
  153. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH_JSON_DOTNOTATION);
  154. break;
  155. default:
  156. $feed->_kind(FreshRSS_Feed::KIND_RSS);
  157. break;
  158. }
  159. $feed->_priority(match (strtolower($feed_elt['frss:priority'] ?? '')) {
  160. FreshRSS_Export_Service::PRIORITY_IMPORTANT => FreshRSS_Feed::PRIORITY_IMPORTANT,
  161. FreshRSS_Export_Service::PRIORITY_MAIN_STREAM => FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  162. FreshRSS_Export_Service::PRIORITY_CATEGORY => FreshRSS_Feed::PRIORITY_CATEGORY,
  163. FreshRSS_Export_Service::PRIORITY_FEED => FreshRSS_Feed::PRIORITY_FEED,
  164. FreshRSS_Export_Service::PRIORITY_HIDDEN => FreshRSS_Feed::PRIORITY_HIDDEN,
  165. default => FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  166. });
  167. if (isset($feed_elt['frss:cssFullContent'])) {
  168. $feed->_pathEntries(Minz_Helper::htmlspecialchars_utf8($feed_elt['frss:cssFullContent']));
  169. }
  170. if (isset($feed_elt['frss:cssFullContentConditions'])) {
  171. $feed->_attribute(
  172. 'path_entries_conditions',
  173. preg_split('/\R/u', $feed_elt['frss:cssFullContentConditions']) ?: []
  174. );
  175. }
  176. if (isset($feed_elt['frss:cssContentFilter']) || isset($feed_elt['frss:cssFullContentFilter'])) {
  177. $feed->_attribute('path_entries_filter', $feed_elt['frss:cssContentFilter'] ?? $feed_elt['frss:cssFullContentFilter']);
  178. }
  179. if (isset($feed_elt['frss:filtersActionRead'])) {
  180. $feed->_filtersAction(
  181. 'read',
  182. preg_split('/\R/u', $feed_elt['frss:filtersActionRead']) ?: []
  183. );
  184. }
  185. $xPathSettings = [];
  186. if (isset($feed_elt['frss:xPathItem'])) {
  187. $xPathSettings['item'] = $feed_elt['frss:xPathItem'];
  188. }
  189. if (isset($feed_elt['frss:xPathItemTitle'])) {
  190. $xPathSettings['itemTitle'] = $feed_elt['frss:xPathItemTitle'];
  191. }
  192. if (isset($feed_elt['frss:xPathItemContent'])) {
  193. $xPathSettings['itemContent'] = $feed_elt['frss:xPathItemContent'];
  194. }
  195. if (isset($feed_elt['frss:xPathItemUri'])) {
  196. $xPathSettings['itemUri'] = $feed_elt['frss:xPathItemUri'];
  197. }
  198. if (isset($feed_elt['frss:xPathItemAuthor'])) {
  199. $xPathSettings['itemAuthor'] = $feed_elt['frss:xPathItemAuthor'];
  200. }
  201. if (isset($feed_elt['frss:xPathItemTimestamp'])) {
  202. $xPathSettings['itemTimestamp'] = $feed_elt['frss:xPathItemTimestamp'];
  203. }
  204. if (isset($feed_elt['frss:xPathItemTimeFormat'])) {
  205. $xPathSettings['itemTimeFormat'] = $feed_elt['frss:xPathItemTimeFormat'];
  206. }
  207. if (isset($feed_elt['frss:xPathItemThumbnail'])) {
  208. $xPathSettings['itemThumbnail'] = $feed_elt['frss:xPathItemThumbnail'];
  209. }
  210. if (isset($feed_elt['frss:xPathItemCategories'])) {
  211. $xPathSettings['itemCategories'] = $feed_elt['frss:xPathItemCategories'];
  212. }
  213. if (isset($feed_elt['frss:xPathItemUid'])) {
  214. $xPathSettings['itemUid'] = $feed_elt['frss:xPathItemUid'];
  215. }
  216. if (!empty($xPathSettings)) {
  217. $feed->_attribute('xpath', $xPathSettings);
  218. }
  219. $jsonSettings = [];
  220. if (isset($feed_elt['frss:jsonItem'])) {
  221. $jsonSettings['item'] = $feed_elt['frss:jsonItem'];
  222. }
  223. if (isset($feed_elt['frss:jsonItemTitle'])) {
  224. $jsonSettings['itemTitle'] = $feed_elt['frss:jsonItemTitle'];
  225. }
  226. if (isset($feed_elt['frss:jsonItemContent'])) {
  227. $jsonSettings['itemContent'] = $feed_elt['frss:jsonItemContent'];
  228. }
  229. if (isset($feed_elt['frss:jsonItemUri'])) {
  230. $jsonSettings['itemUri'] = $feed_elt['frss:jsonItemUri'];
  231. }
  232. if (isset($feed_elt['frss:jsonItemAuthor'])) {
  233. $jsonSettings['itemAuthor'] = $feed_elt['frss:jsonItemAuthor'];
  234. }
  235. if (isset($feed_elt['frss:jsonItemTimestamp'])) {
  236. $jsonSettings['itemTimestamp'] = $feed_elt['frss:jsonItemTimestamp'];
  237. }
  238. if (isset($feed_elt['frss:jsonItemTimeFormat'])) {
  239. $jsonSettings['itemTimeFormat'] = $feed_elt['frss:jsonItemTimeFormat'];
  240. }
  241. if (isset($feed_elt['frss:jsonItemThumbnail'])) {
  242. $jsonSettings['itemThumbnail'] = $feed_elt['frss:jsonItemThumbnail'];
  243. }
  244. if (isset($feed_elt['frss:jsonItemCategories'])) {
  245. $jsonSettings['itemCategories'] = $feed_elt['frss:jsonItemCategories'];
  246. }
  247. if (isset($feed_elt['frss:jsonItemUid'])) {
  248. $jsonSettings['itemUid'] = $feed_elt['frss:jsonItemUid'];
  249. }
  250. if (!empty($jsonSettings)) {
  251. $feed->_attribute('json_dotnotation', $jsonSettings);
  252. }
  253. $feed->_attribute('xPathToJson', $feed_elt['frss:xPathToJson'] ?? null);
  254. $curl_params = [];
  255. if (isset($feed_elt['frss:CURLOPT_COOKIE'])) {
  256. $curl_params[CURLOPT_COOKIE] = $feed_elt['frss:CURLOPT_COOKIE'];
  257. }
  258. if (isset($feed_elt['frss:CURLOPT_COOKIEFILE'])) {
  259. // Allow only an empty value just to enable the libcurl cookie engine
  260. $curl_params[CURLOPT_COOKIEFILE] = '';
  261. }
  262. if (isset($feed_elt['frss:CURLOPT_FOLLOWLOCATION'])) {
  263. $curl_params[CURLOPT_FOLLOWLOCATION] = (bool)$feed_elt['frss:CURLOPT_FOLLOWLOCATION'];
  264. }
  265. if (isset($feed_elt['frss:CURLOPT_HTTPHEADER'])) {
  266. $curl_params[CURLOPT_HTTPHEADER] = preg_split('/\R/u', $feed_elt['frss:CURLOPT_HTTPHEADER']) ?: [];
  267. }
  268. if (isset($feed_elt['frss:CURLOPT_MAXREDIRS'])) {
  269. $curl_params[CURLOPT_MAXREDIRS] = (int)$feed_elt['frss:CURLOPT_MAXREDIRS'];
  270. }
  271. if (isset($feed_elt['frss:CURLOPT_POST'])) {
  272. $curl_params[CURLOPT_POST] = (bool)$feed_elt['frss:CURLOPT_POST'];
  273. }
  274. if (isset($feed_elt['frss:CURLOPT_POSTFIELDS'])) {
  275. $curl_params[CURLOPT_POSTFIELDS] = $feed_elt['frss:CURLOPT_POSTFIELDS'];
  276. }
  277. if (isset($feed_elt['frss:CURLOPT_PROXY'])) {
  278. $curl_params[CURLOPT_PROXY] = $feed_elt['frss:CURLOPT_PROXY'];
  279. }
  280. if (isset($feed_elt['frss:CURLOPT_PROXYTYPE'])) {
  281. $curl_params[CURLOPT_PROXYTYPE] = (int)$feed_elt['frss:CURLOPT_PROXYTYPE'];
  282. if ($curl_params[CURLOPT_PROXYTYPE] === 3) { // Legacy for NONE
  283. $curl_params[CURLOPT_PROXYTYPE] = -1;
  284. }
  285. }
  286. if (isset($feed_elt['frss:CURLOPT_USERAGENT'])) {
  287. $curl_params[CURLOPT_USERAGENT] = $feed_elt['frss:CURLOPT_USERAGENT'];
  288. }
  289. if (!empty($curl_params)) {
  290. $feed->_attribute('curl_params', $curl_params);
  291. }
  292. // Call the extension hook
  293. /** @var FreshRSS_Feed|null */
  294. $feed = Minz_ExtensionManager::callHook(Minz_HookType::FeedBeforeInsert, $feed);
  295. if ($dry_run) {
  296. if ($feed !== null) {
  297. $category->addFeed($feed);
  298. }
  299. return $feed;
  300. }
  301. if ($feed !== null) {
  302. // addFeedObject checks if feed is already in DB
  303. $id = $this->feedDAO->addFeedObject($feed);
  304. if ($id == false) {
  305. $this->lastStatus = false;
  306. } else {
  307. $feed->_id($id);
  308. $category->addFeed($feed);
  309. return $feed;
  310. }
  311. }
  312. } catch (FreshRSS_Feed_Exception $e) {
  313. self::log($e->getMessage());
  314. $this->lastStatus = false;
  315. }
  316. $clean_url = \SimplePie\Misc::url_remove_credentials($url);
  317. self::log("Cannot create {$clean_url} feed in category {$category->name()}");
  318. return null;
  319. }
  320. /**
  321. * Create and return a category.
  322. *
  323. * @param array<string,string> $category_element An OPML element (must be a category element).
  324. * @param bool $dry_run true to not create the category in database.
  325. * @return FreshRSS_Category|null The created category, or null if it failed.
  326. */
  327. private function createCategory(array $category_element, bool $dry_run): ?FreshRSS_Category {
  328. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  329. $name = Minz_Helper::htmlspecialchars_utf8($name);
  330. $category = new FreshRSS_Category($name);
  331. if (isset($category_element['frss:opmlUrl'])) {
  332. $opml_url = FreshRSS_http_Util::checkUrl($category_element['frss:opmlUrl']);
  333. if ($opml_url != '') {
  334. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  335. $category->_attribute('opml_url', $opml_url);
  336. }
  337. }
  338. if ($dry_run) {
  339. return $category;
  340. }
  341. $id = $this->catDAO->addCategoryObject($category);
  342. if ($id !== false) {
  343. $category->_id($id);
  344. return $category;
  345. } else {
  346. self::log("Cannot create category {$category->name()}");
  347. $this->lastStatus = false;
  348. return null;
  349. }
  350. }
  351. /**
  352. * Return the list of category and feed outlines by categories names.
  353. *
  354. * This method is applied to a list of outlines. It merges the different
  355. * list of feeds from several outlines into one array.
  356. *
  357. * @param array<array<mixed>> $outlines The outlines from which to extract the outlines.
  358. * @param string $parent_category_name The name of the parent category of the current outlines.
  359. * @return array{0:array<string,array<string,string>>,1:array<string,list<array<string,string>>>}
  360. */
  361. private function loadFromOutlines(array $outlines, string $parent_category_name): array {
  362. $categories_elements = [];
  363. $categories_to_feeds = [];
  364. foreach ($outlines as $outline) {
  365. if (!is_array($outline)) {
  366. continue;
  367. }
  368. // Get the categories and feeds from the child outline (it may
  369. // return several categories and feeds if the outline is a category).
  370. [$outline_categories, $outline_categories_to_feeds] = $this->loadFromOutline($outline, $parent_category_name);
  371. // Then, we merge the initial arrays with the arrays returned by
  372. // the outline.
  373. $categories_elements = array_merge($categories_elements, $outline_categories);
  374. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  375. if (!is_string($category_name) || !is_array($feeds)) {
  376. continue;
  377. }
  378. if (!isset($categories_to_feeds[$category_name])) {
  379. $categories_to_feeds[$category_name] = [];
  380. }
  381. $categories_to_feeds[$category_name] = array_merge(
  382. $categories_to_feeds[$category_name],
  383. $feeds
  384. );
  385. }
  386. }
  387. return [$categories_elements, $categories_to_feeds];
  388. }
  389. /**
  390. * Return the list of category and feed outlines by categories names.
  391. *
  392. * This method is applied to a specific outline. If the outline represents
  393. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  394. * to its children. If the outline represents a feed (i.e. xmlUrl key
  395. * exists), it will add the outline to an array accessible by its category
  396. * name.
  397. *
  398. * @param array<mixed> $outline The outline from which to extract the categories and feeds outlines.
  399. * @param string $parent_category_name The name of the parent category of the current outline.
  400. *
  401. * @return array{0:array<string,array<string,string>>,1:array<string,list<array<string,string>>>}
  402. */
  403. private function loadFromOutline(array $outline, string $parent_category_name): array {
  404. $categories_elements = [];
  405. $categories_to_feeds = [];
  406. if ($parent_category_name === '' && isset($outline['category']) && is_array($outline['category'])) {
  407. // The outline has no parent category, but its OPML category
  408. // attribute is set, so we use it as the category name.
  409. // lib_opml parses this attribute as an array of strings, so we
  410. // rebuild a string here.
  411. $parent_category_name = implode(', ', $outline['category']);
  412. $categories_elements[$parent_category_name] = [
  413. 'text' => $parent_category_name,
  414. ];
  415. }
  416. if (is_array($outline['@outlines'] ?? null)) {
  417. // The outline has children, it’s probably a category
  418. if (!empty($outline['text']) && is_string($outline['text'])) {
  419. $category_name = $outline['text'];
  420. } elseif (!empty($outline['title']) && is_string($outline['title'])) {
  421. $category_name = $outline['title'];
  422. } else {
  423. $category_name = $parent_category_name;
  424. }
  425. $children = array_filter($outline['@outlines'], 'is_array');
  426. [$categories_elements, $categories_to_feeds] = $this->loadFromOutlines($children, $category_name);
  427. unset($outline['@outlines']);
  428. $categories_elements[$category_name] = array_filter($outline, static fn($value, $key) => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  429. }
  430. // The xmlUrl means it’s a feed URL: add the outline to the array if it exists.
  431. if (isset($outline['xmlUrl'])) {
  432. if (!isset($categories_to_feeds[$parent_category_name])) {
  433. $categories_to_feeds[$parent_category_name] = [];
  434. }
  435. $feed = array_filter($outline, static fn($value, $key) => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  436. $categories_to_feeds[$parent_category_name][] = $feed;
  437. }
  438. return [$categories_elements, $categories_to_feeds];
  439. }
  440. private static function log(string $message): void {
  441. if (FreshRSS_Context::$isCli) {
  442. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  443. } else {
  444. Minz_Log::warning("Error during OPML import: {$message}");
  445. }
  446. }
  447. }