ImportService.php 13 KB

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