userController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. $tos_enabled = file_exists(join_path(DATA_PATH, 'tos.html'));
  243. $accept_tos = Minz_Request::param('accept_tos', false);
  244. if ($system_conf->force_email_validation && empty($email)) {
  245. Minz_Request::bad(
  246. _t('user.email.feedback.required'),
  247. array('c' => 'auth', 'a' => 'register')
  248. );
  249. }
  250. if (!empty($email) && !validateEmailAddress($email)) {
  251. Minz_Request::bad(
  252. _t('user.email.feedback.invalid'),
  253. array('c' => 'auth', 'a' => 'register')
  254. );
  255. }
  256. if ($tos_enabled && !$accept_tos) {
  257. Minz_Request::bad(
  258. _t('user.tos.feedback.invalid'),
  259. array('c' => 'auth', 'a' => 'register')
  260. );
  261. }
  262. $ok = self::createUser($new_user_name, $email, $passwordPlain, array(
  263. 'language' => Minz_Request::param('new_user_language', FreshRSS_Context::$user_conf->language),
  264. 'is_admin' => Minz_Request::paramBoolean('new_user_is_admin'),
  265. ));
  266. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  267. $_POST['new_user_passwordPlain'] = '';
  268. invalidateHttpCache();
  269. // If the user has admin access, it means he's already logged in
  270. // and we don't want to login with the new account. Otherwise, the
  271. // user just created its account himself so he probably wants to
  272. // get started immediately.
  273. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  274. $user_conf = get_user_configuration($new_user_name);
  275. Minz_Session::_param('currentUser', $new_user_name);
  276. Minz_Session::_param('passwordHash', $user_conf->passwordHash);
  277. Minz_Session::_param('csrf');
  278. FreshRSS_Auth::giveAccess();
  279. }
  280. $notif = array(
  281. 'type' => $ok ? 'good' : 'bad',
  282. 'content' => _t('feedback.user.created' . (!$ok ? '.error' : ''), $new_user_name)
  283. );
  284. Minz_Session::_param('notification', $notif);
  285. }
  286. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  287. if (!$redirect_url) {
  288. $redirect_url = array('c' => 'user', 'a' => 'manage');
  289. }
  290. Minz_Request::forward($redirect_url, true);
  291. }
  292. public static function deleteUser($username) {
  293. $ok = self::checkUsername($username);
  294. if ($ok) {
  295. $default_user = FreshRSS_Context::$system_conf->default_user;
  296. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  297. }
  298. $user_data = join_path(DATA_PATH, 'users', $username);
  299. $ok &= is_dir($user_data);
  300. if ($ok) {
  301. FreshRSS_fever_Util::deleteKey($username);
  302. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  303. $ok &= $oldUserDAO->deleteUser();
  304. $ok &= recursive_unlink($user_data);
  305. array_map('unlink', glob(PSHB_PATH . '/feeds/*/' . $username . '.txt'));
  306. }
  307. return $ok;
  308. }
  309. /**
  310. * This action validates an email address, based on the token sent by email.
  311. * It also serves the main page when user is blocked.
  312. *
  313. * Request parameters are:
  314. * - username
  315. * - token
  316. *
  317. * This route works with GET requests since the URL is provided by email.
  318. * The security risks (e.g. forged URL by an attacker) are not very high so
  319. * it's ok.
  320. *
  321. * It returns 404 error if `force_email_validation` is disabled or if the
  322. * user doesn't exist.
  323. *
  324. * It returns 403 if user isn't logged in and `username` param isn't passed.
  325. */
  326. public function validateEmailAction() {
  327. if (!FreshRSS_Context::$system_conf->force_email_validation) {
  328. Minz_Error::error(404);
  329. }
  330. Minz_View::prependTitle(_t('user.email.validation.title') . ' · ');
  331. $this->view->_layout('simple');
  332. $username = Minz_Request::param('username');
  333. $token = Minz_Request::param('token');
  334. if ($username) {
  335. $user_config = get_user_configuration($username);
  336. } elseif (FreshRSS_Auth::hasAccess()) {
  337. $user_config = FreshRSS_Context::$user_conf;
  338. } else {
  339. Minz_Error::error(403);
  340. }
  341. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  342. Minz_Error::error(404);
  343. }
  344. if ($user_config->email_validation_token === '') {
  345. Minz_Request::good(
  346. _t('user.email.validation.feedback.unnecessary'),
  347. array('c' => 'index', 'a' => 'index')
  348. );
  349. }
  350. if ($token) {
  351. if ($user_config->email_validation_token !== $token) {
  352. Minz_Request::bad(
  353. _t('user.email.validation.feedback.wrong_token'),
  354. array('c' => 'user', 'a' => 'validateEmail')
  355. );
  356. }
  357. $user_config->email_validation_token = '';
  358. if ($user_config->save()) {
  359. Minz_Request::good(
  360. _t('user.email.validation.feedback.ok'),
  361. array('c' => 'index', 'a' => 'index')
  362. );
  363. } else {
  364. Minz_Request::bad(
  365. _t('user.email.validation.feedback.error'),
  366. array('c' => 'user', 'a' => 'validateEmail')
  367. );
  368. }
  369. }
  370. }
  371. /**
  372. * This action resends a validation email to the current user.
  373. *
  374. * It only acts on POST requests but doesn't require any param (except the
  375. * CSRF token).
  376. *
  377. * It returns 403 error if the user is not logged in or 404 if request is
  378. * not POST. Else it redirects silently to the index if user has already
  379. * validated its email, or to the user#validateEmail route.
  380. */
  381. public function sendValidationEmailAction() {
  382. if (!FreshRSS_Auth::hasAccess()) {
  383. Minz_Error::error(403);
  384. }
  385. if (!Minz_Request::isPost()) {
  386. Minz_Error::error(404);
  387. }
  388. $username = Minz_Session::param('currentUser', '_');
  389. $user_config = FreshRSS_Context::$user_conf;
  390. if ($user_config->email_validation_token === '') {
  391. Minz_Request::forward(array(
  392. 'c' => 'index',
  393. 'a' => 'index',
  394. ), true);
  395. }
  396. $mailer = new FreshRSS_User_Mailer();
  397. $ok = $mailer->send_email_need_validation($username, $user_config);
  398. $redirect_url = array('c' => 'user', 'a' => 'validateEmail');
  399. if ($ok) {
  400. Minz_Request::good(
  401. _t('user.email.validation.feedback.email_sent'),
  402. $redirect_url
  403. );
  404. } else {
  405. Minz_Request::bad(
  406. _t('user.email.validation.feedback.email_failed'),
  407. $redirect_url
  408. );
  409. }
  410. }
  411. /**
  412. * This action delete an existing user.
  413. *
  414. * Request parameter is:
  415. * - username
  416. *
  417. * @todo clean up this method. Idea: create a User->clean() method.
  418. */
  419. public function deleteAction() {
  420. $username = Minz_Request::param('username');
  421. $self_deletion = Minz_Session::param('currentUser', '_') === $username;
  422. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  423. Minz_Error::error(403);
  424. }
  425. $redirect_url = urldecode(Minz_Request::param('r', false, true));
  426. if (!$redirect_url) {
  427. $redirect_url = array('c' => 'user', 'a' => 'manage');
  428. }
  429. if (Minz_Request::isPost()) {
  430. $ok = true;
  431. if ($ok && $self_deletion) {
  432. // We check the password if it's a self-destruction
  433. $nonce = Minz_Session::param('nonce');
  434. $challenge = Minz_Request::param('challenge', '');
  435. $ok &= FreshRSS_FormAuth::checkCredentials(
  436. $username, FreshRSS_Context::$user_conf->passwordHash,
  437. $nonce, $challenge
  438. );
  439. }
  440. if ($ok) {
  441. $ok &= self::deleteUser($username);
  442. }
  443. if ($ok && $self_deletion) {
  444. FreshRSS_Auth::removeAccess();
  445. $redirect_url = array('c' => 'index', 'a' => 'index');
  446. }
  447. invalidateHttpCache();
  448. $notif = array(
  449. 'type' => $ok ? 'good' : 'bad',
  450. 'content' => _t('feedback.user.deleted' . (!$ok ? '.error' : ''), $username)
  451. );
  452. Minz_Session::_param('notification', $notif);
  453. }
  454. Minz_Request::forward($redirect_url, true);
  455. }
  456. public function promoteAction() {
  457. $this->switchAdminAction(true);
  458. }
  459. public function demoteAction() {
  460. $this->switchAdminAction(false);
  461. }
  462. private function switchAdminAction($isAdmin) {
  463. if (!FreshRSS_Auth::hasAccess('admin')) {
  464. Minz_Error::error(403);
  465. }
  466. if (!Minz_Request::isPost()) {
  467. Minz_Error::error(403);
  468. }
  469. $username = Minz_Request::param('username');
  470. if (!FreshRSS_UserDAO::exists($username)) {
  471. Minz_Error::error(404);
  472. }
  473. if (null === $userConfig = get_user_configuration($username)) {
  474. Minz_Error::error(500);
  475. }
  476. $userConfig->_param('is_admin', $isAdmin);
  477. $ok = $userConfig->save();
  478. if ($ok) {
  479. Minz_Request::good(_t('feedback.user.updated', $username), array('c' => 'user', 'a' => 'manage'));
  480. } else {
  481. Minz_Request::bad(_t('feedback.user.updated.error', $username),
  482. array('c' => 'user', 'a' => 'manage'));
  483. }
  484. }
  485. public function detailsAction() {
  486. if (!FreshRSS_Auth::hasAccess('admin')) {
  487. Minz_Error::error(403);
  488. }
  489. $username = Minz_Request::param('username');
  490. if (!FreshRSS_UserDAO::exists($username)) {
  491. Minz_Error::error(404);
  492. }
  493. $this->view->isDefaultUser = $username === FreshRSS_Context::$system_conf->default_user;
  494. $this->view->username = $username;
  495. $this->view->details = $this->retrieveUserDetails($username);
  496. }
  497. private function retrieveUserDetails($username) {
  498. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  499. $entryDAO = FreshRSS_Factory::createEntryDao($username);
  500. $databaseDAO = FreshRSS_Factory::createDatabaseDAO($username);
  501. $userConfiguration = get_user_configuration($username);
  502. return array(
  503. 'feed_count' => $feedDAO->count(),
  504. 'article_count' => $entryDAO->count(),
  505. 'database_size' => $databaseDAO->size(),
  506. 'language' => $userConfiguration->language,
  507. 'mail_login' => $userConfiguration->mail_login,
  508. 'is_admin' => $userConfiguration->is_admin,
  509. );
  510. }
  511. }