abstractconfigurecommand.class.php 15.1 KB
Newer Older
1
2
3
4
<?php
/**
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
5
 * Copyright (C) 2015-2021 Teclib' and contributors.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * GLPI is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GLPI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 */

namespace Glpi\Console\Database;

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

use Config;
use DBConnection;
41
use DBmysql;
42
43
use Glpi\Console\AbstractCommand;
use Glpi\Console\Command\ForceNoPluginsOptionCommandInterface;
44
use Glpi\System\Requirement\DbTimezones;
45
use mysqli;
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

abstract class AbstractConfigureCommand extends AbstractCommand implements ForceNoPluginsOptionCommandInterface {

   /**
    * Error code returned if DB configuration is aborted by user.
    *
    * @var integer
    */
   const ABORTED_BY_USER = -1;

   /**
    * Error code returned if DB configuration succeed.
    *
    * @var integer
    */
   const SUCCESS = 0;

   /**
    * Error code returned if DB connection initialization fails.
    *
    * @var integer
    */
   const ERROR_DB_CONNECTION_FAILED = 1;

   /**
    * Error code returned if DB engine is unsupported.
    *
    * @var integer
    */
   const ERROR_DB_ENGINE_UNSUPPORTED = 2;

   /**
    * Error code returned when trying to configure and having a DB config already set.
    *
    * @var integer
    */
   const ERROR_DB_CONFIG_ALREADY_SET = 3;

   /**
    * Error code returned when failing to save database configuration file.
    *
    * @var integer
    */
   const ERROR_DB_CONFIG_FILE_NOT_SAVED = 4;

98
99
   protected $requires_db_up_to_date = false;

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
   protected function configure() {

      parent::configure();

      $this->setName('glpi:database:install');
      $this->setAliases(['db:install']);
      $this->setDescription('Install database schema');

      $this->addOption(
         'db-host',
         'H',
         InputOption::VALUE_OPTIONAL,
         __('Database host'),
         'localhost'
      );

      $this->addOption(
         'db-name',
         'd',
         InputOption::VALUE_REQUIRED,
         __('Database name')
      );

      $this->addOption(
         'db-password',
         'p',
         InputOption::VALUE_OPTIONAL,
         __('Database password (will be prompted for value if option passed without value)'),
         '' // Empty string by default (enable detection of null if passed without value)
      );

      $this->addOption(
         'db-port',
         'P',
         InputOption::VALUE_OPTIONAL,
         __('Database port')
      );

      $this->addOption(
         'db-user',
         'u',
         InputOption::VALUE_REQUIRED,
         __('Database user')
      );

      $this->addOption(
         'reconfigure',
         'r',
         InputOption::VALUE_NONE,
         __('Reconfigure database, override configuration file if it already exists')
      );
151
152
153
154
155
156
157

      $this->addOption(
         'log-deprecation-warnings',
         null,
         InputOption::VALUE_NONE,
         __('Indicated if deprecation warnings sent by database server should be logged')
      );
158
159
160
161
162
163
164
165
166
167
168
169
170
   }

   protected function interact(InputInterface $input, OutputInterface $output) {

      $questions = [
         'db-name'     => new Question(__('Database name:'), ''), // Required
         'db-user'     => new Question(__('Database user:'), ''), // Required
         'db-password' => new Question(__('Database password:'), ''), // Prompt if null (passed without value)
      ];
      $questions['db-password']->setHidden(true); // Make password input hidden

      foreach ($questions as $name => $question) {
         if (null === $input->getOption($name)) {
Cédric Anne's avatar
Cédric Anne committed
171
            /** @var \Symfony\Component\Console\Helper\QuestionHelper $question_helper */
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
            $question_helper = $this->getHelper('question');
            $value = $question_helper->ask($input, $output, $question);
            $input->setOption($name, $value);
         }
      }
   }

   protected function initDbConnection() {

      return; // Prevent DB connection
   }

   /**
    * Save database configuration file.
    *
    * @param InputInterface $input
    * @param OutputInterface $output
189
    * @param bool $auto_config_flags
Cédric Anne's avatar
Cédric Anne committed
190
    * @param bool $use_utf8mb4
191
    * @param bool $allow_myisam
Cédric Anne's avatar
Cédric Anne committed
192
    *
193
    * @throws InvalidArgumentException
Cédric Anne's avatar
Cédric Anne committed
194
    *
195
196
    * @return string
    */
197
198
199
200
   protected function configureDatabase(
      InputInterface $input,
      OutputInterface $output,
      bool $auto_config_flags = true,
201
202
      bool $use_utf8mb4 = false,
      bool $allow_myisam = true
203
   ) {
204
205
206
207
208
209
210
211
212

      $db_pass     = $input->getOption('db-password');
      $db_host     = $input->getOption('db-host');
      $db_name     = $input->getOption('db-name');
      $db_port     = $input->getOption('db-port');
      $db_user     = $input->getOption('db-user');
      $db_hostport = $db_host . (!empty($db_port) ? ':' . $db_port : '');

      $reconfigure    = $input->getOption('reconfigure');
213
      $log_deprecation_warnings = $input->getOption('log-deprecation-warnings');
214
215
216
217
218
219
220
221
222

      if (file_exists(GLPI_CONFIG_DIR . '/config_db.php') && !$reconfigure) {
         // Prevent overriding of existing DB
         $output->writeln(
            '<error>' . __('Database configuration already exists. Use --reconfigure option to override existing configuration.') . '</error>'
         );
         return self::ERROR_DB_CONFIG_ALREADY_SET;
      }

223
      $this->validateConfigInput($input);
224

225
226
227
228
229
230
231
232
233
234
235
      $run = $this->askForDbConfigConfirmation(
         $input,
         $output,
         $db_hostport,
         $db_name,
         $db_user
      );
      if (!$run) {
         $output->writeln(
            '<comment>' . __('Configuration aborted.') . '</comment>',
            OutputInterface::VERBOSITY_VERBOSE
236
         );
237
         return self::ABORTED_BY_USER;
238
239
      }

240
      $mysqli = new mysqli();
241
242
243
244
245
246
247
      if (intval($db_port) > 0) {
         // Network port
         @$mysqli->connect($db_host, $db_user, $db_pass, null, $db_port);
      } else {
         // Unix Domain Socket
         @$mysqli->connect($db_host, $db_user, $db_pass, null, 0, $db_port);
      }
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

      if (0 !== $mysqli->connect_errno) {
         $message = sprintf(
            __('Database connection failed with message "(%s) %s".'),
            $mysqli->connect_errno,
            $mysqli->connect_error
         );
         $output->writeln('<error>' . $message . '</error>', OutputInterface::VERBOSITY_QUIET);
         return self::ERROR_DB_CONNECTION_FAILED;
      }

      ob_start();
      $db_version_data = $mysqli->query('SELECT version()')->fetch_array();
      $checkdb = Config::displayCheckDbEngine(false, $db_version_data[0]);
      $message = ob_get_clean();
      if ($checkdb > 0) {
         $output->writeln('<error>' . $message . '</error>', OutputInterface::VERBOSITY_QUIET);
         return self::ERROR_DB_ENGINE_UNSUPPORTED;
      }

268
269
270
271
272
273
274
275
276
277
278
279
280
      if ($auto_config_flags) {
         // Instanciate DB to be able to compute boolean properties flags.
         $db = new class($db_hostport, $db_user, $db_pass, $db_name) extends DBmysql {
            public function __construct($dbhost, $dbuser, $dbpassword, $dbdefault) {
               $this->dbhost     = $dbhost;
               $this->dbuser     = $dbuser;
               $this->dbpassword = $dbpassword;
               $this->dbdefault  = $dbdefault;
               parent::__construct();
            }
         };
         $config_flags = $db->getComputedConfigBooleanFlags();
         $use_utf8mb4 = $config_flags[DBConnection::PROPERTY_USE_UTF8MB4] ?? $use_utf8mb4;
281
         $allow_myisam = $config_flags[DBConnection::PROPERTY_ALLOW_MYISAM] ?? $allow_myisam;
282
283
284
285
      }

      DBConnection::setConnectionCharset($mysqli, $use_utf8mb4);

286
287
      $use_timezones = $this->checkTimezonesAvailability($mysqli);

288
289
290
291
292
293
      $db_name = $mysqli->real_escape_string($db_name);

      $output->writeln(
         '<comment>' . __('Saving configuration file...') . '</comment>',
         OutputInterface::VERBOSITY_VERBOSE
      );
294
295
296
297
298
      $result = DBConnection::createMainConfig(
         $db_hostport,
         $db_user,
         $db_pass,
         $db_name,
299
         $use_timezones,
300
301
302
303
304
         $log_deprecation_warnings,
         $use_utf8mb4,
         $allow_myisam
      );
      if (!$result) {
305
306
307
308
309
310
311
312
313
314
315
         $message = sprintf(
            __('Cannot write configuration file "%s".'),
            GLPI_CONFIG_DIR . DIRECTORY_SEPARATOR . 'config_db.php'
         );
         $output->writeln(
            '<error>' . $message . '</error>',
            OutputInterface::VERBOSITY_QUIET
         );
         return self::ERROR_DB_CONFIG_FILE_NOT_SAVED;
      }

316
      // Set $db instance to use new connection properties
317
318
319
320
321
      $this->db = new class(
         $db_hostport,
         $db_user,
         $db_pass,
         $db_name,
322
         $use_timezones,
323
324
325
326
327
328
329
330
331
         $log_deprecation_warnings,
         $use_utf8mb4,
         $allow_myisam
      ) extends DBmysql {
         public function __construct(
            $dbhost,
            $dbuser,
            $dbpassword,
            $dbdefault,
332
            $use_timezones,
333
334
335
336
            $log_deprecation_warnings,
            $use_utf8mb4,
            $allow_myisam
         ) {
337
338
339
340
341
342
343
            $this->dbhost        = $dbhost;
            $this->dbuser        = $dbuser;
            $this->dbpassword    = $dbpassword;
            $this->dbdefault     = $dbdefault;
            $this->use_timezones = $use_timezones;
            $this->use_utf8mb4   = $use_utf8mb4;
            $this->allow_myisam  = $allow_myisam;
344
345
346
347
348
349
350
351
352

            $this->log_deprecation_warnings = $log_deprecation_warnings;

            $this->clearSchemaCache();

            parent::__construct();
         }
      };

353
354
355
356
357
358
359
      return self::SUCCESS;
   }

   public function getNoPluginsOptionValue() {

      return true;
   }
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

   /**
    * Check if DB is already configured.
    *
    * @return boolean
    */
   protected function isDbAlreadyConfigured() {

      return file_exists(GLPI_CONFIG_DIR . '/config_db.php');
   }

   /**
    * Validate configuration variables from input.
    *
    * @param InputInterface $input
    *
    * @throws InvalidArgumentException
    */
   protected function validateConfigInput(InputInterface $input) {

      $db_name = $input->getOption('db-name');
      $db_user = $input->getOption('db-user');
      $db_pass = $input->getOption('db-password');

      if (empty($db_name)) {
385
         throw new \Symfony\Component\Console\Exception\InvalidArgumentException(
386
387
388
389
390
            __('Database name defined by --db-name option cannot be empty.')
         );
      }

      if (empty($db_user)) {
391
         throw new \Symfony\Component\Console\Exception\InvalidArgumentException(
392
393
394
395
396
397
            __('Database user defined by --db-user option cannot be empty.')
         );
      }

      if (null === $db_pass) {
         // Will be null if option used without value and without interaction
398
         throw new \Symfony\Component\Console\Exception\InvalidArgumentException(
399
400
401
402
403
404
405
406
407
408
            __('--db-password option value cannot be null.')
         );
      }
   }

   /**
    * Ask user to confirm DB configuration.
    *
    * @param InputInterface $input
    * @param OutputInterface $output
cconard96's avatar
cconard96 committed
409
410
411
    * @param string $db_hostport DB host and port
    * @param string $db_name DB name
    * @param string $db_user DB username
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    *
    * @return boolean
    */
   protected function askForDbConfigConfirmation(
      InputInterface $input,
      OutputInterface $output,
      $db_hostport,
      $db_name,
      $db_user) {

      $informations = new Table($output);
      $informations->addRow([__('Database host'), $db_hostport]);
      $informations->addRow([__('Database name'), $db_name]);
      $informations->addRow([__('Database user'), $db_user]);
      $informations->render();

      if ($input->getOption('no-interaction')) {
         // Consider that config is validated if user require no interaction
         return true;
      }

Cédric Anne's avatar
Cédric Anne committed
433
      /** @var \Symfony\Component\Console\Helper\QuestionHelper $question_helper */
434
435
436
437
      $question_helper = $this->getHelper('question');
      return $question_helper->ask(
         $input,
         $output,
438
         new ConfirmationQuestion(__('Do you want to continue?') . ' [Yes/no]', true)
439
440
      );
   }
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491

   /**
    * Check timezones availability and return availability state.
    *
    * @param mysqli $mysqli
    *
    * @return bool
    */
   private function checkTimezonesAvailability(mysqli $mysqli): bool {

      $db = new class($mysqli) extends DBmysql {
         public function __construct($dbh) {
            $this->dbh = $dbh;
         }
      };
      $timezones_requirement = new DbTimezones($db);

      if (!$timezones_requirement->isValidated()) {
         $message = __('Timezones usage cannot be activated due to following errors:');
         foreach ($timezones_requirement->getValidationMessages() as $validation_message) {
            $message .= "\n - " . $validation_message;
         }
         $this->output->writeln(
            '<comment>' . $message . '</comment>',
            OutputInterface::VERBOSITY_QUIET
         );
         if ($this->input->getOption('no-interaction')) {
            $message = sprintf(
               __('Fix them and run the "php bin/console %1$s" command to enable timezones.'),
               'glpi:database:enable_timezones'
            );
            $this->output->writeln('<comment>' . $message . '</comment>', OutputInterface::VERBOSITY_QUIET);
         } else {
            /** @var \Symfony\Component\Console\Helper\QuestionHelper $question_helper */
            $question_helper = $this->getHelper('question');
            $continue = $question_helper->ask(
               $this->input,
               $this->output,
               new ConfirmationQuestion(__('Do you want to continue?') . ' [Yes/no]', true)
            );
            if (!$continue) {
               throw new \Glpi\Console\Exception\EarlyExitException(
                  '<comment>' . __('Configuration aborted.') . '</comment>',
                  self::ABORTED_BY_USER
               );
            }
         }
      }

      return $timezones_requirement->isValidated();
   }
492
}