Context.php 16 KB

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