ImportService.php 16 KB

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