Context.php 25 KB

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