Context.php 15 KB

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