ImportService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. @set_time_limit(300);
  32. $this->lastStatus = true;
  33. $opml_array = array();
  34. try {
  35. $libopml = new \marienfressinaud\LibOpml\LibOpml(false);
  36. $opml_array = $libopml->parseString($opml_file);
  37. } catch (\marienfressinaud\LibOpml\Exception $e) {
  38. self::log($e->getMessage());
  39. $this->lastStatus = false;
  40. return;
  41. }
  42. $this->catDAO->checkDefault();
  43. $default_category = $this->catDAO->getDefault();
  44. if (!$default_category) {
  45. self::log('Cannot get the default category');
  46. $this->lastStatus = false;
  47. return;
  48. }
  49. // Get the categories by names so we can use this array to retrieve
  50. // existing categories later.
  51. $categories = $this->catDAO->listCategories(false) ?: [];
  52. $categories_by_names = [];
  53. foreach ($categories as $category) {
  54. $categories_by_names[$category->name()] = $category;
  55. }
  56. // Get current numbers of categories and feeds, and the limits to
  57. // verify the user can import its categories/feeds.
  58. $nb_categories = count($categories);
  59. $nb_feeds = count($this->feedDAO->listFeeds());
  60. $limits = FreshRSS_Context::$system_conf->limits;
  61. // Process the OPML outlines to get a list of categories and a list of
  62. // feeds elements indexed by their categories names.
  63. list (
  64. $categories_elements,
  65. $categories_to_feeds,
  66. ) = $this->loadFromOutlines($opml_array['body'], '');
  67. foreach ($categories_to_feeds as $category_name => $feeds_elements) {
  68. $category_element = $categories_elements[$category_name] ?? null;
  69. $category = null;
  70. if ($forced_category) {
  71. // If the category is forced, ignore the actual category name
  72. $category = $forced_category;
  73. } elseif (isset($categories_by_names[$category_name])) {
  74. // If the category already exists, get it from $categories_by_names
  75. $category = $categories_by_names[$category_name];
  76. } elseif ($category_element) {
  77. // Otherwise, create the category (if possible)
  78. $limit_reached = $nb_categories >= $limits['max_categories'];
  79. $can_create_category = FreshRSS_Context::$isCli || !$limit_reached;
  80. if ($can_create_category) {
  81. $category = $this->createCategory($category_element, $dry_run);
  82. if ($category) {
  83. $categories_by_names[$category->name()] = $category;
  84. $nb_categories++;
  85. }
  86. } else {
  87. Minz_Log::warning(
  88. _t('feedback.sub.category.over_max', $limits['max_categories'])
  89. );
  90. }
  91. }
  92. if (!$category) {
  93. // Category can be null if the feeds weren't in a category
  94. // outline, or if we weren't able to create the category.
  95. $category = $default_category;
  96. }
  97. // Then, create the feeds one by one and attach them to the
  98. // category we just got.
  99. foreach ($feeds_elements as $feed_element) {
  100. $limit_reached = $nb_feeds >= $limits['max_feeds'];
  101. $can_create_feed = FreshRSS_Context::$isCli || !$limit_reached;
  102. if (!$can_create_feed) {
  103. Minz_Log::warning(
  104. _t('feedback.sub.feed.over_max', $limits['max_feeds'])
  105. );
  106. $this->lastStatus = false;
  107. break;
  108. }
  109. if ($this->createFeed($feed_element, $category, $dry_run)) {
  110. // TODO what if the feed already exists in the database?
  111. $nb_feeds++;
  112. } else {
  113. $this->lastStatus = false;
  114. }
  115. }
  116. }
  117. }
  118. /**
  119. * Create a feed from a feed element (i.e. OPML outline).
  120. *
  121. * @param array<string,string> $feed_elt An OPML element (must be a feed element).
  122. * @param FreshRSS_Category $category The category to associate to the feed.
  123. * @param bool $dry_run true to not create the feed in database.
  124. * @return FreshRSS_Feed|null The created feed, or null if it failed.
  125. */
  126. private function createFeed(array $feed_elt, FreshRSS_Category $category, bool $dry_run): ?FreshRSS_Feed {
  127. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  128. $name = $feed_elt['text'] ?? $feed_elt['title'] ?? '';
  129. $name = Minz_Helper::htmlspecialchars_utf8($name);
  130. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl'] ?? '');
  131. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description'] ?? '');
  132. try {
  133. // Create a Feed object and add it in DB
  134. $feed = new FreshRSS_Feed($url);
  135. $feed->_categoryId($category->id());
  136. $category->addFeed($feed);
  137. $feed->_name($name);
  138. $feed->_website($website);
  139. $feed->_description($description);
  140. switch (strtolower($feed_elt['type'] ?? '')) {
  141. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH):
  142. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH);
  143. break;
  144. case strtolower(FreshRSS_Export_Service::TYPE_XML_XPATH):
  145. $feed->_kind(FreshRSS_Feed::KIND_XML_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 bool $dry_run true to not create the category in database.
  227. * @return FreshRSS_Category|null The created category, or null if it failed.
  228. */
  229. private function createCategory(array $category_element, bool $dry_run): ?FreshRSS_Category {
  230. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  231. $name = Minz_Helper::htmlspecialchars_utf8($name);
  232. $category = new FreshRSS_Category($name);
  233. if (isset($category_element['frss:opmlUrl'])) {
  234. $opml_url = checkUrl($category_element['frss:opmlUrl']);
  235. if ($opml_url != '') {
  236. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  237. $category->_attributes('opml_url', $opml_url);
  238. }
  239. }
  240. if ($dry_run) {
  241. return $category;
  242. }
  243. $id = $this->catDAO->addCategoryObject($category);
  244. if ($id !== false) {
  245. $category->_id($id);
  246. return $category;
  247. } else {
  248. self::log("Cannot create category {$category->name()}");
  249. $this->lastStatus = false;
  250. return null;
  251. }
  252. }
  253. /**
  254. * Return the list of category and feed outlines by categories names.
  255. *
  256. * This method is applied to a list of outlines. It merges the different
  257. * list of feeds from several outlines into one array.
  258. *
  259. * @param array<mixed> $outlines
  260. * The outlines from which to extract the outlines.
  261. * @param string $parent_category_name
  262. * The name of the parent category of the current outlines.
  263. * @return array{0:array<mixed>,1:array<mixed>}
  264. */
  265. private function loadFromOutlines(array $outlines, string $parent_category_name): array {
  266. $categories_elements = [];
  267. $categories_to_feeds = [];
  268. foreach ($outlines as $outline) {
  269. // Get the categories and feeds from the child outline (it may
  270. // return several categories and feeds if the outline is a category).
  271. list (
  272. $outline_categories,
  273. $outline_categories_to_feeds,
  274. ) = $this->loadFromOutline($outline, $parent_category_name);
  275. // Then, we merge the initial arrays with the arrays returned by
  276. // the outline.
  277. $categories_elements = array_merge($categories_elements, $outline_categories);
  278. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  279. if (!isset($categories_to_feeds[$category_name])) {
  280. $categories_to_feeds[$category_name] = [];
  281. }
  282. $categories_to_feeds[$category_name] = array_merge(
  283. $categories_to_feeds[$category_name],
  284. $feeds
  285. );
  286. }
  287. }
  288. return [$categories_elements, $categories_to_feeds];
  289. }
  290. /**
  291. * Return the list of category and feed outlines by categories names.
  292. *
  293. * This method is applied to a specific outline. If the outline represents
  294. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  295. * to its children. If the outline represents a feed (i.e. xmlUrl key
  296. * exists), it will add the outline to an array accessible by its category
  297. * name.
  298. *
  299. * @param array<mixed> $outline
  300. * The outline from which to extract the categories and feeds outlines.
  301. * @param string $parent_category_name
  302. * The name of the parent category of the current outline.
  303. *
  304. * @return array{0:array<string,mixed>,1:array<string,mixed>}
  305. */
  306. private function loadFromOutline($outline, $parent_category_name): array {
  307. $categories_elements = [];
  308. $categories_to_feeds = [];
  309. if ($parent_category_name === '' && isset($outline['category'])) {
  310. // The outline has no parent category, but its OPML category
  311. // attribute is set, so we use it as the category name.
  312. // lib_opml parses this attribute as an array of strings, so we
  313. // rebuild a string here.
  314. $parent_category_name = implode(', ', $outline['category']);
  315. $categories_elements[$parent_category_name] = [
  316. 'text' => $parent_category_name,
  317. ];
  318. }
  319. if (isset($outline['@outlines'])) {
  320. // The outline has children, it’s probably a category
  321. if (!empty($outline['text'])) {
  322. $category_name = $outline['text'];
  323. } elseif (!empty($outline['title'])) {
  324. $category_name = $outline['title'];
  325. } else {
  326. $category_name = $parent_category_name;
  327. }
  328. list (
  329. $categories_elements,
  330. $categories_to_feeds,
  331. ) = $this->loadFromOutlines($outline['@outlines'], $category_name);
  332. unset($outline['@outlines']);
  333. $categories_elements[$category_name] = $outline;
  334. }
  335. // The xmlUrl means it’s a feed URL: add the outline to the array if it exists.
  336. if (isset($outline['xmlUrl'])) {
  337. if (!isset($categories_to_feeds[$parent_category_name])) {
  338. $categories_to_feeds[$parent_category_name] = [];
  339. }
  340. $categories_to_feeds[$parent_category_name][] = $outline;
  341. }
  342. return [$categories_elements, $categories_to_feeds];
  343. }
  344. private static function log(string $message): void {
  345. if (FreshRSS_Context::$isCli) {
  346. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  347. } else {
  348. Minz_Log::warning("Error during OPML import: {$message}");
  349. }
  350. }
  351. }