]> git.mxchange.org Git - friendica.git/blob - src/Console/User.php
383a77f70ebc805ae80d4fc2aa6891aab140af4b
[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\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 IPConfig
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>]]]] [-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, IPConfig $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()
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 (!$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 (!$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
236                 if (empty($name)) {
237                         $this->out($this->l10n->t('Enter user name: '));
238                         $name = CliPrompt::prompt();
239                         if (empty($name)) {
240                                 throw new RuntimeException('A name must be set.');
241                         }
242                 }
243
244                 if (empty($nick)) {
245                         $this->out($this->l10n->t('Enter user nickname: '));
246                         $nick = CliPrompt::prompt();
247                         if (empty($nick)) {
248                                 throw new RuntimeException('A nick name must be set.');
249                         }
250                 }
251
252                 if (empty($email)) {
253                         $this->out($this->l10n->t('Enter user email address: '));
254                         $email = CliPrompt::prompt();
255                         if (empty($email)) {
256                                 throw new RuntimeException('A email address must be set.');
257                         }
258                 }
259
260                 if (empty($lang)) {
261                         $this->out($this->l10n->t('Enter a language (optional): '));
262                         $lang = CliPrompt::prompt();
263                 }
264
265                 if (empty($lang)) {
266                         return UserModel::createMinimal($name, $email, $nick);
267                 } else {
268                         return UserModel::createMinimal($name, $email, $nick, $lang);
269                 }
270         }
271
272         /**
273          * Allows or denys a user based on it's nickname
274          *
275          * @param bool $allow True, if the pending user is allowed, false if denies
276          *
277          * @return bool True, if allow was successful
278          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279          */
280         private function pendingUser(bool $allow = true)
281         {
282                 $user = $this->getUserByNick(1);
283
284                 $pending = Register::getPendingForUser($user['uid'] ?? 0);
285                 if (empty($pending)) {
286                         throw new RuntimeException($this->l10n->t('User is not pending.'));
287                 }
288
289                 return ($allow) ? UserModel::allow($pending['hash']) : UserModel::deny($pending['hash']);
290         }
291
292         /**
293          * Blocks/unblocks a user
294          *
295          * @param bool $block True, if the given user should get blocked
296          *
297          * @return bool True, if the command was successful
298          * @throws \Exception
299          */
300         private function blockUser(bool $block = true)
301         {
302                 $user = $this->getUserByNick(1);
303
304                 return $block ? UserModel::block($user['uid'] ?? 0) : UserModel::block($user['uid'] ?? 0, false);
305         }
306
307         /**
308          * Deletes a user
309          *
310          * @return bool True, if the delete was successful
311          * @throws \Exception
312          */
313         private function deleteUser()
314         {
315                 $user = $this->getUserByNick(1);
316
317                 if (!empty($user['account_removed'])) {
318                         $this->out($this->l10n->t('User has already been marked for deletion.'));
319                         return true;
320                 }
321
322                 if (!$this->getOption('y')) {
323                         $this->out($this->l10n->t('Type "yes" to delete %s', $this->getArgument(1)));
324                         if (CliPrompt::prompt() !== 'yes') {
325                                 throw new RuntimeException($this->l10n->t('Deletion aborted.'));
326                         }
327                 }
328
329                 return UserModel::remove($user['uid']);
330         }
331
332         /**
333          * List users of the current node
334          *
335          * @return bool True, if the command was successful
336          */
337         private function listUser()
338         {
339                 $subCmd = $this->getArgument(1);
340                 $start  = $this->getOption(['s', 'start'], 0);
341                 $count  = $this->getOption(['c', 'count'], Pager::ITEMS_PER_PAGE);
342
343                 $table = new Console_Table();
344
345                 switch ($subCmd) {
346                         case 'pending':
347                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register Date', 'Comment']);
348                                 $pending = Register::getPending($start, $count);
349                                 foreach ($pending as $contact) {
350                                         $table->addRow([
351                                                 $contact['nick'],
352                                                 $contact['name'],
353                                                 $contact['url'],
354                                                 $contact['email'],
355                                                 Temporal::getRelativeDate($contact['created']),
356                                                 $contact['note'],
357                                         ]);
358                                 }
359                                 $this->out($table->getTable());
360                                 return true;
361                         case 'all':
362                         case 'active':
363                         case 'removed':
364                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register', 'Login', 'Last Item']);
365                                 $contacts = UserModel::getList($start, $count, $subCmd);
366                                 foreach ($contacts as $contact) {
367                                         $table->addRow([
368                                                 $contact['nick'],
369                                                 $contact['name'],
370                                                 $contact['url'],
371                                                 $contact['email'],
372                                                 Temporal::getRelativeDate($contact['created']),
373                                                 Temporal::getRelativeDate($contact['login_date']),
374                                                 Temporal::getRelativeDate($contact['last-item']),
375                                         ]);
376                                 }
377                                 $this->out($table->getTable());
378                                 return true;
379                         default:
380                                 $this->out($this->getHelp());
381                                 return false;
382                 }
383         }
384
385         /**
386          * Returns a user based on search parameter
387          *
388          * @return bool True, if the command was successful
389          */
390         private function searchUser()
391         {
392                 $fields = [
393                         'uid',
394                         'guid',
395                         'username',
396                         'nickname',
397                         'email',
398                         'register_date',
399                         'login_date',
400                         'verified',
401                         'blocked',
402                 ];
403
404                 $subCmd = $this->getArgument(1);
405                 $param  = $this->getArgument(2);
406
407                 $table = new Console_Table();
408                 $table->setHeaders(['UID', 'GUID', 'Name', 'Nick', 'E-Mail', 'Register', 'Login', 'Verified', 'Blocked']);
409
410                 switch ($subCmd) {
411                         case 'id':
412                                 $user = UserModel::getById($param, $fields);
413                                 break;
414                         case 'guid':
415                                 $user = UserModel::getByGuid($param, $fields);
416                                 break;
417                         case 'mail':
418                                 $user = UserModel::getByEmail($param, $fields);
419                                 break;
420                         case 'nick':
421                                 $user = UserModel::getByNickname($param, $fields);
422                                 break;
423                         default:
424                                 $this->out($this->getHelp());
425                                 return false;
426                 }
427
428                 if ($user) {
429                         $table->addRow($user);
430                 }
431                 $this->out($table->getTable());
432
433                 return true;
434         }
435
436         /**
437          * Queries and modifies user-specific configuration
438          *
439          * @return bool True, if the command was successful
440          */
441         private function configUser()
442         {
443                 $subCmd = $this->getArgument(1);
444
445                 $user = $this->getUserByNick(2);
446
447                 $category = $this->getArgument(3);
448
449                 if (is_null($category)) {
450                         $this->out($this->l10n->t('Enter category: '), false);
451                         $category = CliPrompt::prompt();
452                         if (empty($category)) {
453                                 throw new RuntimeException('A category must be selected.');
454                         }
455                 }
456
457                 $key = $this->getArgument(4);
458
459                 if ($subCmd != 'list' and is_null($key)) {
460                         $this->out($this->l10n->t('Enter key: '), false);
461                         $key = CliPrompt::prompt();
462                         if (empty($key)) {
463                                 throw new RuntimeException('A key must be selected.');
464                         }
465                 }
466
467                 $values = $this->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($this->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                                 $this->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                                 $this->pConfig->delete($user['uid'], $category, $key);
518                                 break;
519                         default:
520                                 $this->out($this->getHelp());
521                                 return false;
522                 }
523         }
524 }