ImportService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. /**
  3. * Provide methods to import files.
  4. */
  5. class FreshRSS_Import_Service {
  6. /** @var FreshRSS_CategoryDAO */
  7. private $catDAO;
  8. /** @var FreshRSS_FeedDAO */
  9. private $feedDAO;
  10. /** @var bool true if success, false otherwise */
  11. private $lastStatus;
  12. /**
  13. * Initialize the service for the given user.
  14. *
  15. * @param string $username
  16. */
  17. public function __construct($username = null) {
  18. $this->catDAO = FreshRSS_Factory::createCategoryDao($username);
  19. $this->feedDAO = FreshRSS_Factory::createFeedDao($username);
  20. }
  21. /** @return bool true if success, false otherwise */
  22. public function lastStatus(): bool {
  23. return $this->lastStatus;
  24. }
  25. /**
  26. * This method parses and imports an OPML file.
  27. *
  28. * @param string $opml_file the OPML file content.
  29. * @param FreshRSS_Category|null $forced_category force the feeds to be associated to this category.
  30. * @param boolean $dry_run true to not create categories and feeds in database.
  31. */
  32. public function importOpml(string $opml_file, $forced_category = null, $dry_run = false) {
  33. $this->lastStatus = true;
  34. $opml_array = 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) {
  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::$system_conf->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. list (
  65. $categories_elements,
  66. $categories_to_feeds,
  67. ) = $this->loadFromOutlines($opml_array['body'], '');
  68. foreach ($categories_to_feeds as $category_name => $feeds_elements) {
  69. $category_element = $categories_elements[$category_name] ?? null;
  70. $category = null;
  71. if ($forced_category) {
  72. // If the category is forced, ignore the actual category name
  73. $category = $forced_category;
  74. } elseif (isset($categories_by_names[$category_name])) {
  75. // If the category already exists, get it from $categories_by_names
  76. $category = $categories_by_names[$category_name];
  77. } elseif ($category_element) {
  78. // Otherwise, create the category (if possible)
  79. $limit_reached = $nb_categories >= $limits['max_categories'];
  80. $can_create_category = FreshRSS_Context::$isCli || !$limit_reached;
  81. if ($can_create_category) {
  82. $category = $this->createCategory($category_element, $dry_run);
  83. if ($category) {
  84. $categories_by_names[$category->name()] = $category;
  85. $nb_categories++;
  86. }
  87. } else {
  88. Minz_Log::warning(
  89. _t('feedback.sub.category.over_max', $limits['max_categories'])
  90. );
  91. }
  92. }
  93. if (!$category) {
  94. // Category can be null if the feeds weren't in a category
  95. // outline, or if we weren't able to create the category.
  96. $category = $default_category;
  97. }
  98. // Then, create the feeds one by one and attach them to the
  99. // category we just got.
  100. foreach ($feeds_elements as $feed_element) {
  101. $limit_reached = $nb_feeds >= $limits['max_feeds'];
  102. $can_create_feed = FreshRSS_Context::$isCli || !$limit_reached;
  103. if (!$can_create_feed) {
  104. Minz_Log::warning(
  105. _t('feedback.sub.feed.over_max', $limits['max_feeds'])
  106. );
  107. $this->lastStatus = false;
  108. break;
  109. }
  110. if ($this->createFeed($feed_element, $category, $dry_run)) {
  111. // TODO what if the feed already exists in the database?
  112. $nb_feeds++;
  113. } else {
  114. $this->lastStatus = false;
  115. }
  116. }
  117. }
  118. return;
  119. }
  120. /**
  121. * Create a feed from a feed element (i.e. OPML outline).
  122. *
  123. * @param array<string, string> $feed_elt An OPML element (must be a feed element).
  124. * @param FreshRSS_Category $category The category to associate to the feed.
  125. * @param boolean $dry_run true to not create the feed in database.
  126. *
  127. * @return FreshRSS_Feed|null The created feed, or null if it failed.
  128. */
  129. private function createFeed($feed_elt, $category, $dry_run) {
  130. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  131. $name = $feed_elt['text'] ?? $feed_elt['title'] ?? '';
  132. $name = Minz_Helper::htmlspecialchars_utf8($name);
  133. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl'] ?? '');
  134. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description'] ?? '');
  135. try {
  136. // Create a Feed object and add it in DB
  137. $feed = new FreshRSS_Feed($url);
  138. $feed->_categoryId($category->id());
  139. $category->addFeed($feed);
  140. $feed->_name($name);
  141. $feed->_website($website);
  142. $feed->_description($description);
  143. switch ($feed_elt['type'] ?? '') {
  144. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH):
  145. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH);
  146. break;
  147. case strtolower(FreshRSS_Export_Service::TYPE_RSS_ATOM):
  148. default:
  149. $feed->_kind(FreshRSS_Feed::KIND_RSS);
  150. break;
  151. }
  152. if (isset($feed_elt['frss:cssFullContent'])) {
  153. $feed->_pathEntries(Minz_Helper::htmlspecialchars_utf8($feed_elt['frss:cssFullContent']));
  154. }
  155. if (isset($feed_elt['frss:cssFullContentFilter'])) {
  156. $feed->_attributes('path_entries_filter', $feed_elt['frss:cssFullContentFilter']);
  157. }
  158. if (isset($feed_elt['frss:filtersActionRead'])) {
  159. $feed->_filtersAction(
  160. 'read',
  161. preg_split('/[\n\r]+/', $feed_elt['frss:filtersActionRead'])
  162. );
  163. }
  164. $xPathSettings = [];
  165. if (isset($feed_elt['frss:xPathItem'])) {
  166. $xPathSettings['item'] = $feed_elt['frss:xPathItem'];
  167. }
  168. if (isset($feed_elt['frss:xPathItemTitle'])) {
  169. $xPathSettings['itemTitle'] = $feed_elt['frss:xPathItemTitle'];
  170. }
  171. if (isset($feed_elt['frss:xPathItemContent'])) {
  172. $xPathSettings['itemContent'] = $feed_elt['frss:xPathItemContent'];
  173. }
  174. if (isset($feed_elt['frss:xPathItemUri'])) {
  175. $xPathSettings['itemUri'] = $feed_elt['frss:xPathItemUri'];
  176. }
  177. if (isset($feed_elt['frss:xPathItemAuthor'])) {
  178. $xPathSettings['itemAuthor'] = $feed_elt['frss:xPathItemAuthor'];
  179. }
  180. if (isset($feed_elt['frss:xPathItemTimestamp'])) {
  181. $xPathSettings['itemTimestamp'] = $feed_elt['frss:xPathItemTimestamp'];
  182. }
  183. if (isset($feed_elt['frss:xPathItemTimeFormat'])) {
  184. $xPathSettings['itemTimeFormat'] = $feed_elt['frss:xPathItemTimeFormat'];
  185. }
  186. if (isset($feed_elt['frss:xPathItemThumbnail'])) {
  187. $xPathSettings['itemThumbnail'] = $feed_elt['frss:xPathItemThumbnail'];
  188. }
  189. if (isset($feed_elt['frss:xPathItemCategories'])) {
  190. $xPathSettings['itemCategories'] = $feed_elt['frss:xPathItemCategories'];
  191. }
  192. if (isset($feed_elt['frss:xPathItemUid'])) {
  193. $xPathSettings['itemUid'] = $feed_elt['frss:xPathItemUid'];
  194. }
  195. if (!empty($xPathSettings)) {
  196. $feed->_attributes('xpath', $xPathSettings);
  197. }
  198. // Call the extension hook
  199. /** @var FreshRSS_Feed|null */
  200. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  201. if ($dry_run) {
  202. return $feed;
  203. }
  204. if ($feed != null) {
  205. // addFeedObject checks if feed is already in DB
  206. $id = $this->feedDAO->addFeedObject($feed);
  207. if ($id == false) {
  208. $this->lastStatus = false;
  209. } else {
  210. $feed->_id($id);
  211. return $feed;
  212. }
  213. }
  214. } catch (FreshRSS_Feed_Exception $e) {
  215. self::log($e->getMessage());
  216. $this->lastStatus = false;
  217. }
  218. $clean_url = SimplePie_Misc::url_remove_credentials($url);
  219. self::log("Cannot create {$clean_url} feed in category {$category->name()}");
  220. return null;
  221. }
  222. /**
  223. * Create and return a category.
  224. *
  225. * @param array<string, string> $category_element An OPML element (must be a category element).
  226. * @param boolean $dry_run true to not create the category in database.
  227. *
  228. * @return FreshRSS_Category|null The created category, or null if it failed.
  229. */
  230. private function createCategory($category_element, $dry_run) {
  231. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  232. $name = Minz_Helper::htmlspecialchars_utf8($name);
  233. $category = new FreshRSS_Category($name);
  234. if (isset($category_element['frss:opmlUrl'])) {
  235. $opml_url = checkUrl($category_element['frss:opmlUrl']);
  236. if ($opml_url != '') {
  237. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  238. $category->_attributes('opml_url', $opml_url);
  239. }
  240. }
  241. if ($dry_run) {
  242. return $category;
  243. }
  244. $id = $this->catDAO->addCategoryObject($category);
  245. if ($id !== false) {
  246. $category->_id($id);
  247. return $category;
  248. } else {
  249. self::log("Cannot create category {$category->name()}");
  250. $this->lastStatus = false;
  251. return null;
  252. }
  253. }
  254. /**
  255. * Return the list of category and feed outlines by categories names.
  256. *
  257. * This method is applied to a list of outlines. It merges the different
  258. * list of feeds from several outlines into one array.
  259. *
  260. * @param array $outlines
  261. * The outlines from which to extract the outlines.
  262. * @param string $parent_category_name
  263. * The name of the parent category of the current outlines.
  264. *
  265. * @return array[]
  266. */
  267. private function loadFromOutlines($outlines, $parent_category_name) {
  268. $categories_elements = [];
  269. $categories_to_feeds = [];
  270. foreach ($outlines as $outline) {
  271. // Get the categories and feeds from the child outline (it may
  272. // return several categories and feeds if the outline is a category).
  273. list (
  274. $outline_categories,
  275. $outline_categories_to_feeds,
  276. ) = $this->loadFromOutline($outline, $parent_category_name);
  277. // Then, we merge the initial arrays with the arrays returned by
  278. // the outline.
  279. $categories_elements = array_merge($categories_elements, $outline_categories);
  280. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  281. if (!isset($categories_to_feeds[$category_name])) {
  282. $categories_to_feeds[$category_name] = [];
  283. }
  284. $categories_to_feeds[$category_name] = array_merge(
  285. $categories_to_feeds[$category_name],
  286. $feeds
  287. );
  288. }
  289. }
  290. return [$categories_elements, $categories_to_feeds];
  291. }
  292. /**
  293. * Return the list of category and feed outlines by categories names.
  294. *
  295. * This method is applied to a specific outline. If the outline represents
  296. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  297. * to its children. If the outline represents a feed (i.e. xmlUrl key
  298. * exists), it will add the outline to an array accessible by its category
  299. * name.
  300. *
  301. * @param array $outline
  302. * The outline from which to extract the categories and feeds outlines.
  303. * @param string $parent_category_name
  304. * The name of the parent category of the current outline.
  305. *
  306. * @return array[]
  307. */
  308. private function loadFromOutline($outline, $parent_category_name) {
  309. $categories_elements = [];
  310. $categories_to_feeds = [];
  311. if ($parent_category_name === '' && isset($outline['category'])) {
  312. // The outline has no parent category, but its OPML category
  313. // attribute is set, so we use it as the category name.
  314. // lib_opml parses this attribute as an array of strings, so we
  315. // rebuild a string here.
  316. $parent_category_name = implode(', ', $outline['category']);
  317. $categories_elements[$parent_category_name] = [
  318. 'text' => $parent_category_name,
  319. ];
  320. }
  321. if (isset($outline['@outlines'])) {
  322. // The outline has children, it's probably a category
  323. if (!empty($outline['text'])) {
  324. $category_name = $outline['text'];
  325. } elseif (!empty($outline['title'])) {
  326. $category_name = $outline['title'];
  327. } else {
  328. $category_name = $parent_category_name;
  329. }
  330. list (
  331. $categories_elements,
  332. $categories_to_feeds,
  333. ) = $this->loadFromOutlines($outline['@outlines'], $category_name);
  334. unset($outline['@outlines']);
  335. $categories_elements[$category_name] = $outline;
  336. }
  337. // The xmlUrl means it's a feed URL: add the outline to the array if it
  338. // exists.
  339. if (isset($outline['xmlUrl'])) {
  340. if (!isset($categories_to_feeds[$parent_category_name])) {
  341. $categories_to_feeds[$parent_category_name] = [];
  342. }
  343. $categories_to_feeds[$parent_category_name][] = $outline;
  344. }
  345. return [$categories_elements, $categories_to_feeds];
  346. }
  347. private static function log($message) {
  348. if (FreshRSS_Context::$isCli) {
  349. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  350. } else {
  351. Minz_Log::warning("Error during OPML import: {$message}");
  352. }
  353. }
  354. }