Context.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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::paramString('get') ?: 'a');
  192. self::$state = Minz_Request::paramInt('state') ?: self::$user_conf->default_state;
  193. $state_forced_by_user = Minz_Request::paramString('state') !== '';
  194. if (!$state_forced_by_user && !self::isStateEnabled(FreshRSS_Entry::STATE_READ)) {
  195. if (self::$user_conf->default_view === 'adaptive' && self::$get_unread <= 0) {
  196. self::$state |= FreshRSS_Entry::STATE_READ;
  197. }
  198. if (self::$user_conf->show_fav_unread &&
  199. (self::isCurrentGet('s') || self::isCurrentGet('T') || self::isTag())) {
  200. self::$state |= FreshRSS_Entry::STATE_READ;
  201. }
  202. }
  203. self::$search = new FreshRSS_BooleanSearch(Minz_Request::paramString('search'));
  204. self::$order = Minz_Request::paramString('order') ?: self::$user_conf->sort_order;
  205. self::$number = Minz_Request::paramInt('nb') ?: self::$user_conf->posts_per_page;
  206. if (self::$number > self::$user_conf->max_posts_per_rss) {
  207. self::$number = max(
  208. self::$user_conf->max_posts_per_rss,
  209. self::$user_conf->posts_per_page);
  210. }
  211. self::$first_id = Minz_Request::paramString('next');
  212. self::$sinceHours = Minz_Request::paramInt('hours');
  213. }
  214. /**
  215. * Returns if the current state includes $state parameter.
  216. */
  217. public static function isStateEnabled(int $state): int {
  218. return self::$state & $state;
  219. }
  220. /**
  221. * Returns the current state with or without $state parameter.
  222. */
  223. public static function getRevertState(int $state): int {
  224. if (self::$state & $state) {
  225. return self::$state & ~$state;
  226. }
  227. return self::$state | $state;
  228. }
  229. /**
  230. * Return the current get as a string or an array.
  231. *
  232. * If $array is true, the first item of the returned value is 'f' or 'c' and
  233. * the second is the id.
  234. * @return string|array{string,bool|int}
  235. */
  236. public static function currentGet(bool $asArray = false) {
  237. if (self::$current_get['all']) {
  238. return 'a';
  239. } elseif (self::$current_get['starred']) {
  240. return 's';
  241. } elseif (self::$current_get['feed']) {
  242. if ($asArray) {
  243. return array('f', self::$current_get['feed']);
  244. } else {
  245. return 'f_' . self::$current_get['feed'];
  246. }
  247. } elseif (self::$current_get['category']) {
  248. if ($asArray) {
  249. return array('c', self::$current_get['category']);
  250. } else {
  251. return 'c_' . self::$current_get['category'];
  252. }
  253. } elseif (self::$current_get['tag']) {
  254. if ($asArray) {
  255. return array('t', self::$current_get['tag']);
  256. } else {
  257. return 't_' . self::$current_get['tag'];
  258. }
  259. } elseif (self::$current_get['tags']) {
  260. return 'T';
  261. }
  262. return '';
  263. }
  264. /**
  265. * @return bool true if the current request targets all feeds (main view), false otherwise.
  266. */
  267. public static function isAll(): bool {
  268. return self::$current_get['all'] != false;
  269. }
  270. /**
  271. * @return bool true if the current request targets a category, false otherwise.
  272. */
  273. public static function isCategory(): bool {
  274. return self::$current_get['category'] != false;
  275. }
  276. /**
  277. * @return bool true if the current request targets a feed (and not a category or all articles), false otherwise.
  278. */
  279. public static function isFeed(): bool {
  280. return self::$current_get['feed'] != false;
  281. }
  282. /**
  283. * @return bool true if the current request targets a tag (though not all tags), false otherwise.
  284. */
  285. public static function isTag(): bool {
  286. return self::$current_get['tag'] != false;
  287. }
  288. /**
  289. * @return bool whether $get parameter corresponds to the $current_get attribute.
  290. */
  291. public static function isCurrentGet(string $get): bool {
  292. $type = substr($get, 0, 1);
  293. $id = substr($get, 2);
  294. switch($type) {
  295. case 'a':
  296. return self::$current_get['all'];
  297. case 's':
  298. return self::$current_get['starred'];
  299. case 'f':
  300. return self::$current_get['feed'] == $id;
  301. case 'c':
  302. return self::$current_get['category'] == $id;
  303. case 't':
  304. return self::$current_get['tag'] == $id;
  305. case 'T':
  306. return self::$current_get['tags'] || self::$current_get['tag'];
  307. default:
  308. return false;
  309. }
  310. }
  311. /**
  312. * Set the current $get attribute.
  313. *
  314. * Valid $get parameter are:
  315. * - a
  316. * - s
  317. * - f_<feed id>
  318. * - c_<category id>
  319. * - t_<tag id>
  320. *
  321. * $name and $get_unread attributes are also updated as $next_get
  322. * Raise an exception if id or $get is invalid.
  323. * @throws FreshRSS_Context_Exception
  324. * @throws Minz_ConfigurationNamespaceException
  325. * @throws Minz_PDOConnectionException
  326. */
  327. public static function _get(string $get): void {
  328. $type = $get[0];
  329. $id = (int)substr($get, 2);
  330. if (empty(self::$categories)) {
  331. $catDAO = FreshRSS_Factory::createCategoryDao();
  332. self::$categories = $catDAO->listCategories();
  333. }
  334. switch($type) {
  335. case 'a':
  336. self::$current_get['all'] = true;
  337. self::$name = _t('index.feed.title');
  338. self::$description = self::$system_conf->meta_description;
  339. self::$get_unread = self::$total_unread;
  340. break;
  341. case 's':
  342. self::$current_get['starred'] = true;
  343. self::$name = _t('index.feed.title_fav');
  344. self::$description = self::$system_conf->meta_description;
  345. self::$get_unread = self::$total_starred['unread'];
  346. // Update state if favorite is not yet enabled.
  347. self::$state = self::$state | FreshRSS_Entry::STATE_FAVORITE;
  348. break;
  349. case 'f':
  350. // We try to find the corresponding feed. When allowing robots, always retrieve the full feed including description
  351. $feed = FreshRSS_Context::$system_conf->allow_robots ? null : FreshRSS_CategoryDAO::findFeed(self::$categories, $id);
  352. if ($feed === null) {
  353. $feedDAO = FreshRSS_Factory::createFeedDao();
  354. $feed = $feedDAO->searchById($id);
  355. if (!$feed) {
  356. throw new FreshRSS_Context_Exception('Invalid feed: ' . $id);
  357. }
  358. }
  359. self::$current_get['feed'] = $id;
  360. self::$current_get['category'] = $feed->categoryId();
  361. self::$name = $feed->name();
  362. self::$description = $feed->description();
  363. self::$get_unread = $feed->nbNotRead();
  364. break;
  365. case 'c':
  366. // We try to find the corresponding category.
  367. self::$current_get['category'] = $id;
  368. if (!isset(self::$categories[$id])) {
  369. $catDAO = FreshRSS_Factory::createCategoryDao();
  370. $cat = $catDAO->searchById($id);
  371. if (!$cat) {
  372. throw new FreshRSS_Context_Exception('Invalid category: ' . $id);
  373. }
  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) {
  387. throw new FreshRSS_Context_Exception('Invalid tag: ' . $id);
  388. }
  389. } else {
  390. $tag = self::$tags[$id];
  391. }
  392. self::$name = $tag->name();
  393. self::$get_unread = $tag->nbUnread();
  394. break;
  395. case 'T':
  396. $tagDAO = FreshRSS_Factory::createTagDao();
  397. self::$current_get['tags'] = true;
  398. self::$name = _t('index.menu.tags');
  399. self::$get_unread = $tagDAO->countNotRead();
  400. break;
  401. default:
  402. throw new FreshRSS_Context_Exception('Invalid getter: ' . $get);
  403. }
  404. self::_nextGet();
  405. }
  406. /**
  407. * Set the value of $next_get attribute.
  408. */
  409. private static function _nextGet(): void {
  410. $get = self::currentGet();
  411. // By default, $next_get == $get
  412. self::$next_get = $get;
  413. if (empty(self::$categories)) {
  414. $catDAO = FreshRSS_Factory::createCategoryDao();
  415. self::$categories = $catDAO->listCategories();
  416. }
  417. if (self::$user_conf->onread_jump_next && strlen($get) > 2) {
  418. $another_unread_id = '';
  419. $found_current_get = false;
  420. switch ($get[0]) {
  421. case 'f':
  422. // We search the next unread feed with the following priorities: next in same category, or previous in same category, or next, or previous.
  423. foreach (self::$categories as $cat) {
  424. $sameCat = false;
  425. foreach ($cat->feeds() as $feed) {
  426. if ($found_current_get) {
  427. if ($feed->nbNotRead() > 0) {
  428. $another_unread_id = $feed->id();
  429. break 2;
  430. }
  431. } elseif ($feed->id() == self::$current_get['feed']) {
  432. $found_current_get = true;
  433. } elseif ($feed->nbNotRead() > 0) {
  434. $another_unread_id = $feed->id();
  435. $sameCat = true;
  436. }
  437. }
  438. if ($found_current_get && $sameCat) {
  439. break;
  440. }
  441. }
  442. // If there is no more unread feed, show main stream
  443. self::$next_get = $another_unread_id == '' ? 'a' : 'f_' . $another_unread_id;
  444. break;
  445. case 'c':
  446. // We search the next category with at least one unread article.
  447. foreach (self::$categories as $cat) {
  448. if ($cat->id() == self::$current_get['category']) {
  449. // Here is our current category! Next one could be our
  450. // champion if it has unread articles.
  451. $found_current_get = true;
  452. continue;
  453. }
  454. if ($cat->nbNotRead() > 0) {
  455. $another_unread_id = $cat->id();
  456. if ($found_current_get) {
  457. // Unread articles and the current category has
  458. // already been found? Leave the loop!
  459. break;
  460. }
  461. }
  462. }
  463. // If there is no more unread category, show main stream
  464. self::$next_get = $another_unread_id == '' ? 'a' : 'c_' . $another_unread_id;
  465. break;
  466. }
  467. }
  468. }
  469. /**
  470. * Determine if the auto remove is available in the current context.
  471. * This feature is available if:
  472. * - it is activated in the configuration
  473. * - the "read" state is not enable
  474. * - the "unread" state is enable
  475. */
  476. public static function isAutoRemoveAvailable(): bool {
  477. if (!self::$user_conf->auto_remove_article) {
  478. return false;
  479. }
  480. if (self::isStateEnabled(FreshRSS_Entry::STATE_READ)) {
  481. return false;
  482. }
  483. if (!self::isStateEnabled(FreshRSS_Entry::STATE_NOT_READ)) {
  484. return false;
  485. }
  486. return true;
  487. }
  488. /**
  489. * Determine if the "sticky post" option is enabled. It can be enable
  490. * by the user when it is selected in the configuration page or by the
  491. * application when the context allows to auto-remove articles when they
  492. * are read.
  493. */
  494. public static function isStickyPostEnabled(): bool {
  495. if (self::$user_conf->sticky_post) {
  496. return true;
  497. }
  498. if (self::isAutoRemoveAvailable()) {
  499. return true;
  500. }
  501. return false;
  502. }
  503. public static function defaultTimeZone(): string {
  504. $timezone = ini_get('date.timezone');
  505. return $timezone != '' ? $timezone : 'UTC';
  506. }
  507. }