Context.php 15 KB

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