Context.php 17 KB

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