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