Context.php 15 KB

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