Context.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * The context object handles the current configuration file and different
  5. * useful functions associated to the current view state.
  6. */
  7. final class FreshRSS_Context {
  8. /** @var array<int,FreshRSS_Category> where the key is the category ID */
  9. private static array $categories = [];
  10. /** @var array<int,FreshRSS_Tag> where the key is the label ID */
  11. private static array $tags = [];
  12. public static string $name = '';
  13. public static string $description = '';
  14. public static int $total_unread = 0;
  15. public static int $total_important_unread = 0;
  16. /** @var array{all:int,read:int,unread:int} */
  17. public static array $total_starred = [
  18. 'all' => 0,
  19. 'read' => 0,
  20. 'unread' => 0,
  21. ];
  22. public static int $get_unread = 0;
  23. /** @var array{all:bool,A:bool,starred:bool,important:bool,feed:int|false,category:int|false,tag:int|false,tags:bool,Z:bool} */
  24. public static array $current_get = [
  25. 'all' => false,
  26. 'A' => false,
  27. 'starred' => false,
  28. 'important' => false,
  29. 'feed' => false,
  30. 'category' => false,
  31. 'tag' => false,
  32. 'tags' => false,
  33. 'Z' => false,
  34. ];
  35. public static string $next_get = 'a';
  36. public static int $state = 0;
  37. /** @var 'ASC'|'DESC' */
  38. public static string $order = 'DESC';
  39. /** @var 'id'|'c.name'|'date'|'f.name'|'lastUserModified'|'length'|'link'|'rand'|'title' */
  40. public static string $sort = 'id';
  41. /** @var 'ASC'|'DESC' */
  42. public static string $secondary_sort_order = 'DESC';
  43. /** @var 'id'|'date'|'link'|'title' */
  44. public static string $secondary_sort = 'id';
  45. public static int $number = 0;
  46. public static int $offset = 0;
  47. public static FreshRSS_BooleanSearch $search;
  48. /** @var numeric-string */
  49. public static string $continuation_id = '0';
  50. /** @var numeric-string */
  51. public static string $id_max = '0';
  52. public static int $sinceHours = 0;
  53. public static bool $isCli = false;
  54. /**
  55. * @access private
  56. * @deprecated Will be made `private`; use `FreshRSS_Context::systemConf()` instead.
  57. * @internal
  58. */
  59. public static ?FreshRSS_SystemConfiguration $system_conf = null;
  60. /**
  61. * @access private
  62. * @deprecated Will be made `private`; use `FreshRSS_Context::userConf()` instead.
  63. * @internal
  64. */
  65. public static ?FreshRSS_UserConfiguration $user_conf = null;
  66. /**
  67. * Initialize the context for the global system.
  68. */
  69. public static function initSystem(bool $reload = false): void {
  70. if ($reload || FreshRSS_Context::$system_conf === null) {
  71. //TODO: Keep in session what we need instead of always reloading from disk
  72. FreshRSS_Context::$system_conf = FreshRSS_SystemConfiguration::init(DATA_PATH . '/config.php', FRESHRSS_PATH . '/config.default.php');
  73. }
  74. }
  75. /**
  76. * @throws FreshRSS_Context_Exception
  77. */
  78. public static function &systemConf(): FreshRSS_SystemConfiguration {
  79. if (FreshRSS_Context::$system_conf === null) {
  80. throw new FreshRSS_Context_Exception('System configuration not initialised!');
  81. }
  82. return FreshRSS_Context::$system_conf;
  83. }
  84. public static function hasSystemConf(): bool {
  85. return FreshRSS_Context::$system_conf !== null;
  86. }
  87. /**
  88. * Initialize the context for the current user.
  89. */
  90. public static function initUser(string $username = '', bool $userMustExist = true): void {
  91. FreshRSS_Context::$user_conf = null;
  92. // Per-user caches must not survive a change of user:
  93. self::$categories = [];
  94. self::$tags = [];
  95. if (!isset($_SESSION)) {
  96. Minz_Session::init('FreshRSS');
  97. }
  98. Minz_Session::lock();
  99. if ($username == '') {
  100. $username = Minz_User::name() ?? '';
  101. }
  102. if (($username === Minz_User::INTERNAL_USER || FreshRSS_user_Controller::checkUsername($username)) &&
  103. (!$userMustExist || FreshRSS_user_Controller::userExists($username))) {
  104. try {
  105. //TODO: Keep in session what we need instead of always reloading from disk
  106. FreshRSS_Context::$user_conf = FreshRSS_UserConfiguration::init(
  107. USERS_PATH . '/' . $username . '/config.php',
  108. FRESHRSS_PATH . '/config-user.default.php');
  109. Minz_User::change($username);
  110. } catch (Exception $ex) {
  111. Minz_Log::warning($ex->getMessage(), USERS_PATH . '/_/' . LOG_FILENAME);
  112. }
  113. }
  114. if (FreshRSS_Context::$user_conf == null) {
  115. Minz_Session::_params([
  116. 'loginOk' => false,
  117. Minz_User::CURRENT_USER => false,
  118. ]);
  119. }
  120. Minz_Session::unlock();
  121. if (FreshRSS_Context::$user_conf == null) {
  122. return;
  123. }
  124. FreshRSS_Context::$search = new FreshRSS_BooleanSearch('');
  125. //Legacy
  126. $oldEntries = FreshRSS_Context::$user_conf->attributeInt('old_entries') ?? 0;
  127. $keepMin = FreshRSS_Context::$user_conf->attributeInt('keep_history_default') ?? -5;
  128. if ($oldEntries > 0 || $keepMin > -5) { //Freshrss < 1.15
  129. $archiving = FreshRSS_Context::$user_conf->archiving;
  130. $archiving['keep_max'] = false;
  131. if ($oldEntries > 0) {
  132. $archiving['keep_period'] = 'P' . $oldEntries . 'M';
  133. }
  134. if ($keepMin > 0) {
  135. $archiving['keep_min'] = $keepMin;
  136. } elseif ($keepMin == -1) { //Infinite
  137. $archiving['keep_period'] = false;
  138. $archiving['keep_min'] = false;
  139. }
  140. FreshRSS_Context::$user_conf->archiving = $archiving;
  141. }
  142. //Legacy < 1.16.1
  143. if (!in_array(FreshRSS_Context::$user_conf->display_categories, [ 'active', 'remember', 'all', 'none' ], true)) {
  144. FreshRSS_Context::$user_conf->display_categories = FreshRSS_Context::$user_conf->display_categories === true ? 'all' : 'active';
  145. }
  146. // FreshRSS 1.27.1+
  147. if (isset(FreshRSS_Context::$user_conf->shortcuts['close_dropdown'])) {
  148. $shortcuts = FreshRSS_Context::$user_conf->shortcuts;
  149. $shortcuts['close_menus'] = $shortcuts['close_dropdown'];
  150. unset($shortcuts['close_dropdown']);
  151. FreshRSS_Context::$user_conf->shortcuts = $shortcuts;
  152. FreshRSS_Context::$user_conf->save();
  153. }
  154. FreshRSS_Context::$user_conf->language = preg_replace_callback(
  155. '/-(\\w{2})$/',
  156. static fn (array $matches): string => strtoupper($matches[0]),
  157. FreshRSS_Context::$user_conf->language ?? Minz_Translate::DEFAULT_LANGUAGE
  158. ) ?? Minz_Translate::DEFAULT_LANGUAGE;
  159. }
  160. /**
  161. * @throws FreshRSS_Context_Exception
  162. */
  163. public static function &userConf(): FreshRSS_UserConfiguration {
  164. if (FreshRSS_Context::$user_conf === null) {
  165. throw new FreshRSS_Context_Exception('User configuration not initialised!');
  166. }
  167. return FreshRSS_Context::$user_conf;
  168. }
  169. public static function hasUserConf(): bool {
  170. return FreshRSS_Context::$user_conf !== null;
  171. }
  172. public static function clearUserConf(): void {
  173. FreshRSS_Context::$user_conf = null;
  174. }
  175. /**
  176. * @internal
  177. */
  178. public static function setUserConf(?FreshRSS_UserConfiguration $user_conf): void {
  179. FreshRSS_Context::$user_conf = $user_conf;
  180. }
  181. /** @return array<int,FreshRSS_Category> where the key is the category ID */
  182. public static function categories(): array {
  183. if (empty(self::$categories)) {
  184. $catDAO = FreshRSS_Factory::createCategoryDao();
  185. self::$categories = $catDAO->listSortedCategories(prePopulateFeeds: true, details: false);
  186. }
  187. return self::$categories;
  188. }
  189. /** @return array<int,FreshRSS_Feed> where the key is the feed ID */
  190. public static function feeds(): array {
  191. return FreshRSS_Category::findFeeds(self::categories());
  192. }
  193. /** @return array<int,FreshRSS_Tag> where the key is the label ID */
  194. public static function labels(bool $precounts = false): array {
  195. if (empty(self::$tags) || $precounts) {
  196. $tagDAO = FreshRSS_Factory::createTagDao();
  197. self::$tags = $tagDAO->listTags($precounts);
  198. }
  199. return self::$tags;
  200. }
  201. /**
  202. * This action updates the Context object by using request parameters.
  203. *
  204. * HTTP GET request parameters are:
  205. * - state (default: conf->default_view)
  206. * - search (default: empty string)
  207. * - order (default: conf->sort_order)
  208. * - nb (default: conf->posts_per_page)
  209. * - next (default: empty string)
  210. * - hours (default: 0)
  211. * @throws FreshRSS_Context_Exception
  212. * @throws Minz_BadRequestException if the search is too long or if the parentheses are nested too deeply
  213. * @throws Minz_ConfigurationNamespaceException
  214. * @throws Minz_PDOConnectionException
  215. */
  216. public static function updateUsingRequest(bool $computeStatistics): void {
  217. if ($computeStatistics && self::$total_unread === 0) {
  218. // Update number of read / unread variables.
  219. $entryDAO = FreshRSS_Factory::createEntryDao();
  220. self::$total_starred = $entryDAO->countUnreadReadFavorites();
  221. self::$total_unread = FreshRSS_Category::countUnread(self::categories(), FreshRSS_Feed::PRIORITY_MAIN_STREAM);
  222. self::$total_important_unread = FreshRSS_Category::countUnread(self::categories(), FreshRSS_Feed::PRIORITY_IMPORTANT);
  223. }
  224. self::_get(Minz_Request::paramString('get', plaintext: true) ?: 'a');
  225. self::$state = Minz_Request::paramInt('state') ?: FreshRSS_Context::userConf()->default_state;
  226. $state_forced_by_user = Minz_Request::paramString('state', plaintext: true) !== '';
  227. if (!$state_forced_by_user) {
  228. if (FreshRSS_Context::userConf()->show_fav_unread && (self::isCurrentGet('s') || self::isCurrentGet('T') || self::isTag())) {
  229. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  230. } elseif (FreshRSS_Context::userConf()->default_view === 'all') {
  231. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  232. } elseif (FreshRSS_Context::userConf()->default_view === 'unread_or_favorite') {
  233. self::$state = FreshRSS_Entry::STATE_OR_NOT_READ | FreshRSS_Entry::STATE_OR_FAVORITE;
  234. } elseif (FreshRSS_Context::userConf()->default_view === 'adaptive' && self::$get_unread <= 0) {
  235. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  236. }
  237. }
  238. self::$search = new FreshRSS_BooleanSearch(Minz_Request::paramString('search', plaintext: true));
  239. $default_order = null;
  240. $default_sort = null;
  241. if (Minz_Request::paramString('order', plaintext: true) === '' || Minz_Request::paramString('sort', plaintext: true) === '') {
  242. if (!empty(self::$current_get['feed'])) {
  243. $id = self::$current_get['feed'];
  244. // We most likely already have the feed object in cache
  245. $feed = FreshRSS_Category::findFeed(FreshRSS_Context::categories(), $id);
  246. if ($feed === null) {
  247. $feedDAO = FreshRSS_Factory::createFeedDao();
  248. $feed = $feedDAO->searchById($id);
  249. }
  250. $default_order = $feed?->defaultOrder();
  251. $default_sort = $feed?->defaultSort();
  252. } elseif (!empty(self::$current_get['category'])) {
  253. $id = self::$current_get['category'];
  254. // We most likely already have the category object in cache
  255. $category = FreshRSS_Context::categories()[$id] ?? null;
  256. if ($category === null) {
  257. $categoryDAO = FreshRSS_Factory::createCategoryDao();
  258. $category = $categoryDAO->searchById($id);
  259. }
  260. $default_order = $category?->defaultOrder();
  261. $default_sort = $category?->defaultSort();
  262. }
  263. }
  264. $order = Minz_Request::paramString('order', plaintext: true) ?: $default_order ?: FreshRSS_Context::userConf()->sort_order;
  265. self::$order = in_array($order, ['ASC', 'DESC'], true) ? $order : 'DESC';
  266. $sort = Minz_Request::paramString('sort', plaintext: true) ?: $default_sort ?: FreshRSS_Context::userConf()->sort;
  267. self::$sort = in_array($sort, ['id', 'c.name', 'date', 'f.name', 'lastUserModified', 'length', 'link', 'title', 'rand'], true) ? $sort : 'id';
  268. if (in_array(self::$sort, ['c.name', 'f.name'], true)) {
  269. self::$secondary_sort = FreshRSS_Context::userConf()->secondary_sort;
  270. self::$secondary_sort_order = FreshRSS_Context::userConf()->secondary_sort_order;
  271. if ($order !== ($default_order ?: FreshRSS_Context::userConf()->sort_order)) {
  272. // User swapped order so swap secondary order as well
  273. self::$secondary_sort_order = self::$secondary_sort_order === 'DESC' ? 'ASC' : 'DESC';
  274. }
  275. }
  276. self::$number = max(0, Minz_Request::paramInt('nb')) ?: FreshRSS_Context::userConf()->posts_per_page;
  277. if (self::$number > FreshRSS_Context::userConf()->max_posts_per_rss) {
  278. self::$number = max(
  279. FreshRSS_Context::userConf()->max_posts_per_rss,
  280. FreshRSS_Context::userConf()->posts_per_page);
  281. }
  282. self::$offset = Minz_Request::paramInt('offset');
  283. $id_max = Minz_Request::paramString('idMax', plaintext: true);
  284. self::$id_max = ctype_digit($id_max) ? $id_max : '0';
  285. $continuation_id = Minz_Request::paramString('cid', plaintext: true);
  286. self::$continuation_id = ctype_digit($continuation_id) ? $continuation_id : '0';
  287. self::$sinceHours = Minz_Request::paramInt('hours');
  288. }
  289. /** Return the requested navigation state, or 0 to reapply the reading preference after the action. */
  290. public static function getStateForRedirect(): int {
  291. return Minz_Request::paramIntNull('stateForRedirect') ?? Minz_Request::paramInt('state');
  292. }
  293. /**
  294. * Checks whether the $state parameter is consequential, i.e. has any effect
  295. * (not zero, and not just including opposite states).
  296. */
  297. public static function isStateConsequential(int $state): bool {
  298. return (($state & FreshRSS_Entry::STATE_READ) xor ($state & FreshRSS_Entry::STATE_NOT_READ)) ||
  299. (($state & FreshRSS_Entry::STATE_FAVORITE) xor ($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) ||
  300. ($state & FreshRSS_Entry::STATE_OR_NOT_READ) ||
  301. ($state & FreshRSS_Entry::STATE_OR_FAVORITE);
  302. }
  303. /**
  304. * Checks whether the current state includes $state parameter.
  305. */
  306. public static function isStateEnabled(int $state): bool {
  307. return (self::$state & $state) !== 0;
  308. }
  309. /**
  310. * Returns the current state with or without $state parameter.
  311. */
  312. public static function getRevertState(int $state): int {
  313. if (self::$state & $state) {
  314. return self::$state & ~$state;
  315. }
  316. return self::$state | $state;
  317. }
  318. /**
  319. * Return the current get as a string or an array.
  320. *
  321. * If $array is true, the first item of the returned value is 'f' or 'c' or 't' and the second is the id.
  322. * @phpstan-return ($asArray is true ? array{'a'|'A'|'c'|'f'|'i'|'s'|'t'|'T'|'Z',bool|int} : string)
  323. * @return string|array{string,bool|int}
  324. */
  325. public static function currentGet(bool $asArray = false): string|array {
  326. if (self::$current_get['all']) {
  327. return $asArray ? ['a', true] : 'a';
  328. } elseif (self::$current_get['A']) {
  329. return $asArray ? ['A', true] : 'A';
  330. } elseif (self::$current_get['important']) {
  331. return $asArray ? ['i', true] : 'i';
  332. } elseif (self::$current_get['starred']) {
  333. return $asArray ? ['s', true] : 's';
  334. } elseif (self::$current_get['feed']) {
  335. if ($asArray) {
  336. return ['f', self::$current_get['feed']];
  337. } else {
  338. return 'f_' . self::$current_get['feed'];
  339. }
  340. } elseif (self::$current_get['category']) {
  341. if ($asArray) {
  342. return ['c', self::$current_get['category']];
  343. } else {
  344. return 'c_' . self::$current_get['category'];
  345. }
  346. } elseif (self::$current_get['tag']) {
  347. if ($asArray) {
  348. return ['t', self::$current_get['tag']];
  349. } else {
  350. return 't_' . self::$current_get['tag'];
  351. }
  352. } elseif (self::$current_get['tags']) {
  353. return $asArray ? ['T', true] : 'T';
  354. } elseif (self::$current_get['Z']) {
  355. return $asArray ? ['Z', true] : 'Z';
  356. }
  357. return '';
  358. }
  359. /**
  360. * @return bool true if the current request targets all feeds (main view), false otherwise.
  361. */
  362. public static function isAll(): bool {
  363. return self::$current_get['all'] != false;
  364. }
  365. public static function isAllAndCategories(): bool {
  366. return self::$current_get['A'] != false;
  367. }
  368. public static function isAllAndArchived(): bool {
  369. return self::$current_get['Z'] != false;
  370. }
  371. /**
  372. * @return bool true if the current request targets important feeds, false otherwise.
  373. */
  374. public static function isImportant(): bool {
  375. return self::$current_get['important'] != false;
  376. }
  377. /**
  378. * @return bool true if the current request targets a category, false otherwise.
  379. */
  380. public static function isCategory(): bool {
  381. return self::$current_get['category'] != false;
  382. }
  383. /**
  384. * @return bool true if the current request targets a feed (and not a category or all articles), false otherwise.
  385. */
  386. public static function isFeed(): bool {
  387. return self::$current_get['feed'] != false;
  388. }
  389. /**
  390. * @return bool true if the current request targets a tag (though not all tags), false otherwise.
  391. */
  392. public static function isTag(): bool {
  393. return self::$current_get['tag'] != false;
  394. }
  395. /**
  396. * @return bool whether $get parameter corresponds to the $current_get attribute.
  397. */
  398. public static function isCurrentGet(string $get): bool {
  399. $type = substr($get, 0, 1);
  400. $id = substr($get, 2);
  401. return match ($type) {
  402. 'a' => self::$current_get['all'],
  403. 'A' => self::$current_get['A'],
  404. 'i' => self::$current_get['important'],
  405. 's' => self::$current_get['starred'],
  406. 'f' => self::$current_get['feed'] == $id,
  407. 'c' => self::$current_get['category'] == $id,
  408. 't' => self::$current_get['tag'] == $id,
  409. 'T' => self::$current_get['tags'] || self::$current_get['tag'],
  410. 'Z' => self::$current_get['Z'],
  411. default => false,
  412. };
  413. }
  414. /**
  415. * Set the current $get attribute.
  416. *
  417. * Valid $get parameter are:
  418. * - a
  419. * - s
  420. * - f_<feed id>
  421. * - c_<category id>
  422. * - t_<tag id>
  423. *
  424. * $name and $get_unread attributes are also updated as $next_get
  425. * Raise an exception if id or $get is invalid.
  426. * @throws FreshRSS_Context_Exception
  427. * @throws Minz_ConfigurationNamespaceException
  428. * @throws Minz_PDOConnectionException
  429. */
  430. private static function _get(string $get): void {
  431. $type = $get[0];
  432. $id = (int)substr($get, 2);
  433. if (empty(self::$categories)) {
  434. // TODO: Check whether this section is used
  435. $catDAO = FreshRSS_Factory::createCategoryDao();
  436. $details = $type === 'f'; // Load additional feed details in the case of feed view
  437. self::$categories = $catDAO->listCategories(prePopulateFeeds: true, details: $details);
  438. }
  439. switch ($type) {
  440. case 'a': // All PRIORITY_MAIN_STREAM
  441. self::$current_get['all'] = true;
  442. self::$description = FreshRSS_Context::systemConf()->meta_description;
  443. self::$get_unread = self::$total_unread;
  444. break;
  445. case 'A': // All except PRIORITY_HIDDEN
  446. self::$current_get['A'] = true;
  447. self::$description = FreshRSS_Context::systemConf()->meta_description;
  448. self::$get_unread = self::$total_unread;
  449. break;
  450. case 'Z': // All including PRIORITY_HIDDEN
  451. self::$current_get['Z'] = true;
  452. self::$name = _t('index.feed.title');
  453. self::$description = FreshRSS_Context::systemConf()->meta_description;
  454. self::$get_unread = self::$total_unread;
  455. break;
  456. case 'i': // Priority important feeds
  457. self::$current_get['important'] = true;
  458. self::$name = _t('index.menu.important');
  459. self::$description = FreshRSS_Context::systemConf()->meta_description;
  460. self::$get_unread = self::$total_unread;
  461. break;
  462. case 's': // Starred. Deprecated: use $state instead
  463. self::$current_get['starred'] = true;
  464. self::$name = _t('index.feed.title_fav');
  465. self::$description = FreshRSS_Context::systemConf()->meta_description;
  466. self::$get_unread = self::$total_starred['unread'];
  467. // Update state if favorite is not yet enabled.
  468. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  469. break;
  470. case 'f': // Feed
  471. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  472. $feed = FreshRSS_Context::systemConf()->allow_robots ? null : FreshRSS_Category::findFeed(self::$categories, $id);
  473. if ($feed === null) {
  474. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  475. }
  476. self::$current_get['feed'] = $id;
  477. self::$current_get['category'] = $feed->categoryId();
  478. self::$name = $feed->name();
  479. self::$description = $feed->description();
  480. self::$get_unread = $feed->nbNotRead();
  481. break;
  482. case 'c': // Category
  483. // We try to find the corresponding category.
  484. self::$current_get['category'] = $id;
  485. $cat = null;
  486. foreach (self::$categories as $category) {
  487. if ($category->id() === $id) {
  488. $cat = $category;
  489. break;
  490. }
  491. }
  492. if ($cat === null) {
  493. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  494. }
  495. self::$name = $cat->name();
  496. self::$get_unread = $cat->nbNotRead();
  497. break;
  498. case 't': // Tag (label)
  499. // We try to find the corresponding tag.
  500. self::$current_get['tag'] = $id;
  501. $tag = null;
  502. foreach (self::$tags as $t) {
  503. if ($t->id() === $id) {
  504. $tag = $t;
  505. break;
  506. }
  507. }
  508. if ($tag === null) {
  509. $tagDAO = FreshRSS_Factory::createTagDao();
  510. $tag = $tagDAO->searchById($id);
  511. if ($tag === null) {
  512. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  513. }
  514. }
  515. self::$name = $tag->name();
  516. self::$get_unread = $tag->nbUnread();
  517. break;
  518. case 'T': // Any tag (label)
  519. $tagDAO = FreshRSS_Factory::createTagDao();
  520. self::$current_get['tags'] = true;
  521. self::$name = _t('index.menu.mylabels');
  522. self::$get_unread = $tagDAO->countNotRead();
  523. break;
  524. default:
  525. throw new FreshRSS_Context_Exception('Invalid getter: ' . $get);
  526. }
  527. self::_nextGet();
  528. }
  529. /**
  530. * Set the value of $next_get attribute.
  531. */
  532. private static function _nextGet(): void {
  533. $get = self::currentGet();
  534. // By default, $next_get == $get
  535. self::$next_get = $get;
  536. if (empty(self::$categories)) {
  537. $catDAO = FreshRSS_Factory::createCategoryDao();
  538. self::$categories = $catDAO->listCategories(prePopulateFeeds: true);
  539. }
  540. if (FreshRSS_Context::userConf()->onread_jump_next && strlen($get) > 2) {
  541. $another_unread_id = '';
  542. $found_current_get = false;
  543. switch ($get[0]) {
  544. case 'f':
  545. // We search the next unread feed with the following priorities: next in same category, or previous in same category, or next, or previous.
  546. foreach (self::$categories as $cat) {
  547. $sameCat = false;
  548. foreach ($cat->feeds() as $feed) {
  549. if ($found_current_get) {
  550. if ($feed->nbNotRead() > 0) {
  551. $another_unread_id = $feed->id();
  552. break 2;
  553. }
  554. } elseif ($feed->id() == self::$current_get['feed']) {
  555. $found_current_get = true;
  556. } elseif ($feed->nbNotRead() > 0) {
  557. $another_unread_id = $feed->id();
  558. $sameCat = true;
  559. }
  560. }
  561. if ($found_current_get && $sameCat) {
  562. break;
  563. }
  564. }
  565. // If there is no more unread feed, show main stream
  566. self::$next_get = $another_unread_id == '' ? 'a' : 'f_' . $another_unread_id;
  567. break;
  568. case 'c':
  569. // We search the next category with at least one unread article.
  570. foreach (self::$categories as $cat) {
  571. if ($cat->id() == self::$current_get['category']) {
  572. // Here is our current category! Next one could be our
  573. // champion if it has unread articles.
  574. $found_current_get = true;
  575. continue;
  576. }
  577. if ($cat->nbNotRead(minPriority: FreshRSS_Feed::PRIORITY_CATEGORY) > 0) {
  578. $another_unread_id = $cat->id();
  579. if ($found_current_get) {
  580. // Unread articles and the current category has
  581. // already been found? Leave the loop!
  582. break;
  583. }
  584. }
  585. }
  586. // If there is no more unread category, show main stream
  587. self::$next_get = $another_unread_id == '' ? 'a' : 'c_' . $another_unread_id;
  588. break;
  589. case 't':
  590. // We can't know what the next unread tag is because entries can be in multiple tags
  591. // so marking all entries in a tag can indirectly mark all entries in multiple tags.
  592. // Default is to return to the current tag, so mark it as next_get = 'a' instead when
  593. // userconf -> onread_jump_next so the readAction knows to jump to the next unread
  594. // tag.
  595. self::$next_get = 'a';
  596. break;
  597. }
  598. }
  599. }
  600. /**
  601. * Determine if the auto remove is available in the current context.
  602. * This feature is available if:
  603. * - it is activated in the configuration
  604. * - the "read" state is not enable
  605. * - the "unread" state is enable
  606. */
  607. public static function isAutoRemoveAvailable(): bool {
  608. return FreshRSS_Context::userConf()->auto_remove_article && !self::isStateEnabled(FreshRSS_Entry::STATE_READ) &&
  609. (self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ) || self::isStateEnabled(FreshRSS_Entry::STATE_OR_NOT_READ));
  610. }
  611. /**
  612. * Determine if the "sticky post" option is enabled. It can be enable
  613. * by the user when it is selected in the configuration page or by the
  614. * application when the context allows to auto-remove articles when they
  615. * are read.
  616. */
  617. public static function isStickyPostEnabled(): bool {
  618. if (FreshRSS_Context::userConf()->sticky_post) {
  619. return true;
  620. }
  621. if (self::isAutoRemoveAvailable()) {
  622. return true;
  623. }
  624. return false;
  625. }
  626. public static function defaultTimeZone(): string {
  627. $timezone = ini_get('date.timezone');
  628. return $timezone != false ? $timezone : 'UTC';
  629. }
  630. /**
  631. * Sort locale-aware with Collator if available
  632. */
  633. public static function localeCompare(string $a, string $b): int {
  634. static $collator = null;
  635. if ($collator === null) {
  636. $language = FreshRSS_Context::hasUserConf() ? FreshRSS_Context::userConf()->language : '';
  637. if ($language === '' || !class_exists(\Collator::class)) {
  638. $collator = false;
  639. } else {
  640. $collator = \Collator::create($language) ?? false;
  641. }
  642. if ($collator instanceof \Collator) {
  643. $collator->setAttribute(\Collator::NUMERIC_COLLATION, \Collator::ON);
  644. }
  645. }
  646. if (!($collator instanceof \Collator)) {
  647. return strnatcasecmp($a, $b);
  648. }
  649. $result = $collator->compare($a, $b);
  650. return $result === false ? strnatcasecmp($a, $b) : $result;
  651. }
  652. }