4
0

Context.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. /**
  287. * Checks whether the $state parameter is consequential, i.e. has any effect
  288. * (not zero, and not just including opposite states).
  289. */
  290. public static function isStateConsequential(int $state): bool {
  291. return (($state & FreshRSS_Entry::STATE_READ) xor ($state & FreshRSS_Entry::STATE_NOT_READ)) ||
  292. (($state & FreshRSS_Entry::STATE_FAVORITE) xor ($state & FreshRSS_Entry::STATE_NOT_FAVORITE)) ||
  293. ($state & FreshRSS_Entry::STATE_OR_NOT_READ) ||
  294. ($state & FreshRSS_Entry::STATE_OR_FAVORITE);
  295. }
  296. /**
  297. * Checks whether the current state includes $state parameter.
  298. */
  299. public static function isStateEnabled(int $state): bool {
  300. return (self::$state & $state) !== 0;
  301. }
  302. /**
  303. * Returns the current state with or without $state parameter.
  304. */
  305. public static function getRevertState(int $state): int {
  306. if (self::$state & $state) {
  307. return self::$state & ~$state;
  308. }
  309. return self::$state | $state;
  310. }
  311. /**
  312. * Return the current get as a string or an array.
  313. *
  314. * If $array is true, the first item of the returned value is 'f' or 'c' or 't' and the second is the id.
  315. * @phpstan-return ($asArray is true ? array{'a'|'A'|'c'|'f'|'i'|'s'|'t'|'T'|'Z',bool|int} : string)
  316. * @return string|array{string,bool|int}
  317. */
  318. public static function currentGet(bool $asArray = false): string|array {
  319. if (self::$current_get['all']) {
  320. return $asArray ? ['a', true] : 'a';
  321. } elseif (self::$current_get['A']) {
  322. return $asArray ? ['A', true] : 'A';
  323. } elseif (self::$current_get['important']) {
  324. return $asArray ? ['i', true] : 'i';
  325. } elseif (self::$current_get['starred']) {
  326. return $asArray ? ['s', true] : 's';
  327. } elseif (self::$current_get['feed']) {
  328. if ($asArray) {
  329. return ['f', self::$current_get['feed']];
  330. } else {
  331. return 'f_' . self::$current_get['feed'];
  332. }
  333. } elseif (self::$current_get['category']) {
  334. if ($asArray) {
  335. return ['c', self::$current_get['category']];
  336. } else {
  337. return 'c_' . self::$current_get['category'];
  338. }
  339. } elseif (self::$current_get['tag']) {
  340. if ($asArray) {
  341. return ['t', self::$current_get['tag']];
  342. } else {
  343. return 't_' . self::$current_get['tag'];
  344. }
  345. } elseif (self::$current_get['tags']) {
  346. return $asArray ? ['T', true] : 'T';
  347. } elseif (self::$current_get['Z']) {
  348. return $asArray ? ['Z', true] : 'Z';
  349. }
  350. return '';
  351. }
  352. /**
  353. * @return bool true if the current request targets all feeds (main view), false otherwise.
  354. */
  355. public static function isAll(): bool {
  356. return self::$current_get['all'] != false;
  357. }
  358. public static function isAllAndCategories(): bool {
  359. return self::$current_get['A'] != false;
  360. }
  361. public static function isAllAndArchived(): bool {
  362. return self::$current_get['Z'] != false;
  363. }
  364. /**
  365. * @return bool true if the current request targets important feeds, false otherwise.
  366. */
  367. public static function isImportant(): bool {
  368. return self::$current_get['important'] != false;
  369. }
  370. /**
  371. * @return bool true if the current request targets a category, false otherwise.
  372. */
  373. public static function isCategory(): bool {
  374. return self::$current_get['category'] != false;
  375. }
  376. /**
  377. * @return bool true if the current request targets a feed (and not a category or all articles), false otherwise.
  378. */
  379. public static function isFeed(): bool {
  380. return self::$current_get['feed'] != false;
  381. }
  382. /**
  383. * @return bool true if the current request targets a tag (though not all tags), false otherwise.
  384. */
  385. public static function isTag(): bool {
  386. return self::$current_get['tag'] != false;
  387. }
  388. /**
  389. * @return bool whether $get parameter corresponds to the $current_get attribute.
  390. */
  391. public static function isCurrentGet(string $get): bool {
  392. $type = substr($get, 0, 1);
  393. $id = substr($get, 2);
  394. return match ($type) {
  395. 'a' => self::$current_get['all'],
  396. 'A' => self::$current_get['A'],
  397. 'i' => self::$current_get['important'],
  398. 's' => self::$current_get['starred'],
  399. 'f' => self::$current_get['feed'] == $id,
  400. 'c' => self::$current_get['category'] == $id,
  401. 't' => self::$current_get['tag'] == $id,
  402. 'T' => self::$current_get['tags'] || self::$current_get['tag'],
  403. 'Z' => self::$current_get['Z'],
  404. default => false,
  405. };
  406. }
  407. /**
  408. * Set the current $get attribute.
  409. *
  410. * Valid $get parameter are:
  411. * - a
  412. * - s
  413. * - f_<feed id>
  414. * - c_<category id>
  415. * - t_<tag id>
  416. *
  417. * $name and $get_unread attributes are also updated as $next_get
  418. * Raise an exception if id or $get is invalid.
  419. * @throws FreshRSS_Context_Exception
  420. * @throws Minz_ConfigurationNamespaceException
  421. * @throws Minz_PDOConnectionException
  422. */
  423. private static function _get(string $get): void {
  424. $type = $get[0];
  425. $id = (int)substr($get, 2);
  426. if (empty(self::$categories)) {
  427. // TODO: Check whether this section is used
  428. $catDAO = FreshRSS_Factory::createCategoryDao();
  429. $details = $type === 'f'; // Load additional feed details in the case of feed view
  430. self::$categories = $catDAO->listCategories(prePopulateFeeds: true, details: $details);
  431. }
  432. switch ($type) {
  433. case 'a': // All PRIORITY_MAIN_STREAM
  434. self::$current_get['all'] = true;
  435. self::$description = FreshRSS_Context::systemConf()->meta_description;
  436. self::$get_unread = self::$total_unread;
  437. break;
  438. case 'A': // All except PRIORITY_HIDDEN
  439. self::$current_get['A'] = true;
  440. self::$description = FreshRSS_Context::systemConf()->meta_description;
  441. self::$get_unread = self::$total_unread;
  442. break;
  443. case 'Z': // All including PRIORITY_HIDDEN
  444. self::$current_get['Z'] = true;
  445. self::$name = _t('index.feed.title');
  446. self::$description = FreshRSS_Context::systemConf()->meta_description;
  447. self::$get_unread = self::$total_unread;
  448. break;
  449. case 'i': // Priority important feeds
  450. self::$current_get['important'] = true;
  451. self::$name = _t('index.menu.important');
  452. self::$description = FreshRSS_Context::systemConf()->meta_description;
  453. self::$get_unread = self::$total_unread;
  454. break;
  455. case 's': // Starred. Deprecated: use $state instead
  456. self::$current_get['starred'] = true;
  457. self::$name = _t('index.feed.title_fav');
  458. self::$description = FreshRSS_Context::systemConf()->meta_description;
  459. self::$get_unread = self::$total_starred['unread'];
  460. // Update state if favorite is not yet enabled.
  461. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  462. break;
  463. case 'f': // Feed
  464. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  465. $feed = FreshRSS_Context::systemConf()->allow_robots ? null : FreshRSS_Category::findFeed(self::$categories, $id);
  466. if ($feed === null) {
  467. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  468. }
  469. self::$current_get['feed'] = $id;
  470. self::$current_get['category'] = $feed->categoryId();
  471. self::$name = $feed->name();
  472. self::$description = $feed->description();
  473. self::$get_unread = $feed->nbNotRead();
  474. break;
  475. case 'c': // Category
  476. // We try to find the corresponding category.
  477. self::$current_get['category'] = $id;
  478. $cat = null;
  479. foreach (self::$categories as $category) {
  480. if ($category->id() === $id) {
  481. $cat = $category;
  482. break;
  483. }
  484. }
  485. if ($cat === null) {
  486. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  487. }
  488. self::$name = $cat->name();
  489. self::$get_unread = $cat->nbNotRead();
  490. break;
  491. case 't': // Tag (label)
  492. // We try to find the corresponding tag.
  493. self::$current_get['tag'] = $id;
  494. $tag = null;
  495. foreach (self::$tags as $t) {
  496. if ($t->id() === $id) {
  497. $tag = $t;
  498. break;
  499. }
  500. }
  501. if ($tag === null) {
  502. $tagDAO = FreshRSS_Factory::createTagDao();
  503. $tag = $tagDAO->searchById($id);
  504. if ($tag === null) {
  505. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  506. }
  507. }
  508. self::$name = $tag->name();
  509. self::$get_unread = $tag->nbUnread();
  510. break;
  511. case 'T': // Any tag (label)
  512. $tagDAO = FreshRSS_Factory::createTagDao();
  513. self::$current_get['tags'] = true;
  514. self::$name = _t('index.menu.mylabels');
  515. self::$get_unread = $tagDAO->countNotRead();
  516. break;
  517. default:
  518. throw new FreshRSS_Context_Exception('Invalid getter: ' . $get);
  519. }
  520. self::_nextGet();
  521. }
  522. /**
  523. * Set the value of $next_get attribute.
  524. */
  525. private static function _nextGet(): void {
  526. $get = self::currentGet();
  527. // By default, $next_get == $get
  528. self::$next_get = $get;
  529. if (empty(self::$categories)) {
  530. $catDAO = FreshRSS_Factory::createCategoryDao();
  531. self::$categories = $catDAO->listCategories(prePopulateFeeds: true);
  532. }
  533. if (FreshRSS_Context::userConf()->onread_jump_next && strlen($get) > 2) {
  534. $another_unread_id = '';
  535. $found_current_get = false;
  536. switch ($get[0]) {
  537. case 'f':
  538. // We search the next unread feed with the following priorities: next in same category, or previous in same category, or next, or previous.
  539. foreach (self::$categories as $cat) {
  540. $sameCat = false;
  541. foreach ($cat->feeds() as $feed) {
  542. if ($found_current_get) {
  543. if ($feed->nbNotRead() > 0) {
  544. $another_unread_id = $feed->id();
  545. break 2;
  546. }
  547. } elseif ($feed->id() == self::$current_get['feed']) {
  548. $found_current_get = true;
  549. } elseif ($feed->nbNotRead() > 0) {
  550. $another_unread_id = $feed->id();
  551. $sameCat = true;
  552. }
  553. }
  554. if ($found_current_get && $sameCat) {
  555. break;
  556. }
  557. }
  558. // If there is no more unread feed, show main stream
  559. self::$next_get = $another_unread_id == '' ? 'a' : 'f_' . $another_unread_id;
  560. break;
  561. case 'c':
  562. // We search the next category with at least one unread article.
  563. foreach (self::$categories as $cat) {
  564. if ($cat->id() == self::$current_get['category']) {
  565. // Here is our current category! Next one could be our
  566. // champion if it has unread articles.
  567. $found_current_get = true;
  568. continue;
  569. }
  570. if ($cat->nbNotRead(minPriority: FreshRSS_Feed::PRIORITY_CATEGORY) > 0) {
  571. $another_unread_id = $cat->id();
  572. if ($found_current_get) {
  573. // Unread articles and the current category has
  574. // already been found? Leave the loop!
  575. break;
  576. }
  577. }
  578. }
  579. // If there is no more unread category, show main stream
  580. self::$next_get = $another_unread_id == '' ? 'a' : 'c_' . $another_unread_id;
  581. break;
  582. case 't':
  583. // We can't know what the next unread tag is because entries can be in multiple tags
  584. // so marking all entries in a tag can indirectly mark all entries in multiple tags.
  585. // Default is to return to the current tag, so mark it as next_get = 'a' instead when
  586. // userconf -> onread_jump_next so the readAction knows to jump to the next unread
  587. // tag.
  588. self::$next_get = 'a';
  589. break;
  590. }
  591. }
  592. }
  593. /**
  594. * Determine if the auto remove is available in the current context.
  595. * This feature is available if:
  596. * - it is activated in the configuration
  597. * - the "read" state is not enable
  598. * - the "unread" state is enable
  599. */
  600. public static function isAutoRemoveAvailable(): bool {
  601. return FreshRSS_Context::userConf()->auto_remove_article && !self::isStateEnabled(FreshRSS_Entry::STATE_READ) &&
  602. (self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ) || self::isStateEnabled(FreshRSS_Entry::STATE_OR_NOT_READ));
  603. }
  604. /**
  605. * Determine if the "sticky post" option is enabled. It can be enable
  606. * by the user when it is selected in the configuration page or by the
  607. * application when the context allows to auto-remove articles when they
  608. * are read.
  609. */
  610. public static function isStickyPostEnabled(): bool {
  611. if (FreshRSS_Context::userConf()->sticky_post) {
  612. return true;
  613. }
  614. if (self::isAutoRemoveAvailable()) {
  615. return true;
  616. }
  617. return false;
  618. }
  619. public static function defaultTimeZone(): string {
  620. $timezone = ini_get('date.timezone');
  621. return $timezone != false ? $timezone : 'UTC';
  622. }
  623. /**
  624. * Sort locale-aware with Collator if available
  625. */
  626. public static function localeCompare(string $a, string $b): int {
  627. static $collator = null;
  628. if ($collator === null) {
  629. $language = FreshRSS_Context::hasUserConf() ? FreshRSS_Context::userConf()->language : '';
  630. if ($language === '' || !class_exists(\Collator::class)) {
  631. $collator = false;
  632. } else {
  633. $collator = \Collator::create($language) ?? false;
  634. }
  635. if ($collator instanceof \Collator) {
  636. $collator->setAttribute(\Collator::NUMERIC_COLLATION, \Collator::ON);
  637. }
  638. }
  639. if (!($collator instanceof \Collator)) {
  640. return strnatcasecmp($a, $b);
  641. }
  642. $result = $collator->compare($a, $b);
  643. return $result === false ? strnatcasecmp($a, $b) : $result;
  644. }
  645. }