Context.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. // Register the configuration setter for the system configuration
  100. $configurationSetter = new FreshRSS_ConfigurationSetter();
  101. FreshRSS_Context::$system_conf->_configurationSetter($configurationSetter);
  102. }
  103. return FreshRSS_Context::$system_conf;
  104. }
  105. /**
  106. * Initialize the context for the current user.
  107. * @return FreshRSS_UserConfiguration|false
  108. * @throws Minz_ConfigurationParamException
  109. */
  110. public static function initUser(string $username = '', bool $userMustExist = true) {
  111. FreshRSS_Context::$user_conf = null;
  112. if (!isset($_SESSION)) {
  113. Minz_Session::init('FreshRSS');
  114. }
  115. Minz_Session::lock();
  116. if ($username == '') {
  117. $username = Minz_User::name() ?? '';
  118. }
  119. if (($username === Minz_User::INTERNAL_USER || FreshRSS_user_Controller::checkUsername($username)) &&
  120. (!$userMustExist || FreshRSS_user_Controller::userExists($username))) {
  121. try {
  122. //TODO: Keep in session what we need instead of always reloading from disk
  123. FreshRSS_Context::$user_conf = FreshRSS_UserConfiguration::init(
  124. USERS_PATH . '/' . $username . '/config.php',
  125. FRESHRSS_PATH . '/config-user.default.php',
  126. FreshRSS_Context::$system_conf->configurationSetter());
  127. Minz_User::change($username);
  128. } catch (Exception $ex) {
  129. Minz_Log::warning($ex->getMessage(), USERS_PATH . '/_/' . LOG_FILENAME);
  130. }
  131. }
  132. if (FreshRSS_Context::$user_conf == null) {
  133. Minz_Session::_params([
  134. 'loginOk' => false,
  135. Minz_User::CURRENT_USER => false,
  136. ]);
  137. }
  138. Minz_Session::unlock();
  139. if (FreshRSS_Context::$user_conf == null) {
  140. return false;
  141. }
  142. FreshRSS_Context::$search = new FreshRSS_BooleanSearch('');
  143. //Legacy
  144. $oldEntries = (int)FreshRSS_Context::$user_conf->param('old_entries', 0);
  145. $keepMin = (int)FreshRSS_Context::$user_conf->param('keep_history_default', -5);
  146. if ($oldEntries > 0 || $keepMin > -5) { //Freshrss < 1.15
  147. $archiving = FreshRSS_Context::$user_conf->archiving;
  148. $archiving['keep_max'] = false;
  149. if ($oldEntries > 0) {
  150. $archiving['keep_period'] = 'P' . $oldEntries . 'M';
  151. }
  152. if ($keepMin > 0) {
  153. $archiving['keep_min'] = $keepMin;
  154. } elseif ($keepMin == -1) { //Infinite
  155. $archiving['keep_period'] = false;
  156. $archiving['keep_min'] = false;
  157. }
  158. FreshRSS_Context::$user_conf->archiving = $archiving;
  159. }
  160. //Legacy < 1.16.1
  161. if (!in_array(FreshRSS_Context::$user_conf->display_categories, [ 'active', 'remember', 'all', 'none' ], true)) {
  162. FreshRSS_Context::$user_conf->display_categories = FreshRSS_Context::$user_conf->display_categories === true ? 'all' : 'active';
  163. }
  164. return FreshRSS_Context::$user_conf;
  165. }
  166. /**
  167. * This action updates the Context object by using request parameters.
  168. *
  169. * Parameters are:
  170. * - state (default: conf->default_view)
  171. * - search (default: empty string)
  172. * - order (default: conf->sort_order)
  173. * - nb (default: conf->posts_per_page)
  174. * - next (default: empty string)
  175. * - hours (default: 0)
  176. * @throws FreshRSS_Context_Exception
  177. * @throws Minz_ConfigurationNamespaceException
  178. * @throws Minz_PDOConnectionException
  179. */
  180. public static function updateUsingRequest(): void {
  181. if (empty(self::$categories)) {
  182. $catDAO = FreshRSS_Factory::createCategoryDao();
  183. self::$categories = $catDAO->listSortedCategories();
  184. }
  185. // Update number of read / unread variables.
  186. $entryDAO = FreshRSS_Factory::createEntryDao();
  187. self::$total_starred = $entryDAO->countUnreadReadFavorites();
  188. self::$total_unread = FreshRSS_CategoryDAO::countUnread(
  189. self::$categories, 1
  190. );
  191. self::_get(Minz_Request::param('get', 'a', false));
  192. self::$state = Minz_Request::param(
  193. 'state', self::$user_conf->default_state
  194. );
  195. $state_forced_by_user = Minz_Request::param('state') !== false;
  196. if (!$state_forced_by_user && !self::isStateEnabled(FreshRSS_Entry::STATE_READ)) {
  197. if (self::$user_conf->default_view === 'adaptive' && self::$get_unread <= 0) {
  198. self::$state |= FreshRSS_Entry::STATE_READ;
  199. }
  200. if (self::$user_conf->show_fav_unread &&
  201. (self::isCurrentGet('s') || self::isCurrentGet('T') || self::isTag())) {
  202. self::$state |= FreshRSS_Entry::STATE_READ;
  203. }
  204. }
  205. self::$search = new FreshRSS_BooleanSearch(Minz_Request::param('search', ''));
  206. self::$order = Minz_Request::param(
  207. 'order', self::$user_conf->sort_order
  208. );
  209. self::$number = (int)Minz_Request::param('nb', self::$user_conf->posts_per_page);
  210. if (self::$number > self::$user_conf->max_posts_per_rss) {
  211. self::$number = max(
  212. self::$user_conf->max_posts_per_rss,
  213. self::$user_conf->posts_per_page);
  214. }
  215. self::$first_id = Minz_Request::param('next', '');
  216. self::$sinceHours = (int)Minz_Request::param('hours', 0);
  217. }
  218. /**
  219. * Returns if the current state includes $state parameter.
  220. */
  221. public static function isStateEnabled(int $state): int {
  222. return self::$state & $state;
  223. }
  224. /**
  225. * Returns the current state with or without $state parameter.
  226. */
  227. public static function getRevertState(int $state): int {
  228. if (self::$state & $state) {
  229. return self::$state & ~$state;
  230. }
  231. return self::$state | $state;
  232. }
  233. /**
  234. * Return the current get as a string or an array.
  235. *
  236. * If $array is true, the first item of the returned value is 'f' or 'c' and
  237. * the second is the id.
  238. * @return string|array{string,bool|int}
  239. */
  240. public static function currentGet(bool $asArray = false) {
  241. if (self::$current_get['all']) {
  242. return 'a';
  243. } elseif (self::$current_get['starred']) {
  244. return 's';
  245. } elseif (self::$current_get['feed']) {
  246. if ($asArray) {
  247. return array('f', self::$current_get['feed']);
  248. } else {
  249. return 'f_' . self::$current_get['feed'];
  250. }
  251. } elseif (self::$current_get['category']) {
  252. if ($asArray) {
  253. return array('c', self::$current_get['category']);
  254. } else {
  255. return 'c_' . self::$current_get['category'];
  256. }
  257. } elseif (self::$current_get['tag']) {
  258. if ($asArray) {
  259. return array('t', self::$current_get['tag']);
  260. } else {
  261. return 't_' . self::$current_get['tag'];
  262. }
  263. } elseif (self::$current_get['tags']) {
  264. return 'T';
  265. }
  266. return '';
  267. }
  268. /**
  269. * @return bool true if the current request targets all feeds (main view), false otherwise.
  270. */
  271. public static function isAll(): bool {
  272. return self::$current_get['all'] != false;
  273. }
  274. /**
  275. * @return bool true if the current request targets a category, false otherwise.
  276. */
  277. public static function isCategory(): bool {
  278. return self::$current_get['category'] != false;
  279. }
  280. /**
  281. * @return bool true if the current request targets a feed (and not a category or all articles), false otherwise.
  282. */
  283. public static function isFeed(): bool {
  284. return self::$current_get['feed'] != false;
  285. }
  286. /**
  287. * @return bool true if the current request targets a tag (though not all tags), false otherwise.
  288. */
  289. public static function isTag(): bool {
  290. return self::$current_get['tag'] != false;
  291. }
  292. /**
  293. * @return bool whether $get parameter corresponds to the $current_get attribute.
  294. */
  295. public static function isCurrentGet(string $get): bool {
  296. $type = substr($get, 0, 1);
  297. $id = substr($get, 2);
  298. switch($type) {
  299. case 'a':
  300. return self::$current_get['all'];
  301. case 's':
  302. return self::$current_get['starred'];
  303. case 'f':
  304. return self::$current_get['feed'] == $id;
  305. case 'c':
  306. return self::$current_get['category'] == $id;
  307. case 't':
  308. return self::$current_get['tag'] == $id;
  309. case 'T':
  310. return self::$current_get['tags'] || self::$current_get['tag'];
  311. default:
  312. return false;
  313. }
  314. }
  315. /**
  316. * Set the current $get attribute.
  317. *
  318. * Valid $get parameter are:
  319. * - a
  320. * - s
  321. * - f_<feed id>
  322. * - c_<category id>
  323. * - t_<tag id>
  324. *
  325. * $name and $get_unread attributes are also updated as $next_get
  326. * Raise an exception if id or $get is invalid.
  327. * @throws FreshRSS_Context_Exception
  328. * @throws Minz_ConfigurationNamespaceException
  329. * @throws Minz_PDOConnectionException
  330. */
  331. public static function _get(string $get): void {
  332. $type = $get[0];
  333. $id = (int)substr($get, 2);
  334. if (empty(self::$categories)) {
  335. $catDAO = FreshRSS_Factory::createCategoryDao();
  336. self::$categories = $catDAO->listCategories();
  337. }
  338. switch($type) {
  339. case 'a':
  340. self::$current_get['all'] = true;
  341. self::$name = _t('index.feed.title');
  342. self::$description = self::$system_conf->meta_description;
  343. self::$get_unread = self::$total_unread;
  344. break;
  345. case 's':
  346. self::$current_get['starred'] = true;
  347. self::$name = _t('index.feed.title_fav');
  348. self::$description = self::$system_conf->meta_description;
  349. self::$get_unread = self::$total_starred['unread'];
  350. // Update state if favorite is not yet enabled.
  351. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  352. break;
  353. case 'f':
  354. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  355. $feed = FreshRSS_Context::$system_conf->allow_robots ? null : FreshRSS_CategoryDAO::findFeed(self::$categories, $id);
  356. if ($feed === null) {
  357. $feedDAO = FreshRSS_Factory::createFeedDao();
  358. $feed = $feedDAO->searchById($id);
  359. if (!$feed) {
  360. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  361. }
  362. }
  363. self::$current_get['feed'] = $id;
  364. self::$current_get['category'] = $feed->categoryId();
  365. self::$name = $feed->name();
  366. self::$description = $feed->description();
  367. self::$get_unread = $feed->nbNotRead();
  368. break;
  369. case 'c':
  370. // We try to find the corresponding category.
  371. self::$current_get['category'] = $id;
  372. if (!isset(self::$categories[$id])) {
  373. $catDAO = FreshRSS_Factory::createCategoryDao();
  374. $cat = $catDAO->searchById($id);
  375. if (!$cat) {
  376. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  377. }
  378. } else {
  379. $cat = self::$categories[$id];
  380. }
  381. self::$name = $cat->name();
  382. self::$get_unread = $cat->nbNotRead();
  383. break;
  384. case 't':
  385. // We try to find the corresponding tag.
  386. self::$current_get['tag'] = $id;
  387. if (!isset(self::$tags[$id])) {
  388. $tagDAO = FreshRSS_Factory::createTagDao();
  389. $tag = $tagDAO->searchById($id);
  390. if (!$tag) {
  391. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  392. }
  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 (self::$user_conf->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 (!self::$user_conf->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 (self::$user_conf->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 != '' ? $timezone : 'UTC';
  510. }
  511. }