Context.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 && !self::isStateEnabled(FreshRSS_Entry::STATE_READ)) {
  202. if (FreshRSS_Context::userConf()->default_view === 'all') {
  203. self::$state |= FreshRSS_Entry::STATE_ALL;
  204. } elseif (FreshRSS_Context::userConf()->default_view === 'adaptive' && self::$get_unread <= 0) {
  205. self::$state |= FreshRSS_Entry::STATE_READ;
  206. }
  207. if (FreshRSS_Context::userConf()->show_fav_unread &&
  208. (self::isCurrentGet('s') || self::isCurrentGet('T') || self::isTag())) {
  209. self::$state |= 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) {
  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. switch ($type) {
  314. case 'a':
  315. return self::$current_get['all'];
  316. case 'i':
  317. return self::$current_get['important'];
  318. case 's':
  319. return self::$current_get['starred'];
  320. case 'f':
  321. return self::$current_get['feed'] == $id;
  322. case 'c':
  323. return self::$current_get['category'] == $id;
  324. case 't':
  325. return self::$current_get['tag'] == $id;
  326. case 'T':
  327. return self::$current_get['tags'] || self::$current_get['tag'];
  328. default:
  329. return false;
  330. }
  331. }
  332. /**
  333. * Set the current $get attribute.
  334. *
  335. * Valid $get parameter are:
  336. * - a
  337. * - s
  338. * - f_<feed id>
  339. * - c_<category id>
  340. * - t_<tag id>
  341. *
  342. * $name and $get_unread attributes are also updated as $next_get
  343. * Raise an exception if id or $get is invalid.
  344. * @throws FreshRSS_Context_Exception
  345. * @throws Minz_ConfigurationNamespaceException
  346. * @throws Minz_PDOConnectionException
  347. */
  348. public static function _get(string $get): void {
  349. $type = $get[0];
  350. $id = (int)substr($get, 2);
  351. if (empty(self::$categories)) {
  352. $catDAO = FreshRSS_Factory::createCategoryDao();
  353. $details = $type === 'f'; // Load additional feed details in the case of feed view
  354. self::$categories = $catDAO->listCategories(true, $details);
  355. }
  356. switch ($type) {
  357. case 'a':
  358. self::$current_get['all'] = true;
  359. self::$name = _t('index.feed.title');
  360. self::$description = FreshRSS_Context::systemConf()->meta_description;
  361. self::$get_unread = self::$total_unread;
  362. break;
  363. case 'i':
  364. self::$current_get['important'] = true;
  365. self::$name = _t('index.menu.important');
  366. self::$description = FreshRSS_Context::systemConf()->meta_description;
  367. self::$get_unread = self::$total_unread;
  368. break;
  369. case 's':
  370. self::$current_get['starred'] = true;
  371. self::$name = _t('index.feed.title_fav');
  372. self::$description = FreshRSS_Context::systemConf()->meta_description;
  373. self::$get_unread = self::$total_starred['unread'];
  374. // Update state if favorite is not yet enabled.
  375. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  376. break;
  377. case 'f':
  378. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  379. $feed = FreshRSS_Context::systemConf()->allow_robots ? null : FreshRSS_Category::findFeed(self::$categories, $id);
  380. if ($feed === null) {
  381. $feedDAO = FreshRSS_Factory::createFeedDao();
  382. $feed = $feedDAO->searchById($id);
  383. if ($feed === null) {
  384. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  385. }
  386. }
  387. self::$current_get['feed'] = $id;
  388. self::$current_get['category'] = $feed->categoryId();
  389. self::$name = $feed->name();
  390. self::$description = $feed->description();
  391. self::$get_unread = $feed->nbNotRead();
  392. break;
  393. case 'c':
  394. // We try to find the corresponding category.
  395. self::$current_get['category'] = $id;
  396. if (!isset(self::$categories[$id])) {
  397. $catDAO = FreshRSS_Factory::createCategoryDao();
  398. $cat = $catDAO->searchById($id);
  399. if ($cat === null) {
  400. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  401. }
  402. self::$categories[$id] = $cat;
  403. } else {
  404. $cat = self::$categories[$id];
  405. }
  406. self::$name = $cat->name();
  407. self::$get_unread = $cat->nbNotRead();
  408. break;
  409. case 't':
  410. // We try to find the corresponding tag.
  411. self::$current_get['tag'] = $id;
  412. if (!isset(self::$tags[$id])) {
  413. $tagDAO = FreshRSS_Factory::createTagDao();
  414. $tag = $tagDAO->searchById($id);
  415. if ($tag === null) {
  416. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  417. }
  418. self::$tags[$id] = $tag;
  419. } else {
  420. $tag = self::$tags[$id];
  421. }
  422. self::$name = $tag->name();
  423. self::$get_unread = $tag->nbUnread();
  424. break;
  425. case 'T':
  426. $tagDAO = FreshRSS_Factory::createTagDao();
  427. self::$current_get['tags'] = true;
  428. self::$name = _t('index.menu.tags');
  429. self::$get_unread = $tagDAO->countNotRead();
  430. break;
  431. default:
  432. throw new FreshRSS_Context_Exception('Invalid getter: ' . $get);
  433. }
  434. self::_nextGet();
  435. }
  436. /**
  437. * Set the value of $next_get attribute.
  438. */
  439. private static function _nextGet(): void {
  440. $get = self::currentGet();
  441. // By default, $next_get == $get
  442. self::$next_get = $get;
  443. if (empty(self::$categories)) {
  444. $catDAO = FreshRSS_Factory::createCategoryDao();
  445. self::$categories = $catDAO->listCategories(true);
  446. }
  447. if (FreshRSS_Context::userConf()->onread_jump_next && strlen($get) > 2) {
  448. $another_unread_id = '';
  449. $found_current_get = false;
  450. switch ($get[0]) {
  451. case 'f':
  452. // We search the next unread feed with the following priorities: next in same category, or previous in same category, or next, or previous.
  453. foreach (self::$categories as $cat) {
  454. $sameCat = false;
  455. foreach ($cat->feeds() as $feed) {
  456. if ($found_current_get) {
  457. if ($feed->nbNotRead() > 0) {
  458. $another_unread_id = $feed->id();
  459. break 2;
  460. }
  461. } elseif ($feed->id() == self::$current_get['feed']) {
  462. $found_current_get = true;
  463. } elseif ($feed->nbNotRead() > 0) {
  464. $another_unread_id = $feed->id();
  465. $sameCat = true;
  466. }
  467. }
  468. if ($found_current_get && $sameCat) {
  469. break;
  470. }
  471. }
  472. // If there is no more unread feed, show main stream
  473. self::$next_get = $another_unread_id == '' ? 'a' : 'f_' . $another_unread_id;
  474. break;
  475. case 'c':
  476. // We search the next category with at least one unread article.
  477. foreach (self::$categories as $cat) {
  478. if ($cat->id() == self::$current_get['category']) {
  479. // Here is our current category! Next one could be our
  480. // champion if it has unread articles.
  481. $found_current_get = true;
  482. continue;
  483. }
  484. if ($cat->nbNotRead() > 0) {
  485. $another_unread_id = $cat->id();
  486. if ($found_current_get) {
  487. // Unread articles and the current category has
  488. // already been found? Leave the loop!
  489. break;
  490. }
  491. }
  492. }
  493. // If there is no more unread category, show main stream
  494. self::$next_get = $another_unread_id == '' ? 'a' : 'c_' . $another_unread_id;
  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. if (!FreshRSS_Context::userConf()->auto_remove_article) {
  508. return false;
  509. }
  510. if (self::isStateEnabled(FreshRSS_Entry::STATE_READ)) {
  511. return false;
  512. }
  513. if (!self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ)) {
  514. return false;
  515. }
  516. return true;
  517. }
  518. /**
  519. * Determine if the "sticky post" option is enabled. It can be enable
  520. * by the user when it is selected in the configuration page or by the
  521. * application when the context allows to auto-remove articles when they
  522. * are read.
  523. */
  524. public static function isStickyPostEnabled(): bool {
  525. if (FreshRSS_Context::userConf()->sticky_post) {
  526. return true;
  527. }
  528. if (self::isAutoRemoveAvailable()) {
  529. return true;
  530. }
  531. return false;
  532. }
  533. public static function defaultTimeZone(): string {
  534. $timezone = ini_get('date.timezone');
  535. return $timezone != false ? $timezone : 'UTC';
  536. }
  537. }