indexController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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(), mayBeFuture: false)) .
  56. ' — ' . timestamptodate($entry->lastUserModified(), 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(),
  85. default => throw new InvalidArgumentException('Unsupported sort criterion for transition: ' . FreshRSS_Context::$sort),
  86. };
  87. $searchString = $operator . ':' . ($offset < 0 ? '/' : '') . date('Y-m-d', $timestamp + ($offset * 86400)) . ($offset > 0 ? '/' : '');
  88. return Minz_Url::display(Minz_Request::modifiedCurrentRequest([
  89. 'search' => FreshRSS_Context::$search->__toString() === '' ? $searchString :
  90. FreshRSS_Context::$search->enforce(new FreshRSS_Search($searchString))->__toString(),
  91. ]));
  92. }
  93. /**
  94. * This action displays the normal view of FreshRSS.
  95. */
  96. public function normalAction(): void {
  97. $allow_anonymous = FreshRSS_Context::systemConf()->allow_anonymous;
  98. if (!FreshRSS_Auth::hasAccess() && !$allow_anonymous) {
  99. Minz_Request::forward(['c' => 'auth', 'a' => 'login']);
  100. return;
  101. }
  102. $id = Minz_Request::paramInt('id');
  103. if ($id !== 0) {
  104. $view = Minz_Request::paramString('a');
  105. $url_redirect = ['c' => 'subscription', 'a' => 'feed', 'params' => ['id' => (string)$id, 'from' => $view]];
  106. Minz_Request::forward($url_redirect, true);
  107. return;
  108. }
  109. try {
  110. FreshRSS_Context::updateUsingRequest(true);
  111. } catch (FreshRSS_Context_Exception $e) {
  112. Minz_Error::error(404);
  113. }
  114. $this->_csp([
  115. 'default-src' => "'self'",
  116. 'frame-src' => '*',
  117. 'img-src' => '* data: blob:',
  118. 'frame-ancestors' => FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'",
  119. 'media-src' => '*',
  120. ]);
  121. $this->view->categories = FreshRSS_Context::categories();
  122. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  123. $title = FreshRSS_Context::$name;
  124. $search = FreshRSS_Context::$search->__toString();
  125. if ($search !== '') {
  126. $title = '“' . htmlspecialchars($search, ENT_COMPAT, 'UTF-8') . '”';
  127. }
  128. if (FreshRSS_Context::$get_unread > 0) {
  129. $title = '(' . FreshRSS_Context::$get_unread . ') ' . $title;
  130. }
  131. FreshRSS_View::prependTitle($title . ' · ');
  132. if (FreshRSS_Context::$id_max === '0') {
  133. FreshRSS_Context::$id_max = uTimeString();
  134. }
  135. $this->view->callbackBeforeFeeds = static function (FreshRSS_View $view) {
  136. $view->tags = FreshRSS_Context::labels(true);
  137. $view->nbUnreadTags = 0;
  138. foreach ($view->tags as $tag) {
  139. $view->nbUnreadTags += $tag->nbUnread();
  140. }
  141. };
  142. $this->view->callbackBeforeEntries = static function (FreshRSS_View $view) {
  143. try {
  144. // +1 to account for paging logic
  145. $view->entries = FreshRSS_index_Controller::listEntriesByContext(FreshRSS_Context::$number + 1);
  146. ob_start(); //Buffer "one entry at a time"
  147. } catch (FreshRSS_EntriesGetter_Exception $e) {
  148. Minz_Log::notice($e->getMessage());
  149. Minz_Error::error(404);
  150. }
  151. };
  152. $this->view->callbackBeforePagination = static function (?FreshRSS_View $view, int $nbEntries, FreshRSS_Entry $lastEntry) {
  153. if ($nbEntries > FreshRSS_Context::$number) {
  154. //We have enough entries: we discard the last one to use it for the next articles' page
  155. ob_clean();
  156. FreshRSS_Context::$continuation_id = $lastEntry->id();
  157. } else {
  158. FreshRSS_Context::$continuation_id = '0';
  159. }
  160. ob_end_flush();
  161. };
  162. }
  163. /**
  164. * This action displays the reader view of FreshRSS.
  165. *
  166. * @todo: change this view into specific CSS rules?
  167. */
  168. public function readerAction(): void {
  169. $this->normalAction();
  170. }
  171. /**
  172. * This action displays the global view of FreshRSS.
  173. */
  174. public function globalAction(): void {
  175. $allow_anonymous = FreshRSS_Context::systemConf()->allow_anonymous;
  176. if (!FreshRSS_Auth::hasAccess() && !$allow_anonymous) {
  177. Minz_Request::forward(['c' => 'auth', 'a' => 'login']);
  178. return;
  179. }
  180. FreshRSS_View::appendScript(Minz_Url::display('/scripts/extra.js?' . @filemtime(PUBLIC_PATH . '/scripts/extra.js')));
  181. FreshRSS_View::appendScript(Minz_Url::display('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js')));
  182. try {
  183. FreshRSS_Context::updateUsingRequest(true);
  184. } catch (FreshRSS_Context_Exception) {
  185. Minz_Error::error(404);
  186. }
  187. $this->view->categories = FreshRSS_Context::categories();
  188. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  189. $title = _t('index.feed.title_global');
  190. if (FreshRSS_Context::$get_unread > 0) {
  191. $title = '(' . FreshRSS_Context::$get_unread . ') ' . $title;
  192. }
  193. FreshRSS_View::prependTitle($title . ' · ');
  194. $this->_csp([
  195. 'default-src' => "'self'",
  196. 'frame-src' => '*',
  197. 'img-src' => '* data: blob:',
  198. 'frame-ancestors' => FreshRSS_Context::systemConf()->attributeString('csp.frame-ancestors') ?? "'none'",
  199. 'media-src' => '*',
  200. ]);
  201. }
  202. /**
  203. * This action displays the RSS feed of FreshRSS.
  204. */
  205. #[Deprecated('See user query RSS sharing instead')]
  206. public function rssAction(): void {
  207. $allow_anonymous = FreshRSS_Context::systemConf()->allow_anonymous;
  208. // Check if user has access.
  209. if (!FreshRSS_Auth::hasAccess() && !$allow_anonymous) {
  210. Minz_Error::error(403);
  211. }
  212. try {
  213. FreshRSS_Context::updateUsingRequest(false);
  214. } catch (FreshRSS_Context_Exception $e) {
  215. Minz_Error::error(404);
  216. }
  217. try {
  218. $this->view->entries = FreshRSS_index_Controller::listEntriesByContext();
  219. } catch (FreshRSS_EntriesGetter_Exception $e) {
  220. Minz_Log::notice($e->getMessage());
  221. Minz_Error::error(404);
  222. }
  223. $this->view->html_url = Minz_Url::display('', 'html', true);
  224. $this->view->rss_title = FreshRSS_Context::$name . ' | ' . FreshRSS_View::title();
  225. $queryString = $_SERVER['QUERY_STRING'] ?? '';
  226. $this->view->rss_url = htmlspecialchars(
  227. PUBLIC_TO_INDEX_PATH . '/' . ($queryString === '' || !is_string($queryString) ? '' : '?' . $queryString), ENT_COMPAT, 'UTF-8');
  228. // No layout for RSS output.
  229. $this->view->_layout(null);
  230. header('Content-Type: application/rss+xml; charset=utf-8');
  231. }
  232. #[Deprecated('See user query OPML sharing instead')]
  233. public function opmlAction(): void {
  234. $allow_anonymous = FreshRSS_Context::systemConf()->allow_anonymous;
  235. // Check if user has access.
  236. if (!FreshRSS_Auth::hasAccess() && !$allow_anonymous) {
  237. Minz_Error::error(403);
  238. }
  239. try {
  240. FreshRSS_Context::updateUsingRequest(false);
  241. } catch (FreshRSS_Context_Exception) {
  242. Minz_Error::error(404);
  243. }
  244. $get = FreshRSS_Context::currentGet(true);
  245. $type = (string)$get[0];
  246. $id = (int)$get[1];
  247. $this->view->excludeMutedFeeds = $type !== 'f'; // Exclude muted feeds except when we focus on a feed
  248. switch ($type) {
  249. case 'a': // All PRIORITY_MAIN_STREAM
  250. case 'A': // All except PRIORITY_HIDDEN
  251. case 'Z': // All including PRIORITY_HIDDEN
  252. $this->view->categories = FreshRSS_Context::categories();
  253. break;
  254. case 'c':
  255. $cat = FreshRSS_Context::categories()[$id] ?? null;
  256. if ($cat == null) {
  257. Minz_Error::error(404);
  258. return;
  259. }
  260. $this->view->categories = [$cat->id() => $cat];
  261. break;
  262. case 'f':
  263. // We most likely already have the feed object in cache
  264. $feed = FreshRSS_Category::findFeed(FreshRSS_Context::categories(), $id);
  265. if ($feed === null) {
  266. $feedDAO = FreshRSS_Factory::createFeedDao();
  267. $feed = $feedDAO->searchById($id);
  268. if ($feed == null) {
  269. Minz_Error::error(404);
  270. return;
  271. }
  272. }
  273. $this->view->feeds = [$feed->id() => $feed];
  274. break;
  275. case 's':
  276. case 't':
  277. case 'T':
  278. default:
  279. Minz_Error::error(404);
  280. return;
  281. }
  282. // No layout for OPML output.
  283. $this->view->_layout(null);
  284. header('Content-Type: application/xml; charset=utf-8');
  285. }
  286. /**
  287. * This method returns a list of entries based on the Context object.
  288. * @param int $postsPerPage override `FreshRSS_Context::$number`
  289. * @return Traversable<FreshRSS_Entry>
  290. * @throws FreshRSS_EntriesGetter_Exception
  291. */
  292. public static function listEntriesByContext(?int $postsPerPage = null): Traversable {
  293. $entryDAO = FreshRSS_Factory::createEntryDao();
  294. $get = FreshRSS_Context::currentGet(true);
  295. if (is_array($get)) {
  296. $type = $get[0];
  297. $id = (int)($get[1]);
  298. } else {
  299. $type = $get;
  300. $id = 0;
  301. }
  302. $id_min = '0';
  303. if (FreshRSS_Context::$sinceHours > 0) {
  304. $id_min = (time() - (FreshRSS_Context::$sinceHours * 3600)) . '000000';
  305. }
  306. $continuation_values = [];
  307. if (FreshRSS_Context::$continuation_id !== '0') {
  308. if (in_array(FreshRSS_Context::$sort, ['c.name', 'date', 'f.name', 'link', 'title', 'lastUserModified', 'length'], true)) {
  309. $pagingEntry = $entryDAO->searchById(FreshRSS_Context::$continuation_id);
  310. if ($pagingEntry !== null && in_array(FreshRSS_Context::$sort, ['c.name', 'f.name'], true)) {
  311. // We most likely already have the feed object in cache
  312. $feed = FreshRSS_Category::findFeed(FreshRSS_Context::categories(), $pagingEntry->feedId());
  313. if ($feed !== null) {
  314. $pagingEntry->_feed($feed);
  315. }
  316. }
  317. $continuation_values[] = $pagingEntry === null ? 0 : match (FreshRSS_Context::$sort) {
  318. 'c.name' => $pagingEntry->feed()?->categoryId() === FreshRSS_CategoryDAO::DEFAULTCATEGORYID ?
  319. FreshRSS_CategoryDAO::DEFAULT_CATEGORY_NAME : $pagingEntry->feed()?->category()?->name() ?? '',
  320. 'date' => $pagingEntry->date(raw: true),
  321. 'f.name' => $pagingEntry->feed()?->name() ?? '',
  322. 'link' => $pagingEntry->link(raw: true),
  323. 'title' => $pagingEntry->title(),
  324. 'lastUserModified' => $pagingEntry->lastUserModified(),
  325. 'length' => $pagingEntry->sqlContentLength() ?? 0,
  326. };
  327. if ($pagingEntry !== null && FreshRSS_Context::$sort === 'c.name') {
  328. // Secondary sort criterion
  329. $continuation_values[] = $pagingEntry->feed()?->name() ?? '';
  330. }
  331. } elseif (FreshRSS_Context::$sort === 'rand') {
  332. FreshRSS_Context::$continuation_id = '0';
  333. }
  334. }
  335. foreach ($entryDAO->listWhere(
  336. $type, $id, FreshRSS_Context::$state, FreshRSS_Context::$search,
  337. id_min: $id_min, id_max: FreshRSS_Context::$id_max, sort: FreshRSS_Context::$sort, order: FreshRSS_Context::$order,
  338. continuation_id: FreshRSS_Context::$continuation_id, continuation_values: $continuation_values,
  339. limit: $postsPerPage ?? FreshRSS_Context::$number, offset: FreshRSS_Context::$offset) as $entry) {
  340. yield $entry;
  341. }
  342. }
  343. /**
  344. * This action displays the about page of FreshRSS.
  345. */
  346. public function aboutAction(): void {
  347. FreshRSS_View::prependTitle(_t('index.about.title') . ' · ');
  348. }
  349. /**
  350. * This action displays the EULA/TOS (Terms of Service) page of FreshRSS.
  351. * This page is enabled only if admin created a data/tos.html file.
  352. * The content of the page is the content of data/tos.html.
  353. * It returns 404 if there is no EULA/TOS.
  354. */
  355. public function tosAction(): void {
  356. $terms_of_service = file_get_contents(TOS_FILENAME);
  357. if ($terms_of_service === false) {
  358. Minz_Error::error(404);
  359. return;
  360. }
  361. $this->view->terms_of_service = $terms_of_service;
  362. $this->view->can_register = !FreshRSS_user_Controller::max_registrations_reached();
  363. FreshRSS_View::prependTitle(_t('index.tos.title') . ' · ');
  364. }
  365. /**
  366. * This action displays logs of FreshRSS for the current user.
  367. */
  368. public function logsAction(): void {
  369. if (!FreshRSS_Auth::hasAccess()) {
  370. Minz_Error::error(403);
  371. }
  372. FreshRSS_View::prependTitle(_t('index.log.title') . ' · ');
  373. if (Minz_Request::isPost()) {
  374. FreshRSS_LogDAO::truncate();
  375. }
  376. $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines
  377. //gestion pagination
  378. $page = Minz_Request::paramInt('page') ?: 1;
  379. $this->view->logsPaginator = new Minz_Paginator($logs);
  380. $this->view->logsPaginator->_nbItemsPerPage(50);
  381. $this->view->logsPaginator->_currentPage($page);
  382. }
  383. }