]> git.mxchange.org Git - friendica.git/blob - src/Console/User.php
Add basic search
[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 [start=0 [count=50]] [-h|--help|-?] [-v]
68         bin/console user list removed [start=0 [count=50]] [-h|--help|-?] [-v]
69         bin/console user list all [start=0 [count=50]] [-h|--help|-?] [-v]
70         bin/console user search id <UID> [-h|--help|-?] [-v]
71         bin/console user search nick <nick> [-h|--help|-?] [-v]
72         bin/console user search mail <mail> [-h|--help|-?] [-v]
73         bin/console user search guid <GUID> [-h|--help|-?] [-v]
74
75 Description
76         Modify user settings per console commands.
77
78 Options
79     -h|--help|-? Show help information
80     -v           Show more debug information.
81     -q           Quiet mode (don't ask for a command).
82 HELP;
83                 return $help;
84         }
85
86         public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, array $argv = null)
87         {
88                 parent::__construct($argv);
89
90                 $this->appMode     = $appMode;
91                 $this->l10n        = $l10n;
92                 $this->dba         = $dba;
93         }
94
95         protected function doExecute()
96         {
97                 if ($this->getOption('v')) {
98                         $this->out('Class: ' . __CLASS__);
99                         $this->out('Arguments: ' . var_export($this->args, true));
100                         $this->out('Options: ' . var_export($this->options, true));
101                 }
102
103                 if (count($this->args) == 0) {
104                         $this->out($this->getHelp());
105                         return 0;
106                 }
107
108                 if ($this->appMode->isInstall()) {
109                         throw new RuntimeException('Database isn\'t ready or populated yet');
110                 }
111
112                 $command = $this->getArgument(0);
113
114                 switch ($command) {
115                         case 'password':
116                                 return $this->password();
117                         case 'add':
118                                 return $this->addUser();
119                         case 'allow':
120                                 return $this->pendingUser(true);
121                         case 'deny':
122                                 return $this->pendingUser(false);
123                         case 'block':
124                                 return $this->blockUser(true);
125                         case 'unblock':
126                                 return $this->blockUser(false);
127                         case 'delete':
128                                 return $this->deleteUser();
129                         case 'list':
130                                 return $this->listUser();
131                         case 'search':
132                                 return $this->searchUser();
133                         default:
134                                 throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.');
135                 }
136         }
137
138         /**
139          * Sets a new password
140          *
141          * @return int Return code of this command
142          *
143          * @throws \Exception
144          */
145         private function password()
146         {
147                 $nick = $this->getArgument(1);
148
149                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
150                 if (!$this->dba->isResult($user)) {
151                         throw new RuntimeException($this->l10n->t('User not found'));
152                 }
153
154                 $password = $this->getArgument(2);
155
156                 if (is_null($password)) {
157                         $this->out($this->l10n->t('Enter new password: '), false);
158                         $password = CliPrompt::hiddenPrompt(true);
159                 }
160
161                 try {
162                         $result = UserModel::updatePassword($user['uid'], $password);
163
164                         if (!$this->dba->isResult($result)) {
165                                 throw new \Exception($this->l10n->t('Password update failed. Please try again.'));
166                         }
167
168                         $this->out($this->l10n->t('Password changed.'));
169                 } catch (\Exception $e) {
170                         throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
171                 }
172
173                 return 0;
174         }
175
176         /**
177          * Adds a new user based on given console arguments
178          *
179          * @return bool True, if the command was successful
180          * @throws \ErrorException
181          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
182          * @throws \ImagickException
183          */
184         private function addUser()
185         {
186                 $name  = $this->getArgument(1);
187                 $nick  = $this->getArgument(2);
188                 $email = $this->getArgument(3);
189                 $lang  = $this->getArgument(4);
190
191                 if (empty($name)) {
192                         $this->out($this->l10n->t('Enter user name: '));
193                         $name = CliPrompt::prompt();
194                         if (empty($name)) {
195                                 throw new RuntimeException('A name must be set.');
196                         }
197                 }
198
199                 if (empty($nick)) {
200                         $this->out($this->l10n->t('Enter user nickname: '));
201                         $nick = CliPrompt::prompt();
202                         if (empty($nick)) {
203                                 throw new RuntimeException('A nick name must be set.');
204                         }
205                 }
206
207                 if (empty($email)) {
208                         $this->out($this->l10n->t('Enter user email address: '));
209                         $email = CliPrompt::prompt();
210                         if (empty($email)) {
211                                 throw new RuntimeException('A email address must be set.');
212                         }
213                 }
214
215                 if (empty($lang)) {
216                         $this->out($this->l10n->t('Enter a language (optional): '));
217                         $lang = CliPrompt::prompt();
218                 }
219
220                 if (empty($lang)) {
221                         return UserModel::createMinimal($name, $email, $nick);
222                 } else {
223                         return UserModel::createMinimal($name, $email, $nick, $lang);
224                 }
225         }
226
227         /**
228          * Allows or denys a user based on it's nickname
229          *
230          * @param bool $allow True, if the pending user is allowed, false if denies
231          *
232          * @return bool True, if allow was successful
233          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234          */
235         private function pendingUser(bool $allow = true)
236         {
237                 $nick = $this->getArgument(1);
238
239                 if (!$nick) {
240                         $this->out($this->l10n->t('Enter user nickname: '));
241                         $nick = CliPrompt::prompt();
242                         if (empty($nick)) {
243                                 throw new RuntimeException('A nick name must be set.');
244                         }
245                 }
246
247                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
248                 if (empty($user)) {
249                         throw new RuntimeException($this->l10n->t('User not found'));
250                 }
251
252                 $pending = Register::getPendingForUser($user['uid'] ?? 0);
253                 if (empty($pending)) {
254                         throw new RuntimeException($this->l10n->t('User is not pending.'));
255                 }
256
257                 return ($allow) ? UserModel::allow($pending['hash']) : UserModel::deny($pending['hash']);
258         }
259
260         /**
261          * Blocks/unblocks a user
262          *
263          * @param bool $block True, if the given user should get blocked
264          *
265          * @return bool True, if the command was successful
266          * @throws \Exception
267          */
268         private function blockUser(bool $block = true)
269         {
270                 $nick = $this->getArgument(1);
271
272                 if (!$nick) {
273                         $this->out($this->l10n->t('Enter user nickname: '));
274                         $nick = CliPrompt::prompt();
275                         if (empty($nick)) {
276                                 throw new RuntimeException('A nick name must be set.');
277                         }
278                 }
279
280                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
281                 if (empty($user)) {
282                         throw new RuntimeException($this->l10n->t('User not found'));
283                 }
284
285                 return $block ? UserModel::block($user['uid'] ?? 0) : UserModel::block($user['uid'] ?? 0, false);
286         }
287
288         /**
289          * Deletes a user
290          *
291          * @return bool True, if the delete was successful
292          * @throws \Exception
293          */
294         private function deleteUser()
295         {
296                 $nick = $this->getArgument(1);
297
298                 if (!$nick) {
299                         $this->out($this->l10n->t('Enter user nickname: '));
300                         $nick = CliPrompt::prompt();
301                         if (empty($nick)) {
302                                 throw new RuntimeException('A nick name must be set.');
303                         }
304                 }
305
306                 $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]);
307                 if (empty($user)) {
308                         throw new RuntimeException($this->l10n->t('User not found'));
309                 }
310
311                 if (!$this->getOption('q')) {
312                         $this->out($this->l10n->t('Type "yes" to delete %s', $nick));
313                         if (CliPrompt::prompt() !== 'yes') {
314                                 throw new RuntimeException('Delete abort.');
315                         }
316                 }
317
318                 return UserModel::remove($user['uid'] ?? -1);
319         }
320
321         /**
322          * List users of the current node
323          *
324          * @return bool True, if the command was successful
325          */
326         private function listUser()
327         {
328                 $subCmd = $this->getArgument(1);
329                 $start = $this->getArgument(2, 0);
330                 $count = $this->getArgument(3, Pager::ITEMS_PER_PAGE);
331
332                 $table = new Console_Table();
333
334                 switch ($subCmd) {
335                         case 'pending':
336                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register Date', 'Comment']);
337                                 $pending = Register::getPending($start, $count);
338                                 foreach ($pending as $contact) {
339                                         $table->addRow([
340                                                 $contact['nick'],
341                                                 $contact['name'],
342                                                 $contact['url'],
343                                                 $contact['email'],
344                                                 Temporal::getRelativeDate($contact['created']),
345                                                 $contact['note'],
346                                         ]);
347                                 }
348                                 $this->out($table->getTable());
349                                 return true;
350                         case 'all':
351                         case 'removed':
352                                 $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register', 'Login', 'Last Item']);
353                                 $contacts = UserModel::getUsers($start, $count);
354                                 foreach ($contacts as $contact) {
355                                         if (($subCmd != 'removed') && !empty($contact['account_removed']) ||
356                                             ($subCmd == 'removed') && empty($contact['account_removed'])) {
357                                                 continue;
358                                         }
359
360                                         $table->addRow([
361                                                 $contact['nick'],
362                                                 $contact['name'],
363                                                 $contact['url'],
364                                                 $contact['email'],
365                                                 Temporal::getRelativeDate($contact['created']),
366                                                 Temporal::getRelativeDate($contact['login_date']),
367                                                 Temporal::getRelativeDate($contact['lastitem_date']),
368                                         ]);
369                                 }
370                                 $this->out($table->getTable());
371                                 return true;
372                         default:
373                                 $this->out($this->getHelp());
374                                 return false;
375                 }
376         }
377
378         /**
379          * Returns a user based on search parameter
380          *
381          * @return bool True, if the command was successful
382          */
383         private function searchUser()
384         {
385                 $fields = [
386                         'uid',
387                         'guid',
388                         'username',
389                         'nickname',
390                         'email',
391                         'register_date',
392                         'login_date',
393                         'verified',
394                         'blocked',
395                 ];
396
397                 $subCmd = $this->getArgument(1);
398                 $param = $this->getArgument(2);
399
400                 $table = new Console_Table();
401                 $table->setHeaders(['UID', 'GUID', 'Name', 'Nick', 'E-Mail', 'Register', 'Login', 'Verified', 'Blocked']);
402
403                 switch ($subCmd) {
404                         case 'id':
405                                 $user = UserModel::getById($param, $fields);
406                                 break;
407                         case 'guid':
408                                 $user = UserModel::getByGuid($param, $fields);
409                                 break;
410                         case 'email':
411                                 $user = UserModel::getByEmail($param, $fields);
412                                 break;
413                         case 'nick':
414                                 $user = UserModel::getByNickname($param, $fields);
415                                 break;
416                         default:
417                                 $this->out($this->getHelp());
418                                 return false;
419                 }
420
421                 $table->addRow($user);
422                 $this->out($table->getTable());
423
424                 return true;
425         }
426 }