Context.php 20 KB

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