indexController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This class handles main actions of FreshRSS.
  5. */
  6. class FreshRSS_index_Controller extends FreshRSS_ActionController {
  7. #[\Override]
  8. public function firstAction(): void {
  9. $this->view->html_url = Minz_Url::display(['c' => 'index', 'a' => 'index'], 'html', 'root');
  10. }
  11. /**
  12. * This action only redirect on the default view mode (normal or global)
  13. */
  14. public function indexAction(): void {
  15. $preferred_output = FreshRSS_Context::userConf()->view_mode;
  16. $viewMode = FreshRSS_ViewMode::getAllModes()[$preferred_output] ?? null;
  17. // Fallback to 'normal' if the preferred mode was not found
  18. if ($viewMode === null) {
  19. Minz_Request::setBadNotification(_t('feedback.extensions.invalid_view_mode', $preferred_output));
  20. $viewMode = FreshRSS_ViewMode::getAllModes()['normal'];
  21. }
  22. Minz_Request::forward([
  23. 'c' => $viewMode->controller(),
  24. 'a' => $viewMode->action(),
  25. ]);
  26. }
  27. /**
  28. * @return '.future'|'.today'|'.yesterday'|''
  29. */
  30. private static function dayRelative(int $timestamp, bool $mayBeFuture): string {
  31. static $today = null;
  32. if (!is_int($today)) {
  33. $today = strtotime('today') ?: 0;
  34. }
  35. if ($today <= 0) {
  36. return '';
  37. } elseif ($mayBeFuture && ($timestamp >= $today + 86400)) {
  38. return '.future';
  39. } elseif ($timestamp >= $today) {
  40. return '.today';
  41. } elseif ($timestamp >= $today - 86400) {
  42. return '.yesterday';
  43. }
  44. return '';
  45. }
  46. /**
  47. * Content for displaying a transition between entries when sorting by specific criteria.
  48. */
  49. public static function transition(FreshRSS_Entry $entry): string {
  50. return match (FreshRSS_Context::$sort) {
  51. 'id' => _t('index.feed.received' . self::dayRelative($entry->dateAdded(raw: true), mayBeFuture: false)) .
  52. ' — ' . timestamptodate($entry->dateAdded(raw: true), hour: false),
  53. 'date' => _t('index.feed.published' . self::dayRelative($entry->date(raw: true), mayBeFuture: true)) .
  54. ' — ' . timestamptodate($entry->date(raw: true), hour: false),
  55. 'lastUserModified' => _t('index.feed.userModified' . self::dayRelative($entry->lastUserModified() ?? 0, mayBeFuture: false)) .
  56. ' — ' . timestamptodate($entry->lastUserModified() ?? 0, hour: false),
  57. 'c.name' => $entry->feed()?->category()?->name() ?? '',
  58. 'f.name' => $entry->feed()?->name() ?? '',
  59. default => '',
  60. };
  61. }
  62. /**
  63. * Produce a hyperlink to the next transition of entries.
  64. */
  65. public static function transitionLink(FreshRSS_Entry $entry, int $offset = 0): string {
  66. if (in_array(FreshRSS_Context::$sort, ['c.name', 'f.name'], true)) {
  67. return Minz_Url::display(Minz_Request::modifiedCurrentRequest([
  68. 'get' => match (FreshRSS_Context::$sort) {
  69. 'c.name' => 'c_' . ($entry->feed()?->category()?->id() ?? '0'),
  70. 'f.name' => 'f_' . ($entry->feed()?->id() ?? '0'),
  71. },
  72. ]));
  73. }
  74. $operator = match (FreshRSS_Context::$sort) {
  75. 'id' => 'date',
  76. 'date' => 'pubdate',
  77. 'lastUserModified' => 'userdate',
  78. default => throw new InvalidArgumentException('Unsupported sort criterion for transition: ' . FreshRSS_Context::$sort),
  79. };
  80. $offset = FreshRSS_Context::$order === 'ASC' ? $offset : -$offset;
  81. $timestamp = match (FreshRSS_Context::$sort) {
  82. 'id' => $entry->dateAdded(raw: true),
  83. 'date' => $entry->date(raw: true),
  84. 'lastUserModified' => $entry->lastUserModified() ?? 0,
  85. };
  86. $searchString = $operator . ':' . ($offset < 0 ? '/' : '') . date('Y-m-d', $timestamp + ($offset * 86400)) . ($offset > 0 ? '/' : '');
  87. return Minz_Url::display(Minz_Request::modifiedCurrentRequest([
  88. 'search' => FreshRSS_Context::$search->toString() === '' ? $searchString :
  89. FreshRSS_Context::$search->enforce(new FreshRSS_Search($searchString))->toString(),
  90. ]));
  91. }
  92. /**
  93. * This action displays the normal view of FreshRSS.
  94. */
  95. public function normalAction(): void {
  96. if (!FreshRSS_Auth::hasAccess() && !FreshRSS_Auth::allowAnonymous()) {
  97. if (Minz_Request::paramString('user') !== '') {
  98. Minz_Error::error(403, redirect: false);
  99. } else {
  100. Minz_Request::forward(['c' => 'auth', 'a' => 'login']);
  101. }
  102. return;
  103. }
  104. $id = Minz_Request::paramInt('id');
  105. if ($id !== 0) {
  106. if (Minz_Request::paramString('type') === 'tag') {
  107. $tagDAO = FreshRSS_Factory::createTagDao();
  108. $tag = $tagDAO->searchById($id);
  109. $this->view->tag = $tag;
  110. } else {
  111. $feedDAO = FreshRSS_Factory::createFeedDao();
  112. $feed = $feedDAO->searchById($id);
  113. $this->view->feed = $feed;
  114. }
  115. $this->view->displaySlider = true;
  116. $this->view->cfrom = Minz_Request::actionName();
  117. }
  118. try {
  119. FreshRSS_Context::updateUsingRequest(true);
  120. } catch (FreshRSS_Context_Exception $e) {
  121. Minz_Error::error(404);
  122. }
  123. $this->_csp([
  124. 'default-src' => "'self'",
  125. 'frame-src' => '*',
  126. 'img-src' => '* data: blob:',
  127. 'frame-ancestors' => FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'",
  128. 'media-src' => '*',
  129. ]);
  130. $this->view->categories = FreshRSS_Context::categories();
  131. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  132. $title = FreshRSS_Context::$name;
  133. $search = FreshRSS_Context::$search->toString(expandUserQueries: false);
  134. if ($search !== '') {
  135. $title = '“' . htmlspecialchars($search, ENT_COMPAT, 'UTF-8') . '”';
  136. }
  137. if (FreshRSS_Context::userConf()->show_title_unread && FreshRSS_Context::$get_unread > 0) {
  138. $title = '(' . format_number(FreshRSS_Context::$get_unread) . ') ' . $title;
  139. }
  140. if (strlen($title) > 0) {
  141. FreshRSS_View::prependTitle($title . ' · ');
  142. }
  143. if (FreshRSS_Context::$id_max === '0') {
  144. FreshRSS_Context::$id_max = uTimeString();
  145. }
  146. $this->view->callbackBeforeFeeds = static function (FreshRSS_View $view) {
  147. $view->nbUnreadTags = 0;
  148. if (Minz_Request::paramBoolean('ajax')) {
  149. // Disable label counts for AJAX requests: faster and not needed
  150. $view->tags = FreshRSS_Context::labels(precounts: false);
  151. return;
  152. }
  153. $view->tags = FreshRSS_Context::labels(precounts: true);
  154. foreach ($view->tags as $tag) {
  155. $view->nbUnreadTags += $tag->nbUnread();
  156. }
  157. };
  158. $this->view->callbackBeforeEntries = static function (FreshRSS_View $view) {
  159. try {
  160. // +1 to account for paging logic
  161. $view->entries = FreshRSS_index_Controller::listEntriesByContext(FreshRSS_Context::$number + 1);
  162. if (!$view->entries->valid()) { // Init the generator to catch potential exceptions
  163. $view->entries = new EmptyIterator();
  164. }
  165. ob_start(); //Buffer "one entry at a time"
  166. } catch (FreshRSS_EntriesGetter_Exception $e) {
  167. Minz_Log::notice($e->getMessage());
  168. Minz_Error::error(404);
  169. }
  170. };
  171. $this->view->callbackBeforePagination = static function (?FreshRSS_View $view, int $nbEntries, FreshRSS_Entry $lastEntry) {
  172. if ($nbEntries > FreshRSS_Context::$number) {
  173. //We have enough entries: we discard the last one to use it for the next articles' page
  174. ob_clean();
  175. FreshRSS_Context::$continuation_id = $lastEntry->id();
  176. } else {
  177. FreshRSS_Context::$continuation_id = '0';
  178. }
  179. ob_end_flush();
  180. };
  181. }
  182. /**
  183. * This action displays the reader view of FreshRSS.
  184. *
  185. * @todo: change this view into specific CSS rules?
  186. */
  187. public function readerAction(): void {
  188. $this->normalAction();
  189. }
  190. /**
  191. * This action displays the global view of FreshRSS.
  192. */
  193. public function globalAction(): void {
  194. if (!FreshRSS_Auth::hasAccess() && !FreshRSS_Auth::allowAnonymous()) {
  195. if (Minz_Request::paramString('user') !== '') {
  196. Minz_Error::error(403, redirect: false);
  197. } else {
  198. Minz_Request::forward(['c' => 'auth', 'a' => 'login']);
  199. }
  200. return;
  201. }
  202. FreshRSS_View::appendScript(Minz_Url::display('/scripts/extra.js?' . @filemtime(PUBLIC_PATH . '/scripts/extra.js')));
  203. FreshRSS_View::appendScript(Minz_Url::display('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js')));
  204. try {
  205. FreshRSS_Context::updateUsingRequest(true);
  206. } catch (FreshRSS_Context_Exception) {
  207. Minz_Error::error(404);
  208. }
  209. $this->view->categories = FreshRSS_Context::categories();
  210. // Filter feed list when searching or when a restrictive state filter is active
  211. if (FreshRSS_Context::$search->toString() !== '' || FreshRSS_Context::isStateConsequential(FreshRSS_Context::$state)) {
  212. $entryDAO = FreshRSS_Factory::createEntryDao();
  213. $this->view->feedIdsMatching = $entryDAO->listFeedIdsMatching(FreshRSS_Context::$state, FreshRSS_Context::$search);
  214. }
  215. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  216. $title = _t('index.feed.title_global');
  217. if (FreshRSS_Context::userConf()->show_title_unread && FreshRSS_Context::$get_unread > 0) {
  218. $title = '(' . format_number(FreshRSS_Context::$get_unread) . ') ' . $title;
  219. }
  220. FreshRSS_View::prependTitle($title . ' · ');
  221. $this->_csp([
  222. 'default-src' => "'self'",
  223. 'frame-src' => '*',
  224. 'img-src' => '* data: blob:',
  225. 'frame-ancestors' => FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'",
  226. 'media-src' => '*',
  227. ]);
  228. }
  229. /**
  230. * This action displays the RSS feed of FreshRSS.
  231. * @deprecated See user query RSS sharing instead
  232. */
  233. public function rssAction(): void {
  234. // Check if user has access.
  235. if (!FreshRSS_Auth::hasAccess() && !FreshRSS_Auth::allowAnonymous() && !Minz_Request::tokenIsOk()) {
  236. Minz_Error::error(403, redirect: false);
  237. return;
  238. }
  239. try {
  240. FreshRSS_Context::updateUsingRequest(false);
  241. } catch (FreshRSS_Context_Exception $e) {
  242. Minz_Error::error(404);
  243. }
  244. try {
  245. $this->view->entries = FreshRSS_index_Controller::listEntriesByContext();
  246. if (!$this->view->entries->valid()) { // Init the generator to catch potential exceptions
  247. $this->view->entries = new EmptyIterator();
  248. }
  249. } catch (FreshRSS_EntriesGetter_Exception $e) {
  250. Minz_Log::notice($e->getMessage());
  251. Minz_Error::error(404);
  252. }
  253. $this->view->html_url = Minz_Url::display('', 'html', true);
  254. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  255. $queryString = $_SERVER['QUERY_STRING'] ?? '';
  256. $this->view->rss_url = htmlspecialchars(
  257. PUBLIC_TO_INDEX_PATH . '/' . ($queryString === '' || !is_string($queryString) ? '' : '?' . $queryString), ENT_COMPAT, 'UTF-8');
  258. // No layout for RSS output.
  259. $this->view->_layout(null);
  260. header('Content-Type: application/rss+xml; charset=utf-8');
  261. }
  262. public function opmlAction(): void {
  263. // Check if user has access.
  264. if (!FreshRSS_Auth::hasAccess() && !FreshRSS_Auth::allowAnonymous() && !Minz_Request::tokenIsOk()) {
  265. Minz_Error::error(403, redirect: false);
  266. return;
  267. }
  268. try {
  269. FreshRSS_Context::updateUsingRequest(false);
  270. } catch (FreshRSS_Context_Exception) {
  271. Minz_Error::error(404);
  272. }
  273. $get = FreshRSS_Context::currentGet(true);
  274. $type = (string)$get[0];
  275. $id = (int)$get[1];
  276. $this->view->excludeMutedFeeds = $type !== 'f'; // Exclude muted feeds except when we focus on a feed
  277. switch ($type) {
  278. case 'a': // All PRIORITY_MAIN_STREAM
  279. case 'A': // All except PRIORITY_HIDDEN
  280. case 'Z': // All including PRIORITY_HIDDEN
  281. $this->view->categories = FreshRSS_Context::categories();
  282. break;
  283. case 'c': // Category
  284. $cat = FreshRSS_Context::categories()[$id] ?? null;
  285. if ($cat == null) {
  286. Minz_Error::error(404);
  287. return;
  288. }
  289. $this->view->categories = [$cat->id() => $cat];
  290. break;
  291. case 'f': // Feed
  292. // We most likely already have the feed object in cache
  293. $feed = FreshRSS_Category::findFeed(FreshRSS_Context::categories(), $id);
  294. if ($feed === null) {
  295. $feedDAO = FreshRSS_Factory::createFeedDao();
  296. $feed = $feedDAO->searchById($id);
  297. if ($feed == null) {
  298. Minz_Error::error(404);
  299. return;
  300. }
  301. }
  302. $this->view->feeds = [$feed->id() => $feed];
  303. break;
  304. default:
  305. Minz_Error::error(404);
  306. return;
  307. }
  308. // No layout for OPML output.
  309. $this->view->_layout(null);
  310. header('Content-Type: application/xml; charset=utf-8');
  311. }
  312. /**
  313. * This method returns a list of entries based on the Context object.
  314. * @param int $postsPerPage override `FreshRSS_Context::$number`
  315. * @return Generator<FreshRSS_Entry>
  316. * @throws FreshRSS_EntriesGetter_Exception
  317. */
  318. public static function listEntriesByContext(?int $postsPerPage = null): Generator {
  319. $entryDAO = FreshRSS_Factory::createEntryDao();
  320. $get = FreshRSS_Context::currentGet(true);
  321. if (is_array($get)) {
  322. $type = $get[0];
  323. $id = (int)($get[1]);
  324. } else {
  325. $type = $get;
  326. $id = 0;
  327. }
  328. $id_min = '0';
  329. if (FreshRSS_Context::$sinceHours > 0) {
  330. $id_min = (time() - (FreshRSS_Context::$sinceHours * 3600)) . '000000';
  331. }
  332. $continuation_values = [];
  333. if (FreshRSS_Context::$continuation_id !== '0') {
  334. if (in_array(FreshRSS_Context::$sort, ['c.name', 'date', 'f.name', 'link', 'title', 'lastUserModified', 'length'], true)) {
  335. $pagingEntry = $entryDAO->searchById(FreshRSS_Context::$continuation_id);
  336. if ($pagingEntry !== null && in_array(FreshRSS_Context::$sort, ['c.name', 'f.name'], true)) {
  337. // We most likely already have the feed object in cache
  338. $feed = FreshRSS_Category::findFeed(FreshRSS_Context::categories(), $pagingEntry->feedId());
  339. if ($feed !== null) {
  340. $pagingEntry->_feed($feed);
  341. }
  342. }
  343. $continuation_values[] = $pagingEntry === null ? 0 : match (FreshRSS_Context::$sort) {
  344. 'c.name' => $pagingEntry->feed()?->categoryId() === FreshRSS_CategoryDAO::DEFAULTCATEGORYID ?
  345. FreshRSS_CategoryDAO::DEFAULT_CATEGORY_NAME : $pagingEntry->feed()?->category()?->name() ?? '',
  346. 'date' => $pagingEntry->date(raw: true),
  347. 'f.name' => $pagingEntry->feed()?->name(raw: true) ?? '',
  348. 'link' => $pagingEntry->link(raw: true),
  349. 'title' => $pagingEntry->title(),
  350. 'lastUserModified' => $pagingEntry->lastUserModified() ?? 0,
  351. 'length' => $pagingEntry->sqlContentLength() ?? 0,
  352. };
  353. if (FreshRSS_Context::$sort === 'c.name') {
  354. // Internal secondary sort criterion for category name
  355. $continuation_values[] = $pagingEntry?->feed()?->name(raw: true) ?? '';
  356. }
  357. if (in_array(FreshRSS_Context::$sort, ['c.name', 'f.name'], true)) {
  358. // User secondary sort criterion
  359. $continuation_values[] = $pagingEntry === null ? 0 : match (FreshRSS_Context::$secondary_sort) {
  360. 'id' => $pagingEntry->id(),
  361. 'date' => $pagingEntry->date(raw: true),
  362. 'link' => $pagingEntry->link(raw: true),
  363. 'title' => $pagingEntry->title(),
  364. };
  365. }
  366. } elseif (FreshRSS_Context::$sort === 'rand') {
  367. FreshRSS_Context::$continuation_id = '0';
  368. }
  369. }
  370. yield from $entryDAO->listWhere(
  371. $type, $id, FreshRSS_Context::$state, FreshRSS_Context::$search,
  372. id_min: $id_min, id_max: FreshRSS_Context::$id_max, sort: FreshRSS_Context::$sort, order: FreshRSS_Context::$order,
  373. continuation_id: FreshRSS_Context::$continuation_id, continuation_values: $continuation_values,
  374. limit: $postsPerPage ?? FreshRSS_Context::$number, offset: FreshRSS_Context::$offset,
  375. secondary_sort: FreshRSS_Context::$secondary_sort, secondary_sort_order: FreshRSS_Context::$secondary_sort_order);
  376. }
  377. /**
  378. * This action displays the about page of FreshRSS.
  379. */
  380. public function aboutAction(): void {
  381. FreshRSS_View::prependTitle(_t('index.about.title') . ' · ');
  382. }
  383. /**
  384. * This action displays the EULA/TOS (Terms of Service) page of FreshRSS.
  385. * This page is enabled only if admin created a data/tos.html file.
  386. * The content of the page is the content of data/tos.html.
  387. * It returns 404 if there is no EULA/TOS.
  388. */
  389. public function tosAction(): void {
  390. $terms_of_service = file_get_contents(TOS_FILENAME);
  391. if ($terms_of_service === false) {
  392. Minz_Error::error(404);
  393. return;
  394. }
  395. $this->view->terms_of_service = $terms_of_service;
  396. $this->view->can_register = !FreshRSS_user_Controller::max_registrations_reached();
  397. FreshRSS_View::prependTitle(_t('index.tos.title') . ' · ');
  398. }
  399. /**
  400. * This action displays logs of FreshRSS for the current user.
  401. */
  402. public function logsAction(): void {
  403. if (!FreshRSS_Auth::hasAccess()) {
  404. Minz_Error::error(403);
  405. }
  406. FreshRSS_View::prependTitle(_t('index.log.title') . ' · ');
  407. if (Minz_Request::isPost()) {
  408. FreshRSS_LogDAO::truncate();
  409. }
  410. $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines
  411. $search = trim(Minz_Request::paramString('search', plaintext: true));
  412. if ($search !== '') {
  413. $logs = array_values(array_filter($logs, static fn(FreshRSS_Log $log): bool =>
  414. stripos($log->level(), $search) !== false ||
  415. stripos($log->date(), $search) !== false ||
  416. stripos($log->info(), $search) !== false));
  417. }
  418. $this->view->logSearch = $search;
  419. //gestion pagination
  420. $page = Minz_Request::paramInt('page') ?: 1;
  421. $this->view->logsPaginator = new Minz_Paginator($logs);
  422. $this->view->logsPaginator->_nbItemsPerPage(50);
  423. $this->view->logsPaginator->_currentPage($page);
  424. }
  425. }