userController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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::_params([
  301. 'currentUser' => $new_user_name,
  302. 'passwordHash' => $user_conf->passwordHash,
  303. 'csrf' => false,
  304. ]);
  305. FreshRSS_Auth::giveAccess();
  306. }
  307. if ($ok) {
  308. Minz_Request::setGoodNotification(_t('feedback.user.created', $new_user_name));
  309. } else {
  310. Minz_Request::setBadNotification(_t('feedback.user.created.error', $new_user_name));
  311. }
  312. }
  313. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  314. if (!$redirect_url) {
  315. $redirect_url = array('c' => 'user', 'a' => 'manage');
  316. }
  317. Minz_Request::forward($redirect_url, true);
  318. }
  319. public static function deleteUser($username) {
  320. $ok = self::checkUsername($username);
  321. if ($ok) {
  322. $default_user = FreshRSS_Context::$system_conf->default_user;
  323. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  324. }
  325. $user_data = join_path(DATA_PATH, 'users', $username);
  326. $ok &= is_dir($user_data);
  327. if ($ok) {
  328. FreshRSS_fever_Util::deleteKey($username);
  329. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  330. $ok &= $oldUserDAO->deleteUser();
  331. $ok &= recursive_unlink($user_data);
  332. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  333. }
  334. return $ok;
  335. }
  336. /**
  337. * This action validates an email address, based on the token sent by email.
  338. * It also serves the main page when user is blocked.
  339. *
  340. * Request parameters are:
  341. * - username
  342. * - token
  343. *
  344. * This route works with GET requests since the URL is provided by email.
  345. * The security risks (e.g. forged URL by an attacker) are not very high so
  346. * it's ok.
  347. *
  348. * It returns 404 error if `force_email_validation` is disabled or if the
  349. * user doesn't exist.
  350. *
  351. * It returns 403 if user isn't logged in and `username` param isn't passed.
  352. */
  353. public function validateEmailAction() {
  354. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  355. Minz_Error::error(404);
  356. }
  357. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  358. $this->view->_layout('simple');
  359. $username = Minz_Request::param('username');
  360. $token = Minz_Request::param('token');
  361. if ($username) {
  362. $user_config = get_user_configuration($username);
  363. } elseif (FreshRSS_Auth::hasAccess()) {
  364. $user_config = FreshRSS_Context::$user_conf;
  365. } else {
  366. Minz_Error::error(403);
  367. }
  368. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  369. Minz_Error::error(404);
  370. }
  371. if ($user_config->email_validation_token === '') {
  372. Minz_Request::good(
  373. _t('user.email.validation.feedback.unnecessary'),
  374. array('c' => 'index', 'a' => 'index')
  375. );
  376. }
  377. if ($token) {
  378. if ($user_config->email_validation_token !== $token) {
  379. Minz_Request::bad(
  380. _t('user.email.validation.feedback.wrong_token'),
  381. array('c' => 'user', 'a' => 'validateEmail')
  382. );
  383. }
  384. $user_config->email_validation_token = '';
  385. if ($user_config->save()) {
  386. Minz_Request::good(
  387. _t('user.email.validation.feedback.ok'),
  388. array('c' => 'index', 'a' => 'index')
  389. );
  390. } else {
  391. Minz_Request::bad(
  392. _t('user.email.validation.feedback.error'),
  393. array('c' => 'user', 'a' => 'validateEmail')
  394. );
  395. }
  396. }
  397. }
  398. /**
  399. * This action resends a validation email to the current user.
  400. *
  401. * It only acts on POST requests but doesn't require any param (except the
  402. * CSRF token).
  403. *
  404. * It returns 403 error if the user is not logged in or 404 if request is
  405. * not POST. Else it redirects silently to the index if user has already
  406. * validated its email, or to the user#validateEmail route.
  407. */
  408. public function sendValidationEmailAction() {
  409. if (!FreshRSS_Auth::hasAccess()) {
  410. Minz_Error::error(403);
  411. }
  412. if (!Minz_Request::isPost()) {
  413. Minz_Error::error(404);
  414. }
  415. $username = Minz_Session::param('currentUser', '_');
  416. $user_config = FreshRSS_Context::$user_conf;
  417. if ($user_config->email_validation_token === '') {
  418. Minz_Request::forward(array(
  419. 'c' => 'index',
  420. 'a' => 'index',
  421. ), true);
  422. }
  423. $mailer = new FreshRSS_User_Mailer();
  424. $ok = $mailer->send_email_need_validation($username, $user_config);
  425. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  426. if ($ok) {
  427. Minz_Request::good(
  428. _t('user.email.validation.feedback.email_sent'),
  429. $redirect_url
  430. );
  431. } else {
  432. Minz_Request::bad(
  433. _t('user.email.validation.feedback.email_failed'),
  434. $redirect_url
  435. );
  436. }
  437. }
  438. /**
  439. * This action delete an existing user.
  440. *
  441. * Request parameter is:
  442. * - username
  443. *
  444. * @todo clean up this method. Idea: create a User->clean() method.
  445. */
  446. public function deleteAction() {
  447. $username = Minz_Request::param('username');
  448. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  449. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  450. Minz_Error::error(403);
  451. }
  452. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  453. if (!$redirect_url) {
  454. $redirect_url = array('c' => 'user', 'a' => 'manage');
  455. }
  456. if (Minz_Request::isPost()) {
  457. $ok = true;
  458. if ($ok && $self_deletion) {
  459. // We check the password if it's a self-destruction
  460. $nonce = Minz_Session::param('nonce');
  461. $challenge = Minz_Request::param('challenge', '');
  462. $ok &= FreshRSS_FormAuth::checkCredentials(
  463. $username, FreshRSS_Context::$user_conf->passwordHash,
  464. $nonce, $challenge
  465. );
  466. }
  467. if ($ok) {
  468. $ok &= self::deleteUser($username);
  469. }
  470. if ($ok && $self_deletion) {
  471. FreshRSS_Auth::removeAccess();
  472. $redirect_url = array('c' => 'index', 'a' => 'index');
  473. }
  474. invalidateHttpCache();
  475. if ($ok) {
  476. Minz_Request::setGoodNotification(_t('feedback.user.deleted', $username));
  477. } else {
  478. Minz_Request::setBadNotification(_t('feedback.user.deleted.error', $username));
  479. }
  480. }
  481. Minz_Request::forward($redirect_url, true);
  482. }
  483. public function promoteAction() {
  484. $this->toggleAction('is_admin', true);
  485. }
  486. public function demoteAction() {
  487. $this->toggleAction('is_admin', false);
  488. }
  489. public function enableAction() {
  490. $this->toggleAction('enabled', true);
  491. }
  492. public function disableAction() {
  493. $this->toggleAction('enabled', false);
  494. }
  495. private function toggleAction($field, $value) {
  496. if (!FreshRSS_Auth::hasAccess('admin')) {
  497. Minz_Error::error(403);
  498. }
  499. if (!Minz_Request::isPost()) {
  500. Minz_Error::error(403);
  501. }
  502. $username = Minz_Request::param('username');
  503. if (!FreshRSS_UserDAO::exists($username)) {
  504. Minz_Error::error(404);
  505. }
  506. if (null === $userConfig = get_user_configuration($username)) {
  507. Minz_Error::error(500);
  508. }
  509. $userConfig->_param($field, $value);
  510. $ok = $userConfig->save();
  511. FreshRSS_UserDAO::touch($username);
  512. if ($ok) {
  513. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  514. } else {
  515. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  516. array('c' => 'user', 'a' => 'manage'));
  517. }
  518. }
  519. public function detailsAction() {
  520. if (!FreshRSS_Auth::hasAccess('admin')) {
  521. Minz_Error::error(403);
  522. }
  523. $username = Minz_Request::param('username');
  524. if (!FreshRSS_UserDAO::exists($username)) {
  525. Minz_Error::error(404);
  526. }
  527. $this->view->username = $username;
  528. $this->view->details = $this->retrieveUserDetails($username);
  529. }
  530. private function retrieveUserDetails($username) {
  531. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  532. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  533. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  534. $userConfiguration = get_user_configuration($username);
  535. return array(
  536. 'feed_count' => $feedDAO->count(),
  537. 'article_count' => $entryDAO->count(),
  538. 'database_size' => $databaseDAO->size(),
  539. 'language' => $userConfiguration->language,
  540. 'mail_login' => $userConfiguration->mail_login,
  541. 'enabled' => $userConfiguration->enabled,
  542. 'is_admin' => $userConfiguration->is_admin,
  543. 'last_user_activity' => date('c', FreshRSS_UserDAO::mtime($username)),
  544. 'is_default' => FreshRSS_Context::$system_conf->default_user === $username,
  545. );
  546. }
  547. }