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