Context.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. /**
  9. * @var array<int,FreshRSS_Category>
  10. */
  11. private static array $categories = [];
  12. /**
  13. * @var array<int,FreshRSS_Tag>
  14. */
  15. private static array $tags = [];
  16. public static string $name = '';
  17. public static string $description = '';
  18. public static int $total_unread = 0;
  19. public static int $total_important_unread = 0;
  20. /** @var array{'all':int,'read':int,'unread':int} */
  21. public static array $total_starred = [
  22. 'all' => 0,
  23. 'read' => 0,
  24. 'unread' => 0,
  25. ];
  26. public static int $get_unread = 0;
  27. /** @var array{'all':bool,'starred':bool,'important':bool,'feed':int|false,'category':int|false,'tag':int|false,'tags':bool} */
  28. public static array $current_get = [
  29. 'all' => false,
  30. 'starred' => false,
  31. 'important' => false,
  32. 'feed' => false,
  33. 'category' => false,
  34. 'tag' => false,
  35. 'tags' => false,
  36. ];
  37. public static string $next_get = 'a';
  38. public static int $state = 0;
  39. /**
  40. * @phpstan-var 'ASC'|'DESC'
  41. */
  42. public static string $order = 'DESC';
  43. public static int $number = 0;
  44. public static int $offset = 0;
  45. public static FreshRSS_BooleanSearch $search;
  46. public static string $first_id = '';
  47. public static string $next_id = '';
  48. public static string $id_max = '';
  49. public static int $sinceHours = 0;
  50. public static bool $isCli = false;
  51. /**
  52. * @deprecated Will be made `private`; use `FreshRSS_Context::systemConf()` instead.
  53. * @internal
  54. */
  55. public static ?FreshRSS_SystemConfiguration $system_conf = null;
  56. /**
  57. * @deprecated Will be made `private`; use `FreshRSS_Context::userConf()` instead.
  58. * @internal
  59. */
  60. public static ?FreshRSS_UserConfiguration $user_conf = null;
  61. /**
  62. * Initialize the context for the global system.
  63. */
  64. public static function initSystem(bool $reload = false): void {
  65. if ($reload || FreshRSS_Context::$system_conf === null) {
  66. //TODO: Keep in session what we need instead of always reloading from disk
  67. FreshRSS_Context::$system_conf = FreshRSS_SystemConfiguration::init(DATA_PATH . '/config.php', FRESHRSS_PATH . '/config.default.php');
  68. }
  69. }
  70. /**
  71. * @throws FreshRSS_Context_Exception
  72. */
  73. public static function &systemConf(): FreshRSS_SystemConfiguration {
  74. if (FreshRSS_Context::$system_conf === null) {
  75. throw new FreshRSS_Context_Exception('System configuration not initialised!');
  76. }
  77. return FreshRSS_Context::$system_conf;
  78. }
  79. public static function hasSystemConf(): bool {
  80. return FreshRSS_Context::$system_conf !== null;
  81. }
  82. /**
  83. * Initialize the context for the current user.
  84. */
  85. public static function initUser(string $username = '', bool $userMustExist = true): void {
  86. FreshRSS_Context::$user_conf = null;
  87. if (!isset($_SESSION)) {
  88. Minz_Session::init('FreshRSS');
  89. }
  90. Minz_Session::lock();
  91. if ($username == '') {
  92. $username = Minz_User::name() ?? '';
  93. }
  94. if (($username === Minz_User::INTERNAL_USER || FreshRSS_user_Controller::checkUsername($username)) &&
  95. (!$userMustExist || FreshRSS_user_Controller::userExists($username))) {
  96. try {
  97. //TODO: Keep in session what we need instead of always reloading from disk
  98. FreshRSS_Context::$user_conf = FreshRSS_UserConfiguration::init(
  99. USERS_PATH . '/' . $username . '/config.php',
  100. FRESHRSS_PATH . '/config-user.default.php');
  101. Minz_User::change($username);
  102. } catch (Exception $ex) {
  103. Minz_Log::warning($ex->getMessage(), USERS_PATH . '/_/' . LOG_FILENAME);
  104. }
  105. }
  106. if (FreshRSS_Context::$user_conf == null) {
  107. Minz_Session::_params([
  108. 'loginOk' => false,
  109. Minz_User::CURRENT_USER => false,
  110. ]);
  111. }
  112. Minz_Session::unlock();
  113. if (FreshRSS_Context::$user_conf == null) {
  114. return;
  115. }
  116. FreshRSS_Context::$search = new FreshRSS_BooleanSearch('');
  117. //Legacy
  118. $oldEntries = FreshRSS_Context::$user_conf->param('old_entries', 0);
  119. $oldEntries = is_numeric($oldEntries) ? (int)$oldEntries : 0;
  120. $keepMin = FreshRSS_Context::$user_conf->param('keep_history_default', -5);
  121. $keepMin = is_numeric($keepMin) ? (int)$keepMin : -5;
  122. if ($oldEntries > 0 || $keepMin > -5) { //Freshrss < 1.15
  123. $archiving = FreshRSS_Context::$user_conf->archiving;
  124. $archiving['keep_max'] = false;
  125. if ($oldEntries > 0) {
  126. $archiving['keep_period'] = 'P' . $oldEntries . 'M';
  127. }
  128. if ($keepMin > 0) {
  129. $archiving['keep_min'] = $keepMin;
  130. } elseif ($keepMin == -1) { //Infinite
  131. $archiving['keep_period'] = false;
  132. $archiving['keep_min'] = false;
  133. }
  134. FreshRSS_Context::$user_conf->archiving = $archiving;
  135. }
  136. //Legacy < 1.16.1
  137. if (!in_array(FreshRSS_Context::$user_conf->display_categories, [ 'active', 'remember', 'all', 'none' ], true)) {
  138. FreshRSS_Context::$user_conf->display_categories = FreshRSS_Context::$user_conf->display_categories === true ? 'all' : 'active';
  139. }
  140. }
  141. /**
  142. * @throws FreshRSS_Context_Exception
  143. */
  144. public static function &userConf(): FreshRSS_UserConfiguration {
  145. if (FreshRSS_Context::$user_conf === null) {
  146. throw new FreshRSS_Context_Exception('User configuration not initialised!');
  147. }
  148. return FreshRSS_Context::$user_conf;
  149. }
  150. public static function hasUserConf(): bool {
  151. return FreshRSS_Context::$user_conf !== null;
  152. }
  153. public static function clearUserConf(): void {
  154. FreshRSS_Context::$user_conf = null;
  155. }
  156. /** @return array<int,FreshRSS_Category> */
  157. public static function categories(): array {
  158. if (empty(self::$categories)) {
  159. $catDAO = FreshRSS_Factory::createCategoryDao();
  160. self::$categories = $catDAO->listSortedCategories(true, false);
  161. }
  162. return self::$categories;
  163. }
  164. /** @return array<int,FreshRSS_Feed> */
  165. public static function feeds(): array {
  166. return FreshRSS_Category::findFeeds(self::categories());
  167. }
  168. /** @return array<int,FreshRSS_Tag> */
  169. public static function labels(bool $precounts = false): array {
  170. if (empty(self::$tags) || $precounts) {
  171. $tagDAO = FreshRSS_Factory::createTagDao();
  172. self::$tags = $tagDAO->listTags($precounts) ?: [];
  173. }
  174. return self::$tags;
  175. }
  176. /**
  177. * This action updates the Context object by using request parameters.
  178. *
  179. * HTTP GET request parameters are:
  180. * - state (default: conf->default_view)
  181. * - search (default: empty string)
  182. * - order (default: conf->sort_order)
  183. * - nb (default: conf->posts_per_page)
  184. * - next (default: empty string)
  185. * - hours (default: 0)
  186. * @throws FreshRSS_Context_Exception
  187. * @throws Minz_ConfigurationNamespaceException
  188. * @throws Minz_PDOConnectionException
  189. */
  190. public static function updateUsingRequest(bool $computeStatistics): void {
  191. if ($computeStatistics && self::$total_unread === 0) {
  192. // Update number of read / unread variables.
  193. $entryDAO = FreshRSS_Factory::createEntryDao();
  194. self::$total_starred = $entryDAO->countUnreadReadFavorites();
  195. self::$total_unread = FreshRSS_Category::countUnread(self::categories(), FreshRSS_Feed::PRIORITY_MAIN_STREAM);
  196. self::$total_important_unread = FreshRSS_Category::countUnread(self::categories(), FreshRSS_Feed::PRIORITY_IMPORTANT);
  197. }
  198. self::_get(Minz_Request::paramString('get') ?: 'a');
  199. self::$state = Minz_Request::paramInt('state') ?: FreshRSS_Context::userConf()->default_state;
  200. $state_forced_by_user = Minz_Request::paramString('state') !== '';
  201. if (!$state_forced_by_user) {
  202. if (FreshRSS_Context::userConf()->show_fav_unread && (self::isCurrentGet('s') || self::isCurrentGet('T') || self::isTag())) {
  203. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  204. } elseif (FreshRSS_Context::userConf()->default_view === 'all') {
  205. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  206. } elseif (FreshRSS_Context::userConf()->default_view === 'unread_or_favorite') {
  207. self::$state = FreshRSS_Entry::STATE_OR_NOT_READ | FreshRSS_Entry::STATE_OR_FAVORITE;
  208. } elseif (FreshRSS_Context::userConf()->default_view === 'adaptive' && self::$get_unread <= 0) {
  209. self::$state = FreshRSS_Entry::STATE_NOT_READ | FreshRSS_Entry::STATE_READ;
  210. }
  211. }
  212. self::$search = new FreshRSS_BooleanSearch(Minz_Request::paramString('search'));
  213. $order = Minz_Request::paramString('order') ?: FreshRSS_Context::userConf()->sort_order;
  214. self::$order = in_array($order, ['ASC', 'DESC'], true) ? $order : 'DESC';
  215. self::$number = Minz_Request::paramInt('nb') ?: FreshRSS_Context::userConf()->posts_per_page;
  216. if (self::$number > FreshRSS_Context::userConf()->max_posts_per_rss) {
  217. self::$number = max(
  218. FreshRSS_Context::userConf()->max_posts_per_rss,
  219. FreshRSS_Context::userConf()->posts_per_page);
  220. }
  221. self::$offset = Minz_Request::paramInt('offset');
  222. self::$first_id = Minz_Request::paramString('next');
  223. self::$sinceHours = Minz_Request::paramInt('hours');
  224. }
  225. /**
  226. * Returns if the current state includes $state parameter.
  227. */
  228. public static function isStateEnabled(int $state): int {
  229. return self::$state & $state;
  230. }
  231. /**
  232. * Returns the current state with or without $state parameter.
  233. */
  234. public static function getRevertState(int $state): int {
  235. if (self::$state & $state) {
  236. return self::$state & ~$state;
  237. }
  238. return self::$state | $state;
  239. }
  240. /**
  241. * Return the current get as a string or an array.
  242. *
  243. * If $array is true, the first item of the returned value is 'f' or 'c' or 't' and the second is the id.
  244. * @phpstan-return ($asArray is true ? array{'a'|'c'|'f'|'i'|'s'|'t'|'T',bool|int} : string)
  245. * @return string|array{string,bool|int}
  246. */
  247. public static function currentGet(bool $asArray = false): string|array {
  248. if (self::$current_get['all']) {
  249. return $asArray ? ['a', true] : 'a';
  250. } elseif (self::$current_get['important']) {
  251. return $asArray ? ['i', true] : 'i';
  252. } elseif (self::$current_get['starred']) {
  253. return $asArray ? ['s', true] : 's';
  254. } elseif (self::$current_get['feed']) {
  255. if ($asArray) {
  256. return ['f', self::$current_get['feed']];
  257. } else {
  258. return 'f_' . self::$current_get['feed'];
  259. }
  260. } elseif (self::$current_get['category']) {
  261. if ($asArray) {
  262. return ['c', self::$current_get['category']];
  263. } else {
  264. return 'c_' . self::$current_get['category'];
  265. }
  266. } elseif (self::$current_get['tag']) {
  267. if ($asArray) {
  268. return ['t', self::$current_get['tag']];
  269. } else {
  270. return 't_' . self::$current_get['tag'];
  271. }
  272. } elseif (self::$current_get['tags']) {
  273. return $asArray ? ['T', true] : 'T';
  274. }
  275. return '';
  276. }
  277. /**
  278. * @return bool true if the current request targets all feeds (main view), false otherwise.
  279. */
  280. public static function isAll(): bool {
  281. return self::$current_get['all'] != false;
  282. }
  283. /**
  284. * @return bool true if the current request targets important feeds, false otherwise.
  285. */
  286. public static function isImportant(): bool {
  287. return self::$current_get['important'] != false;
  288. }
  289. /**
  290. * @return bool true if the current request targets a category, false otherwise.
  291. */
  292. public static function isCategory(): bool {
  293. return self::$current_get['category'] != false;
  294. }
  295. /**
  296. * @return bool true if the current request targets a feed (and not a category or all articles), false otherwise.
  297. */
  298. public static function isFeed(): bool {
  299. return self::$current_get['feed'] != false;
  300. }
  301. /**
  302. * @return bool true if the current request targets a tag (though not all tags), false otherwise.
  303. */
  304. public static function isTag(): bool {
  305. return self::$current_get['tag'] != false;
  306. }
  307. /**
  308. * @return bool whether $get parameter corresponds to the $current_get attribute.
  309. */
  310. public static function isCurrentGet(string $get): bool {
  311. $type = substr($get, 0, 1);
  312. $id = substr($get, 2);
  313. return match ($type) {
  314. 'a' => self::$current_get['all'],
  315. 'i' => self::$current_get['important'],
  316. 's' => self::$current_get['starred'],
  317. 'f' => self::$current_get['feed'] == $id,
  318. 'c' => self::$current_get['category'] == $id,
  319. 't' => self::$current_get['tag'] == $id,
  320. 'T' => self::$current_get['tags'] || self::$current_get['tag'],
  321. default => false,
  322. };
  323. }
  324. /**
  325. * Set the current $get attribute.
  326. *
  327. * Valid $get parameter are:
  328. * - a
  329. * - s
  330. * - f_<feed id>
  331. * - c_<category id>
  332. * - t_<tag id>
  333. *
  334. * $name and $get_unread attributes are also updated as $next_get
  335. * Raise an exception if id or $get is invalid.
  336. * @throws FreshRSS_Context_Exception
  337. * @throws Minz_ConfigurationNamespaceException
  338. * @throws Minz_PDOConnectionException
  339. */
  340. public static function _get(string $get): void {
  341. $type = $get[0];
  342. $id = (int)substr($get, 2);
  343. if (empty(self::$categories)) {
  344. $catDAO = FreshRSS_Factory::createCategoryDao();
  345. $details = $type === 'f'; // Load additional feed details in the case of feed view
  346. self::$categories = $catDAO->listCategories(true, $details);
  347. }
  348. switch ($type) {
  349. case 'a':
  350. self::$current_get['all'] = true;
  351. self::$name = _t('index.feed.title');
  352. self::$description = FreshRSS_Context::systemConf()->meta_description;
  353. self::$get_unread = self::$total_unread;
  354. break;
  355. case 'i':
  356. self::$current_get['important'] = true;
  357. self::$name = _t('index.menu.important');
  358. self::$description = FreshRSS_Context::systemConf()->meta_description;
  359. self::$get_unread = self::$total_unread;
  360. break;
  361. case 's':
  362. self::$current_get['starred'] = true;
  363. self::$name = _t('index.feed.title_fav');
  364. self::$description = FreshRSS_Context::systemConf()->meta_description;
  365. self::$get_unread = self::$total_starred['unread'];
  366. // Update state if favorite is not yet enabled.
  367. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  368. break;
  369. case 'f':
  370. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  371. $feed = FreshRSS_Context::systemConf()->allow_robots ? null : FreshRSS_Category::findFeed(self::$categories, $id);
  372. if ($feed === null) {
  373. $feedDAO = FreshRSS_Factory::createFeedDao();
  374. $feed = $feedDAO->searchById($id);
  375. if ($feed === null) {
  376. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  377. }
  378. }
  379. self::$current_get['feed'] = $id;
  380. self::$current_get['category'] = $feed->categoryId();
  381. self::$name = $feed->name();
  382. self::$description = $feed->description();
  383. self::$get_unread = $feed->nbNotRead();
  384. break;
  385. case 'c':
  386. // We try to find the corresponding category.
  387. self::$current_get['category'] = $id;
  388. if (!isset(self::$categories[$id])) {
  389. $catDAO = FreshRSS_Factory::createCategoryDao();
  390. $cat = $catDAO->searchById($id);
  391. if ($cat === null) {
  392. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  393. }
  394. self::$categories[$id] = $cat;
  395. } else {
  396. $cat = self::$categories[$id];
  397. }
  398. self::$name = $cat->name();
  399. self::$get_unread = $cat->nbNotRead();
  400. break;
  401. case 't':
  402. // We try to find the corresponding tag.
  403. self::$current_get['tag'] = $id;
  404. if (!isset(self::$tags[$id])) {
  405. $tagDAO = FreshRSS_Factory::createTagDao();
  406. $tag = $tagDAO->searchById($id);
  407. if ($tag === null) {
  408. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  409. }
  410. self::$tags[$id] = $tag;
  411. } else {
  412. $tag = self::$tags[$id];
  413. }
  414. self::$name = $tag->name();
  415. self::$get_unread = $tag->nbUnread();
  416. break;
  417. case 'T':
  418. $tagDAO = FreshRSS_Factory::createTagDao();
  419. self::$current_get['tags'] = true;
  420. self::$name = _t('index.menu.tags');
  421. self::$get_unread = $tagDAO->countNotRead();
  422. break;
  423. default:
  424. throw new FreshRSS_Context_Exception('Invalid getter: ' . $get);
  425. }
  426. self::_nextGet();
  427. }
  428. /**
  429. * Set the value of $next_get attribute.
  430. */
  431. private static function _nextGet(): void {
  432. $get = self::currentGet();
  433. // By default, $next_get == $get
  434. self::$next_get = $get;
  435. if (empty(self::$categories)) {
  436. $catDAO = FreshRSS_Factory::createCategoryDao();
  437. self::$categories = $catDAO->listCategories(true);
  438. }
  439. if (FreshRSS_Context::userConf()->onread_jump_next && strlen($get) > 2) {
  440. $another_unread_id = '';
  441. $found_current_get = false;
  442. switch ($get[0]) {
  443. case 'f':
  444. // We search the next unread feed with the following priorities: next in same category, or previous in same category, or next, or previous.
  445. foreach (self::$categories as $cat) {
  446. $sameCat = false;
  447. foreach ($cat->feeds() as $feed) {
  448. if ($found_current_get) {
  449. if ($feed->nbNotRead() > 0) {
  450. $another_unread_id = $feed->id();
  451. break 2;
  452. }
  453. } elseif ($feed->id() == self::$current_get['feed']) {
  454. $found_current_get = true;
  455. } elseif ($feed->nbNotRead() > 0) {
  456. $another_unread_id = $feed->id();
  457. $sameCat = true;
  458. }
  459. }
  460. if ($found_current_get && $sameCat) {
  461. break;
  462. }
  463. }
  464. // If there is no more unread feed, show main stream
  465. self::$next_get = $another_unread_id == '' ? 'a' : 'f_' . $another_unread_id;
  466. break;
  467. case 'c':
  468. // We search the next category with at least one unread article.
  469. foreach (self::$categories as $cat) {
  470. if ($cat->id() == self::$current_get['category']) {
  471. // Here is our current category! Next one could be our
  472. // champion if it has unread articles.
  473. $found_current_get = true;
  474. continue;
  475. }
  476. if ($cat->nbNotRead() > 0) {
  477. $another_unread_id = $cat->id();
  478. if ($found_current_get) {
  479. // Unread articles and the current category has
  480. // already been found? Leave the loop!
  481. break;
  482. }
  483. }
  484. }
  485. // If there is no more unread category, show main stream
  486. self::$next_get = $another_unread_id == '' ? 'a' : 'c_' . $another_unread_id;
  487. break;
  488. case 't':
  489. // We can't know what the next unread tag is because entries can be in multiple tags
  490. // so marking all entries in a tag can indirectly mark all entries in multiple tags.
  491. // Default is to return to the current tag, so mark it as next_get = 'a' instead when
  492. // userconf -> onread_jump_next so the readAction knows to jump to the next unread
  493. // tag.
  494. self::$next_get = 'a';
  495. break;
  496. }
  497. }
  498. }
  499. /**
  500. * Determine if the auto remove is available in the current context.
  501. * This feature is available if:
  502. * - it is activated in the configuration
  503. * - the "read" state is not enable
  504. * - the "unread" state is enable
  505. */
  506. public static function isAutoRemoveAvailable(): bool {
  507. return FreshRSS_Context::userConf()->auto_remove_article && !self::isStateEnabled(FreshRSS_Entry::STATE_READ) &&
  508. (self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ) || self::isStateEnabled(FreshRSS_Entry::STATE_OR_NOT_READ));
  509. }
  510. /**
  511. * Determine if the "sticky post" option is enabled. It can be enable
  512. * by the user when it is selected in the configuration page or by the
  513. * application when the context allows to auto-remove articles when they
  514. * are read.
  515. */
  516. public static function isStickyPostEnabled(): bool {
  517. if (FreshRSS_Context::userConf()->sticky_post) {
  518. return true;
  519. }
  520. if (self::isAutoRemoveAvailable()) {
  521. return true;
  522. }
  523. return false;
  524. }
  525. public static function defaultTimeZone(): string {
  526. $timezone = ini_get('date.timezone');
  527. return $timezone != false ? $timezone : 'UTC';
  528. }
  529. }