ImportService.php 17 KB

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