indexController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. class FreshRSS_index_Controller extends Minz_ActionController {
  3. private $nb_not_read_cat = 0;
  4. public function indexAction () {
  5. $output = Minz_Request::param ('output');
  6. $token = $this->view->conf->token;
  7. // check if user is logged in
  8. if (!$this->view->loginOk && !Minz_Configuration::allowAnonymous()) {
  9. $token_param = Minz_Request::param ('token', '');
  10. $token_is_ok = ($token != '' && $token === $token_param);
  11. if ($output === 'rss' && !$token_is_ok) {
  12. Minz_Error::error (
  13. 403,
  14. array ('error' => array (Minz_Translate::t ('access_denied')))
  15. );
  16. return;
  17. } elseif ($output !== 'rss') {
  18. // "hard" redirection is not required, just ask dispatcher to
  19. // forward to the login form without 302 redirection
  20. Minz_Request::forward(array('c' => 'index', 'a' => 'formLogin'));
  21. return;
  22. }
  23. }
  24. $params = Minz_Request::params ();
  25. if (isset ($params['search'])) {
  26. $params['search'] = urlencode ($params['search']);
  27. }
  28. if (!Minz_Configuration::allowAnonymous()) {
  29. $params['token'] = $token;
  30. }
  31. $this->view->url = array (
  32. 'c' => 'index',
  33. 'a' => 'index',
  34. 'params' => $params
  35. );
  36. if ($output === 'rss') {
  37. // no layout for RSS output
  38. $this->view->_useLayout (false);
  39. header('Content-Type: application/rss+xml; charset=utf-8');
  40. } elseif ($output === 'global') {
  41. Minz_View::appendScript (Minz_Url::display ('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js')));
  42. }
  43. $catDAO = new FreshRSS_CategoryDAO();
  44. $entryDAO = new FreshRSS_EntryDAO();
  45. $this->view->cat_aside = $catDAO->listCategories ();
  46. $this->view->nb_favorites = $entryDAO->countUnreadReadFavorites ();
  47. $this->view->nb_not_read = FreshRSS_CategoryDAO::CountUnreads($this->view->cat_aside, 1);
  48. $this->view->currentName = '';
  49. $this->view->get_c = '';
  50. $this->view->get_f = '';
  51. $get = Minz_Request::param ('get', 'a');
  52. $getType = $get[0];
  53. $getId = substr ($get, 2);
  54. if (!$this->checkAndProcessType ($getType, $getId)) {
  55. Minz_Log::record ('Not found [' . $getType . '][' . $getId . ']', Minz_Log::DEBUG);
  56. Minz_Error::error (
  57. 404,
  58. array ('error' => array (Minz_Translate::t ('page_not_found')))
  59. );
  60. return;
  61. }
  62. // mise à jour des titres
  63. $this->view->rss_title = $this->view->currentName . ' | ' . Minz_View::title();
  64. if ($this->view->nb_not_read > 0) {
  65. Minz_View::appendTitle (' (' . formatNumber($this->view->nb_not_read) . ')');
  66. }
  67. Minz_View::prependTitle (
  68. $this->view->currentName .
  69. ($this->nb_not_read_cat > 0 ? ' (' . formatNumber($this->nb_not_read_cat) . ')' : '') .
  70. ' · '
  71. );
  72. // On récupère les différents éléments de filtrage
  73. $this->view->state = $state = Minz_Request::param ('state', $this->view->conf->default_view);
  74. $state_param = Minz_Request::param ('state', null);
  75. $filter = Minz_Request::param ('search', '');
  76. $this->view->order = $order = Minz_Request::param ('order', $this->view->conf->sort_order);
  77. $nb = Minz_Request::param ('nb', $this->view->conf->posts_per_page);
  78. $first = Minz_Request::param ('next', '');
  79. if ($state === FreshRSS_Entry::STATE_NOT_READ) { //Any unread article in this category at all?
  80. switch ($getType) {
  81. case 'a':
  82. $hasUnread = $this->view->nb_not_read > 0;
  83. break;
  84. case 's':
  85. // This is deprecated. The favorite button does not exist anymore
  86. $hasUnread = $this->view->nb_favorites['unread'] > 0;
  87. break;
  88. case 'c':
  89. $hasUnread = (!isset($this->view->cat_aside[$getId])) || ($this->view->cat_aside[$getId]->nbNotRead() > 0);
  90. break;
  91. case 'f':
  92. $myFeed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId);
  93. $hasUnread = ($myFeed === null) || ($myFeed->nbNotRead() > 0);
  94. break;
  95. default:
  96. $hasUnread = true;
  97. break;
  98. }
  99. if (!$hasUnread && ($state_param === null)) {
  100. $this->view->state = $state = FreshRSS_Entry::STATE_ALL;
  101. }
  102. }
  103. $today = @strtotime('today');
  104. $this->view->today = $today;
  105. // on calcule la date des articles les plus anciens qu'on affiche
  106. $nb_month_old = $this->view->conf->old_entries;
  107. $date_min = $today - (3600 * 24 * 30 * $nb_month_old); //Do not use a fast changing value such as time() to allow SQL caching
  108. $keepHistoryDefault = $this->view->conf->keep_history_default;
  109. try {
  110. $entries = $entryDAO->listWhere($getType, $getId, $state, $order, $nb + 1, $first, $filter, $date_min, true, $keepHistoryDefault);
  111. // Si on a récupéré aucun article "non lus"
  112. // on essaye de récupérer tous les articles
  113. if ($state === FreshRSS_Entry::STATE_NOT_READ && empty($entries) && ($state_param === null)) {
  114. Minz_Log::record ('Conflicting information about nbNotRead!', Minz_Log::DEBUG);
  115. $this->view->state = FreshRSS_Entry::STATE_ALL;
  116. $entries = $entryDAO->listWhere($getType, $getId, $this->view->state, $order, $nb, $first, $filter, $date_min, true, $keepHistoryDefault);
  117. }
  118. if (count($entries) <= $nb) {
  119. $this->view->nextId = '';
  120. } else { //We have more elements for pagination
  121. $lastEntry = array_pop($entries);
  122. $this->view->nextId = $lastEntry->id();
  123. }
  124. $this->view->entries = $entries;
  125. } catch (FreshRSS_EntriesGetter_Exception $e) {
  126. Minz_Log::record ($e->getMessage (), Minz_Log::NOTICE);
  127. Minz_Error::error (
  128. 404,
  129. array ('error' => array (Minz_Translate::t ('page_not_found')))
  130. );
  131. }
  132. }
  133. /*
  134. * Vérifie que la catégorie / flux sélectionné existe
  135. * + Initialise correctement les variables de vue get_c et get_f
  136. * + Met à jour la variable $this->nb_not_read_cat
  137. */
  138. private function checkAndProcessType ($getType, $getId) {
  139. switch ($getType) {
  140. case 'a':
  141. $this->view->currentName = Minz_Translate::t ('your_rss_feeds');
  142. $this->nb_not_read_cat = $this->view->nb_not_read;
  143. $this->view->get_c = $getType;
  144. return true;
  145. case 's':
  146. $this->view->currentName = Minz_Translate::t ('your_favorites');
  147. $this->nb_not_read_cat = $this->view->nb_favorites['unread'];
  148. $this->view->get_c = $getType;
  149. return true;
  150. case 'c':
  151. $cat = isset($this->view->cat_aside[$getId]) ? $this->view->cat_aside[$getId] : null;
  152. if ($cat === null) {
  153. $catDAO = new FreshRSS_CategoryDAO();
  154. $cat = $catDAO->searchById($getId);
  155. }
  156. if ($cat) {
  157. $this->view->currentName = $cat->name ();
  158. $this->nb_not_read_cat = $cat->nbNotRead ();
  159. $this->view->get_c = $getId;
  160. return true;
  161. } else {
  162. return false;
  163. }
  164. case 'f':
  165. $feed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId);
  166. if (empty($feed)) {
  167. $feedDAO = new FreshRSS_FeedDAO();
  168. $feed = $feedDAO->searchById($getId);
  169. }
  170. if ($feed) {
  171. $this->view->currentName = $feed->name ();
  172. $this->nb_not_read_cat = $feed->nbNotRead ();
  173. $this->view->get_f = $getId;
  174. $this->view->get_c = $feed->category ();
  175. return true;
  176. } else {
  177. return false;
  178. }
  179. default:
  180. return false;
  181. }
  182. }
  183. public function statsAction () {
  184. if (!$this->view->loginOk) {
  185. Minz_Error::error (
  186. 403,
  187. array ('error' => array (Minz_Translate::t ('access_denied')))
  188. );
  189. }
  190. Minz_View::prependTitle (Minz_Translate::t ('stats') . ' · ');
  191. $statsDAO = new FreshRSS_StatsDAO ();
  192. Minz_View::appendScript (Minz_Url::display ('/scripts/flotr2.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/flotr2.min.js')));
  193. $this->view->repartition = $statsDAO->calculateEntryRepartition();
  194. $this->view->count = ($statsDAO->calculateEntryCount());
  195. $this->view->feedByCategory = $statsDAO->calculateFeedByCategory();
  196. $this->view->entryByCategory = $statsDAO->calculateEntryByCategory();
  197. $this->view->topFeed = $statsDAO->calculateTopFeed();
  198. }
  199. public function aboutAction () {
  200. Minz_View::prependTitle (Minz_Translate::t ('about') . ' · ');
  201. }
  202. public function logsAction () {
  203. if (!$this->view->loginOk) {
  204. Minz_Error::error (
  205. 403,
  206. array ('error' => array (Minz_Translate::t ('access_denied')))
  207. );
  208. }
  209. Minz_View::prependTitle (Minz_Translate::t ('logs') . ' · ');
  210. if (Minz_Request::isPost ()) {
  211. FreshRSS_LogDAO::truncate();
  212. }
  213. $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines
  214. //gestion pagination
  215. $page = Minz_Request::param ('page', 1);
  216. $this->view->logsPaginator = new Minz_Paginator ($logs);
  217. $this->view->logsPaginator->_nbItemsPerPage (50);
  218. $this->view->logsPaginator->_currentPage ($page);
  219. }
  220. public function loginAction () {
  221. $this->view->_useLayout (false);
  222. $url = 'https://verifier.login.persona.org/verify';
  223. $assert = Minz_Request::param ('assertion');
  224. $params = 'assertion=' . $assert . '&audience=' .
  225. urlencode (Minz_Url::display (null, 'php', true));
  226. $ch = curl_init ();
  227. $options = array (
  228. CURLOPT_URL => $url,
  229. CURLOPT_RETURNTRANSFER => TRUE,
  230. CURLOPT_POST => 2,
  231. CURLOPT_POSTFIELDS => $params
  232. );
  233. curl_setopt_array ($ch, $options);
  234. $result = curl_exec ($ch);
  235. curl_close ($ch);
  236. $res = json_decode ($result, true);
  237. $loginOk = false;
  238. $reason = '';
  239. if ($res['status'] === 'okay') {
  240. $email = filter_var($res['email'], FILTER_VALIDATE_EMAIL);
  241. if ($email != '') {
  242. $personaFile = DATA_PATH . '/persona/' . $email . '.txt';
  243. if (($currentUser = @file_get_contents($personaFile)) !== false) {
  244. $currentUser = trim($currentUser);
  245. if (ctype_alnum($currentUser)) {
  246. try {
  247. $this->conf = new FreshRSS_Configuration($currentUser);
  248. $loginOk = strcasecmp($email, $this->conf->mail_login) === 0;
  249. } catch (Minz_Exception $e) {
  250. $reason = 'Invalid configuration for user [' . $currentUser . ']! ' . $e->getMessage(); //Permission denied or conf file does not exist
  251. }
  252. } else {
  253. $reason = 'Invalid username format [' . $currentUser . ']!';
  254. }
  255. }
  256. } else {
  257. $reason = 'Invalid email format [' . $res['email'] . ']!';
  258. }
  259. }
  260. if ($loginOk) {
  261. Minz_Session::_param('currentUser', $currentUser);
  262. Minz_Session::_param ('mail', $email);
  263. $this->view->loginOk = true;
  264. invalidateHttpCache();
  265. } else {
  266. $res = array ();
  267. $res['status'] = 'failure';
  268. $res['reason'] = $reason == '' ? Minz_Translate::t ('invalid_login') : $reason;
  269. Minz_Log::record ('Persona: ' . $res['reason'], Minz_Log::WARNING);
  270. }
  271. header('Content-Type: application/json; charset=UTF-8');
  272. $this->view->res = json_encode ($res);
  273. }
  274. public function logoutAction () {
  275. $this->view->_useLayout(false);
  276. invalidateHttpCache();
  277. Minz_Session::_param('currentUser');
  278. Minz_Session::_param('mail');
  279. Minz_Session::_param('passwordHash');
  280. }
  281. public function formLoginAction () {
  282. if (Minz_Request::isPost()) {
  283. $ok = false;
  284. $nonce = Minz_Session::param('nonce');
  285. $username = Minz_Request::param('username', '');
  286. $c = Minz_Request::param('challenge', '');
  287. if (ctype_alnum($username) && ctype_graph($c) && ctype_alnum($nonce)) {
  288. if (!function_exists('password_verify')) {
  289. include_once(LIB_PATH . '/password_compat.php');
  290. }
  291. try {
  292. $conf = new FreshRSS_Configuration($username);
  293. $s = $conf->passwordHash;
  294. $ok = password_verify($nonce . $s, $c);
  295. if ($ok) {
  296. Minz_Session::_param('currentUser', $username);
  297. Minz_Session::_param('passwordHash', $s);
  298. } else {
  299. Minz_Log::record('Password mismatch for user ' . $username . ', nonce=' . $nonce . ', c=' . $c, Minz_Log::WARNING);
  300. }
  301. } catch (Minz_Exception $me) {
  302. Minz_Log::record('Login failure: ' . $me->getMessage(), Minz_Log::WARNING);
  303. }
  304. } else {
  305. Minz_Log::record('Invalid credential parameters: user=' . $username . ' challenge=' . $c . ' nonce=' . $nonce, Minz_Log::DEBUG);
  306. }
  307. if (!$ok) {
  308. $notif = array(
  309. 'type' => 'bad',
  310. 'content' => Minz_Translate::t('invalid_login')
  311. );
  312. Minz_Session::_param('notification', $notif);
  313. }
  314. $this->view->_useLayout(false);
  315. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  316. } elseif (Minz_Configuration::unsafeAutologinEnabled() && isset($_GET['u']) && isset($_GET['p'])) {
  317. Minz_Session::_param('currentUser');
  318. Minz_Session::_param('mail');
  319. Minz_Session::_param('passwordHash');
  320. $username = ctype_alnum($_GET['u']) ? $_GET['u'] : '';
  321. $passwordPlain = $_GET['p'];
  322. Minz_Request::_param('p'); //Discard plain-text password ASAP
  323. $_GET['p'] = '';
  324. if (!function_exists('password_verify')) {
  325. include_once(LIB_PATH . '/password_compat.php');
  326. }
  327. try {
  328. $conf = new FreshRSS_Configuration($username);
  329. $s = $conf->passwordHash;
  330. $ok = password_verify($passwordPlain, $s);
  331. unset($passwordPlain);
  332. if ($ok) {
  333. Minz_Session::_param('currentUser', $username);
  334. Minz_Session::_param('passwordHash', $s);
  335. } else {
  336. Minz_Log::record('Unsafe password mismatch for user ' . $username, Minz_Log::WARNING);
  337. }
  338. } catch (Minz_Exception $me) {
  339. Minz_Log::record('Unsafe login failure: ' . $me->getMessage(), Minz_Log::WARNING);
  340. }
  341. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  342. } elseif (!Minz_Configuration::canLogIn()) {
  343. Minz_Error::error (
  344. 403,
  345. array ('error' => array (Minz_Translate::t ('access_denied')))
  346. );
  347. }
  348. invalidateHttpCache();
  349. }
  350. public function formLogoutAction () {
  351. $this->view->_useLayout(false);
  352. invalidateHttpCache();
  353. Minz_Session::_param('currentUser');
  354. Minz_Session::_param('mail');
  355. Minz_Session::_param('passwordHash');
  356. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  357. }
  358. }