4
0

userController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?php
  2. /**
  3. * Controller to handle user actions.
  4. */
  5. class FreshRSS_user_Controller extends Minz_ActionController {
  6. /**
  7. * The username is also used as folder name, file name, and part of SQL table name.
  8. * '_' is a reserved internal username.
  9. */
  10. const USERNAME_PATTERN = '([0-9a-zA-Z_][0-9a-zA-Z_.@-]{1,38}|[0-9a-zA-Z])';
  11. public static function checkUsername($username) {
  12. return preg_match('/^' . self::USERNAME_PATTERN . '$/', $username) === 1;
  13. }
  14. public static function updateUser($user, $email, $passwordPlain, $userConfigUpdated = array()) {
  15. $userConfig = get_user_configuration($user);
  16. if ($userConfig === null) {
  17. return false;
  18. }
  19. if ($email !== null && $userConfig->mail_login !== $email) {
  20. $userConfig->mail_login = $email;
  21. if (FreshRSS_Context::$system_conf->force_email_validation) {
  22. $salt = FreshRSS_Context::$system_conf->salt;
  23. $userConfig->email_validation_token = sha1($salt . uniqid(mt_rand(), true));
  24. $mailer = new FreshRSS_User_Mailer();
  25. $mailer->send_email_need_validation($user, $userConfig);
  26. }
  27. }
  28. if ($passwordPlain != '') {
  29. $passwordHash = FreshRSS_password_Util::hash($passwordPlain);
  30. $userConfig->passwordHash = $passwordHash;
  31. }
  32. if (is_array($userConfigUpdated)) {
  33. foreach ($userConfigUpdated as $configName => $configValue) {
  34. if ($configValue !== null) {
  35. $userConfig->_param($configName, $configValue);
  36. }
  37. }
  38. }
  39. $ok = $userConfig->save();
  40. return $ok;
  41. }
  42. public function updateAction() {
  43. if (!FreshRSS_Auth::hasAccess('admin')) {
  44. Minz_Error::error(403);
  45. }
  46. if (Minz_Request::isPost()) {
  47. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  48. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  49. $_POST['newPasswordPlain'] = '';
  50. $username = Minz_Request::param('username');
  51. $ok = self::updateUser($username, null, $passwordPlain, array(
  52. 'token' => Minz_Request::param('token', null),
  53. ));
  54. if ($ok) {
  55. $isSelfUpdate = Minz_Session::param('currentUser', '_') === $username;
  56. if ($passwordPlain == '' || !$isSelfUpdate) {
  57. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  58. } else {
  59. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  60. }
  61. } else {
  62. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  63. array('c' => 'user', 'a' => 'manage'));
  64. }
  65. }
  66. }
  67. /**
  68. * This action displays the user profile page.
  69. */
  70. public function profileAction() {
  71. if (!FreshRSS_Auth::hasAccess()) {
  72. Minz_Error::error(403);
  73. }
  74. $email_not_verified = FreshRSS_Context::$user_conf->email_validation_token != '';
  75. $this->view->disable_aside = false;
  76. if ($email_not_verified) {
  77. $this->view->_layout('simple');
  78. $this->view->disable_aside = true;
  79. }
  80. Minz_View::prependTitle(_t('conf.profile.title') . ' · ');
  81. Minz_View::appendScript(Minz_Url::display('/scripts/bcrypt.min.js?' . @filemtime(PUBLIC_PATH . '/scripts/bcrypt.min.js')));
  82. if (Minz_Request::isPost()) {
  83. $system_conf = FreshRSS_Context::$system_conf;
  84. $user_config = FreshRSS_Context::$user_conf;
  85. $old_email = $user_config->mail_login;
  86. $email = trim(Minz_Request::param('email', ''));
  87. $passwordPlain = Minz_Request::param('newPasswordPlain', '', true);
  88. Minz_Request::_param('newPasswordPlain'); //Discard plain-text password ASAP
  89. $_POST['newPasswordPlain'] = '';
  90. if ($system_conf->force_email_validation && empty($email)) {
  91. Minz_Request::bad(
  92. _t('user.email.feedback.required'),
  93. array('c' => 'user', 'a' => 'profile')
  94. );
  95. }
  96. if (!empty($email) && !validateEmailAddress($email)) {
  97. Minz_Request::bad(
  98. _t('user.email.feedback.invalid'),
  99. array('c' => 'user', 'a' => 'profile')
  100. );
  101. }
  102. $ok = self::updateUser(
  103. Minz_Session::param('currentUser'),
  104. $email,
  105. $passwordPlain,
  106. array(
  107. 'token' => Minz_Request::param('token', null),
  108. )
  109. );
  110. Minz_Session::_param('passwordHash', FreshRSS_Context::$user_conf->passwordHash);
  111. if ($ok) {
  112. if ($system_conf->force_email_validation && $email !== $old_email) {
  113. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'validateEmail'));
  114. } elseif ($passwordPlain == '') {
  115. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'user', 'a' => 'profile'));
  116. } else {
  117. Minz_Request::good(_t('feedback.profile.updated'), array('c' => 'index', 'a' => 'index'));
  118. }
  119. } else {
  120. Minz_Request::bad(_t('feedback.profile.error'),
  121. array('c' => 'user', 'a' => 'profile'));
  122. }
  123. }
  124. }
  125. public function purgeAction() {
  126. if (!FreshRSS_Auth::hasAccess('admin')) {
  127. Minz_Error::error(403);
  128. }
  129. if (Minz_Request::isPost()) {
  130. $username = Minz_Request::param('username');
  131. if (!FreshRSS_UserDAO::exists($username)) {
  132. Minz_Error::error(404);
  133. }
  134. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  135. $feedDAO->purge();
  136. }
  137. }
  138. /**
  139. * This action displays the user management page.
  140. */
  141. public function manageAction() {
  142. if (!FreshRSS_Auth::hasAccess('admin')) {
  143. Minz_Error::error(403);
  144. }
  145. Minz_View::prependTitle(_t('admin.user.title') . ' · ');
  146. if (Minz_Request::isPost()) {
  147. $action = Minz_Request::param('action');
  148. switch ($action) {
  149. case 'delete':
  150. $this->deleteAction();
  151. break;
  152. case 'update':
  153. $this->updateAction();
  154. break;
  155. case 'purge':
  156. $this->purgeAction();
  157. break;
  158. case 'promote':
  159. $this->promoteAction();
  160. break;
  161. case 'demote':
  162. $this->demoteAction();
  163. break;
  164. case 'enable':
  165. $this->enableAction();
  166. break;
  167. case 'disable':
  168. $this->disableAction();
  169. break;
  170. }
  171. }
  172. $this->view->show_email_field = FreshRSS_Context::$system_conf->force_email_validation;
  173. $this->view->current_user = Minz_Request::param('u');
  174. foreach (listUsers() as $user) {
  175. $this->view->users[$user] = $this->retrieveUserDetails($user);
  176. }
  177. }
  178. public static function createUser($new_user_name, $email, $passwordPlain, $userConfigOverride = [], $insertDefaultFeeds = true) {
  179. $userConfig = [];
  180. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  181. if (file_exists($customUserConfigPath)) {
  182. $customUserConfig = include($customUserConfigPath);
  183. if (is_array($customUserConfig)) {
  184. $userConfig = $customUserConfig;
  185. }
  186. }
  187. if (is_array($userConfigOverride)) {
  188. $userConfig = array_merge($userConfig, $userConfigOverride);
  189. }
  190. $ok = self::checkUsername($new_user_name);
  191. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  192. if ($ok) {
  193. $languages = Minz_Translate::availableLanguages();
  194. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages)) {
  195. $userConfig['language'] = 'en';
  196. }
  197. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive
  198. $configPath = join_path($homeDir, 'config.php');
  199. $ok &= !file_exists($configPath);
  200. }
  201. if ($ok) {
  202. if (!is_dir($homeDir)) {
  203. mkdir($homeDir);
  204. }
  205. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  206. }
  207. if ($ok) {
  208. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  209. $ok &= $newUserDAO->createUser();
  210. if ($ok && $insertDefaultFeeds) {
  211. $opmlPath = DATA_PATH . '/opml.xml';
  212. if (!file_exists($opmlPath)) {
  213. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  214. }
  215. $importController = new FreshRSS_importExport_Controller();
  216. try {
  217. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  218. } catch (Exception $e) {
  219. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  220. }
  221. }
  222. $ok &= self::updateUser($new_user_name, $email, $passwordPlain);
  223. }
  224. return $ok;
  225. }
  226. /**
  227. * This action creates a new user.
  228. *
  229. * Request parameters are:
  230. * - new_user_language
  231. * - new_user_name
  232. * - new_user_email
  233. * - new_user_passwordPlain
  234. * - r (i.e. a redirection url, optional)
  235. *
  236. * @todo clean up this method. Idea: write a method to init a user with basic information.
  237. * @todo handle r redirection in Minz_Request::forward directly?
  238. */
  239. public function createAction() {
  240. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  241. Minz_Error::error(403);
  242. }
  243. if (Minz_Request::isPost()) {
  244. $system_conf = FreshRSS_Context::$system_conf;
  245. $new_user_name = Minz_Request::param('new_user_name');
  246. $email = Minz_Request::param('new_user_email', '');
  247. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  248. if (!self::checkUsername($new_user_name)) {
  249. Minz_Request::bad(
  250. _t('user.username.invalid'),
  251. array('c' => 'auth', 'a' => 'register')
  252. );
  253. }
  254. if (FreshRSS_UserDAO::exists($new_user_name)) {
  255. Minz_Request::bad(
  256. _t('user.username.taken', $new_user_name),
  257. array('c' => 'auth', 'a' => 'register')
  258. );
  259. }
  260. if (!FreshRSS_password_Util::check($passwordPlain)) {
  261. Minz_Request::bad(
  262. _t('user.password.invalid'),
  263. array('c' => 'auth', 'a' => 'register')
  264. );
  265. }
  266. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  267. $accept_tos = Minz_Request::param('accept_tos', false);
  268. if ($system_conf->force_email_validation && empty($email)) {
  269. Minz_Request::bad(
  270. _t('user.email.feedback.required'),
  271. array('c' => 'auth', 'a' => 'register')
  272. );
  273. }
  274. if (!empty($email) && !validateEmailAddress($email)) {
  275. Minz_Request::bad(
  276. _t('user.email.feedback.invalid'),
  277. array('c' => 'auth', 'a' => 'register')
  278. );
  279. }
  280. if ($tos_enabled && !$accept_tos) {
  281. Minz_Request::bad(
  282. _t('user.tos.feedback.invalid'),
  283. array('c' => 'auth', 'a' => 'register')
  284. );
  285. }
  286. $ok = self::createUser($new_user_name, $email, $passwordPlain, array(
  287. 'language' => Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language),
  288. 'is_admin' => Minz_Request::paramBoolean('new_user_is_admin'),
  289. 'enabled' => true,
  290. ));
  291. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  292. $_POST['new_user_passwordPlain'] = '';
  293. invalidateHttpCache();
  294. // If the user has admin access, it means he's already logged in
  295. // and we don't want to login with the new account. Otherwise, the
  296. // user just created its account himself so he probably wants to
  297. // get started immediately.
  298. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  299. $user_conf = get_user_configuration($new_user_name);
  300. Minz_Session::_param('currentUser', $new_user_name);
  301. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  302. Minz_Session::_param('csrf');
  303. FreshRSS_Auth::giveAccess();
  304. }
  305. $notif = array(
  306. 'type' => $ok ? 'good' : 'bad',
  307. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  308. );
  309. Minz_Session::_param('notification', $notif);
  310. }
  311. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  312. if (!$redirect_url) {
  313. $redirect_url = array('c' => 'user', 'a' => 'manage');
  314. }
  315. Minz_Request::forward($redirect_url, true);
  316. }
  317. public static function deleteUser($username) {
  318. $ok = self::checkUsername($username);
  319. if ($ok) {
  320. $default_user = FreshRSS_Context::$system_conf->default_user;
  321. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  322. }
  323. $user_data = join_path(DATA_PATH, 'users', $username);
  324. $ok &= is_dir($user_data);
  325. if ($ok) {
  326. FreshRSS_fever_Util::deleteKey($username);
  327. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  328. $ok &= $oldUserDAO->deleteUser();
  329. $ok &= recursive_unlink($user_data);
  330. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  331. }
  332. return $ok;
  333. }
  334. /**
  335. * This action validates an email address, based on the token sent by email.
  336. * It also serves the main page when user is blocked.
  337. *
  338. * Request parameters are:
  339. * - username
  340. * - token
  341. *
  342. * This route works with GET requests since the URL is provided by email.
  343. * The security risks (e.g. forged URL by an attacker) are not very high so
  344. * it's ok.
  345. *
  346. * It returns 404 error if `force_email_validation` is disabled or if the
  347. * user doesn't exist.
  348. *
  349. * It returns 403 if user isn't logged in and `username` param isn't passed.
  350. */
  351. public function validateEmailAction() {
  352. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  353. Minz_Error::error(404);
  354. }
  355. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  356. $this->view->_layout('simple');
  357. $username = Minz_Request::param('username');
  358. $token = Minz_Request::param('token');
  359. if ($username) {
  360. $user_config = get_user_configuration($username);
  361. } elseif (FreshRSS_Auth::hasAccess()) {
  362. $user_config = FreshRSS_Context::$user_conf;
  363. } else {
  364. Minz_Error::error(403);
  365. }
  366. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  367. Minz_Error::error(404);
  368. }
  369. if ($user_config->email_validation_token === '') {
  370. Minz_Request::good(
  371. _t('user.email.validation.feedback.unnecessary'),
  372. array('c' => 'index', 'a' => 'index')
  373. );
  374. }
  375. if ($token) {
  376. if ($user_config->email_validation_token !== $token) {
  377. Minz_Request::bad(
  378. _t('user.email.validation.feedback.wrong_token'),
  379. array('c' => 'user', 'a' => 'validateEmail')
  380. );
  381. }
  382. $user_config->email_validation_token = '';
  383. if ($user_config->save()) {
  384. Minz_Request::good(
  385. _t('user.email.validation.feedback.ok'),
  386. array('c' => 'index', 'a' => 'index')
  387. );
  388. } else {
  389. Minz_Request::bad(
  390. _t('user.email.validation.feedback.error'),
  391. array('c' => 'user', 'a' => 'validateEmail')
  392. );
  393. }
  394. }
  395. }
  396. /**
  397. * This action resends a validation email to the current user.
  398. *
  399. * It only acts on POST requests but doesn't require any param (except the
  400. * CSRF token).
  401. *
  402. * It returns 403 error if the user is not logged in or 404 if request is
  403. * not POST. Else it redirects silently to the index if user has already
  404. * validated its email, or to the user#validateEmail route.
  405. */
  406. public function sendValidationEmailAction() {
  407. if (!FreshRSS_Auth::hasAccess()) {
  408. Minz_Error::error(403);
  409. }
  410. if (!Minz_Request::isPost()) {
  411. Minz_Error::error(404);
  412. }
  413. $username = Minz_Session::param('currentUser', '_');
  414. $user_config = FreshRSS_Context::$user_conf;
  415. if ($user_config->email_validation_token === '') {
  416. Minz_Request::forward(array(
  417. 'c' => 'index',
  418. 'a' => 'index',
  419. ), true);
  420. }
  421. $mailer = new FreshRSS_User_Mailer();
  422. $ok = $mailer->send_email_need_validation($username, $user_config);
  423. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  424. if ($ok) {
  425. Minz_Request::good(
  426. _t('user.email.validation.feedback.email_sent'),
  427. $redirect_url
  428. );
  429. } else {
  430. Minz_Request::bad(
  431. _t('user.email.validation.feedback.email_failed'),
  432. $redirect_url
  433. );
  434. }
  435. }
  436. /**
  437. * This action delete an existing user.
  438. *
  439. * Request parameter is:
  440. * - username
  441. *
  442. * @todo clean up this method. Idea: create a User->clean() method.
  443. */
  444. public function deleteAction() {
  445. $username = Minz_Request::param('username');
  446. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  447. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  448. Minz_Error::error(403);
  449. }
  450. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  451. if (!$redirect_url) {
  452. $redirect_url = array('c' => 'user', 'a' => 'manage');
  453. }
  454. if (Minz_Request::isPost()) {
  455. $ok = true;
  456. if ($ok && $self_deletion) {
  457. // We check the password if it's a self-destruction
  458. $nonce = Minz_Session::param('nonce');
  459. $challenge = Minz_Request::param('challenge', '');
  460. $ok &= FreshRSS_FormAuth::checkCredentials(
  461. $username, FreshRSS_Context::$user_conf->passwordHash,
  462. $nonce, $challenge
  463. );
  464. }
  465. if ($ok) {
  466. $ok &= self::deleteUser($username);
  467. }
  468. if ($ok && $self_deletion) {
  469. FreshRSS_Auth::removeAccess();
  470. $redirect_url = array('c' => 'index', 'a' => 'index');
  471. }
  472. invalidateHttpCache();
  473. $notif = array(
  474. 'type' => $ok ? 'good' : 'bad',
  475. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  476. );
  477. Minz_Session::_param('notification', $notif);
  478. }
  479. Minz_Request::forward($redirect_url, true);
  480. }
  481. public function promoteAction() {
  482. $this->toggleAction('is_admin', true);
  483. }
  484. public function demoteAction() {
  485. $this->toggleAction('is_admin', false);
  486. }
  487. public function enableAction() {
  488. $this->toggleAction('enabled', true);
  489. }
  490. public function disableAction() {
  491. $this->toggleAction('enabled', false);
  492. }
  493. private function toggleAction($field, $value) {
  494. if (!FreshRSS_Auth::hasAccess('admin')) {
  495. Minz_Error::error(403);
  496. }
  497. if (!Minz_Request::isPost()) {
  498. Minz_Error::error(403);
  499. }
  500. $username = Minz_Request::param('username');
  501. if (!FreshRSS_UserDAO::exists($username)) {
  502. Minz_Error::error(404);
  503. }
  504. if (null === $userConfig = get_user_configuration($username)) {
  505. Minz_Error::error(500);
  506. }
  507. $userConfig->_param($field, $value);
  508. $ok = $userConfig->save();
  509. FreshRSS_UserDAO::touch($username);
  510. if ($ok) {
  511. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  512. } else {
  513. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  514. array('c' => 'user', 'a' => 'manage'));
  515. }
  516. }
  517. public function detailsAction() {
  518. if (!FreshRSS_Auth::hasAccess('admin')) {
  519. Minz_Error::error(403);
  520. }
  521. $username = Minz_Request::param('username');
  522. if (!FreshRSS_UserDAO::exists($username)) {
  523. Minz_Error::error(404);
  524. }
  525. $this->view->username = $username;
  526. $this->view->details = $this->retrieveUserDetails($username);
  527. }
  528. private function retrieveUserDetails($username) {
  529. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  530. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  531. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  532. $userConfiguration = get_user_configuration($username);
  533. return array(
  534. 'feed_count' => $feedDAO->count(),
  535. 'article_count' => $entryDAO->count(),
  536. 'database_size' => $databaseDAO->size(),
  537. 'language' => $userConfiguration->language,
  538. 'mail_login' => $userConfiguration->mail_login,
  539. 'enabled' => $userConfiguration->enabled,
  540. 'is_admin' => $userConfiguration->is_admin,
  541. 'last_user_activity' => date('c', FreshRSS_UserDAO::mtime($username)),
  542. 'is_default' => FreshRSS_Context::$system_conf->default_user === $username,
  543. );
  544. }
  545. }