userController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. }
  165. }
  166. $this->view->show_email_field = FreshRSS_Context::$system_conf->force_email_validation;
  167. $this->view->current_user = Minz_Request::param('u');
  168. foreach (listUsers() as $user) {
  169. $this->view->users[$user] = $this->retrieveUserDetails($user);
  170. }
  171. }
  172. public static function createUser($new_user_name, $email, $passwordPlain, $userConfigOverride = [], $insertDefaultFeeds = true) {
  173. $userConfig = [];
  174. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  175. if (file_exists($customUserConfigPath)) {
  176. $customUserConfig = include($customUserConfigPath);
  177. if (is_array($customUserConfig)) {
  178. $userConfig = $customUserConfig;
  179. }
  180. }
  181. if (is_array($userConfigOverride)) {
  182. $userConfig = array_merge($userConfig, $userConfigOverride);
  183. }
  184. $ok = self::checkUsername($new_user_name);
  185. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  186. if ($ok) {
  187. $languages = Minz_Translate::availableLanguages();
  188. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages)) {
  189. $userConfig['language'] = 'en';
  190. }
  191. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers())); //Not an existing user, case-insensitive
  192. $configPath = join_path($homeDir, 'config.php');
  193. $ok &= !file_exists($configPath);
  194. }
  195. if ($ok) {
  196. if (!is_dir($homeDir)) {
  197. mkdir($homeDir);
  198. }
  199. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  200. }
  201. if ($ok) {
  202. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  203. $ok &= $newUserDAO->createUser();
  204. if ($ok && $insertDefaultFeeds) {
  205. $opmlPath = DATA_PATH . '/opml.xml';
  206. if (!file_exists($opmlPath)) {
  207. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  208. }
  209. $importController = new FreshRSS_importExport_Controller();
  210. try {
  211. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  212. } catch (Exception $e) {
  213. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  214. }
  215. }
  216. $ok &= self::updateUser($new_user_name, $email, $passwordPlain);
  217. }
  218. return $ok;
  219. }
  220. /**
  221. * This action creates a new user.
  222. *
  223. * Request parameters are:
  224. * - new_user_language
  225. * - new_user_name
  226. * - new_user_email
  227. * - new_user_passwordPlain
  228. * - r (i.e. a redirection url, optional)
  229. *
  230. * @todo clean up this method. Idea: write a method to init a user with basic information.
  231. * @todo handle r redirection in Minz_Request::forward directly?
  232. */
  233. public function createAction() {
  234. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  235. Minz_Error::error(403);
  236. }
  237. if (Minz_Request::isPost()) {
  238. $system_conf = FreshRSS_Context::$system_conf;
  239. $new_user_name = Minz_Request::param('new_user_name');
  240. $email = Minz_Request::param('new_user_email', '');
  241. $passwordPlain = Minz_Request::param('new_user_passwordPlain', '', true);
  242. if (!self::checkUsername($new_user_name)) {
  243. Minz_Request::bad(
  244. _t('user.username.invalid'),
  245. array('c' => 'auth', 'a' => 'register')
  246. );
  247. }
  248. if (FreshRSS_UserDAO::exists($new_user_name)) {
  249. Minz_Request::bad(
  250. _t('user.username.taken', $new_user_name),
  251. array('c' => 'auth', 'a' => 'register')
  252. );
  253. }
  254. if (!FreshRSS_password_Util::check($passwordPlain)) {
  255. Minz_Request::bad(
  256. _t('user.password.invalid'),
  257. array('c' => 'auth', 'a' => 'register')
  258. );
  259. }
  260. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  261. $accept_tos = Minz_Request::param('accept_tos', false);
  262. if ($system_conf->force_email_validation && empty($email)) {
  263. Minz_Request::bad(
  264. _t('user.email.feedback.required'),
  265. array('c' => 'auth', 'a' => 'register')
  266. );
  267. }
  268. if (!empty($email) && !validateEmailAddress($email)) {
  269. Minz_Request::bad(
  270. _t('user.email.feedback.invalid'),
  271. array('c' => 'auth', 'a' => 'register')
  272. );
  273. }
  274. if ($tos_enabled && !$accept_tos) {
  275. Minz_Request::bad(
  276. _t('user.tos.feedback.invalid'),
  277. array('c' => 'auth', 'a' => 'register')
  278. );
  279. }
  280. $ok = self::createUser($new_user_name, $email, $passwordPlain, array(
  281. 'language' => Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language),
  282. 'is_admin' => Minz_Request::paramBoolean('new_user_is_admin'),
  283. ));
  284. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  285. $_POST['new_user_passwordPlain'] = '';
  286. invalidateHttpCache();
  287. // If the user has admin access, it means he's already logged in
  288. // and we don't want to login with the new account. Otherwise, the
  289. // user just created its account himself so he probably wants to
  290. // get started immediately.
  291. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  292. $user_conf = get_user_configuration($new_user_name);
  293. Minz_Session::_param('currentUser', $new_user_name);
  294. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  295. Minz_Session::_param('csrf');
  296. FreshRSS_Auth::giveAccess();
  297. }
  298. $notif = array(
  299. 'type' => $ok ? 'good' : 'bad',
  300. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  301. );
  302. Minz_Session::_param('notification', $notif);
  303. }
  304. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  305. if (!$redirect_url) {
  306. $redirect_url = array('c' => 'user', 'a' => 'manage');
  307. }
  308. Minz_Request::forward($redirect_url, true);
  309. }
  310. public static function deleteUser($username) {
  311. $ok = self::checkUsername($username);
  312. if ($ok) {
  313. $default_user = FreshRSS_Context::$system_conf->default_user;
  314. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  315. }
  316. $user_data = join_path(DATA_PATH, 'users', $username);
  317. $ok &= is_dir($user_data);
  318. if ($ok) {
  319. FreshRSS_fever_Util::deleteKey($username);
  320. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  321. $ok &= $oldUserDAO->deleteUser();
  322. $ok &= recursive_unlink($user_data);
  323. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  324. }
  325. return $ok;
  326. }
  327. /**
  328. * This action validates an email address, based on the token sent by email.
  329. * It also serves the main page when user is blocked.
  330. *
  331. * Request parameters are:
  332. * - username
  333. * - token
  334. *
  335. * This route works with GET requests since the URL is provided by email.
  336. * The security risks (e.g. forged URL by an attacker) are not very high so
  337. * it's ok.
  338. *
  339. * It returns 404 error if `force_email_validation` is disabled or if the
  340. * user doesn't exist.
  341. *
  342. * It returns 403 if user isn't logged in and `username` param isn't passed.
  343. */
  344. public function validateEmailAction() {
  345. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  346. Minz_Error::error(404);
  347. }
  348. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  349. $this->view->_layout('simple');
  350. $username = Minz_Request::param('username');
  351. $token = Minz_Request::param('token');
  352. if ($username) {
  353. $user_config = get_user_configuration($username);
  354. } elseif (FreshRSS_Auth::hasAccess()) {
  355. $user_config = FreshRSS_Context::$user_conf;
  356. } else {
  357. Minz_Error::error(403);
  358. }
  359. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  360. Minz_Error::error(404);
  361. }
  362. if ($user_config->email_validation_token === '') {
  363. Minz_Request::good(
  364. _t('user.email.validation.feedback.unnecessary'),
  365. array('c' => 'index', 'a' => 'index')
  366. );
  367. }
  368. if ($token) {
  369. if ($user_config->email_validation_token !== $token) {
  370. Minz_Request::bad(
  371. _t('user.email.validation.feedback.wrong_token'),
  372. array('c' => 'user', 'a' => 'validateEmail')
  373. );
  374. }
  375. $user_config->email_validation_token = '';
  376. if ($user_config->save()) {
  377. Minz_Request::good(
  378. _t('user.email.validation.feedback.ok'),
  379. array('c' => 'index', 'a' => 'index')
  380. );
  381. } else {
  382. Minz_Request::bad(
  383. _t('user.email.validation.feedback.error'),
  384. array('c' => 'user', 'a' => 'validateEmail')
  385. );
  386. }
  387. }
  388. }
  389. /**
  390. * This action resends a validation email to the current user.
  391. *
  392. * It only acts on POST requests but doesn't require any param (except the
  393. * CSRF token).
  394. *
  395. * It returns 403 error if the user is not logged in or 404 if request is
  396. * not POST. Else it redirects silently to the index if user has already
  397. * validated its email, or to the user#validateEmail route.
  398. */
  399. public function sendValidationEmailAction() {
  400. if (!FreshRSS_Auth::hasAccess()) {
  401. Minz_Error::error(403);
  402. }
  403. if (!Minz_Request::isPost()) {
  404. Minz_Error::error(404);
  405. }
  406. $username = Minz_Session::param('currentUser', '_');
  407. $user_config = FreshRSS_Context::$user_conf;
  408. if ($user_config->email_validation_token === '') {
  409. Minz_Request::forward(array(
  410. 'c' => 'index',
  411. 'a' => 'index',
  412. ), true);
  413. }
  414. $mailer = new FreshRSS_User_Mailer();
  415. $ok = $mailer->send_email_need_validation($username, $user_config);
  416. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  417. if ($ok) {
  418. Minz_Request::good(
  419. _t('user.email.validation.feedback.email_sent'),
  420. $redirect_url
  421. );
  422. } else {
  423. Minz_Request::bad(
  424. _t('user.email.validation.feedback.email_failed'),
  425. $redirect_url
  426. );
  427. }
  428. }
  429. /**
  430. * This action delete an existing user.
  431. *
  432. * Request parameter is:
  433. * - username
  434. *
  435. * @todo clean up this method. Idea: create a User->clean() method.
  436. */
  437. public function deleteAction() {
  438. $username = Minz_Request::param('username');
  439. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  440. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  441. Minz_Error::error(403);
  442. }
  443. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  444. if (!$redirect_url) {
  445. $redirect_url = array('c' => 'user', 'a' => 'manage');
  446. }
  447. if (Minz_Request::isPost()) {
  448. $ok = true;
  449. if ($ok && $self_deletion) {
  450. // We check the password if it's a self-destruction
  451. $nonce = Minz_Session::param('nonce');
  452. $challenge = Minz_Request::param('challenge', '');
  453. $ok &= FreshRSS_FormAuth::checkCredentials(
  454. $username, FreshRSS_Context::$user_conf->passwordHash,
  455. $nonce, $challenge
  456. );
  457. }
  458. if ($ok) {
  459. $ok &= self::deleteUser($username);
  460. }
  461. if ($ok && $self_deletion) {
  462. FreshRSS_Auth::removeAccess();
  463. $redirect_url = array('c' => 'index', 'a' => 'index');
  464. }
  465. invalidateHttpCache();
  466. $notif = array(
  467. 'type' => $ok ? 'good' : 'bad',
  468. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  469. );
  470. Minz_Session::_param('notification', $notif);
  471. }
  472. Minz_Request::forward($redirect_url, true);
  473. }
  474. public function promoteAction() {
  475. $this->switchAdminAction(true);
  476. }
  477. public function demoteAction() {
  478. $this->switchAdminAction(false);
  479. }
  480. private function switchAdminAction($isAdmin) {
  481. if (!FreshRSS_Auth::hasAccess('admin')) {
  482. Minz_Error::error(403);
  483. }
  484. if (!Minz_Request::isPost()) {
  485. Minz_Error::error(403);
  486. }
  487. $username = Minz_Request::param('username');
  488. if (!FreshRSS_UserDAO::exists($username)) {
  489. Minz_Error::error(404);
  490. }
  491. if (null === $userConfig = get_user_configuration($username)) {
  492. Minz_Error::error(500);
  493. }
  494. $userConfig->_param('is_admin', $isAdmin);
  495. $ok = $userConfig->save();
  496. if ($ok) {
  497. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  498. } else {
  499. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  500. array('c' => 'user', 'a' => 'manage'));
  501. }
  502. }
  503. public function detailsAction() {
  504. if (!FreshRSS_Auth::hasAccess('admin')) {
  505. Minz_Error::error(403);
  506. }
  507. $username = Minz_Request::param('username');
  508. if (!FreshRSS_UserDAO::exists($username)) {
  509. Minz_Error::error(404);
  510. }
  511. $this->view->isDefaultUser = $username === FreshRSS_Context::$system_conf->default_user;
  512. $this->view->username = $username;
  513. $this->view->details = $this->retrieveUserDetails($username);
  514. }
  515. private function retrieveUserDetails($username) {
  516. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  517. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  518. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  519. $userConfiguration = get_user_configuration($username);
  520. return array(
  521. 'feed_count' => $feedDAO->count(),
  522. 'article_count' => $entryDAO->count(),
  523. 'database_size' => $databaseDAO->size(),
  524. 'language' => $userConfiguration->language,
  525. 'mail_login' => $userConfiguration->mail_login,
  526. 'is_admin' => $userConfiguration->is_admin,
  527. 'last_user_activity' => date('c', FreshRSS_UserDAO::mtime($username)),
  528. );
  529. }
  530. }