indexController.php 13 KB

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