userController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. ini_set('session.use_cookies', '1');
  128. Minz_Session::lock();
  129. Minz_Session::regenerateID();
  130. Minz_Session::unlock();
  131. }
  132. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  133. Minz_Request::bad(
  134. _t('user.email.feedback.required'),
  135. ['c' => 'user', 'a' => 'profile']
  136. );
  137. }
  138. if (!empty($email) && !validateEmailAddress($email)) {
  139. Minz_Request::bad(
  140. _t('user.email.feedback.invalid'),
  141. ['c' => 'user', 'a' => 'profile']
  142. );
  143. }
  144. $ok = self::updateUser(
  145. Minz_User::name(),
  146. $email,
  147. $newPasswordPlain,
  148. [
  149. 'token' => Minz_Request::paramString('token'),
  150. ]
  151. );
  152. Minz_Session::_param('passwordHash', FreshRSS_Context::userConf()->passwordHash);
  153. if ($ok) {
  154. if (FreshRSS_Context::systemConf()->force_email_validation && $email !== $old_email) {
  155. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'user', 'a' => 'validateEmail']);
  156. } elseif ($newPasswordPlain == '') {
  157. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'user', 'a' => 'profile']);
  158. } else {
  159. Minz_Request::good(_t('feedback.profile.updated'), ['c' => 'index', 'a' => 'index']);
  160. }
  161. } else {
  162. Minz_Request::bad(_t('feedback.profile.error'), ['c' => 'user', 'a' => 'profile']);
  163. }
  164. }
  165. }
  166. public static function reauthRedirect(): bool {
  167. $url_redirect = [
  168. 'c' => 'user',
  169. 'a' => 'manage',
  170. 'params' => [],
  171. ];
  172. $username = Minz_Request::paramStringNull('username');
  173. if ($username !== null) {
  174. $url_redirect['a'] = 'details';
  175. $url_redirect['params']['username'] = $username;
  176. }
  177. return FreshRSS_Auth::requestReauth($url_redirect);
  178. }
  179. public function purgeAction(): void {
  180. if (!FreshRSS_Auth::hasAccess('admin')) {
  181. Minz_Error::error(403);
  182. }
  183. if (!Minz_Request::isPost()) {
  184. Minz_Error::error(403);
  185. }
  186. if (self::reauthRedirect()) {
  187. return;
  188. }
  189. $username = Minz_Request::paramString('username');
  190. if (!FreshRSS_UserDAO::exists($username)) {
  191. Minz_Error::error(404);
  192. }
  193. $feedDAO = FreshRSS_Factory::createFeedDao($username);
  194. $feedDAO->purge();
  195. }
  196. /**
  197. * This action displays the user management page.
  198. */
  199. public function manageAction(): void {
  200. if (!FreshRSS_Auth::hasAccess('admin')) {
  201. Minz_Error::error(403);
  202. }
  203. if (self::reauthRedirect()) {
  204. return;
  205. }
  206. FreshRSS_View::prependTitle(_t('admin.user.title') . ' · ');
  207. if (Minz_Request::isPost()) {
  208. $action = Minz_Request::paramString('action');
  209. switch ($action) {
  210. case 'delete':
  211. $this->deleteAction();
  212. break;
  213. case 'update':
  214. $this->updateAction();
  215. break;
  216. case 'purge':
  217. $this->purgeAction();
  218. break;
  219. case 'promote':
  220. $this->promoteAction();
  221. break;
  222. case 'demote':
  223. $this->demoteAction();
  224. break;
  225. case 'enable':
  226. $this->enableAction();
  227. break;
  228. case 'disable':
  229. $this->disableAction();
  230. break;
  231. }
  232. }
  233. $this->view->show_email_field = FreshRSS_Context::systemConf()->force_email_validation;
  234. $this->view->current_user = Minz_Request::paramString('u');
  235. foreach (listUsers() as $user) {
  236. $this->view->users[$user] = $this->retrieveUserDetails($user);
  237. }
  238. }
  239. /**
  240. * @param array<string,mixed> $userConfigOverride
  241. * @throws Minz_ConfigurationNamespaceException
  242. * @throws Minz_PDOConnectionException
  243. */
  244. public static function createUser(string $new_user_name, ?string $email, string $passwordPlain,
  245. array $userConfigOverride = [], bool $insertDefaultFeeds = true): bool {
  246. $userConfig = [];
  247. $customUserConfigPath = join_path(DATA_PATH, 'config-user.custom.php');
  248. if (file_exists($customUserConfigPath)) {
  249. $customUserConfig = include($customUserConfigPath);
  250. if (is_array($customUserConfig)) {
  251. $userConfig = $customUserConfig;
  252. }
  253. }
  254. $userConfig = array_merge($userConfig, $userConfigOverride);
  255. $ok = self::checkUsername($new_user_name);
  256. $homeDir = join_path(DATA_PATH, 'users', $new_user_name);
  257. // create basepath if missing
  258. if (!is_dir(join_path(DATA_PATH, 'users'))) {
  259. $ok &= mkdir(join_path(DATA_PATH, 'users'), 0770, true);
  260. }
  261. $configPath = '';
  262. if ($ok) {
  263. $languages = Minz_Translate::availableLanguages();
  264. if (empty($userConfig['language']) || !in_array($userConfig['language'], $languages, true)) {
  265. $userConfig['language'] = 'en';
  266. }
  267. $ok &= !in_array(strtoupper($new_user_name), array_map('strtoupper', listUsers()), true); //Not an existing user, case-insensitive
  268. $configPath = join_path($homeDir, 'config.php');
  269. $ok &= !file_exists($configPath);
  270. }
  271. if ($ok) {
  272. // $homeDir must not exist beforehand,
  273. // otherwise it might be multiple remote parties racing to register one username
  274. $ok = mkdir($homeDir, 0770, true);
  275. if ($ok) {
  276. $ok &= (file_put_contents($configPath, "<?php\n return " . var_export($userConfig, true) . ';') !== false);
  277. }
  278. }
  279. if ($ok) {
  280. $newUserDAO = FreshRSS_Factory::createUserDao($new_user_name);
  281. $ok &= $newUserDAO->createUser();
  282. if ($ok && $insertDefaultFeeds) {
  283. $opmlPath = DATA_PATH . '/opml.xml';
  284. if (!file_exists($opmlPath)) {
  285. $opmlPath = FRESHRSS_PATH . '/opml.default.xml';
  286. }
  287. $importController = new FreshRSS_importExport_Controller();
  288. try {
  289. $importController->importFile($opmlPath, $opmlPath, $new_user_name);
  290. } catch (Exception $e) {
  291. Minz_Log::error('Error while importing default OPML for user ' . $new_user_name . ': ' . $e->getMessage());
  292. }
  293. }
  294. $ok &= self::updateUser($new_user_name, $email, $passwordPlain);
  295. }
  296. return (bool)$ok;
  297. }
  298. /**
  299. * This action creates a new user.
  300. *
  301. * Request parameters are:
  302. * - new_user_language
  303. * - new_user_name
  304. * - new_user_email
  305. * - new_user_passwordPlain
  306. * - r (i.e. a redirection url, optional)
  307. *
  308. * @todo clean up this method. Idea: write a method to init a user with basic information.
  309. */
  310. public function createAction(): void {
  311. if (!FreshRSS_Auth::hasAccess('admin') && max_registrations_reached()) {
  312. Minz_Error::error(403);
  313. }
  314. if (self::reauthRedirect()) {
  315. return;
  316. }
  317. if (Minz_Request::isPost()) {
  318. $new_user_name = Minz_Request::paramString('new_user_name');
  319. $email = Minz_Request::paramString('new_user_email');
  320. $passwordPlain = Minz_Request::paramString('new_user_passwordPlain', true);
  321. $badRedirectUrl = [
  322. 'c' => Minz_Request::paramString('originController') ?: 'auth',
  323. 'a' => Minz_Request::paramString('originAction') ?: 'register',
  324. ];
  325. if (!self::checkUsername($new_user_name)) {
  326. Minz_Request::bad(
  327. _t('user.username.invalid'),
  328. $badRedirectUrl
  329. );
  330. }
  331. if (FreshRSS_UserDAO::exists($new_user_name)) {
  332. Minz_Request::bad(
  333. _t('user.username.taken', $new_user_name),
  334. $badRedirectUrl
  335. );
  336. }
  337. if (!FreshRSS_password_Util::check($passwordPlain)) {
  338. Minz_Request::bad(
  339. _t('user.password.invalid'),
  340. $badRedirectUrl
  341. );
  342. }
  343. if (!FreshRSS_Auth::hasAccess('admin')) {
  344. // TODO: We may want to ask the user to accept TOS before first login
  345. $tos_enabled = file_exists(TOS_FILENAME);
  346. $accept_tos = Minz_Request::paramBoolean('accept_tos');
  347. if ($tos_enabled && !$accept_tos) {
  348. Minz_Request::bad(_t('user.tos.feedback.invalid'), $badRedirectUrl);
  349. }
  350. }
  351. if (FreshRSS_Context::systemConf()->force_email_validation && empty($email)) {
  352. Minz_Request::bad(
  353. _t('user.email.feedback.required'),
  354. $badRedirectUrl
  355. );
  356. }
  357. if (!empty($email) && !validateEmailAddress($email)) {
  358. Minz_Request::bad(
  359. _t('user.email.feedback.invalid'),
  360. $badRedirectUrl
  361. );
  362. }
  363. $ok = self::createUser($new_user_name, $email, $passwordPlain, [
  364. 'language' => Minz_Request::paramString('new_user_language') ?: FreshRSS_Context::userConf()->language,
  365. 'timezone' => Minz_Request::paramString('new_user_timezone'),
  366. 'is_admin' => Minz_Request::paramBoolean('new_user_is_admin'),
  367. 'enabled' => true,
  368. ]);
  369. Minz_Request::_param('new_user_passwordPlain'); //Discard plain-text password ASAP
  370. $_POST['new_user_passwordPlain'] = '';
  371. invalidateHttpCache();
  372. // If the user has admin access, it means he’s already logged in
  373. // and we don’t want to login with the new account. Otherwise, the
  374. // user just created its account himself so he probably wants to
  375. // get started immediately.
  376. if ($ok && !FreshRSS_Auth::hasAccess('admin')) {
  377. $user_conf = get_user_configuration($new_user_name);
  378. if ($user_conf !== null) {
  379. Minz_Session::_params([
  380. Minz_User::CURRENT_USER => $new_user_name,
  381. 'passwordHash' => $user_conf->passwordHash,
  382. 'csrf' => false,
  383. ]);
  384. FreshRSS_Auth::giveAccess();
  385. } else {
  386. $ok = false;
  387. }
  388. }
  389. if ($ok) {
  390. Minz_Request::setGoodNotification(_t('feedback.user.created', $new_user_name));
  391. } else {
  392. Minz_Request::setBadNotification(_t('feedback.user.created.error', $new_user_name));
  393. }
  394. }
  395. if (FreshRSS_Auth::hasAccess('admin')) {
  396. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  397. } else {
  398. $redirect_url = ['c' => 'index', 'a' => 'index'];
  399. }
  400. Minz_Request::forward($redirect_url, true);
  401. }
  402. public static function deleteUser(string $username): bool {
  403. $ok = self::checkUsername($username);
  404. if ($ok) {
  405. $default_user = FreshRSS_Context::systemConf()->default_user;
  406. $ok &= (strcasecmp($username, $default_user) !== 0); //It is forbidden to delete the default user
  407. }
  408. $user_data = join_path(DATA_PATH, 'users', $username);
  409. $ok &= is_dir($user_data);
  410. if ($ok) {
  411. FreshRSS_fever_Util::deleteKey($username);
  412. Minz_ModelPdo::$usesSharedPdo = false;
  413. $oldUserDAO = FreshRSS_Factory::createUserDao($username);
  414. $ok &= $oldUserDAO->deleteUser();
  415. Minz_ModelPdo::$usesSharedPdo = true;
  416. $ok &= recursive_unlink($user_data);
  417. $filenames = glob(PSHB_PATH . '/feeds/*/' . $username . '.txt');
  418. if (!empty($filenames)) {
  419. array_map('unlink', $filenames);
  420. }
  421. }
  422. return (bool)$ok;
  423. }
  424. /**
  425. * This action validates an email address, based on the token sent by email.
  426. * It also serves the main page when user is blocked.
  427. *
  428. * Request parameters are:
  429. * - username
  430. * - token
  431. *
  432. * This route works with GET requests since the URL is provided by email.
  433. * The security risks (e.g. forged URL by an attacker) are not very high so
  434. * it’s ok.
  435. *
  436. * It returns 404 error if `force_email_validation` is disabled or if the
  437. * user doesn’t exist.
  438. *
  439. * It returns 403 if user isn’t logged in and `username` param isn’t passed.
  440. */
  441. public function validateEmailAction(): void {
  442. if (!FreshRSS_Context::systemConf()->force_email_validation) {
  443. Minz_Error::error(404);
  444. }
  445. FreshRSS_View::prependTitle(_t('user.email.validation.title') . ' · ');
  446. $this->view->_layout('simple');
  447. $username = Minz_Request::paramString('username');
  448. $token = Minz_Request::paramString('token');
  449. if ($username !== '') {
  450. $user_config = get_user_configuration($username);
  451. } elseif (FreshRSS_Auth::hasAccess()) {
  452. $user_config = FreshRSS_Context::userConf();
  453. } else {
  454. Minz_Error::error(403);
  455. return;
  456. }
  457. if (!FreshRSS_UserDAO::exists($username) || $user_config === null) {
  458. Minz_Error::error(404);
  459. return;
  460. }
  461. if ($user_config->email_validation_token === '') {
  462. Minz_Request::good(
  463. _t('user.email.validation.feedback.unnecessary'),
  464. ['c' => 'index', 'a' => 'index']
  465. );
  466. }
  467. if ($token != '') {
  468. if ($user_config->email_validation_token !== $token) {
  469. Minz_Request::bad(
  470. _t('user.email.validation.feedback.wrong_token'),
  471. ['c' => 'user', 'a' => 'validateEmail']
  472. );
  473. }
  474. $user_config->email_validation_token = '';
  475. if ($user_config->save()) {
  476. Minz_Request::good(
  477. _t('user.email.validation.feedback.ok'),
  478. ['c' => 'index', 'a' => 'index']
  479. );
  480. } else {
  481. Minz_Request::bad(
  482. _t('user.email.validation.feedback.error'),
  483. ['c' => 'user', 'a' => 'validateEmail']
  484. );
  485. }
  486. }
  487. }
  488. /**
  489. * This action resends a validation email to the current user.
  490. *
  491. * It only acts on POST requests but doesn’t require any param (except the
  492. * CSRF token).
  493. *
  494. * It returns 403 error if the user is not logged in or 404 if request is
  495. * not POST. Else it redirects silently to the index if user has already
  496. * validated its email, or to the user#validateEmail route.
  497. */
  498. public function sendValidationEmailAction(): void {
  499. if (!FreshRSS_Auth::hasAccess()) {
  500. Minz_Error::error(403);
  501. }
  502. if (!Minz_Request::isPost()) {
  503. Minz_Error::error(404);
  504. }
  505. $username = Minz_User::name();
  506. if (FreshRSS_Context::userConf()->email_validation_token === '') {
  507. Minz_Request::forward([
  508. 'c' => 'index',
  509. 'a' => 'index',
  510. ], true);
  511. }
  512. $mailer = new FreshRSS_User_Mailer();
  513. $ok = $username != null && $mailer->send_email_need_validation($username, FreshRSS_Context::userConf());
  514. $redirect_url = ['c' => 'user', 'a' => 'validateEmail'];
  515. if ($ok) {
  516. Minz_Request::good(
  517. _t('user.email.validation.feedback.email_sent'),
  518. $redirect_url
  519. );
  520. } else {
  521. Minz_Request::bad(
  522. _t('user.email.validation.feedback.email_failed'),
  523. $redirect_url
  524. );
  525. }
  526. }
  527. /**
  528. * This action delete an existing user.
  529. *
  530. * Request parameter is:
  531. * - username
  532. *
  533. * @todo clean up this method. Idea: create a User->clean() method.
  534. */
  535. public function deleteAction(): void {
  536. $username = Minz_Request::paramString('username');
  537. $self_deletion = Minz_User::name() === $username;
  538. if (!FreshRSS_Auth::hasAccess('admin') && !$self_deletion) {
  539. Minz_Error::error(403);
  540. }
  541. $redirect_url = ['c' => 'user', 'a' => 'manage'];
  542. if (Minz_Request::isPost()) {
  543. $ok = true;
  544. if ($self_deletion) {
  545. // We check the password if it’s a self-destruction
  546. $nonce = Minz_Session::paramString('nonce');
  547. $challenge = Minz_Request::paramString('challenge');
  548. $ok &= FreshRSS_FormAuth::checkCredentials(
  549. $username, FreshRSS_Context::userConf()->passwordHash,
  550. $nonce, $challenge
  551. );
  552. } elseif (self::reauthRedirect()) {
  553. return;
  554. }
  555. if ($ok) {
  556. $ok &= self::deleteUser($username);
  557. }
  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. }