ImportService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Provide methods to import files.
  5. */
  6. class FreshRSS_Import_Service {
  7. private readonly FreshRSS_CategoryDAO $catDAO;
  8. private readonly 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. * @param bool $trusted_source true when the OPML content is explicitly provided by the user (e.g. local file import);
  29. * false by default, and for content fetched from a remote source (e.g. dynamic OPML categories), in which case
  30. * security-relevant attributes (feed cURL parameters, nested dynamic categories) are ignored.
  31. */
  32. public function importOpml(string $opml_file, ?FreshRSS_Category $forced_category = null, bool $dry_run = false, bool $trusted_source = false): void {
  33. if (function_exists('set_time_limit')) {
  34. @set_time_limit(300);
  35. }
  36. $this->lastStatus = true;
  37. $opml_array = [];
  38. try {
  39. $libopml = new \marienfressinaud\LibOpml\LibOpml(strict: false);
  40. /** @var array{body:array<array<mixed>>} $opml_array */
  41. $opml_array = $libopml->parseString($opml_file);
  42. } catch (\marienfressinaud\LibOpml\Exception $e) {
  43. self::log($e->getMessage());
  44. $this->lastStatus = false;
  45. return;
  46. }
  47. $this->catDAO->checkDefault();
  48. $default_category = $this->catDAO->getDefault();
  49. if ($default_category === null) {
  50. self::log('Cannot get the default category');
  51. $this->lastStatus = false;
  52. return;
  53. }
  54. // Get the categories by names so we can use this array to retrieve
  55. // existing categories later.
  56. $categories = $this->catDAO->listCategories(prePopulateFeeds: false);
  57. $categories_by_names = [];
  58. $highest_position = PHP_INT_MIN; // To order the numbers as best as possible in case of negative positions, we choose the lowest possible number first
  59. foreach ($categories as $category) {
  60. $categories_by_names[$category->name()] = $category;
  61. $position = $category->attributeInt('position') ?? PHP_INT_MIN;
  62. if ($position > $highest_position) {
  63. $highest_position = $position;
  64. }
  65. }
  66. if ($highest_position === PHP_INT_MIN) {
  67. // If it's still the same number, default to -1 instead
  68. $highest_position = -1; // will be incremented to 0
  69. }
  70. // Get current numbers of categories and feeds, and the limits to
  71. // verify the user can import its categories/feeds.
  72. $nb_categories = count($categories);
  73. $nb_feeds = count($this->feedDAO->listFeeds());
  74. $limits = FreshRSS_Context::systemConf()->limits;
  75. // Process the OPML outlines to get a list of categories and a list of
  76. // feeds elements indexed by their categories names.
  77. [$categories_elements, $categories_to_feeds] = $this->loadFromOutlines($opml_array['body'], '');
  78. foreach ($categories_to_feeds as $category_name => $feeds_elements) {
  79. $category_element = $categories_elements[$category_name] ?? null;
  80. $category = null;
  81. if ($forced_category !== null) {
  82. // If the category is forced, ignore the actual category name
  83. $category = $forced_category;
  84. } elseif (isset($categories_by_names[$category_name])) {
  85. // If the category already exists, get it from $categories_by_names
  86. $category = $categories_by_names[$category_name];
  87. } elseif (is_array($category_element)) {
  88. // Otherwise, create the category (if possible)
  89. $limit_reached = $nb_categories >= $limits['max_categories'];
  90. $can_create_category = FreshRSS_Context::$isCli || !$limit_reached;
  91. if ($can_create_category) {
  92. // Import category in the exact order as the outline's placement in the OPML, at the end of positioned categories
  93. $category = $this->createCategory($category_element, $dry_run, ++$highest_position, $trusted_source);
  94. if ($category !== null) {
  95. $categories_by_names[$category->name()] = $category;
  96. $nb_categories++;
  97. }
  98. } else {
  99. Minz_Log::warning(
  100. _t('feedback.sub.category.over_max', $limits['max_categories'])
  101. );
  102. }
  103. }
  104. if ($category === null) {
  105. // Category can be null if the feeds weren't in a category
  106. // outline, or if we weren't able to create the category.
  107. $category = $default_category;
  108. }
  109. // Then, create the feeds one by one and attach them to the
  110. // category we just got.
  111. foreach ($feeds_elements as $feed_element) {
  112. $limit_reached = $nb_feeds >= $limits['max_feeds'];
  113. $can_create_feed = FreshRSS_Context::$isCli || !$limit_reached;
  114. if (!$can_create_feed) {
  115. Minz_Log::warning(
  116. _t('feedback.sub.feed.over_max', $limits['max_feeds'])
  117. );
  118. $this->lastStatus = false;
  119. break;
  120. }
  121. if ($this->createFeed($feed_element, $category, $dry_run, $trusted_source) !== null) {
  122. // TODO what if the feed already exists in the database?
  123. $nb_feeds++;
  124. } else {
  125. $this->lastStatus = false;
  126. }
  127. }
  128. }
  129. }
  130. /**
  131. * Create a feed from a feed element (i.e. OPML outline).
  132. *
  133. * @param array<string,string> $feed_elt An OPML element (must be a feed element).
  134. * @param FreshRSS_Category $category The category to associate to the feed.
  135. * @param bool $dry_run true to not create the feed in database.
  136. * @param bool $trusted_source false to ignore security-relevant attributes (feed cURL parameters); see {@see FreshRSS_Import_Service::importOpml()}.
  137. * @return FreshRSS_Feed|null The created feed, or null if it failed.
  138. */
  139. private function createFeed(array $feed_elt, FreshRSS_Category $category, bool $dry_run, bool $trusted_source = false): ?FreshRSS_Feed {
  140. $url = Minz_Helper::htmlspecialchars_utf8($feed_elt['xmlUrl']);
  141. $name = $feed_elt['text'] ?? $feed_elt['title'] ?? '';
  142. $name = Minz_Helper::htmlspecialchars_utf8($name);
  143. $website = Minz_Helper::htmlspecialchars_utf8($feed_elt['htmlUrl'] ?? '');
  144. $description = Minz_Helper::htmlspecialchars_utf8($feed_elt['description'] ?? '');
  145. try {
  146. // Create a Feed object and add it in DB
  147. $feed = new FreshRSS_Feed($url);
  148. $feed->_category($category);
  149. $feed->_name($name);
  150. $feed->_website($website);
  151. $feed->_description($description);
  152. switch (strtolower($feed_elt['type'] ?? '')) {
  153. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH):
  154. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH);
  155. break;
  156. case strtolower(FreshRSS_Export_Service::TYPE_XML_XPATH):
  157. $feed->_kind(FreshRSS_Feed::KIND_XML_XPATH);
  158. break;
  159. case strtolower(FreshRSS_Export_Service::TYPE_JSON_DOTNOTATION):
  160. case strtolower(FreshRSS_Export_Service::TYPE_JSON_DOTPATH):
  161. $feed->_kind(FreshRSS_Feed::KIND_JSON_DOTNOTATION);
  162. break;
  163. case strtolower(FreshRSS_Export_Service::TYPE_JSONFEED):
  164. $feed->_kind(FreshRSS_Feed::KIND_JSONFEED);
  165. break;
  166. case strtolower(FreshRSS_Export_Service::TYPE_HTML_XPATH_JSON_DOTNOTATION):
  167. $feed->_kind(FreshRSS_Feed::KIND_HTML_XPATH_JSON_DOTNOTATION);
  168. break;
  169. default:
  170. $feed->_kind(FreshRSS_Feed::KIND_RSS);
  171. break;
  172. }
  173. $feed->_priority(match (strtolower($feed_elt['frss:priority'] ?? '')) {
  174. FreshRSS_Export_Service::PRIORITY_IMPORTANT => FreshRSS_Feed::PRIORITY_IMPORTANT,
  175. FreshRSS_Export_Service::PRIORITY_MAIN_STREAM => FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  176. FreshRSS_Export_Service::PRIORITY_CATEGORY => FreshRSS_Feed::PRIORITY_CATEGORY,
  177. FreshRSS_Export_Service::PRIORITY_FEED => FreshRSS_Feed::PRIORITY_FEED,
  178. FreshRSS_Export_Service::PRIORITY_HIDDEN => FreshRSS_Feed::PRIORITY_HIDDEN,
  179. default => FreshRSS_Feed::PRIORITY_MAIN_STREAM,
  180. });
  181. if (isset($feed_elt['frss:unicityCriteria']) && $feed_elt['frss:unicityCriteria'] !== 'id'
  182. && preg_match('/^[a-z:_-]{2,64}$/', $feed_elt['frss:unicityCriteria'])) {
  183. $feed->_attribute('unicityCriteria', $feed_elt['frss:unicityCriteria']);
  184. }
  185. if (filter_var($feed_elt['frss:unicityCriteriaForced'] ?? '', FILTER_VALIDATE_BOOLEAN)) {
  186. $feed->_attribute('unicityCriteriaForced', true);
  187. }
  188. if (isset($feed_elt['frss:ttl'])) {
  189. // Signed refresh interval (TTL); a negative value indicates a muted feed
  190. $feed->_ttl((int)$feed_elt['frss:ttl']);
  191. }
  192. if (isset($feed_elt['frss:cssFullContent'])) {
  193. $feed->_pathEntries(Minz_Helper::htmlspecialchars_utf8($feed_elt['frss:cssFullContent']));
  194. }
  195. if (isset($feed_elt['frss:cssFullContentConditions'])) {
  196. $feed->_attribute(
  197. 'path_entries_conditions',
  198. preg_split('/\R/u', $feed_elt['frss:cssFullContentConditions']) ?: []
  199. );
  200. }
  201. if (isset($feed_elt['frss:cssContentFilter']) || isset($feed_elt['frss:cssFullContentFilter'])) {
  202. $feed->_attribute('path_entries_filter', $feed_elt['frss:cssContentFilter'] ?? $feed_elt['frss:cssFullContentFilter']);
  203. }
  204. if (isset($feed_elt['frss:filtersActionRead'])) {
  205. $feed->_filtersAction(
  206. 'read',
  207. preg_split('/\R/u', $feed_elt['frss:filtersActionRead']) ?: []
  208. );
  209. }
  210. $xPathSettings = [];
  211. if (isset($feed_elt['frss:xPathItem'])) {
  212. $xPathSettings['item'] = $feed_elt['frss:xPathItem'];
  213. }
  214. if (isset($feed_elt['frss:xPathItemTitle'])) {
  215. $xPathSettings['itemTitle'] = $feed_elt['frss:xPathItemTitle'];
  216. }
  217. if (isset($feed_elt['frss:xPathItemContent'])) {
  218. $xPathSettings['itemContent'] = $feed_elt['frss:xPathItemContent'];
  219. }
  220. if (isset($feed_elt['frss:xPathItemUri'])) {
  221. $xPathSettings['itemUri'] = $feed_elt['frss:xPathItemUri'];
  222. }
  223. if (isset($feed_elt['frss:xPathItemAuthor'])) {
  224. $xPathSettings['itemAuthor'] = $feed_elt['frss:xPathItemAuthor'];
  225. }
  226. if (isset($feed_elt['frss:xPathItemTimestamp'])) {
  227. $xPathSettings['itemTimestamp'] = $feed_elt['frss:xPathItemTimestamp'];
  228. }
  229. if (isset($feed_elt['frss:xPathItemTimeFormat'])) {
  230. $xPathSettings['itemTimeFormat'] = $feed_elt['frss:xPathItemTimeFormat'];
  231. }
  232. if (isset($feed_elt['frss:xPathItemThumbnail'])) {
  233. $xPathSettings['itemThumbnail'] = $feed_elt['frss:xPathItemThumbnail'];
  234. }
  235. if (isset($feed_elt['frss:xPathItemCategories'])) {
  236. $xPathSettings['itemCategories'] = $feed_elt['frss:xPathItemCategories'];
  237. }
  238. if (isset($feed_elt['frss:xPathItemUid'])) {
  239. $xPathSettings['itemUid'] = $feed_elt['frss:xPathItemUid'];
  240. }
  241. if (!empty($xPathSettings)) {
  242. $feed->_attribute('xpath', $xPathSettings);
  243. }
  244. $jsonSettings = [];
  245. if (isset($feed_elt['frss:jsonItem'])) {
  246. $jsonSettings['item'] = $feed_elt['frss:jsonItem'];
  247. }
  248. if (isset($feed_elt['frss:jsonItemTitle'])) {
  249. $jsonSettings['itemTitle'] = $feed_elt['frss:jsonItemTitle'];
  250. }
  251. if (isset($feed_elt['frss:jsonItemContent'])) {
  252. $jsonSettings['itemContent'] = $feed_elt['frss:jsonItemContent'];
  253. }
  254. if (isset($feed_elt['frss:jsonItemUri'])) {
  255. $jsonSettings['itemUri'] = $feed_elt['frss:jsonItemUri'];
  256. }
  257. if (isset($feed_elt['frss:jsonItemAuthor'])) {
  258. $jsonSettings['itemAuthor'] = $feed_elt['frss:jsonItemAuthor'];
  259. }
  260. if (isset($feed_elt['frss:jsonItemTimestamp'])) {
  261. $jsonSettings['itemTimestamp'] = $feed_elt['frss:jsonItemTimestamp'];
  262. }
  263. if (isset($feed_elt['frss:jsonItemTimeFormat'])) {
  264. $jsonSettings['itemTimeFormat'] = $feed_elt['frss:jsonItemTimeFormat'];
  265. }
  266. if (isset($feed_elt['frss:jsonItemThumbnail'])) {
  267. $jsonSettings['itemThumbnail'] = $feed_elt['frss:jsonItemThumbnail'];
  268. }
  269. if (isset($feed_elt['frss:jsonItemCategories'])) {
  270. $jsonSettings['itemCategories'] = $feed_elt['frss:jsonItemCategories'];
  271. }
  272. if (isset($feed_elt['frss:jsonItemUid'])) {
  273. $jsonSettings['itemUid'] = $feed_elt['frss:jsonItemUid'];
  274. }
  275. if (!empty($jsonSettings)) {
  276. $feed->_attribute('json_dotnotation', $jsonSettings);
  277. }
  278. $feed->_attribute('xPathToJson', $feed_elt['frss:xPathToJson'] ?? null);
  279. $curl_params = [];
  280. if (isset($feed_elt['frss:CURLOPT_COOKIE'])) {
  281. $curl_params[CURLOPT_COOKIE] = $feed_elt['frss:CURLOPT_COOKIE'];
  282. }
  283. if (isset($feed_elt['frss:CURLOPT_COOKIEFILE'])) {
  284. // Allow only an empty value just to enable the libcurl cookie engine
  285. $curl_params[CURLOPT_COOKIEFILE] = '';
  286. }
  287. if (isset($feed_elt['frss:CURLOPT_FOLLOWLOCATION'])) {
  288. $curl_params[CURLOPT_FOLLOWLOCATION] = (bool)$feed_elt['frss:CURLOPT_FOLLOWLOCATION'];
  289. }
  290. if (isset($feed_elt['frss:CURLOPT_HTTPHEADER'])) {
  291. $curl_params[CURLOPT_HTTPHEADER] = preg_split('/\R/u', $feed_elt['frss:CURLOPT_HTTPHEADER']) ?: [];
  292. }
  293. if (isset($feed_elt['frss:CURLOPT_MAXREDIRS'])) {
  294. $curl_params[CURLOPT_MAXREDIRS] = (int)$feed_elt['frss:CURLOPT_MAXREDIRS'];
  295. }
  296. if (isset($feed_elt['frss:CURLOPT_POST'])) {
  297. $curl_params[CURLOPT_POST] = (bool)$feed_elt['frss:CURLOPT_POST'];
  298. }
  299. if (isset($feed_elt['frss:CURLOPT_POSTFIELDS'])) {
  300. $curl_params[CURLOPT_POSTFIELDS] = $feed_elt['frss:CURLOPT_POSTFIELDS'];
  301. }
  302. if (isset($feed_elt['frss:CURLOPT_PROXY'])) {
  303. $curl_params[CURLOPT_PROXY] = $feed_elt['frss:CURLOPT_PROXY'];
  304. }
  305. if (isset($feed_elt['frss:CURLOPT_PROXYTYPE'])) {
  306. $curl_params[CURLOPT_PROXYTYPE] = (int)$feed_elt['frss:CURLOPT_PROXYTYPE'];
  307. if ($curl_params[CURLOPT_PROXYTYPE] === 3) { // Legacy for NONE
  308. $curl_params[CURLOPT_PROXYTYPE] = -1;
  309. }
  310. }
  311. if (isset($feed_elt['frss:CURLOPT_USERAGENT'])) {
  312. $curl_params[CURLOPT_USERAGENT] = $feed_elt['frss:CURLOPT_USERAGENT'];
  313. }
  314. // Feed cURL parameters are only honored for OPML content explicitly provided by the user;
  315. // a remote (dynamic) OPML must not be able to configure the cURL behavior of the instance.
  316. if ($trusted_source && !empty($curl_params)) {
  317. $feed->_attribute('curl_params', FreshRSS_http_Util::sanitizeCurlParams($curl_params));
  318. }
  319. // Call the extension hook
  320. /** @var FreshRSS_Feed|null */
  321. $feed = Minz_ExtensionManager::callHook(Minz_HookType::FeedBeforeInsert, $feed);
  322. if ($dry_run) {
  323. if ($feed !== null) {
  324. $category->addFeed($feed);
  325. }
  326. return $feed;
  327. }
  328. if ($feed !== null) {
  329. // addFeedObject checks if feed is already in DB
  330. $id = $this->feedDAO->addFeedObject($feed);
  331. if ($id == false) {
  332. $this->lastStatus = false;
  333. } else {
  334. $feed->_id($id);
  335. $category->addFeed($feed);
  336. return $feed;
  337. }
  338. }
  339. } catch (FreshRSS_Feed_Exception $e) {
  340. self::log($e->getMessage());
  341. $this->lastStatus = false;
  342. }
  343. $clean_url = \SimplePie\Misc::url_remove_credentials($url);
  344. self::log("Cannot create {$clean_url} feed in category {$category->name()}");
  345. return null;
  346. }
  347. /**
  348. * Create and return a category.
  349. *
  350. * @param array<string,string> $category_element An OPML element (must be a category element).
  351. * @param bool $dry_run true to not create the category in database.
  352. * @param bool $trusted_source false to ignore security-relevant attributes (dynamic OPML); see {@see FreshRSS_Import_Service::importOpml()}.
  353. * @return FreshRSS_Category|null The created category, or null if it failed.
  354. */
  355. private function createCategory(array $category_element, bool $dry_run, int $position, bool $trusted_source = false): ?FreshRSS_Category {
  356. $name = $category_element['text'] ?? $category_element['title'] ?? '';
  357. $name = Minz_Helper::htmlspecialchars_utf8($name);
  358. $category = new FreshRSS_Category($name);
  359. if ($trusted_source && isset($category_element['frss:opmlUrl'])) {
  360. $opml_url = FreshRSS_http_Util::checkUrl($category_element['frss:opmlUrl']);
  361. if ($opml_url != '') {
  362. $category->_kind(FreshRSS_Category::KIND_DYNAMIC_OPML);
  363. $category->_attribute('opml_url', $opml_url);
  364. }
  365. }
  366. $category->_attribute('position', $position);
  367. if ($dry_run) {
  368. return $category;
  369. }
  370. $id = $this->catDAO->addCategoryObject($category);
  371. if ($id !== false) {
  372. $category->_id($id);
  373. return $category;
  374. } else {
  375. self::log("Cannot create category {$category->name()}");
  376. $this->lastStatus = false;
  377. return null;
  378. }
  379. }
  380. /**
  381. * Return the list of category and feed outlines by categories names.
  382. *
  383. * This method is applied to a list of outlines. It merges the different
  384. * list of feeds from several outlines into one array.
  385. *
  386. * @param array<array<mixed>> $outlines The outlines from which to extract the outlines.
  387. * @param string $parent_category_name The name of the parent category of the current outlines.
  388. * @return array{0:array<string,array<string,string>>,1:array<string,list<array<string,string>>>}
  389. */
  390. private function loadFromOutlines(array $outlines, string $parent_category_name): array {
  391. $categories_elements = [];
  392. $categories_to_feeds = [];
  393. foreach ($outlines as $outline) {
  394. if (!is_array($outline)) {
  395. continue;
  396. }
  397. // Get the categories and feeds from the child outline (it may
  398. // return several categories and feeds if the outline is a category).
  399. [$outline_categories, $outline_categories_to_feeds] = $this->loadFromOutline($outline, $parent_category_name);
  400. // Then, we merge the initial arrays with the arrays returned by
  401. // the outline.
  402. $categories_elements = array_merge($categories_elements, $outline_categories);
  403. foreach ($outline_categories_to_feeds as $category_name => $feeds) {
  404. if (!is_string($category_name) || // @phpstan-ignore function.alreadyNarrowedType (defensive)
  405. !is_array($feeds)) { // @phpstan-ignore function.alreadyNarrowedType (defensive)
  406. continue;
  407. }
  408. if (!isset($categories_to_feeds[$category_name])) {
  409. $categories_to_feeds[$category_name] = [];
  410. }
  411. $categories_to_feeds[$category_name] = array_merge(
  412. $categories_to_feeds[$category_name],
  413. $feeds
  414. );
  415. }
  416. }
  417. return [$categories_elements, $categories_to_feeds];
  418. }
  419. /**
  420. * Return the list of category and feed outlines by categories names.
  421. *
  422. * This method is applied to a specific outline. If the outline represents
  423. * a category (i.e. @outlines key exists), it will reapply loadFromOutlines()
  424. * to its children. If the outline represents a feed (i.e. xmlUrl key
  425. * exists), it will add the outline to an array accessible by its category
  426. * name.
  427. *
  428. * @param array<mixed> $outline The outline from which to extract the categories and feeds outlines.
  429. * @param string $parent_category_name The name of the parent category of the current outline.
  430. *
  431. * @return array{0:array<string,array<string,string>>,1:array<string,list<array<string,string>>>}
  432. */
  433. private function loadFromOutline(array $outline, string $parent_category_name): array {
  434. $categories_elements = [];
  435. $categories_to_feeds = [];
  436. if ($parent_category_name === '' && is_array($outline['category'] ?? null)) {
  437. // The outline has no parent category, but its OPML category
  438. // attribute is set, so we use it as the category name.
  439. // lib_opml parses this attribute as an array of strings, so we
  440. // rebuild a string here.
  441. $category_names = array_filter($outline['category'], 'is_string');
  442. $parent_category_name = implode(', ', $category_names);
  443. $categories_elements[$parent_category_name] = [
  444. 'text' => $parent_category_name,
  445. ];
  446. }
  447. if (is_array($outline['@outlines'] ?? null)) {
  448. // The outline has children, it’s probably a category
  449. if (!empty($outline['text']) && is_string($outline['text'])) {
  450. $category_name = $outline['text'];
  451. } elseif (!empty($outline['title']) && is_string($outline['title'])) {
  452. $category_name = $outline['title'];
  453. } else {
  454. $category_name = $parent_category_name;
  455. }
  456. $children = array_filter($outline['@outlines'], 'is_array');
  457. [$categories_elements, $categories_to_feeds] = $this->loadFromOutlines($children, $category_name);
  458. unset($outline['@outlines']);
  459. $categories_elements[$category_name] = array_filter($outline, static fn($value, $key) => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  460. }
  461. // The xmlUrl means it’s a feed URL: add the outline to the array if it exists.
  462. if (isset($outline['xmlUrl'])) {
  463. if (!isset($categories_to_feeds[$parent_category_name])) {
  464. $categories_to_feeds[$parent_category_name] = [];
  465. }
  466. $feed = array_filter($outline, static fn($value, $key) => is_string($key) && is_string($value), ARRAY_FILTER_USE_BOTH);
  467. $categories_to_feeds[$parent_category_name][] = $feed;
  468. }
  469. return [$categories_elements, $categories_to_feeds];
  470. }
  471. private static function log(string $message): void {
  472. if (FreshRSS_Context::$isCli) {
  473. fwrite(STDERR, "FreshRSS error during OPML import: {$message}\n");
  474. } else {
  475. Minz_Log::warning("Error during OPML import: {$message}");
  476. }
  477. }
  478. }