4
0

indexController.php 16 KB

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