From f3f764bc39fe0210ac4cc995cf72ea99fac7bef3 Mon Sep 17 00:00:00 2001 From: nupplaPhil Date: Thu, 20 Feb 2020 23:43:52 +0100 Subject: [PATCH] Add new possibility to add a user per console --- src/Console/User.php | 91 +++++++++++++++++++++------ src/Core/L10n.php | 7 ++- src/DI.php | 6 ++ src/Model/User.php | 15 +++++ src/Model/UserService.php | 125 +++++++++++++++++++++++++++++++++++++ src/Module/Admin/Users.php | 63 +++---------------- 6 files changed, 230 insertions(+), 77 deletions(-) create mode 100644 src/Model/UserService.php diff --git a/src/Console/User.php b/src/Console/User.php index c12ab33832..6db2cf84ee 100644 --- a/src/Console/User.php +++ b/src/Console/User.php @@ -25,7 +25,9 @@ use Friendica\App; use Friendica\Core\L10n; use Friendica\Database\Database; use Friendica\Model\User as UserModel; +use Friendica\Model\UserService; use RuntimeException; +use Seld\CliPrompt\CliPrompt; /** * tool to set a new password for a user @@ -48,13 +50,16 @@ class User extends \Asika\SimpleConsole\Console * @var Database */ private $dba; + /** @var UserService */ + private $userService; protected function getHelp() { $help = << password [] [-h|--help|-?] [-v] + bin/console user password [] [-h|--help|-?] [-v] + bin/console user add [ [ [ []]]] [-h|--help|-?] [-v] Description Modify user settings per console commands. @@ -66,13 +71,14 @@ HELP; return $help; } - public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, array $argv = null) + public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, UserService $userService, array $argv = null) { parent::__construct($argv); $this->appMode = $appMode; $this->l10n = $l10n; $this->dba = $dba; + $this->userService = $userService; } protected function doExecute() @@ -88,26 +94,17 @@ HELP; return 0; } - if (count($this->args) < 2) { - throw new \Asika\SimpleConsole\CommandArgsException('Not enough arguments.'); - } - if ($this->appMode->isInstall()) { throw new RuntimeException('Database isn\'t ready or populated yet'); } - $nick = $this->getArgument(0); - - $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); - if (!$this->dba->isResult($user)) { - throw new RuntimeException($this->l10n->t('User not found')); - } - - $command = $this->getArgument(1); + $command = $this->getArgument(0); switch ($command) { case 'password': - return $this->setPassword($user); + return $this->password(); + case 'add': + return $this->addUser(); default: throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.'); } @@ -116,17 +113,24 @@ HELP; /** * Sets a new password * - * @param array $user The user - * * @return int Return code of this command + * + * @throws \Exception */ - private function setPassword(array $user) + private function password() { + $nick = $this->getArgument(1); + + $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); + if (!$this->dba->isResult($user)) { + throw new RuntimeException($this->l10n->t('User not found')); + } + $password = $this->getArgument(2); if (is_null($password)) { $this->out($this->l10n->t('Enter new password: '), false); - $password = \Seld\CliPrompt\CliPrompt::hiddenPrompt(true); + $password = CliPrompt::hiddenPrompt(true); } try { @@ -143,4 +147,53 @@ HELP; return 0; } + + /** + * Adds a new user based on given console arguments + * + * @return bool True, if the command was successful + * @throws \ErrorException + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws \ImagickException + */ + private function addUser() + { + $name = $this->getArgument(1); + $nick = $this->getArgument(2); + $email= $this->getArgument(3); + $lang = $this->getArgument(4); + + if (empty($name)) { + $this->out($this->l10n->t('Enter user name: ')); + $name = CliPrompt::prompt(); + if (empty($name)) { + throw new RuntimeException('A name must be set.'); + } + } + if (empty($nick)) { + $this->out($this->l10n->t('Enter user nickname: ')); + $nick = CliPrompt::prompt(); + if (empty($nick)) { + throw new RuntimeException('A nick name must be set.'); + } + } + if (empty($email)) { + $this->out($this->l10n->t('Enter user email address: ')); + $email = CliPrompt::prompt(); + if (empty($email)) { + throw new RuntimeException('A email address must be set.'); + } + } + + if (empty($lang)) { + $this->out($this->l10n->t('Enter a language (optional): ')); + $lang = CliPrompt::prompt(); + } + + if (empty($lang)) { + return $this->userService->createMinimal($name, $email, $nick); + } else { + return $this->userService->createMinimal($name, $email, $nick, $lang); + } + } } diff --git a/src/Core/L10n.php b/src/Core/L10n.php index cda83ac3f4..8e6ee171c8 100644 --- a/src/Core/L10n.php +++ b/src/Core/L10n.php @@ -33,6 +33,9 @@ use Psr\Log\LoggerInterface; */ class L10n { + /** @var string The default language */ + const DEFAULT = 'en'; + /** * A string indicating the current language used for translation: * - Two-letter ISO 639-1 code. @@ -64,7 +67,7 @@ class L10n $this->dba = $dba; $this->logger = $logger; - $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en'))); + $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', self::DEFAULT))); $this->setSessionVariable($session); $this->setLangFromSession($session); } @@ -158,7 +161,7 @@ class L10n * * @return string The two-letter language code */ - public static function detectLanguage(array $server, array $get, string $sysLang = 'en') + public static function detectLanguage(array $server, array $get, string $sysLang = self::DEFAULT) { $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null; diff --git a/src/DI.php b/src/DI.php index 39efe2a97b..b1d2b82c1d 100644 --- a/src/DI.php +++ b/src/DI.php @@ -315,6 +315,12 @@ abstract class DI return self::$dice->create(Model\Storage\IStorage::class); } + /** @return Model\UserService */ + public static function userService() + { + return self::$dice->create(Model\UserService::class); + } + // // "Repository" namespace // diff --git a/src/Model/User.php b/src/Model/User.php index e4ef07e473..27b87f9971 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -880,6 +880,21 @@ class User return $return; } + /** + * Sets block state for a given user + * + * @param int $uid The user id + * @param bool $block Block state (default is true) + * + * @return bool True, if successfully blocked + + * @throws Exception + */ + public static function block(int $uid, bool $block = true) + { + return DBA::update('user', ['blocked' => 0], ['uid' => $uid]); + } + /** * Sends pending registration confirmation email * diff --git a/src/Model/UserService.php b/src/Model/UserService.php new file mode 100644 index 0000000000..6da45e40e3 --- /dev/null +++ b/src/Model/UserService.php @@ -0,0 +1,125 @@ +. + * + */ + +namespace Friendica\Model; + +use ErrorException; +use Friendica\App; +use Friendica\Core\Config\IConfig; +use Friendica\Core\L10n; +use Friendica\Network\HTTPException\InternalServerErrorException; +use Friendica\Util\Emailer; +use Friendica\Util\Strings; +use Friendica\Model\User as UserModel; +use ImagickException; + +class UserService +{ + /** @var L10n */ + private $l10n; + /** @var IConfig */ + private $config; + /** @var App\BaseURL */ + private $baseUrl; + /** @var Emailer */ + private $emailer; + + public function __construct(L10n $l10n, IConfig $config, Emailer $emailer, App\BaseURL $baseUrl) + { + $this->l10n = $l10n; + $this->config = $config; + $this->emailer = $emailer; + $this->baseUrl = $baseUrl; + } + + /** + * Creates a new user based on a minimal set and sends an email to this user + * + * @param string $name The user's name + * @param string $email The user's email address + * @param string $nick The user's nick name + * @param string $lang The user's language (default is english) + * + * @return bool True, if the user was created successfully + * @throws InternalServerErrorException + * @throws ErrorException + * @throws ImagickException + */ + public function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT) + { + if (empty($name) || + empty($email) || + empty($nick)) { + throw new InternalServerErrorException('Invalid arguments.'); + } + + $result = UserModel::create([ + 'username' => $name, + 'email' => $email, + 'nickname' => $nick, + 'verified' => 1, + 'language' => $lang + ]); + + $user = $result['user']; + $preamble = Strings::deindent($this->l10n->t(' + Dear %1$s, + the administrator of %2$s has set up an account for you.')); + $body = Strings::deindent($this->l10n->t(' + The login details are as follows: + + Site Location: %1$s + Login Name: %2$s + Password: %3$s + + You may change your password from your account "Settings" page after logging + in. + + Please take a few moments to review the other account settings on that page. + + You may also wish to add some basic information to your default profile + (on the "Profiles" page) so that other people can easily find you. + + We recommend setting your full name, adding a profile photo, + adding some profile "keywords" (very useful in making new friends) - and + perhaps what country you live in; if you do not wish to be more specific + than that. + + We fully respect your right to privacy, and none of these items are necessary. + If you are new and do not know anybody here, they may help + you to make some new and interesting friends. + + If you ever want to delete your account, you can do so at %1$s/removeme + + Thank you and welcome to %4$s.')); + + $preamble = sprintf($preamble, $user['username'], $this->config->get('config', 'sitename')); + $body = sprintf($body, $this->baseUrl->get(), $user['nickname'], $result['password'], $this->config->get('config', 'sitename')); + + $email = $this->emailer + ->newSystemMail() + ->withMessage($this->l10n->t('Registration details for %s', $this->config->get('config', 'sitename')), $preamble, $body) + ->forUser($user) + ->withRecipient($user['email']) + ->build(); + return $this->emailer->send($email); + } +} diff --git a/src/Module/Admin/Users.php b/src/Module/Admin/Users.php index f5e2d5ed37..20a31333c2 100644 --- a/src/Module/Admin/Users.php +++ b/src/Module/Admin/Users.php @@ -48,72 +48,23 @@ class Users extends BaseAdmin if ($nu_name !== '' && $nu_email !== '' && $nu_nickname !== '') { try { - $result = User::create([ - 'username' => $nu_name, - 'email' => $nu_email, - 'nickname' => $nu_nickname, - 'verified' => 1, - 'language' => $nu_language - ]); + DI::userService()->createMinimal($nu_name, $nu_email, $nu_nickname, $nu_language); } catch (\Exception $ex) { notice($ex->getMessage()); return; } - - $user = $result['user']; - $preamble = Strings::deindent(DI::l10n()->t(' - Dear %1$s, - the administrator of %2$s has set up an account for you.')); - $body = Strings::deindent(DI::l10n()->t(' - The login details are as follows: - - Site Location: %1$s - Login Name: %2$s - Password: %3$s - - You may change your password from your account "Settings" page after logging - in. - - Please take a few moments to review the other account settings on that page. - - You may also wish to add some basic information to your default profile - (on the "Profiles" page) so that other people can easily find you. - - We recommend setting your full name, adding a profile photo, - adding some profile "keywords" (very useful in making new friends) - and - perhaps what country you live in; if you do not wish to be more specific - than that. - - We fully respect your right to privacy, and none of these items are necessary. - If you are new and do not know anybody here, they may help - you to make some new and interesting friends. - - If you ever want to delete your account, you can do so at %1$s/removeme - - Thank you and welcome to %4$s.')); - - $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename')); - $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename')); - - $email = DI::emailer() - ->newSystemMail() - ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body) - ->forUser($user) - ->withRecipient($user['email']) - ->build(); - return DI::emailer()->send($email); } if (!empty($_POST['page_users_block'])) { - // @TODO Move this to Model\User:block($users); - DBA::update('user', ['blocked' => 1], ['uid' => $users]); - notice(DI::l10n()->tt('%s user blocked', '%s users blocked', count($users))); + if (User::block($users)) { + notice(DI::l10n()->tt('%s user blocked', '%s users blocked', count($users))); + } } if (!empty($_POST['page_users_unblock'])) { - // @TODO Move this to Model\User:unblock($users); - DBA::update('user', ['blocked' => 0], ['uid' => $users]); - notice(DI::l10n()->tt('%s user unblocked', '%s users unblocked', count($users))); + if (User::block($users, false)) { + notice(DI::l10n()->tt('%s user unblocked', '%s users unblocked', count($users))); + } } if (!empty($_POST['page_users_delete'])) {