Context.php 25 KB

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