userController.php 19 KB

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