Category.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_Category extends Minz_Model {
  4. use FreshRSS_AttributesTrait, FreshRSS_FilterActionsTrait;
  5. /**
  6. * Normal
  7. */
  8. public const KIND_NORMAL = 0;
  9. /**
  10. * Category tracking a third-party Dynamic OPML
  11. */
  12. public const KIND_DYNAMIC_OPML = 2;
  13. private int $id = 0;
  14. private int $kind = 0;
  15. private string $name;
  16. private int $nbFeeds = -1;
  17. /** Number of unread articles in feeds with visibility FreshRSS_Feed::PRIORITY_FEED */
  18. private int $nbNotRead = -1;
  19. /** @var array<int,FreshRSS_Feed>|null where the key is the feed ID */
  20. private ?array $feeds = null;
  21. private bool|int $hasFeedsWithError = false;
  22. private int $lastUpdate = 0;
  23. private bool $error = false;
  24. /**
  25. * @param array<FreshRSS_Feed>|null $feeds
  26. */
  27. public function __construct(string $name = '', int $id = 0, ?array $feeds = null) {
  28. $this->_id($id);
  29. $this->_name($name);
  30. if ($feeds !== null) {
  31. $this->_feeds($feeds);
  32. $this->nbFeeds = 0;
  33. $this->nbNotRead = 0;
  34. foreach ($feeds as $feed) {
  35. $feed->_category($this);
  36. $this->nbFeeds++;
  37. if ($feed->priority() > FreshRSS_Feed::PRIORITY_HIDDEN) {
  38. $this->nbNotRead += $feed->nbNotRead();
  39. $this->hasFeedsWithError |= ($feed->inError() && !$feed->mute());
  40. }
  41. }
  42. }
  43. }
  44. public function id(): int {
  45. return $this->id;
  46. }
  47. public function kind(): int {
  48. return $this->kind;
  49. }
  50. /** @return string HTML-encoded name of the category */
  51. public function name(): string {
  52. return $this->name;
  53. }
  54. public function lastUpdate(): int {
  55. return $this->lastUpdate;
  56. }
  57. /**
  58. * @param int|numeric-string $value
  59. * 32-bit systems provide a string and will fail in year 2038
  60. */
  61. public function _lastUpdate(int|string $value): void {
  62. $this->lastUpdate = (int)$value;
  63. }
  64. public function inError(): bool {
  65. return $this->error;
  66. }
  67. /**
  68. * @param bool|int|numeric-string $value
  69. * 32-bit systems provide a string and will fail in year 2038
  70. */
  71. public function _error(bool|int|string $value): void {
  72. $this->error = (bool)$value;
  73. }
  74. public function isDefault(): bool {
  75. return $this->id == FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
  76. }
  77. public function nbFeeds(): int {
  78. if ($this->nbFeeds < 0) {
  79. $catDAO = FreshRSS_Factory::createCategoryDao();
  80. $this->nbFeeds = $catDAO->countFeed($this->id());
  81. }
  82. return $this->nbFeeds;
  83. }
  84. /**
  85. * @throws Minz_ConfigurationNamespaceException
  86. * @throws Minz_PDOConnectionException
  87. */
  88. public function nbNotRead(int $minPriority = FreshRSS_Feed::PRIORITY_FEED): int {
  89. if ($this->nbNotRead > 0 && $minPriority === FreshRSS_Feed::PRIORITY_FEED) {
  90. return $this->nbNotRead;
  91. }
  92. if ($this->feeds === null) {
  93. $catDAO = FreshRSS_Factory::createCategoryDao();
  94. $nb = $catDAO->countNotRead($this->id(), $minPriority);
  95. if ($minPriority === FreshRSS_Feed::PRIORITY_FEED) {
  96. $this->nbNotRead = $nb;
  97. }
  98. return $nb;
  99. }
  100. $nb = 0;
  101. foreach ($this->feeds as $feed) {
  102. if ($feed->priority() >= $minPriority) {
  103. $nb += $feed->nbNotRead();
  104. }
  105. }
  106. return $nb;
  107. }
  108. /** @return array<int,mixed> */
  109. public function curlOptions(): array {
  110. return []; // TODO (e.g., credentials for Dynamic OPML)
  111. }
  112. public function showUnreadCount(): bool {
  113. return $this->attributeBoolean('show_unread_count') ??
  114. (FreshRSS_Context::userConf()->show_unread_count === 'all');
  115. }
  116. /**
  117. * @return array<int,FreshRSS_Feed> where the key is the feed ID
  118. * @throws Minz_ConfigurationNamespaceException
  119. * @throws Minz_PDOConnectionException
  120. */
  121. public function feeds(): array {
  122. if ($this->feeds === null) {
  123. $feedDAO = FreshRSS_Factory::createFeedDao();
  124. $this->feeds = $feedDAO->listByCategory($this->id());
  125. $this->nbFeeds = 0;
  126. $this->nbNotRead = 0;
  127. foreach ($this->feeds as $feed) {
  128. $this->nbFeeds++;
  129. if ($feed->priority() > FreshRSS_Feed::PRIORITY_HIDDEN) {
  130. $this->nbNotRead += $feed->nbNotRead();
  131. $this->hasFeedsWithError |= ($feed->inError() && !$feed->mute());
  132. }
  133. }
  134. $this->sortFeeds();
  135. }
  136. return $this->feeds ?? [];
  137. }
  138. public function hasFeedsWithError(): bool {
  139. return (bool)($this->hasFeedsWithError);
  140. }
  141. public function _id(int $id): void {
  142. $this->id = $id;
  143. if ($id === FreshRSS_CategoryDAO::DEFAULTCATEGORYID) {
  144. $this->name = _t('gen.short.default_category');
  145. }
  146. }
  147. public function _kind(int $kind): void {
  148. $this->kind = $kind;
  149. }
  150. public function _name(string $value): void {
  151. if ($this->id !== FreshRSS_CategoryDAO::DEFAULTCATEGORYID) {
  152. $this->name = mb_strcut(trim($value), 0, FreshRSS_DatabaseDAO::LENGTH_INDEX_UNICODE, 'UTF-8');
  153. }
  154. }
  155. /** @param array<FreshRSS_Feed>|FreshRSS_Feed $values */
  156. public function _feeds(array|FreshRSS_Feed $values): void {
  157. if (!is_array($values)) {
  158. $values = [$values];
  159. }
  160. $this->feeds = array_values($values);
  161. $this->sortFeeds();
  162. }
  163. public function defaultSort(): ?string {
  164. return $this->attributeString('defaultSort');
  165. }
  166. public function defaultOrder(): ?string {
  167. return $this->attributeString('defaultOrder');
  168. }
  169. /**
  170. * To manually add feeds to this category (not committing to database).
  171. */
  172. public function addFeed(FreshRSS_Feed $feed): void {
  173. if ($this->feeds === null) {
  174. $this->feeds = [];
  175. }
  176. $feed->_category($this);
  177. if ($feed->id() === 0) {
  178. // Feeds created on a dry run do not have an ID
  179. $this->feeds[] = $feed;
  180. } else {
  181. $this->feeds[$feed->id()] = $feed;
  182. }
  183. $this->sortFeeds();
  184. }
  185. /**
  186. * @throws FreshRSS_Context_Exception
  187. */
  188. public function cacheFilename(string $url): string {
  189. $simplePie = new FreshRSS_SimplePieCustom($this->attributes(), $this->curlOptions());
  190. $filename = $simplePie->get_cache_filename($url);
  191. return CACHE_PATH . '/' . $filename . '.opml.xml';
  192. }
  193. public function refreshDynamicOpml(): bool {
  194. $url = $this->attributeString('opml_url');
  195. if ($url == null) {
  196. return false;
  197. }
  198. $ok = true;
  199. $cachePath = $this->cacheFilename($url);
  200. $opml = FreshRSS_http_Util::httpGet($url, $cachePath, 'opml', $this->attributes(), $this->curlOptions())['body'];
  201. if ($opml == '') {
  202. Minz_Log::warning('Error getting dynamic OPML for category ' . $this->id() . '! ' .
  203. \SimplePie\Misc::url_remove_credentials($url));
  204. $ok = false;
  205. } else {
  206. $dryRunCategory = new FreshRSS_Category();
  207. $importService = new FreshRSS_Import_Service();
  208. $importService->importOpml($opml, $dryRunCategory, dry_run: true, trusted_source: false);
  209. if ($importService->lastStatus()) {
  210. $feedDAO = FreshRSS_Factory::createFeedDao();
  211. $limits = FreshRSS_Context::systemConf()->limits;
  212. $maxFeeds = (int)($limits['max_feeds'] ?? 0);
  213. $nbFeeds = $maxFeeds > 0 ? $feedDAO->count() : 0;
  214. /** @var array<string,FreshRSS_Feed> */
  215. $dryRunFeeds = [];
  216. foreach ($dryRunCategory->feeds() as $dryRunFeed) {
  217. $dryRunFeeds[$dryRunFeed->url()] = $dryRunFeed;
  218. }
  219. /** @var array<string,FreshRSS_Feed> */
  220. $existingFeeds = [];
  221. foreach ($this->feeds() as $existingFeed) {
  222. $existingFeeds[$existingFeed->url()] = $existingFeed;
  223. if (empty($dryRunFeeds[$existingFeed->url()])) {
  224. // The feed does not exist in the new dynamic OPML, so mute (disable) that feed
  225. $existingFeed->_mute(true);
  226. $ok &= ($feedDAO->updateFeed($existingFeed->id(), [
  227. 'ttl' => $existingFeed->ttl(true),
  228. ]) !== false);
  229. }
  230. }
  231. foreach ($dryRunCategory->feeds() as $dryRunFeed) {
  232. if (empty($existingFeeds[$dryRunFeed->url()])) {
  233. // The feed does not exist in the current category, so add that feed
  234. if ($maxFeeds > 0 && $nbFeeds >= $maxFeeds) {
  235. // Respect the per-user maximum number of feeds
  236. Minz_Log::warning(_t('feedback.sub.feed.over_max', $maxFeeds) .
  237. ' (dynamic OPML category ' . $this->id() . ')');
  238. $ok = false;
  239. break;
  240. }
  241. $dryRunFeed->_category($this);
  242. if ($feedDAO->addFeedObject($dryRunFeed) === false) {
  243. $ok = false;
  244. } else {
  245. $nbFeeds++;
  246. }
  247. $existingFeeds[$dryRunFeed->url()] = $dryRunFeed;
  248. } else {
  249. $existingFeed = $existingFeeds[$dryRunFeed->url()];
  250. if ($existingFeed->mute()) {
  251. // The feed already exists in the current category but was muted (disabled), so unmute (enable) again
  252. $existingFeed->_mute(false);
  253. $ok &= ($feedDAO->updateFeed($existingFeed->id(), [
  254. 'ttl' => $existingFeed->ttl(true),
  255. ]) !== false);
  256. }
  257. }
  258. }
  259. } else {
  260. $ok = false;
  261. Minz_Log::warning('Error loading dynamic OPML for category ' . $this->id() . '! ' .
  262. \SimplePie\Misc::url_remove_credentials($url));
  263. }
  264. }
  265. $catDAO = FreshRSS_Factory::createCategoryDao();
  266. if ($ok) {
  267. $catDAO->updateLastUpdate($this->id());
  268. } else {
  269. $catDAO->updateLastError($this->id());
  270. }
  271. return (bool)$ok;
  272. }
  273. private function sortFeeds(): void {
  274. if ($this->feeds === null) {
  275. return;
  276. }
  277. uasort($this->feeds, static fn(FreshRSS_Feed $a, FreshRSS_Feed $b): int => FreshRSS_Context::localeCompare($a->name(), $b->name()));
  278. }
  279. /**
  280. * Access cached feed
  281. * @param array<FreshRSS_Category> $categories
  282. */
  283. public static function findFeed(array $categories, int $feed_id): ?FreshRSS_Feed {
  284. foreach ($categories as $category) {
  285. foreach ($category->feeds() as $feed) {
  286. if ($feed->id() === $feed_id) {
  287. $feed->_category($category); // Should already be done; just to be safe
  288. return $feed;
  289. }
  290. }
  291. }
  292. return null;
  293. }
  294. /**
  295. * Access cached feeds
  296. * @param array<FreshRSS_Category> $categories
  297. * @return array<int,FreshRSS_Feed> where the key is the feed ID
  298. */
  299. public static function findFeeds(array $categories): array {
  300. $result = [];
  301. foreach ($categories as $category) {
  302. foreach ($category->feeds() as $feed) {
  303. $result[$feed->id()] = $feed;
  304. }
  305. }
  306. return $result;
  307. }
  308. /**
  309. * @param array<FreshRSS_Category> $categories
  310. */
  311. public static function countUnread(array $categories, int $minPriority = FreshRSS_Feed::PRIORITY_FEED): int {
  312. $n = 0;
  313. foreach ($categories as $category) {
  314. $n += $category->nbNotRead($minPriority);
  315. }
  316. return $n;
  317. }
  318. }