]> git.mxchange.org Git - friendica.git/blob - src/Console/User.php
Merge pull request #10190 from annando/api-attached
[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          * @var IPConfig
57          */
58         private $pConfig;
59
60         protected function getHelp()
61         {
62                 $help = <<<HELP
63 console user - Modify user settings per console commands.
64 Usage
65         bin/console user password <nickname> [<password>] [-h|--help|-?] [-v]
66         bin/console user add [<name> [<nickname> [<email> [<language>]]]] [-h|--help|-?] [-v]
67         bin/console user delete [<nickname>] [-y] [-h|--help|-?] [-v]
68         bin/console user allow [<nickname>] [-h|--help|-?] [-v]
69         bin/console user deny [<nickname>] [-h|--help|-?] [-v]
70         bin/console user block [<nickname>] [-h|--help|-?] [-v]
71         bin/console user unblock [<nickname>] [-h|--help|-?] [-v]
72         bin/console user list pending [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
73         bin/console user list removed [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
74         bin/console user list active [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
75         bin/console user list all [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v]
76         bin/console user search id <UID> [-h|--help|-?] [-v]
77         bin/console user search nick <nick> [-h|--help|-?] [-v]
78         bin/console user search mail <mail> [-h|--help|-?] [-v]
79         bin/console user search guid <GUID> [-h|--help|-?] [-v]
80         bin/console user config list [<nickname>] [<category>] [-h|--help|-?] [-v]
81         bin/console user config get [<nickname>] [<category>] [<key>] [-h|--help|-?] [-v]
82         bin/console user config set [<nickname>] [<category>] [<key>] [<value>] [-h|--help|-?] [-v]
83         bin/console user config delete [<nickname>] [<category>] [<key>] [-h|--help|-?] [-v]
84
85 Description
86         Modify user settings per console commands.
87
88 Options
89     -h|--help|-? Show help information
90     -v           Show more debug information
91     -y           Non-interactive mode, assume "yes" as answer to the user deletion prompt
92 HELP;
93                 return $help;
94         }
95
96         public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, IPConfig $pConfig, array $argv = null)
97         {
98                 parent::__construct($argv);
99
100                 $this->appMode = $appMode;
101                 $this->l10n    = $l10n;
102                 $this->dba     = $dba;
103                 $this->pConfig = $pConfig;
104         }
105
106         protected function doExecute()
107         {
108                 if ($this->getOption('v')) {
109                         $this->out('Class: ' . __CLASS__);
110                         $this->out('Arguments: ' . var_export($this->args, true));
111                         $this->out('Options: ' . var_export($this->options, true));
112                 }
113
114                 if (count($this->args) == 0) {
115                         $this->out($this->getHelp());
116                         return 0;
117                 }
118
119                 if ($this->appMode->isInstall()) {
120                         throw new RuntimeException('Database isn\'t ready or populated yet');
121                 }
122
123                 $command = $this->getArgument(0);
124
125                 switch ($command) {
126                         case 'password':
127                                 return $this->password();
128                         case 'add':
129                                 return $this->addUser();
130                         case 'allow':
131                                 return $this->pendingUser(true);
132                         case 'deny':
133                                 return $this->pendingUser(false);
134                         case 'block':
135                                 return $this->blockUser(true);
136                         case 'unblock':
137                                 return $this->blockUser(false);
138                         case 'delete':
139                                 return $this->deleteUser();
140                         case 'list':
141                                 return $this->listUser();
142                         case 'search':
143                                 return $this->searchUser();
144                         case 'config':
145                                 return $this->configUser();
146                         default:
147                                 throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.');
148                 }
149         }
150
151         /**
152          * Retrieves the user nick, either as an argument or from a prompt
153          *
154          * @param int $arg_index Index of the nick argument in the arguments list
155          *
156          * @return string nick of the user
157          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
158          */
159         private function getNick($arg_index)
160         {
161                 $nick = $this->getArgument($arg_index);
162
163                 if (!$nick) {
164                         $this->out($this->l10n->t('Enter user nickname: '));
165                         $nick = CliPrompt::prompt();
166                         if (empty($nick)) {
167                                 throw new RuntimeException('A nick name must be set.');
168                         }
169                 }
170
171                 return $nick;
172         }
173
174         /**
175          * Retrieves the user from a nick supplied as an argument or from a prompt
176          *
177          * @param int $arg_index Index of the nick argument in the arguments list
178          *
179          * @return mixed user data or dba failure result
180          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
181          */
182         private function getUserByNick($arg_index)
183         {
184                 $nick = $this->getNick($arg_index);
185
186                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
187                 if (!$this->dba->isResult($user)) {
188                         throw new RuntimeException($this->l10n->t('User not found'));
189                 }
190
191                 return $user;
192         }
193
194         /**
195          * Sets a new password
196          *
197          * @return int Return code of this command
198          *
199          * @throws \Exception
200          */
201         private function password()
202         {
203                 $user = $this->getUserByNick(1);
204
205                 $password = $this->getArgument(2);
206
207                 if (is_null($password)) {
208                         $this->out($this->l10n->t('Enter new password: '), false);
209                         $password = CliPrompt::hiddenPrompt(true);
210                 }
211
212                 try {
213                         $result = UserModel::updatePassword($user['uid'], $password);
214
215                         if (!$this->dba->isResult($result)) {
216                                 throw new \Exception($this->l10n->t('Password update failed. Please try again.'));
217                         }
218
219                         $this->out($this->l10n->t('Password changed.'));
220                 } catch (\Exception $e) {
221                         throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
222                 }
223
224                 return 0;
225         }
226
227         /**
228          * Adds a new user based on given console arguments
229          *
230          * @return bool True, if the command was successful
231          * @throws \ErrorException
232          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233          * @throws \ImagickException
234          */
235         private function addUser()
236         {
237                 $name  = $this->getArgument(1);
238                 $nick  = $this->getArgument(2);
239                 $email = $this->getArgument(3);
240                 $lang  = $this->getArgument(4);
241
242                 if (empty($name)) {
243                         $this->out($this->l10n->t('Enter user name: '));
244                         $name = CliPrompt::prompt();
245                         if (empty($name)) {
246                                 throw new RuntimeException('A name must be set.');
247                         }
248                 }
249
250                 if (empty($nick)) {
251                         $this->out($this->l10n->t('Enter user nickname: '));
252                         $nick = CliPrompt::prompt();
253                         if (empty($nick)) {
254                                 throw new RuntimeException('A nick name must be set.');
255                         }
256                 }
257
258                 if (empty($email)) {
259                         $this->out($this->l10n->t('Enter user email address: '));
260                         $email = CliPrompt::prompt();
261                         if (empty($email)) {
262                                 throw new RuntimeException('A email address must be set.');
263                         }
264                 }
265
266                 if (empty($lang)) {
267                         $this->out($this->l10n->t('Enter a language (optional): '));
268                         $lang = 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);
275                 }
276         }
277
278         /**
279          * Allows or denys 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()
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['login_date']),
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                         'login_date',
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                 $table->addRow($user);
435                 $this->out($table->getTable());
436
437                 return true;
438         }
439
440         /**
441          * Queries and modifies user-specific configuration
442          *
443          * @return bool True, if the command was successful
444          */
445         private function configUser()
446         {
447                 $subCmd = $this->getArgument(1);
448
449                 $user = $this->getUserByNick(2);
450
451                 $category = $this->getArgument(3);
452
453                 if (is_null($category)) {
454                         $this->out($this->l10n->t('Enter category: '), false);
455                         $category = CliPrompt::prompt();
456                         if (empty($category)) {
457                                 throw new RuntimeException('A category must be selected.');
458                         }
459                 }
460
461                 $key = $this->getArgument(4);
462
463                 if ($subCmd != 'list' and is_null($key)) {
464                         $this->out($this->l10n->t('Enter key: '), false);
465                         $key = CliPrompt::prompt();
466                         if (empty($key)) {
467                                 throw new RuntimeException('A key must be selected.');
468                         }
469                 }
470
471                 $values = $this->pConfig->load($user['uid'], $category);
472
473                 switch ($subCmd) {
474                         case 'list':
475                                 $table = new Console_Table();
476                                 $table->setHeaders(['Key', 'Value']);
477                                 if (array_key_exists($category, $values)) {
478                                         foreach (array_keys($values[$category]) as $key) {
479                                                 $table->addRow([$key, $values[$category][$key]]);
480                                         }
481                                 }
482                                 $this->out($table->getTable());
483                                 break;
484                         case 'get':
485                                 if (!array_key_exists($category, $values)) {
486                                         throw new RuntimeException('Category does not exist');
487                                 }
488                                 if (!array_key_exists($key, $values[$category])) {
489                                         throw new RuntimeException('Key does not exist');
490                                 }
491
492                                 $this->out($pconfig->get($user['uid'], $category, $key));
493                                 break;
494                         case 'set':
495                                 $value = $this->getArgument(5);
496
497                                 if (is_null($value)) {
498                                         $this->out($this->l10n->t('Enter value: '), false);
499                                         $value = CliPrompt::prompt();
500                                         if (empty($value)) {
501                                                 throw new RuntimeException('A value must be specified.');
502                                         }
503                                 }
504
505                                 if (array_key_exists($category, $values) and
506                                         array_key_exists($key, $values[$category]) and
507                                         $values[$category][$key] == $value) {
508                                         throw new RuntimeException('Value not changed');
509                                 }
510
511                                 $pconfig->set($user['uid'], $category, $key, $value);
512                                 break;
513                         case 'delete':
514                                 if (!array_key_exists($category, $values)) {
515                                         throw new RuntimeException('Category does not exist');
516                                 }
517                                 if (!array_key_exists($key, $values[$category])) {
518                                         throw new RuntimeException('Key does not exist');
519                                 }
520
521                                 $pconfig->delete($user['uid'], $category, $key);
522                                 break;
523                         default:
524                                 $this->out($this->getHelp());
525                                 return false;
526                 }
527         }
528 }