]> git.mxchange.org Git - friendica.git/blob - src/Console/User.php
Merge pull request #13832 from mexon/console-set-password
[friendica.git] / src / Console / User.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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\Core\PConfig\Capability\IManagePersonalConfigValues;
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 IManagePersonalConfigValues
52          */
53         private $pConfig;
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> [<avatar_url>]]]]] [-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         bin/console user config list [<nickname>] [<category>] [-h|--help|-?] [-v]
76         bin/console user config get [<nickname>] [<category>] [<key>] [-h|--help|-?] [-v]
77         bin/console user config set [<nickname>] [<category>] [<key>] [<value>] [-h|--help|-?] [-v]
78         bin/console user config delete [<nickname>] [<category>] [<key>] [-h|--help|-?] [-v]
79
80 Description
81         Modify user settings per console commands.
82
83 Options
84     -h|--help|-? Show help information
85     -v           Show more debug information
86     -y           Non-interactive mode, assume "yes" as answer to the user deletion prompt
87 HELP;
88                 return $help;
89         }
90
91         public function __construct(App\Mode $appMode, L10n $l10n, IManagePersonalConfigValues $pConfig, array $argv = null)
92         {
93                 parent::__construct($argv);
94
95                 $this->appMode = $appMode;
96                 $this->l10n    = $l10n;
97                 $this->pConfig = $pConfig;
98         }
99
100         protected function doExecute(): int
101         {
102                 if ($this->getOption('v')) {
103                         $this->out('Class: ' . __CLASS__);
104                         $this->out('Arguments: ' . var_export($this->args, true));
105                         $this->out('Options: ' . var_export($this->options, true));
106                 }
107
108                 if (count($this->args) == 0) {
109                         $this->out($this->getHelp());
110                         return 0;
111                 }
112
113                 if ($this->appMode->isInstall()) {
114                         throw new RuntimeException('Database isn\'t ready or populated yet');
115                 }
116
117                 $command = $this->getArgument(0);
118
119                 switch ($command) {
120                         case 'password':
121                                 return $this->password();
122                         case 'add':
123                                 return $this->addUser();
124                         case 'allow':
125                                 return $this->pendingUser(true);
126                         case 'deny':
127                                 return $this->pendingUser(false);
128                         case 'block':
129                                 return $this->blockUser(true);
130                         case 'unblock':
131                                 return $this->blockUser(false);
132                         case 'delete':
133                                 return $this->deleteUser();
134                         case 'list':
135                                 return $this->listUser();
136                         case 'search':
137                                 return $this->searchUser();
138                         case 'config':
139                                 return $this->configUser();
140                         default:
141                                 throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.');
142                 }
143         }
144
145         /**
146          * Retrieves the user nick, either as an argument or from a prompt
147          *
148          * @param int $arg_index Index of the nick argument in the arguments list
149          *
150          * @return string nick of the user
151          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152          */
153         private function getNick($arg_index)
154         {
155                 $nick = $this->getArgument($arg_index);
156
157                 if (!$nick) {
158                         $this->out($this->l10n->t('Enter user nickname: '));
159                         $nick = CliPrompt::prompt();
160                         if (empty($nick)) {
161                                 throw new RuntimeException('A nick name must be set.');
162                         }
163                 }
164
165                 return $nick;
166         }
167
168         /**
169          * Retrieves the user from a nick supplied as an argument or from a prompt
170          *
171          * @param int $arg_index Index of the nick argument in the arguments list
172          *
173          * @return array|boolean User record with uid field, or false if user is not found
174          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
175          */
176         private function getUserByNick($arg_index)
177         {
178                 $nick = $this->getNick($arg_index);
179
180                 $user = UserModel::getByNickname($nick, ['uid']);
181                 if (empty($user)) {
182                         throw new RuntimeException($this->l10n->t('User not found'));
183                 }
184
185                 return $user;
186         }
187
188         /**
189          * Sets a new password
190          *
191          * @return int Return code of this command
192          *
193          * @throws \Exception
194          */
195         private function password()
196         {
197                 $user = $this->getUserByNick(1);
198
199                 $password = $this->getArgument(2);
200
201                 if (is_null($password)) {
202                         $this->out($this->l10n->t('Enter new password: '), false);
203                         $password = CliPrompt::hiddenPrompt(true);
204                 }
205
206                 try {
207                         $result = UserModel::updatePassword($user['uid'], $password);
208
209                         if (empty($result)) {
210                                 throw new \Exception($this->l10n->t('Password update failed. Please try again.'));
211                         }
212
213                         $this->out($this->l10n->t('Password changed.'));
214                 } catch (\Exception $e) {
215                         throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
216                 }
217
218                 return 0;
219         }
220
221         /**
222          * Adds a new user based on given console arguments
223          *
224          * @return bool True, if the command was successful
225          * @throws \ErrorException
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          * @throws \ImagickException
228          */
229         private function addUser()
230         {
231                 $name   = $this->getArgument(1);
232                 $nick   = $this->getArgument(2);
233                 $email  = $this->getArgument(3);
234                 $lang   = $this->getArgument(4);
235                 $avatar = $this->getArgument(5);
236
237                 if (empty($name)) {
238                         $this->out($this->l10n->t('Enter user name: '));
239                         $name = CliPrompt::prompt();
240                         if (empty($name)) {
241                                 throw new RuntimeException('A name must be set.');
242                         }
243                 }
244
245                 if (empty($nick)) {
246                         $this->out($this->l10n->t('Enter user nickname: '));
247                         $nick = CliPrompt::prompt();
248                         if (empty($nick)) {
249                                 throw new RuntimeException('A nick name must be set.');
250                         }
251                 }
252
253                 if (empty($email)) {
254                         $this->out($this->l10n->t('Enter user email address: '));
255                         $email = CliPrompt::prompt();
256                         if (empty($email)) {
257                                 throw new RuntimeException('A email address must be set.');
258                         }
259                 }
260
261                 if (empty($lang)) {
262                         $this->out($this->l10n->t('Enter a language (optional): '));
263                         $lang = CliPrompt::prompt();
264                 }
265
266                 if (empty($avatar)) {
267                         $this->out($this->l10n->t('Enter URL of an image to use as avatar (optional): '));
268                         $avatar = CliPrompt::prompt();
269                 }
270
271                 if (empty($lang)) {
272                         return UserModel::createMinimal($name, $email, $nick);
273                 } else {
274                         return UserModel::createMinimal($name, $email, $nick, $lang, $avatar);
275                 }
276         }
277
278         /**
279          * Allows or denies a user based on it's nickname
280          *
281          * @param bool $allow True, if the pending user is allowed, false if denies
282          *
283          * @return bool True, if allow was successful
284          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
285          */
286         private function pendingUser(bool $allow = true)
287         {
288                 $user = $this->getUserByNick(1);
289
290                 $pending = Register::getPendingForUser($user['uid'] ?? 0);
291                 if (empty($pending)) {
292                         throw new RuntimeException($this->l10n->t('User is not pending.'));
293                 }
294
295                 return ($allow) ? UserModel::allow($pending['hash']) : UserModel::deny($pending['hash']);
296         }
297
298         /**
299          * Blocks/unblocks a user
300          *
301          * @param bool $block True, if the given user should get blocked
302          *
303          * @return bool True, if the command was successful
304          * @throws \Exception
305          */
306         private function blockUser(bool $block = true)
307         {
308                 $user = $this->getUserByNick(1);
309
310                 return $block ? UserModel::block($user['uid'] ?? 0) : UserModel::block($user['uid'] ?? 0, false);
311         }
312
313         /**
314          * Deletes a user
315          *
316          * @return bool True, if the delete was successful
317          * @throws \Exception
318          */
319         private function deleteUser(): bool
320         {
321                 $user = $this->getUserByNick(1);
322
323                 if (!empty($user['account_removed'])) {
324                         $this->out($this->l10n->t('User has already been marked for deletion.'));
325                         return true;
326                 }
327
328                 if (!$this->getOption('y')) {
329                         $this->out($this->l10n->t('Type "yes" to delete %s', $this->getArgument(1)));
330                         if (CliPrompt::prompt() !== 'yes') {
331                                 throw new RuntimeException($this->l10n->t('Deletion aborted.'));
332                         }
333                 }
334
335                 return UserModel::remove($user['uid']);
336         }
337
338         /**
339          * List users of the current node
340          *
341          * @return bool True, if the command was successful
342          */
343         private function listUser()
344         {
345                 $subCmd = $this->getArgument(1);
346                 $start  = $this->getOption(['s', 'start'], 0);
347                 $count  = $this->getOption(['c', 'count'], Pager::ITEMS_PER_PAGE);
348
349                 $table = new Console_Table();
350
351                 switch ($subCmd) {
352                         case 'pending':
353                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register Date', 'Comment']);
354                                 $pending = Register::getPending($start, $count);
355                                 foreach ($pending as $contact) {
356                                         $table->addRow([
357                                                 $contact['nick'],
358                                                 $contact['name'],
359                                                 $contact['url'],
360                                                 $contact['email'],
361                                                 Temporal::getRelativeDate($contact['created']),
362                                                 $contact['note'],
363                                         ]);
364                                 }
365                                 $this->out($table->getTable());
366                                 return true;
367                         case 'all':
368                         case 'active':
369                         case 'removed':
370                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register', 'Login', 'Last Item']);
371                                 $contacts = UserModel::getList($start, $count, $subCmd);
372                                 foreach ($contacts as $contact) {
373                                         $table->addRow([
374                                                 $contact['nick'],
375                                                 $contact['name'],
376                                                 $contact['url'],
377                                                 $contact['email'],
378                                                 Temporal::getRelativeDate($contact['created']),
379                                                 Temporal::getRelativeDate($contact['last-activity']),
380                                                 Temporal::getRelativeDate($contact['last-item']),
381                                         ]);
382                                 }
383                                 $this->out($table->getTable());
384                                 return true;
385                         default:
386                                 $this->out($this->getHelp());
387                                 return false;
388                 }
389         }
390
391         /**
392          * Returns a user based on search parameter
393          *
394          * @return bool True, if the command was successful
395          */
396         private function searchUser()
397         {
398                 $fields = [
399                         'uid',
400                         'guid',
401                         'username',
402                         'nickname',
403                         'email',
404                         'register_date',
405                         'last-activity',
406                         'verified',
407                         'blocked',
408                 ];
409
410                 $subCmd = $this->getArgument(1);
411                 $param  = $this->getArgument(2);
412
413                 $table = new Console_Table();
414                 $table->setHeaders(['UID', 'GUID', 'Name', 'Nick', 'E-Mail', 'Register', 'Login', 'Verified', 'Blocked']);
415
416                 switch ($subCmd) {
417                         case 'id':
418                                 $user = UserModel::getById($param, $fields);
419                                 break;
420                         case 'guid':
421                                 $user = UserModel::getByGuid($param, $fields);
422                                 break;
423                         case 'mail':
424                                 $user = UserModel::getByEmail($param, $fields);
425                                 break;
426                         case 'nick':
427                                 $user = UserModel::getByNickname($param, $fields);
428                                 break;
429                         default:
430                                 $this->out($this->getHelp());
431                                 return false;
432                 }
433
434                 if (!empty($user)) {
435                         $table->addRow($user);
436                 }
437                 $this->out($table->getTable());
438
439                 return true;
440         }
441
442         /**
443          * Queries and modifies user-specific configuration
444          *
445          * @return bool True, if the command was successful
446          */
447         private function configUser()
448         {
449                 $subCmd = $this->getArgument(1);
450
451                 $user = $this->getUserByNick(2);
452
453                 $category = $this->getArgument(3);
454
455                 if (is_null($category)) {
456                         $this->out($this->l10n->t('Enter category: '), false);
457                         $category = CliPrompt::prompt();
458                         if (empty($category)) {
459                                 throw new RuntimeException('A category must be selected.');
460                         }
461                 }
462
463                 $key = $this->getArgument(4);
464
465                 if ($subCmd != 'list' and is_null($key)) {
466                         $this->out($this->l10n->t('Enter key: '), false);
467                         $key = CliPrompt::prompt();
468                         if (empty($key)) {
469                                 throw new RuntimeException('A key must be selected.');
470                         }
471                 }
472
473                 $values = $this->pConfig->load($user['uid'], $category);
474
475                 switch ($subCmd) {
476                         case 'list':
477                                 $table = new Console_Table();
478                                 $table->setHeaders(['Key', 'Value']);
479                                 if (array_key_exists($category, $values)) {
480                                         foreach (array_keys($values[$category]) as $key) {
481                                                 $table->addRow([$key, $values[$category][$key]]);
482                                         }
483                                 }
484                                 $this->out($table->getTable());
485                                 break;
486                         case 'get':
487                                 if (!array_key_exists($category, $values)) {
488                                         throw new RuntimeException('Category does not exist');
489                                 }
490                                 if (!array_key_exists($key, $values[$category])) {
491                                         throw new RuntimeException('Key does not exist');
492                                 }
493
494                                 $this->out($this->pConfig->get($user['uid'], $category, $key));
495                                 break;
496                         case 'set':
497                                 $value = $this->getArgument(5);
498
499                                 if (is_null($value)) {
500                                         $this->out($this->l10n->t('Enter value: '), false);
501                                         $value = CliPrompt::prompt();
502                                         if (empty($value)) {
503                                                 throw new RuntimeException('A value must be specified.');
504                                         }
505                                 }
506
507                                 if (array_key_exists($category, $values) and
508                                         array_key_exists($key, $values[$category]) and
509                                         $values[$category][$key] == $value) {
510                                         throw new RuntimeException('Value not changed');
511                                 }
512
513                                 $this->pConfig->set($user['uid'], $category, $key, $value);
514                                 break;
515                         case 'delete':
516                                 if (!array_key_exists($category, $values)) {
517                                         throw new RuntimeException('Category does not exist');
518                                 }
519                                 if (!array_key_exists($key, $values[$category])) {
520                                         throw new RuntimeException('Key does not exist');
521                                 }
522
523                                 $this->pConfig->delete($user['uid'], $category, $key);
524                                 break;
525                         default:
526                                 $this->out($this->getHelp());
527                                 return false;
528                 }
529         }
530 }