ImportService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Provide methods to import files.
  5. */
  6. class FreshRSS_Import_Service {
  7. private FreshRSS_CategoryDAO $catDAO;
  8. private 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(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) {
  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) {
  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)) {
  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. $category->addFeed($feed);
  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. default:
  152. $feed->_kind(FreshRSS_Feed::KIND_RSS);
  153. break;
  154. }
  155. if (isset($feed_elt['frss:cssFullContent'])) {
  156. $feed->_pathEntries(Minz_Helper::htmlspecialchars_utf8($feed_elt['frss:cssFullContent']));
  157. }
  158. if (isset($feed_elt['frss:cssFullContentFilter'])) {
  159. $feed->_attribute('path_entries_filter', $feed_elt['frss:cssFullContentFilter']);
  160. }
  161. if (isset($feed_elt['frss:filtersActionRead'])) {
  162. $feed->_filtersAction(
  163. 'read',
  164. preg_split('/\R/u', $feed_elt['frss:filtersActionRead']) ?: []
  165. );
  166. }
  167. $xPathSettings = [];
  168. if (isset($feed_elt['frss:xPathItem'])) {
  169. $xPathSettings['item'] = $feed_elt['frss:xPathItem'];
  170. }
  171. if (isset($feed_elt['frss:xPathItemTitle'])) {
  172. $xPathSettings['itemTitle'] = $feed_elt['frss:xPathItemTitle'];
  173. }
  174. if (isset($feed_elt['frss:xPathItemContent'])) {
  175. $xPathSettings['itemContent'] = $feed_elt['frss:xPathItemContent'];
  176. }
  177. if (isset($feed_elt['frss:xPathItemUri'])) {
  178. $xPathSettings['itemUri'] = $feed_elt['frss:xPathItemUri'];
  179. }
  180. if (isset($feed_elt['frss:xPathItemAuthor'])) {
  181. $xPathSettings['itemAuthor'] = $feed_elt['frss:xPathItemAuthor'];
  182. }
  183. if (isset($feed_elt['frss:xPathItemTimestamp'])) {
  184. $xPathSettings['itemTimestamp'] = $feed_elt['frss:xPathItemTimestamp'];
  185. }
  186. if (isset($feed_elt['frss:xPathItemTimeFormat'])) {
  187. $xPathSettings['itemTimeFormat'] = $feed_elt['frss:xPathItemTimeFormat'];
  188. }
  189. if (isset($feed_elt['frss:xPathItemThumbnail'])) {
  190. $xPathSettings['itemThumbnail'] = $feed_elt['frss:xPathItemThumbnail'];
  191. }
  192. if (isset($feed_elt['frss:xPathItemCategories'])) {
  193. $xPathSettings['itemCategories'] = $feed_elt['frss:xPathItemCategories'];
  194. }
  195. if (isset($feed_elt['frss:xPathItemUid'])) {
  196. $xPathSettings['itemUid'] = $feed_elt['frss:xPathItemUid'];
  197. }
  198. if (!empty($xPathSettings)) {
  199. $feed->_attribute('xpath', $xPathSettings);
  200. }
  201. $jsonSettings = [];
  202. if (isset($feed_elt['frss:jsonItem'])) {
  203. $jsonSettings['item'] = $feed_elt['frss:jsonItem'];
  204. }
  205. if (isset($feed_elt['frss:jsonItemTitle'])) {
  206. $jsonSettings['itemTitle'] = $feed_elt['frss:jsonItemTitle'];
  207. }
  208. if (isset($feed_elt['frss:jsonItemContent'])) {
  209. $jsonSettings['itemContent'] = $feed_elt['frss:jsonItemContent'];
  210. }
  211. if (isset($feed_elt['frss:jsonItemUri'])) {
  212. $jsonSettings['itemUri'] = $feed_elt['frss:jsonItemUri'];
  213. }
  214. if (isset($feed_elt['frss:jsonItemAuthor'])) {
  215. $jsonSettings['itemAuthor'] = $feed_elt['frss:jsonItemAuthor'];
  216. }
  217. if (isset($feed_elt['frss:jsonItemTimestamp'])) {
  218. $jsonSettings['itemTimestamp'] = $feed_elt['frss:jsonItemTimestamp'];
  219. }
  220. if (isset($feed_elt['frss:jsonItemTimeFormat'])) {
  221. $jsonSettings['itemTimeFormat'] = $feed_elt['frss:jsonItemTimeFormat'];
  222. }
  223. if (isset($feed_elt['frss:jsonItemThumbnail'])) {
  224. $jsonSettings['itemThumbnail'] = $feed_elt['frss:jsonItemThumbnail'];
  225. }
  226. if (isset($feed_elt['frss:jsonItemCategories'])) {
  227. $jsonSettings['itemCategories'] = $feed_elt['frss:jsonItemCategories'];
  228. }
  229. if (isset($feed_elt['frss:jsonItemUid'])) {
  230. $jsonSettings['itemUid'] = $feed_elt['frss:jsonItemUid'];
  231. }
  232. if (!empty($jsonSettings)) {
  233. $feed->_attribute('json_dotnotation', $jsonSettings);
  234. }
  235. $curl_params = [];
  236. if (isset($feed_elt['frss:CURLOPT_COOKIE'])) {
  237. $curl_params[CURLOPT_COOKIE] = $feed_elt['frss:CURLOPT_COOKIE'];
  238. }
  239. if (isset($feed_elt['frss:CURLOPT_COOKIEFILE'])) {
  240. $curl_params[CURLOPT_COOKIEFILE] = $feed_elt['frss:CURLOPT_COOKIEFILE'];
  241. }
  242. if (isset($feed_elt['frss:CURLOPT_FOLLOWLOCATION'])) {
  243. $curl_params[CURLOPT_FOLLOWLOCATION] = (bool)$feed_elt['frss:CURLOPT_FOLLOWLOCATION'];
  244. }
  245. if (isset($feed_elt['frss:CURLOPT_HTTPHEADER'])) {
  246. $curl_params[CURLOPT_HTTPHEADER] = preg_split('/\R/u', $feed_elt['frss:CURLOPT_HTTPHEADER']) ?: [];
  247. }
  248. if (isset($feed_elt['frss:CURLOPT_MAXREDIRS'])) {
  249. $curl_params[CURLOPT_MAXREDIRS] = (int)$feed_elt['frss:CURLOPT_MAXREDIRS'];
  250. }
  251. if (isset($feed_elt['frss:CURLOPT_POST'])) {
  252. $curl_params[CURLOPT_POST] = (bool)$feed_elt['frss:CURLOPT_POST'];
  253. }
  254. if (isset($feed_elt['frss:CURLOPT_POSTFIELDS'])) {
  255. $curl_params[CURLOPT_POSTFIELDS] = $feed_elt['frss:CURLOPT_POSTFIELDS'];
  256. }
  257. if (isset($feed_elt['frss:CURLOPT_PROXY'])) {
  258. $curl_params[CURLOPT_PROXY] = $feed_elt['frss:CURLOPT_PROXY'];
  259. }
  260. if (isset($feed_elt['frss:CURLOPT_PROXYTYPE'])) {
  261. $curl_params[CURLOPT_PROXYTYPE] = (int)$feed_elt['frss:CURLOPT_PROXYTYPE'];
  262. }
  263. if (isset($feed_elt['frss:CURLOPT_USERAGENT'])) {
  264. $curl_params[CURLOPT_USERAGENT] = $feed_elt['frss:CURLOPT_USERAGENT'];
  265. }
  266. if (!empty($curl_params)) {
  267. $feed->_attribute('curl_params', $curl_params);
  268. }
  269. // Call the extension hook
  270. /** @var FreshRSS_Feed|null */
  271. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  272. if ($dry_run) {
  273. return $feed;
  274. }
  275. if ($feed != null) {
  276. // addFeedObject checks if feed is already in DB
  277. $id = $this->feedDAO->addFeedObject($feed);
  278. if ($id == false) {
  279. $this->lastStatus = false;
  280. } else {
  281. $feed->_id($id);
  282. return $feed;
  283. }
  284. }
  285. } catch (FreshRSS_Feed_Exception $e) {
  286. self::log($e->getMessage());
  287. $this->lastStatus = false;
  288. }
  289. $clean_url = SimplePie_Misc::url_remove_credentials($url);
  290. self::log("Cannot create {$clean_url} feed in category {$category->name()}");
  291. return null;
  292. }
  293. /**
  294. * Create and return a category.
  295. *
  296. * @param array<string,string> $category_element An OPML element (must be a category element).
  297. * @param bool $dry_run true to not create the category in database.
  298. * @return FreshRSS_Category|null The created category, or null if it failed.
  299. */
  300. private function createCategory(array $category_element, bool $dry_run): ?FreshRSS_Category {
  301. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  302. $name = Minz_Helper::htmlspecialchars_utf8($name);
  303. $category = new FreshRSS_Category($name);
  304. if (isset($category_element['frss:opmlUrl'])) {
  305. $opml_url = checkUrl($category_element['frss:opmlUrl']);
  306. if ($opml_url != '') {
  307. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  308. $category->_attribute('opml_url', $opml_url);
  309. }
  310. }
  311. if ($dry_run) {
  312. return $category;
  313. }
  314. $id = $this->catDAO->addCategoryObject($category);
  315. if ($id !== false) {
  316. $category->_id($id);
  317. return $category;
  318. } else {
  319. self::log("Cannot create category {$category->name()}");
  320. $this->lastStatus = false;
  321. return null;
  322. }
  323. }
  324. /**
  325. * Return the list of category and feed outlines by categories names.
  326. *
  327. * This method is applied to a list of outlines. It merges the different
  328. * list of feeds from several outlines into one array.
  329. *
  330. * @param array<array<mixed>> $outlines
  331. * The outlines from which to extract the outlines.
  332. * @param string $parent_category_name
  333. * The name of the parent category of the current outlines.
  334. * @return array{0:array<string,array<string,string>>,1:array<string,array<array<string,string>>>}
  335. */
  336. private function loadFromOutlines(array $outlines, string $parent_category_name): array {
  337. $categories_elements = [];
  338. $categories_to_feeds = [];
  339. foreach ($outlines as $outline) {
  340. // Get the categories and feeds from the child outline (it may
  341. // return several categories and feeds if the outline is a category).
  342. [$outline_categories, $outline_categories_to_feeds] = $this->loadFromOutline($outline, $parent_category_name);
  343. // Then, we merge the initial arrays with the arrays returned by
  344. // the outline.
  345. $categories_elements = array_merge($categories_elements, $outline_categories);
  346. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  347. if (!isset($categories_to_feeds[$category_name])) {
  348. $categories_to_feeds[$category_name] = [];
  349. }
  350. $categories_to_feeds[$category_name] = array_merge(
  351. $categories_to_feeds[$category_name],
  352. $feeds
  353. );
  354. }
  355. }
  356. return [$categories_elements, $categories_to_feeds];
  357. }
  358. /**
  359. * Return the list of category and feed outlines by categories names.
  360. *
  361. * This method is applied to a specific outline. If the outline represents
  362. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  363. * to its children. If the outline represents a feed (i.e. xmlUrl key
  364. * exists), it will add the outline to an array accessible by its category
  365. * name.
  366. *
  367. * @param array<mixed> $outline
  368. * The outline from which to extract the categories and feeds outlines.
  369. * @param string $parent_category_name
  370. * The name of the parent category of the current outline.
  371. *
  372. * @return array{0:array<string,array<string,string>>,1:array<array<string,array<string,string>>>}
  373. */
  374. private function loadFromOutline(array $outline, string $parent_category_name): array {
  375. $categories_elements = [];
  376. $categories_to_feeds = [];
  377. if ($parent_category_name === '' && isset($outline['category']) && is_array($outline['category'])) {
  378. // The outline has no parent category, but its OPML category
  379. // attribute is set, so we use it as the category name.
  380. // lib_opml parses this attribute as an array of strings, so we
  381. // rebuild a string here.
  382. $parent_category_name = implode(', ', $outline['category']);
  383. $categories_elements[$parent_category_name] = [
  384. 'text' => $parent_category_name,
  385. ];
  386. }
  387. if (isset($outline['@outlines'])) {
  388. // The outline has children, it’s probably a category
  389. if (!empty($outline['text']) && is_string($outline['text'])) {
  390. $category_name = $outline['text'];
  391. } elseif (!empty($outline['title']) && is_string($outline['title'])) {
  392. $category_name = $outline['title'];
  393. } else {
  394. $category_name = $parent_category_name;
  395. }
  396. [$categories_elements, $categories_to_feeds] = $this->loadFromOutlines($outline['@outlines'], $category_name);
  397. unset($outline['@outlines']);
  398. $categories_elements[$category_name] = $outline;
  399. }
  400. // The xmlUrl means it’s a feed URL: add the outline to the array if it exists.
  401. if (isset($outline['xmlUrl'])) {
  402. if (!isset($categories_to_feeds[$parent_category_name])) {
  403. $categories_to_feeds[$parent_category_name] = [];
  404. }
  405. $categories_to_feeds[$parent_category_name][] = $outline;
  406. }
  407. return [$categories_elements, $categories_to_feeds];
  408. }
  409. private static function log(string $message): void {
  410. if (FreshRSS_Context::$isCli) {
  411. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  412. } else {
  413. Minz_Log::warning("Error during OPML import: {$message}");
  414. }
  415. }
  416. }