]> git.mxchange.org Git - friendica.git/blob - src/Console/User.php
215a09e2597c8f30d489bbe470a0c032793bdcf6
[friendica.git] / src / Console / User.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Console;
23
24 use Console_Table;
25 use Friendica\App;
26 use Friendica\Content\Pager;
27 use Friendica\Core\L10n;
28 use Friendica\Database\Database;
29 use Friendica\Model\Register;
30 use Friendica\Model\User as UserModel;
31 use Friendica\Util\Temporal;
32 use RuntimeException;
33 use Seld\CliPrompt\CliPrompt;
34
35 /**
36  * tool to manage users of the current node
37  */
38 class User extends \Asika\SimpleConsole\Console
39 {
40         protected $helpOptions = ['h', 'help', '?'];
41
42         /**
43          * @var App\Mode
44          */
45         private $appMode;
46         /**
47          * @var L10n
48          */
49         private $l10n;
50         /**
51          * @var Database
52          */
53         private $dba;
54
55         protected function getHelp()
56         {
57                 $help = <<<HELP
58 console user - Modify user settings per console commands.
59 Usage
60         bin/console user password <nickname> [<password>] [-h|--help|-?] [-v]
61         bin/console user add [<name> [<nickname> [<email> [<language>]]]] [-h|--help|-?] [-v]
62         bin/console user delete [<nickname>] [-y] [-h|--help|-?] [-v]
63         bin/console user allow [<nickname>] [-h|--help|-?] [-v]
64         bin/console user deny [<nickname>] [-h|--help|-?] [-v]
65         bin/console user block [<nickname>] [-h|--help|-?] [-v]
66         bin/console user unblock [<nickname>] [-h|--help|-?] [-v]
67         bin/console user list pending [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
68         bin/console user list removed [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
69         bin/console user list active [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
70         bin/console user list all [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
71         bin/console user search id <UID> [-h|--help|-?] [-v]
72         bin/console user search nick <nick> [-h|--help|-?] [-v]
73         bin/console user search mail <mail> [-h|--help|-?] [-v]
74         bin/console user search guid <GUID> [-h|--help|-?] [-v]
75
76 Description
77         Modify user settings per console commands.
78
79 Options
80     -h|--help|-? Show help information
81     -v           Show more debug information
82     -y           Non-interactive mode, assume "yes" as answer to the user deletion prompt
83 HELP;
84                 return $help;
85         }
86
87         public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, array $argv = null)
88         {
89                 parent::__construct($argv);
90
91                 $this->appMode     = $appMode;
92                 $this->l10n        = $l10n;
93                 $this->dba         = $dba;
94         }
95
96         protected function doExecute()
97         {
98                 if ($this->getOption('v')) {
99                         $this->out('Class: ' . __CLASS__);
100                         $this->out('Arguments: ' . var_export($this->args, true));
101                         $this->out('Options: ' . var_export($this->options, true));
102                 }
103
104                 if (count($this->args) == 0) {
105                         $this->out($this->getHelp());
106                         return 0;
107                 }
108
109                 if ($this->appMode->isInstall()) {
110                         throw new RuntimeException('Database isn\'t ready or populated yet');
111                 }
112
113                 $command = $this->getArgument(0);
114
115                 switch ($command) {
116                         case 'password':
117                                 return $this->password();
118                         case 'add':
119                                 return $this->addUser();
120                         case 'allow':
121                                 return $this->pendingUser(true);
122                         case 'deny':
123                                 return $this->pendingUser(false);
124                         case 'block':
125                                 return $this->blockUser(true);
126                         case 'unblock':
127                                 return $this->blockUser(false);
128                         case 'delete':
129                                 return $this->deleteUser();
130                         case 'list':
131                                 return $this->listUser();
132                         case 'search':
133                                 return $this->searchUser();
134                         default:
135                                 throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.');
136                 }
137         }
138
139         /**
140          * Retrieves the user nick, either as an argument or from a prompt
141          *
142          * @param int $arg_index Index of the nick argument in the arguments list
143          *
144          * @return string nick of the user
145          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
146          */
147         private function getNick($arg_index)
148         {
149                 $nick = $this->getArgument($arg_index);
150
151                 if (!$nick) {
152                         $this->out($this->l10n->t('Enter user nickname: '));
153                         $nick = CliPrompt::prompt();
154                         if (empty($nick)) {
155                                 throw new RuntimeException('A nick name must be set.');
156                         }
157                 }
158
159                 return $nick;
160         }
161
162         /**
163          * Retrieves the user from a nick supplied as an argument or from a prompt
164          *
165          * @param int $arg_index Index of the nick argument in the arguments list
166          *
167          * @return mixed user data or dba failure result
168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169          */
170         private function getUserByNick($arg_index)
171         {
172                 $nick = $this->getNick($arg_index);
173
174                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
175                 if (!$this->dba->isResult($user)) {
176                         throw new RuntimeException($this->l10n->t('User not found'));
177                 }
178
179                 return $user;
180         }
181
182         /**
183          * Sets a new password
184          *
185          * @return int Return code of this command
186          *
187          * @throws \Exception
188          */
189         private function password()
190         {
191                 $user = $this->getUserByNick(1);
192
193                 $password = $this->getArgument(2);
194
195                 if (is_null($password)) {
196                         $this->out($this->l10n->t('Enter new password: '), false);
197                         $password = CliPrompt::hiddenPrompt(true);
198                 }
199
200                 try {
201                         $result = UserModel::updatePassword($user['uid'], $password);
202
203                         if (!$this->dba->isResult($result)) {
204                                 throw new \Exception($this->l10n->t('Password update failed. Please try again.'));
205                         }
206
207                         $this->out($this->l10n->t('Password changed.'));
208                 } catch (\Exception $e) {
209                         throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
210                 }
211
212                 return 0;
213         }
214
215         /**
216          * Adds a new user based on given console arguments
217          *
218          * @return bool True, if the command was successful
219          * @throws \ErrorException
220          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
221          * @throws \ImagickException
222          */
223         private function addUser()
224         {
225                 $name  = $this->getArgument(1);
226                 $nick  = $this->getArgument(2);
227                 $email = $this->getArgument(3);
228                 $lang  = $this->getArgument(4);
229
230                 if (empty($name)) {
231                         $this->out($this->l10n->t('Enter user name: '));
232                         $name = CliPrompt::prompt();
233                         if (empty($name)) {
234                                 throw new RuntimeException('A name must be set.');
235                         }
236                 }
237
238                 if (empty($nick)) {
239                         $this->out($this->l10n->t('Enter user nickname: '));
240                         $nick = CliPrompt::prompt();
241                         if (empty($nick)) {
242                                 throw new RuntimeException('A nick name must be set.');
243                         }
244                 }
245
246                 if (empty($email)) {
247                         $this->out($this->l10n->t('Enter user email address: '));
248                         $email = CliPrompt::prompt();
249                         if (empty($email)) {
250                                 throw new RuntimeException('A email address must be set.');
251                         }
252                 }
253
254                 if (empty($lang)) {
255                         $this->out($this->l10n->t('Enter a language (optional): '));
256                         $lang = CliPrompt::prompt();
257                 }
258
259                 if (empty($lang)) {
260                         return UserModel::createMinimal($name, $email, $nick);
261                 } else {
262                         return UserModel::createMinimal($name, $email, $nick, $lang);
263                 }
264         }
265
266         /**
267          * Allows or denys a user based on it's nickname
268          *
269          * @param bool $allow True, if the pending user is allowed, false if denies
270          *
271          * @return bool True, if allow was successful
272          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273          */
274         private function pendingUser(bool $allow = true)
275         {
276                 $user = $this->getUserByNick(1);
277
278                 $pending = Register::getPendingForUser($user['uid'] ?? 0);
279                 if (empty($pending)) {
280                         throw new RuntimeException($this->l10n->t('User is not pending.'));
281                 }
282
283                 return ($allow) ? UserModel::allow($pending['hash']) : UserModel::deny($pending['hash']);
284         }
285
286         /**
287          * Blocks/unblocks a user
288          *
289          * @param bool $block True, if the given user should get blocked
290          *
291          * @return bool True, if the command was successful
292          * @throws \Exception
293          */
294         private function blockUser(bool $block = true)
295         {
296                 $user = $this->getUserByNick(1);
297
298                 return $block ? UserModel::block($user['uid'] ?? 0) : UserModel::block($user['uid'] ?? 0, false);
299         }
300
301         /**
302          * Deletes a user
303          *
304          * @return bool True, if the delete was successful
305          * @throws \Exception
306          */
307         private function deleteUser()
308         {
309                 $user = $this->getUserByNick(1);
310
311                 if (!empty($user['account_removed'])) {
312                         $this->out($this->l10n->t('User has already been marked for deletion.'));
313                         return true;
314                 }
315
316                 if (!$this->getOption('y')) {
317                         $this->out($this->l10n->t('Type "yes" to delete %s', $this->getArgument(1)));
318                         if (CliPrompt::prompt() !== 'yes') {
319                                 throw new RuntimeException($this->l10n->t('Deletion aborted.'));
320                         }
321                 }
322
323                 return UserModel::remove($user['uid']);
324         }
325
326         /**
327          * List users of the current node
328          *
329          * @return bool True, if the command was successful
330          */
331         private function listUser()
332         {
333                 $subCmd = $this->getArgument(1);
334                 $start = $this->getOption(['s', 'start'], 0);
335                 $count = $this->getOption(['c', 'count'], Pager::ITEMS_PER_PAGE);
336
337                 $table = new Console_Table();
338
339                 switch ($subCmd) {
340                         case 'pending':
341                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register Date', 'Comment']);
342                                 $pending = Register::getPending($start, $count);
343                                 foreach ($pending as $contact) {
344                                         $table->addRow([
345                                                 $contact['nick'],
346                                                 $contact['name'],
347                                                 $contact['url'],
348                                                 $contact['email'],
349                                                 Temporal::getRelativeDate($contact['created']),
350                                                 $contact['note'],
351                                         ]);
352                                 }
353                                 $this->out($table->getTable());
354                                 return true;
355                         case 'all':
356                         case 'active':
357                         case 'removed':
358                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register', 'Login', 'Last Item']);
359                                 $contacts = UserModel::getList($start, $count, $subCmd);
360                                 foreach ($contacts as $contact) {
361                                         $table->addRow([
362                                                 $contact['nick'],
363                                                 $contact['name'],
364                                                 $contact['url'],
365                                                 $contact['email'],
366                                                 Temporal::getRelativeDate($contact['created']),
367                                                 Temporal::getRelativeDate($contact['login_date']),
368                                                 Temporal::getRelativeDate($contact['last-item']),
369                                         ]);
370                                 }
371                                 $this->out($table->getTable());
372                                 return true;
373                         default:
374                                 $this->out($this->getHelp());
375                                 return false;
376                 }
377         }
378
379         /**
380          * Returns a user based on search parameter
381          *
382          * @return bool True, if the command was successful
383          */
384         private function searchUser()
385         {
386                 $fields = [
387                         'uid',
388                         'guid',
389                         'username',
390                         'nickname',
391                         'email',
392                         'register_date',
393                         'login_date',
394                         'verified',
395                         'blocked',
396                 ];
397
398                 $subCmd = $this->getArgument(1);
399                 $param = $this->getArgument(2);
400
401                 $table = new Console_Table();
402                 $table->setHeaders(['UID', 'GUID', 'Name', 'Nick', 'E-Mail', 'Register', 'Login', 'Verified', 'Blocked']);
403
404                 switch ($subCmd) {
405                         case 'id':
406                                 $user = UserModel::getById($param, $fields);
407                                 break;
408                         case 'guid':
409                                 $user = UserModel::getByGuid($param, $fields);
410                                 break;
411                         case 'mail':
412                                 $user = UserModel::getByEmail($param, $fields);
413                                 break;
414                         case 'nick':
415                                 $user = UserModel::getByNickname($param, $fields);
416                                 break;
417                         default:
418                                 $this->out($this->getHelp());
419                                 return false;
420                 }
421
422                 $table->addRow($user);
423                 $this->out($table->getTable());
424
425                 return true;
426         }
427 }