Context.php 17 KB

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