ImportService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 (strtolower($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_XML_XPATH):
  148. $feed->_kind(FreshRSS_Feed::KIND_XML_XPATH);
  149. break;
  150. case strtolower(FreshRSS_Export_Service::TYPE_RSS_ATOM):
  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->_attributes('path_entries_filter', $feed_elt['frss:cssFullContentFilter']);
  160. }
  161. if (isset($feed_elt['frss:filtersActionRead'])) {
  162. $feed->_filtersAction(
  163. 'read',
  164. preg_split('/[\n\r]+/', $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->_attributes('xpath', $xPathSettings);
  200. }
  201. // Call the extension hook
  202. /** @var FreshRSS_Feed|null */
  203. $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
  204. if ($dry_run) {
  205. return $feed;
  206. }
  207. if ($feed != null) {
  208. // addFeedObject checks if feed is already in DB
  209. $id = $this->feedDAO->addFeedObject($feed);
  210. if ($id == false) {
  211. $this->lastStatus = false;
  212. } else {
  213. $feed->_id($id);
  214. return $feed;
  215. }
  216. }
  217. } catch (FreshRSS_Feed_Exception $e) {
  218. self::log($e->getMessage());
  219. $this->lastStatus = false;
  220. }
  221. $clean_url = SimplePie_Misc::url_remove_credentials($url);
  222. self::log("Cannot create {$clean_url} feed in category {$category->name()}");
  223. return null;
  224. }
  225. /**
  226. * Create and return a category.
  227. *
  228. * @param array<string, string> $category_element An OPML element (must be a category element).
  229. * @param boolean $dry_run true to not create the category in database.
  230. *
  231. * @return FreshRSS_Category|null The created category, or null if it failed.
  232. */
  233. private function createCategory($category_element, $dry_run) {
  234. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  235. $name = Minz_Helper::htmlspecialchars_utf8($name);
  236. $category = new FreshRSS_Category($name);
  237. if (isset($category_element['frss:opmlUrl'])) {
  238. $opml_url = checkUrl($category_element['frss:opmlUrl']);
  239. if ($opml_url != '') {
  240. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  241. $category->_attributes('opml_url', $opml_url);
  242. }
  243. }
  244. if ($dry_run) {
  245. return $category;
  246. }
  247. $id = $this->catDAO->addCategoryObject($category);
  248. if ($id !== false) {
  249. $category->_id($id);
  250. return $category;
  251. } else {
  252. self::log("Cannot create category {$category->name()}");
  253. $this->lastStatus = false;
  254. return null;
  255. }
  256. }
  257. /**
  258. * Return the list of category and feed outlines by categories names.
  259. *
  260. * This method is applied to a list of outlines. It merges the different
  261. * list of feeds from several outlines into one array.
  262. *
  263. * @param array $outlines
  264. * The outlines from which to extract the outlines.
  265. * @param string $parent_category_name
  266. * The name of the parent category of the current outlines.
  267. *
  268. * @return array[]
  269. */
  270. private function loadFromOutlines($outlines, $parent_category_name) {
  271. $categories_elements = [];
  272. $categories_to_feeds = [];
  273. foreach ($outlines as $outline) {
  274. // Get the categories and feeds from the child outline (it may
  275. // return several categories and feeds if the outline is a category).
  276. list (
  277. $outline_categories,
  278. $outline_categories_to_feeds,
  279. ) = $this->loadFromOutline($outline, $parent_category_name);
  280. // Then, we merge the initial arrays with the arrays returned by
  281. // the outline.
  282. $categories_elements = array_merge($categories_elements, $outline_categories);
  283. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  284. if (!isset($categories_to_feeds[$category_name])) {
  285. $categories_to_feeds[$category_name] = [];
  286. }
  287. $categories_to_feeds[$category_name] = array_merge(
  288. $categories_to_feeds[$category_name],
  289. $feeds
  290. );
  291. }
  292. }
  293. return [$categories_elements, $categories_to_feeds];
  294. }
  295. /**
  296. * Return the list of category and feed outlines by categories names.
  297. *
  298. * This method is applied to a specific outline. If the outline represents
  299. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  300. * to its children. If the outline represents a feed (i.e. xmlUrl key
  301. * exists), it will add the outline to an array accessible by its category
  302. * name.
  303. *
  304. * @param array $outline
  305. * The outline from which to extract the categories and feeds outlines.
  306. * @param string $parent_category_name
  307. * The name of the parent category of the current outline.
  308. *
  309. * @return array[]
  310. */
  311. private function loadFromOutline($outline, $parent_category_name) {
  312. $categories_elements = [];
  313. $categories_to_feeds = [];
  314. if ($parent_category_name === '' && isset($outline['category'])) {
  315. // The outline has no parent category, but its OPML category
  316. // attribute is set, so we use it as the category name.
  317. // lib_opml parses this attribute as an array of strings, so we
  318. // rebuild a string here.
  319. $parent_category_name = implode(', ', $outline['category']);
  320. $categories_elements[$parent_category_name] = [
  321. 'text' => $parent_category_name,
  322. ];
  323. }
  324. if (isset($outline['@outlines'])) {
  325. // The outline has children, it's probably a category
  326. if (!empty($outline['text'])) {
  327. $category_name = $outline['text'];
  328. } elseif (!empty($outline['title'])) {
  329. $category_name = $outline['title'];
  330. } else {
  331. $category_name = $parent_category_name;
  332. }
  333. list (
  334. $categories_elements,
  335. $categories_to_feeds,
  336. ) = $this->loadFromOutlines($outline['@outlines'], $category_name);
  337. unset($outline['@outlines']);
  338. $categories_elements[$category_name] = $outline;
  339. }
  340. // The xmlUrl means it's a feed URL: add the outline to the array if it
  341. // exists.
  342. if (isset($outline['xmlUrl'])) {
  343. if (!isset($categories_to_feeds[$parent_category_name])) {
  344. $categories_to_feeds[$parent_category_name] = [];
  345. }
  346. $categories_to_feeds[$parent_category_name][] = $outline;
  347. }
  348. return [$categories_elements, $categories_to_feeds];
  349. }
  350. private static function log($message) {
  351. if (FreshRSS_Context::$isCli) {
  352. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  353. } else {
  354. Minz_Log::warning("Error during OPML import: {$message}");
  355. }
  356. }
  357. }