Context.php 16 KB

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