Context.php 16 KB

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