Check the database form fields and connection.

@access protected
336995
protected function checkDatabaseInformation()
    {
        $this->title("Database Information");

        $errors = [];
        $driver = Request::$post->get('driver');

        // Check fields
        if ($driver == "pdo_pgsql" || $driver == "pdo_mysql") {
            if (!Request::$post->get('host')) {
                $errors[] = "Server is required";
            }

            if (!Request::$post->get('user')) {
                $errors[] = "Username is required";
            }

            if (!Request::$post->get('dbname')) {
                $errors[] = "Database name is required";
            }
        } elseif ($driver == "pdo_sqlite") {
            if (!Request::$post->get('path')) {
                $errors[] = "Database path is required";
            }
        }

        // Check connection
        if (!count($errors)) {
            $info = [
                'driver' => $driver,
            ];

            switch ($driver) {
                case "pdo_pgsql":
                case "pdo_mysql":
                    $info = $info + [
                        'host'     => Request::$post->get('host'),
                        'user'     => Request::$post->get('user'),
                        'password' => Request::$post->get('password'),
                        'dbname'   => Request::$post->get('dbname')
                    ];
                    break;

                case "pdo_sqlite":
                    $info['path'] = Request::$post->get('path');
                    break;
            }

            try {
                // Lets try to do a few things with the database to confirm a connection.
                $db = ConnectionManager::create($info);
                $sm = $db->getSchemaManager();
                $sm->listTables();
            } catch (DBALException $e) {
                $errors[] = "Unable to connect to database: " . $e->getMessage();
            }
        }

        if (count($errors)) {
            $this->title("Database Information");
            return $this->render("steps/database_information.phtml", [
                'errors' => $errors
            ]);
        }

        $_SESSION['db'] = $info;
    }
822944
private function tryConnect(): void
    {
        $config = $this->getConfig();

        $pdoConfig = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        if (isset($config['adapter_options'])) {
            foreach ($config['adapter_options'] as $key => $value) {
                $pdoConfig[$key] = $value;
            }
        }

        if (isset($config['path'])) {
            $path = $config['path'];
            if (substr($path, 0, 8) == 'storage:') {
                $path = Application::getStoragePath(substr($path, 8));
            }
        } else {
            $path = Application::getStoragePath('data/database.sqlite');
        }

        $directory = dirname($path);
        if (!is_dir($directory)) {
            Directory::mkdir($directory, 0755);
        }

        $this->pdo = new PDO('sqlite:' . $path);
        foreach ($pdoConfig as $key => $value) {
            $this->pdo->setAttribute($key, $value);
        }

        // create needed function(s)
        $this->pdo->sqliteCreateFunction('ILIKE', function ($mask, $value) {
            $mask = str_replace(['%', '_'], ['.*?', '.'], preg_quote($mask, '/'));
            $mask = "/^$mask$/ui";
            return preg_match($mask, $value);
        }, 2);
    }
335379
public function databaseIsEmpty()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database;
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("show tables");
            $command->setFetchMode(\PDO::FETCH_ASSOC);
            $command->execute();
            return empty($command->fetchAll());

        } catch (\PDOException $e) {
            return false;
        }
    }
1303771
protected function checkEnvironment()
	{
		if( version_compare( TYPO3_version, '9.0', '<' ) ) {
			return;
		}

		$objectManager = GeneralUtility::makeInstance( ObjectManager::class );
		$connectionPool = $objectManager->get( TYPO3\CMS\Core\Database\ConnectionPool::class );
		$connection = $connectionPool->getQueryBuilderForTable( 'fe_user' )->getConnection();
		$params = $connection->getParams();

		if( strpos( $connection->getServerVersion(), 'MySQL' ) === false ) {
			return;
		}

		// MariaDB might get identified as a 'MySQL 5.5.5' for some reason
		$result = $connection->prepare('SELECT version()');
		$result->execute();
		$rows = $result->fetchAll();

		if( !isset( $rows[0]['version()'] ) ) {
			return;
		}

		$version = $rows[0]['version()']; // Something like '10.1.29-MariaDB' or '5.6.33-0ubuntu0'

		// Only MySQL < 5.7 and MariaDB < 10.2 don't work
		if( ( strpos( $version, 'MariaDB' ) !== false && version_compare( $version, '10.2', '>=' ) )
			|| version_compare( $version, '5.7', '>=' )
		) {
			return;
		}

		// MySQL < 5.7 and utf8mb4 charset doesn't work due to missing long index support
		if( isset( $params['tableoptions']['charset'] ) && $params['tableoptions']['charset'] !== 'utf8mb4' ) {
			return;
		}

		// Retrieve the name of the connection (which is not part of the connection class)
		foreach ( $connectionPool->getConnectionNames() as $name )
		{
			if( $connectionPool->getConnectionByName( $name ) === $connection ) {
				break;
			}
		}

		$msg = $objectManager->get(
			FlashMessage::class,
			LocalizationUtility::translate( 'LLL:EXT:aimeos/Resources/Private/Language/admin.xlf:t3_9x_config_error_text', 'aimeos', [$name] ),
			LocalizationUtility::translate( 'LLL:EXT:aimeos/Resources/Private/Language/admin.xlf:t3_9x_config_error_header' ),
			FlashMessage::ERROR
		);

		return $objectManager->get( FlashMessageRendererResolver::class )->resolve()->render( [$msg] ) .
			LocalizationUtility::translate( 'LLL:EXT:aimeos/Resources/Private/Language/admin.xlf:t3_9x_config_error_remedy' );
	}
864497
private function checkDatabaseFile()
    {
        if ($this->isDatabaseExists()) return;

        $pathinfo = pathinfo($path = $this->getDatabasePath());

        if ( ! file_exists($pathinfo['dirname'])) {
            mkdir($pathinfo['dirname'], 0777, true);
        }

        copy(realpath(__DIR__ . '/../../data/geoip.mmdb'), $path);
    }
205084
public static function isConnected() {
		return self::$db !== null && (self::$db instanceof Database) && self::$db->isConnected ();
	}
391939
public function check()
	{
		// Check if the db connector has been set.
		if (!($this->db instanceof PgsqlDriver))
		{
			throw new \Exception('Database connection wrong type.');
		}

		// Check if the tables have been specified.
		if (empty($this->from))
		{
			throw new \Exception('ERROR: No Tables Specified');
		}

		return $this;
	}
547118
function check_exts($action,$mode){
		$old_config = new DataConfig($this->config);
		
		$this->connector->event->trigger("before".$mode,$action);
		if ($action->is_ready())
			LogMaster::log("Event code for ".$mode." processed");
		else {
			//check if custom sql defined
			$sql = $this->connector->sql->get_sql($mode,$action);
			if ($sql){
				$this->connector->sql->query($sql);
			}
			else{
				$action->sync_config($this->config);
				if ($this->connector->model && method_exists($this->connector->model, $mode)){
					call_user_func(array($this->connector->model, $mode), $action);
					LogMaster::log("Model object process action: ".$mode);
				}
				if (!$action->is_ready()){
					$method=array($this->connector->sql,$mode);
					if (!is_callable($method))
						throw new Exception("Unknown dataprocessing action: ".$mode);
					call_user_func($method,$action,$this->request);
				}
			}
		}
		$this->connector->event->trigger("after".$mode,$action);
		
		$this->config->copy($old_config);
	}
1191231
public function connectionSettingsAreValid()
    {
        // if there is no adapter how can we initialize the correct validator to check it
        if (!$this->getDbAdapter()) {
            return false;
        }

        /**
         * @var MySQLConnectionSettings $connectionSettings
         */
        $connectionSettings = $this->getDbAdapter()->getConnectionSettings();
        if (!$connectionSettings) {
            return false;
        }

        return $connectionSettings->validateProperties();
    }
744448
public function connect()
    {
        if (self::$profiling) {
            $timer = $this->initProfiler();
        }

        $this->connection = mysqli_init();


        if($this->enable_ssl){
            mysqli_ssl_set($this->connection, $this->ssl_key, $this->ssl_cert, $this->ssl_ca, $this->ssl_ca_path, $this->ssl_cipher);
        }

        // Make sure MySQL returns all matched rows on update queries including
        // rows that actually didn't have to be updated because the values didn't
        // change. This matches common behaviour among other database systems.
        // See #6296 why this is important in tracker
        $flags = MYSQLI_CLIENT_FOUND_ROWS;
        if ($this->enable_ssl){
            $flags = $flags | MYSQLI_CLIENT_SSL;
        }
        if ($this->ssl_no_verify && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')){
            $flags = $flags | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
        }
        mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->dbname, $this->port, $this->socket, $flags);
        if (!$this->connection || mysqli_connect_errno()) {
            throw new DbException("Connect failed: " . mysqli_connect_error());
        }

        if ($this->charset && !mysqli_set_charset($this->connection, $this->charset)) {
            throw new DbException("Set Charset failed: " . mysqli_error($this->connection));
        }

        $this->password = '';

        if (self::$profiling && isset($timer)) {
            $this->recordQueryProfile('connect', $timer);
        }
    }
56951
static public function activeConnectionData()
    {
        if (!self::$activeConnectionName)
            throw new Exception\RuntimeException("No database connection is active");
        return array_merge(self::$_connection_data[self::$activeConnectionName], ['name' => self::$activeConnectionName]);
    }
91238
public function check()
    {
        $returnValue = null;

        
        $report = parent::check();
        $name = $this->getName();
        
        if ($report->getStatus() == common_configuration_Report::VALID){
            $report->setMessage("Database Driver '${name}' is available.");
        }
        else{
            $report->setMessage("Database Driver '${name}' could not be found or is unavailable.");
        }

        $returnValue = $report;
        

        return $returnValue;
    }
384256
public function connect(): bool
    {
        try {
            $this->checkConnect();
            $this->log('Connect to ' . $this->connect['host']);
            $this->handler = new \PDO(
                $this->connect['type'] . ':host=' . $this->connect['host'] . ';dbname=' . $this->connect['name'],
                $this->connect['user'],
                $this->connect['pass'],
                $this->connect['options']
            );

            foreach ($this->attributes as $attribute => $value) {
                $this->handler->setAttribute($attribute, $value);
            }

            $this->ok();
        } catch (\Exception $e) {
            throw new DbException("Attempt connection to database is failed: {$e->getMessage()}");
        }
        return true;
    }
1341940
public function isConnected(): bool
    {
        try{
            return false !== $this->instance->getAttribute(\PDO::ATTR_SERVER_INFO);
        } catch (\Throwable $e) {
        }
        return false;
    }
698851
public function check() {
        $this->_errors = [];

        foreach ($this->_constraints as $constraints) {
            if (!isset($this->_data[$this->_field])) {
                $this->_data[$this->_field] = [];
            }

            if (!is_array($this->_data[$this->_field])) {
                $this->_data[$this->_field] = [$this->_data[$this->_field]];
            }

            foreach ($this->_data[$this->_field] as $value) {
                switch ($constraints['type']) {
                    case self::EQUAL:
                        if ($value != $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::DIFFERENT:
                        if ($value == $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::MORETHAN:
                        if ($value <= $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LESSTHAN:
                        if ($value >= $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::BETWEEN:
                        if ($value < $constraints['value'][0] || $value > $constraints['value'][1]) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::IN:
                        if (!in_array($value, $constraints['value'])) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::NOTIN:
                        if (in_array($value, $constraints['value'])) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LENGTH:
                        if (strlen($value) != $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LENGTHMIN:
                        if (strlen($value) < $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LENGTHMAX:
                        if (strlen($value) > $constraints['value']) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LENGTHIN:
                        if (!in_array(strlen($value), $constraints['value'])) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::LENGTHBETWEEN:
                        if (strlen($value) < $constraints['value'][0] || strlen($value) > $constraints['value'][1]) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::REGEX:
                        if (!preg_match($constraints['value'], $value)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::URL:
                        if (!filter_var($value, FILTER_VALIDATE_URL)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::MAIL:
                        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::INT:
                        if (!filter_var($value, FILTER_VALIDATE_INT)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::FLOAT:
                        if (!filter_var($value, FILTER_VALIDATE_FLOAT)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::ALPHA:
                        if (!preg_match('#^([a-zA-Z]+)$#', $value)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::ALPHANUM:
                        if (!preg_match('#^([a-zA-Z0-9]+)$#', $value)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::ALPHADASH:
                        if (!preg_match('#^([a-zA-Z0-9_-]+)$#', $value)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::IP:
                        if (!filter_var($value, FILTER_VALIDATE_IP)) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::SQL:
                        $sql = new Sql();
                        $sql->query('query-form-validation', $constraints['value']['query']);
                        $sql->vars('value', $value);
                        $sql->vars($constraints['value']['vars']);
                        $data = $sql->fetch('query-form-validation', Sql::PARAM_FETCHCOLUMN);

                        $querySuccess = true;

                        switch ($constraints['value']['constraint']) {
                            case '==':
                                if ($data != $constraints['value']['value']) {
                                    $querySuccess = false;
                                }
                                break;

                            case '!=':
                                if ($data == $constraints['value']['value']) {
                                    $querySuccess = false;
                                }
                                break;

                            case '>':
                                if ($data <= $constraints['value']['value']) {
                                    $querySuccess = false;
                                }
                                break;

                            case '<':
                                if ($data >= $constraints['value']['value']) {
                                    $querySuccess = false;
                                }
                                break;
                        }

                        if (!$querySuccess) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                        }
                        break;

                    case self::CUSTOM:
                        /** @var object[] $constraints */
                        if ($constraints['value']->filter() == false) {
                            array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['value']->error()]);
                        }
                        break;
                }
            }

            switch ($constraints['type']) {
                case self::COUNT:
                    if (count($this->_data[$this->_field]) != $constraints['value']) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;

                case self::COUNTMIN:
                    if (count($this->_data[$this->_field]) < $constraints['value']) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;

                case self::COUNTMAX:
                    if (count($this->_data[$this->_field]) > $constraints['value']) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;

                case self::COUNTIN:
                    /** @var array $constraints */
                    if (!in_array(count($this->_data[$this->_field]), $constraints['value'])) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;

                case self::EXIST:
                    if (count($this->_data[$this->_field]) == 0) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;

                case self::NOTEXIST:
                    if (count($this->_data[$this->_field]) > 0) {
                        array_push($this->_errors, ['name' => $this->_field, 'field' => $this->_label, 'message' => $constraints['message']]);
                    }
                    break;
            }
        }
    }
252591
public static function checkDbConnection()
		{
			try {
				// Check DB Connection
				Yii::$app->db->isActive;

				return TRUE;
			} catch (Exception $e) {
				print_r($e->getMessage());
			}

			return FALSE;
		}
380229
public function checkConnection()
    {
        try {
            $this->runQuery('', [], true);
        } catch (\Exception $e) {
            if ($e->hasResponse()) {
                switch ($e->getResponse()->getStatusCode()) {
                    case 403:
                        return [
                            'status' => 0,
                            'error' => 'auth_error',
                            'verbose' => 'Check Username and Password/Access Key.'
                        ];
                    default:
                        return [
                            'status' => 0,
                            'error' => 'unknown',
                            'verbose' => 'An unknown error has occurred. Server replied with: ' . $e->getResponse()->getStatusCode()
                        ];
                }
            } else {
                return [
                    'status' => 0,
                    'error' => 'conn_error',
                    'verbose' => 'Check CSF or hostname/port.'
                ];
            }
            return false;
        }

        return [
            'status' => 1,
            'error' => false,
            'verbose' => 'Everything is working.'
        ];
    }