Context.php 16 KB

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