indexController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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(_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. $this->view->url = array(
  29. 'c' => 'index',
  30. 'a' => 'index',
  31. 'params' => $params
  32. );
  33. if ($output === 'rss') {
  34. // no layout for RSS output
  35. $this->view->_useLayout(false);
  36. header('Content-Type: application/rss+xml; charset=utf-8');
  37. } elseif ($output === 'global') {
  38. Minz_View::appendScript(Minz_Url::display('/scripts/global_view.js?' . @filemtime(PUBLIC_PATH . '/scripts/global_view.js')));
  39. }
  40. $catDAO = new FreshRSS_CategoryDAO();
  41. $entryDAO = FreshRSS_Factory::createEntryDao();
  42. $this->view->cat_aside = $catDAO->listCategories();
  43. $this->view->nb_favorites = $entryDAO->countUnreadReadFavorites();
  44. $this->view->nb_not_read = FreshRSS_CategoryDAO::CountUnreads($this->view->cat_aside, 1);
  45. $this->view->currentName = '';
  46. $this->view->get_c = '';
  47. $this->view->get_f = '';
  48. $get = Minz_Request::param('get', 'a');
  49. $getType = $get[0];
  50. $getId = substr($get, 2);
  51. if (!$this->checkAndProcessType($getType, $getId)) {
  52. Minz_Log::debug('Not found [' . $getType . '][' . $getId . ']');
  53. Minz_Error::error(
  54. 404,
  55. array('error' => array(_t('page_not_found')))
  56. );
  57. return;
  58. }
  59. // mise à jour des titres
  60. $this->view->rss_title = $this->view->currentName . ' | ' . Minz_View::title();
  61. Minz_View::prependTitle(
  62. ($this->nb_not_read_cat > 0 ? '(' . formatNumber($this->nb_not_read_cat) . ') ' : '') .
  63. $this->view->currentName .
  64. ' · '
  65. );
  66. // On récupère les différents éléments de filtrage
  67. $this->view->state = Minz_Request::param('state', $this->view->conf->default_view);
  68. $state_param = Minz_Request::param('state', null);
  69. $filter = Minz_Request::param('search', '');
  70. $this->view->order = $order = Minz_Request::param('order', $this->view->conf->sort_order);
  71. $nb = Minz_Request::param('nb', $this->view->conf->posts_per_page);
  72. $first = Minz_Request::param('next', '');
  73. $ajax_request = Minz_Request::param('ajax', false);
  74. if ($output === 'reader') {
  75. $nb = max(1, round($nb / 2));
  76. }
  77. if ($this->view->state === FreshRSS_Entry::STATE_NOT_READ) { //Any unread article in this category at all?
  78. switch ($getType) {
  79. case 'a':
  80. $hasUnread = $this->view->nb_not_read > 0;
  81. break;
  82. case 's':
  83. // This is deprecated. The favorite button does not exist anymore
  84. $hasUnread = $this->view->nb_favorites['unread'] > 0;
  85. break;
  86. case 'c':
  87. $hasUnread = (!isset($this->view->cat_aside[$getId]) ||
  88. $this->view->cat_aside[$getId]->nbNotRead() > 0);
  89. break;
  90. case 'f':
  91. $myFeed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId);
  92. $hasUnread = ($myFeed === null) || ($myFeed->nbNotRead() > 0);
  93. break;
  94. default:
  95. $hasUnread = true;
  96. break;
  97. }
  98. if (!$hasUnread && ($state_param === null)) {
  99. $this->view->state = FreshRSS_Entry::STATE_ALL;
  100. }
  101. }
  102. $this->view->today = @strtotime('today');
  103. try {
  104. $entries = $entryDAO->listWhere($getType, $getId, $this->view->state, $order, $nb + 1, $first, $filter);
  105. // Si on a récupéré aucun article "non lus"
  106. // on essaye de récupérer tous les articles
  107. if ($this->view->state === FreshRSS_Entry::STATE_NOT_READ && empty($entries) && ($state_param === null) && ($filter == '')) {
  108. Minz_Log::debug('Conflicting information about nbNotRead!');
  109. $feedDAO = FreshRSS_Factory::createFeedDao();
  110. try {
  111. $feedDAO->updateCachedValues();
  112. } catch (Exception $ex) {
  113. Minz_Log::notice('Failed to automatically correct nbNotRead! ' + $ex->getMessage());
  114. }
  115. $this->view->state = FreshRSS_Entry::STATE_ALL;
  116. $entries = $entryDAO->listWhere($getType, $getId, $this->view->state, $order, $nb, $first, $filter);
  117. }
  118. Minz_Request::_param('state', $this->view->state);
  119. if (count($entries) <= $nb) {
  120. $this->view->nextId = '';
  121. } else { //We have more elements for pagination
  122. $lastEntry = array_pop($entries);
  123. $this->view->nextId = $lastEntry->id();
  124. }
  125. $this->view->entries = $entries;
  126. } catch (FreshRSS_EntriesGetter_Exception $e) {
  127. Minz_Log::notice($e->getMessage());
  128. Minz_Error::error(
  129. 404,
  130. array('error' => array(_t('page_not_found')))
  131. );
  132. }
  133. }
  134. /*
  135. * Vérifie que la catégorie / flux sélectionné existe
  136. * + Initialise correctement les variables de vue get_c et get_f
  137. * + Met à jour la variable $this->nb_not_read_cat
  138. */
  139. private function checkAndProcessType($getType, $getId) {
  140. switch($getType) {
  141. case 'a':
  142. $this->view->currentName = _t('your_rss_feeds');
  143. $this->nb_not_read_cat = $this->view->nb_not_read;
  144. $this->view->get_c = $getType;
  145. return true;
  146. case 's':
  147. $this->view->currentName = _t('your_favorites');
  148. $this->nb_not_read_cat = $this->view->nb_favorites['unread'];
  149. $this->view->get_c = $getType;
  150. return true;
  151. case 'c':
  152. $cat = isset($this->view->cat_aside[$getId]) ? $this->view->cat_aside[$getId] : null;
  153. if ($cat === null) {
  154. $catDAO = new FreshRSS_CategoryDAO();
  155. $cat = $catDAO->searchById($getId);
  156. }
  157. if ($cat) {
  158. $this->view->currentName = $cat->name();
  159. $this->nb_not_read_cat = $cat->nbNotRead();
  160. $this->view->get_c = $getId;
  161. return true;
  162. } else {
  163. return false;
  164. }
  165. case 'f':
  166. $feed = FreshRSS_CategoryDAO::findFeed($this->view->cat_aside, $getId);
  167. if (empty($feed)) {
  168. $feedDAO = FreshRSS_Factory::createFeedDao();
  169. $feed = $feedDAO->searchById($getId);
  170. }
  171. if ($feed) {
  172. $this->view->currentName = $feed->name();
  173. $this->nb_not_read_cat = $feed->nbNotRead();
  174. $this->view->get_f = $getId;
  175. $this->view->get_c = $feed->category();
  176. return true;
  177. } else {
  178. return false;
  179. }
  180. default:
  181. return false;
  182. }
  183. }
  184. public function aboutAction() {
  185. Minz_View::prependTitle(_t('about') . ' · ');
  186. }
  187. public function logsAction() {
  188. if (!$this->view->loginOk) {
  189. Minz_Error::error(
  190. 403,
  191. array('error' => array(_t('access_denied')))
  192. );
  193. }
  194. Minz_View::prependTitle(_t('logs') . ' · ');
  195. if (Minz_Request::isPost()) {
  196. FreshRSS_LogDAO::truncate();
  197. }
  198. $logs = FreshRSS_LogDAO::lines(); //TODO: ask only the necessary lines
  199. //gestion pagination
  200. $page = Minz_Request::param('page', 1);
  201. $this->view->logsPaginator = new Minz_Paginator($logs);
  202. $this->view->logsPaginator->_nbItemsPerPage(50);
  203. $this->view->logsPaginator->_currentPage($page);
  204. }
  205. public function loginAction() {
  206. $this->view->_useLayout(false);
  207. $url = 'https://verifier.login.persona.org/verify';
  208. $assert = Minz_Request::param('assertion');
  209. $params = 'assertion=' . $assert . '&audience=' .
  210. urlencode(Minz_Url::display(null, 'php', true));
  211. $ch = curl_init();
  212. $options = array(
  213. CURLOPT_URL => $url,
  214. CURLOPT_RETURNTRANSFER => TRUE,
  215. CURLOPT_POST => 2,
  216. CURLOPT_POSTFIELDS => $params
  217. );
  218. curl_setopt_array($ch, $options);
  219. $result = curl_exec($ch);
  220. curl_close($ch);
  221. $res = json_decode($result, true);
  222. $loginOk = false;
  223. $reason = '';
  224. if ($res['status'] === 'okay') {
  225. $email = filter_var($res['email'], FILTER_VALIDATE_EMAIL);
  226. if ($email != '') {
  227. $personaFile = DATA_PATH . '/persona/' . $email . '.txt';
  228. if (($currentUser = @file_get_contents($personaFile)) !== false) {
  229. $currentUser = trim($currentUser);
  230. if (ctype_alnum($currentUser)) {
  231. try {
  232. $this->conf = new FreshRSS_Configuration($currentUser);
  233. $loginOk = strcasecmp($email, $this->conf->mail_login) === 0;
  234. } catch (Minz_Exception $e) {
  235. $reason = 'Invalid configuration for user [' . $currentUser . ']! ' . $e->getMessage(); //Permission denied or conf file does not exist
  236. }
  237. } else {
  238. $reason = 'Invalid username format [' . $currentUser . ']!';
  239. }
  240. }
  241. } else {
  242. $reason = 'Invalid email format [' . $res['email'] . ']!';
  243. }
  244. }
  245. if ($loginOk) {
  246. Minz_Session::_param('currentUser', $currentUser);
  247. Minz_Session::_param('mail', $email);
  248. $this->view->loginOk = true;
  249. invalidateHttpCache();
  250. } else {
  251. $res = array();
  252. $res['status'] = 'failure';
  253. $res['reason'] = $reason == '' ? _t('invalid_login') : $reason;
  254. Minz_Log::warning('Persona: ' . $res['reason']);
  255. }
  256. header('Content-Type: application/json; charset=UTF-8');
  257. $this->view->res = json_encode($res);
  258. }
  259. public function logoutAction() {
  260. $this->view->_useLayout(false);
  261. invalidateHttpCache();
  262. Minz_Session::_param('currentUser');
  263. Minz_Session::_param('mail');
  264. Minz_Session::_param('passwordHash');
  265. }
  266. private static function makeLongTermCookie($username, $passwordHash) {
  267. do {
  268. $token = sha1(Minz_Configuration::salt() . $username . uniqid(mt_rand(), true));
  269. $tokenFile = DATA_PATH . '/tokens/' . $token . '.txt';
  270. } while (file_exists($tokenFile));
  271. if (@file_put_contents($tokenFile, $username . "\t" . $passwordHash) === false) {
  272. return false;
  273. }
  274. $expire = time() + 2629744; //1 month //TODO: Use a configuration instead
  275. Minz_Session::setLongTermCookie('FreshRSS_login', $token, $expire);
  276. Minz_Session::_param('token', $token);
  277. return $token;
  278. }
  279. private static function deleteLongTermCookie() {
  280. Minz_Session::deleteLongTermCookie('FreshRSS_login');
  281. $token = Minz_Session::param('token', null);
  282. if (ctype_alnum($token)) {
  283. @unlink(DATA_PATH . '/tokens/' . $token . '.txt');
  284. }
  285. Minz_Session::_param('token');
  286. if (rand(0, 10) === 1) {
  287. self::purgeTokens();
  288. }
  289. }
  290. private static function purgeTokens() {
  291. $oldest = time() - 2629744; //1 month //TODO: Use a configuration instead
  292. foreach (new DirectoryIterator(DATA_PATH . '/tokens/') as $fileInfo) {
  293. if ($fileInfo->getExtension() === 'txt' && $fileInfo->getMTime() < $oldest) {
  294. @unlink($fileInfo->getPathname());
  295. }
  296. }
  297. }
  298. public function formLoginAction() {
  299. if ($this->view->loginOk) {
  300. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  301. }
  302. if (Minz_Request::isPost()) {
  303. $ok = false;
  304. $nonce = Minz_Session::param('nonce');
  305. $username = Minz_Request::param('username', '');
  306. $c = Minz_Request::param('challenge', '');
  307. if (ctype_alnum($username) && ctype_graph($c) && ctype_alnum($nonce)) {
  308. if (!function_exists('password_verify')) {
  309. include_once(LIB_PATH . '/password_compat.php');
  310. }
  311. try {
  312. $conf = new FreshRSS_Configuration($username);
  313. $s = $conf->passwordHash;
  314. $ok = password_verify($nonce . $s, $c);
  315. if ($ok) {
  316. Minz_Session::_param('currentUser', $username);
  317. Minz_Session::_param('passwordHash', $s);
  318. if (Minz_Request::param('keep_logged_in', false)) {
  319. self::makeLongTermCookie($username, $s);
  320. } else {
  321. self::deleteLongTermCookie();
  322. }
  323. } else {
  324. Minz_Log::warning('Password mismatch for user ' . $username . ', nonce=' . $nonce . ', c=' . $c);
  325. }
  326. } catch (Minz_Exception $me) {
  327. Minz_Log::warning('Login failure: ' . $me->getMessage());
  328. }
  329. } else {
  330. Minz_Log::debug('Invalid credential parameters: user=' . $username . ' challenge=' . $c . ' nonce=' . $nonce);
  331. }
  332. if (!$ok) {
  333. $notif = array(
  334. 'type' => 'bad',
  335. 'content' => _t('invalid_login')
  336. );
  337. Minz_Session::_param('notification', $notif);
  338. }
  339. $this->view->_useLayout(false);
  340. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  341. } elseif (Minz_Configuration::unsafeAutologinEnabled() && isset($_GET['u']) && isset($_GET['p'])) {
  342. Minz_Session::_param('currentUser');
  343. Minz_Session::_param('mail');
  344. Minz_Session::_param('passwordHash');
  345. $username = ctype_alnum($_GET['u']) ? $_GET['u'] : '';
  346. $passwordPlain = $_GET['p'];
  347. Minz_Request::_param('p'); //Discard plain-text password ASAP
  348. $_GET['p'] = '';
  349. if (!function_exists('password_verify')) {
  350. include_once(LIB_PATH . '/password_compat.php');
  351. }
  352. try {
  353. $conf = new FreshRSS_Configuration($username);
  354. $s = $conf->passwordHash;
  355. $ok = password_verify($passwordPlain, $s);
  356. unset($passwordPlain);
  357. if ($ok) {
  358. Minz_Session::_param('currentUser', $username);
  359. Minz_Session::_param('passwordHash', $s);
  360. } else {
  361. Minz_Log::warning('Unsafe password mismatch for user ' . $username);
  362. }
  363. } catch (Minz_Exception $me) {
  364. Minz_Log::warning('Unsafe login failure: ' . $me->getMessage());
  365. }
  366. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  367. } elseif (!Minz_Configuration::canLogIn()) {
  368. Minz_Error::error(
  369. 403,
  370. array('error' => array(_t('access_denied')))
  371. );
  372. }
  373. invalidateHttpCache();
  374. }
  375. public function formLogoutAction() {
  376. $this->view->_useLayout(false);
  377. invalidateHttpCache();
  378. Minz_Session::_param('currentUser');
  379. Minz_Session::_param('mail');
  380. Minz_Session::_param('passwordHash');
  381. self::deleteLongTermCookie();
  382. Minz_Request::forward(array('c' => 'index', 'a' => 'index'), true);
  383. }
  384. public function resetAuthAction() {
  385. Minz_View::prependTitle(_t('auth_reset') . ' · ');
  386. Minz_View::appendScript(Minz_Url::display(
  387. '/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')
  388. ));
  389. $this->view->no_form = false;
  390. // Enable changement of auth only if Persona!
  391. if (Minz_Configuration::authType() != 'persona') {
  392. $this->view->message = array(
  393. 'status' => 'bad',
  394. 'title' => _t('damn'),
  395. 'body' => _t('auth_not_persona')
  396. );
  397. $this->view->no_form = true;
  398. return;
  399. }
  400. $conf = new FreshRSS_Configuration(Minz_Configuration::defaultUser());
  401. // Admin user must have set its master password.
  402. if (!$conf->passwordHash) {
  403. $this->view->message = array(
  404. 'status' => 'bad',
  405. 'title' => _t('damn'),
  406. 'body' => _t('auth_no_password_set')
  407. );
  408. $this->view->no_form = true;
  409. return;
  410. }
  411. invalidateHttpCache();
  412. if (Minz_Request::isPost()) {
  413. $nonce = Minz_Session::param('nonce');
  414. $username = Minz_Request::param('username', '');
  415. $c = Minz_Request::param('challenge', '');
  416. if (!(ctype_alnum($username) && ctype_graph($c) && ctype_alnum($nonce))) {
  417. Minz_Log::debug('Invalid credential parameters:' .
  418. ' user=' . $username .
  419. ' challenge=' . $c .
  420. ' nonce=' . $nonce);
  421. Minz_Request::bad(_t('invalid_login'),
  422. array('c' => 'index', 'a' => 'resetAuth'));
  423. }
  424. if (!function_exists('password_verify')) {
  425. include_once(LIB_PATH . '/password_compat.php');
  426. }
  427. $s = $conf->passwordHash;
  428. $ok = password_verify($nonce . $s, $c);
  429. if ($ok) {
  430. Minz_Configuration::_authType('form');
  431. $ok = Minz_Configuration::writeFile();
  432. if ($ok) {
  433. Minz_Request::good(_t('auth_form_set'));
  434. } else {
  435. Minz_Request::bad(_t('auth_form_not_set'),
  436. array('c' => 'index', 'a' => 'resetAuth'));
  437. }
  438. } else {
  439. Minz_Log::debug('Password mismatch for user ' . $username .
  440. ', nonce=' . $nonce . ', c=' . $c);
  441. Minz_Request::bad(_t('invalid_login'),
  442. array('c' => 'index', 'a' => 'resetAuth'));
  443. }
  444. }
  445. }
  446. }