indexController.php 13 KB

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