userController.php 22 KB

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