Opens a connection to the configured database.

@see Securimage::$use_database Use database
@see Securimage::$database_driver Database driver
@see Securimage::$pdo_conn pdo_conn
@return bool true if the database connection was successful, false if not
978128
protected function openDatabase()
    {
        $this->pdo_conn = false;

        if ($this->use_database) {
            $pdo_extension = 'PDO_' . strtoupper($this->database_driver);

            if (!extension_loaded($pdo_extension)) {
                trigger_error("Database support is turned on in Securimage, but the chosen extension $pdo_extension is not loaded in PHP.", E_USER_WARNING);
                return false;
            }
        }

        if ($this->database_driver == self::SI_DRIVER_SQLITE3) {
            if (!file_exists($this->database_file)) {
                $fp = fopen($this->database_file, 'w+');
                if (!$fp) {
                    $err = error_get_last();
                    trigger_error("Securimage failed to create SQLite3 database file '{$this->database_file}'. Reason: {$err['message']}", E_USER_WARNING);
                    return false;
                }
                fclose($fp);
                chmod($this->database_file, 0666);
            } else if (!is_writeable($this->database_file)) {
                trigger_error("Securimage does not have read/write access to database file '{$this->database_file}. Make sure permissions are 0666 and writeable by user '" . get_current_user() . "'", E_USER_WARNING);
                return false;
            }
        }

        try {
            $dsn = $this->getDsn();

            $options = array();
            $this->pdo_conn = new PDO($dsn, $this->database_user, $this->database_pass, $options);
        } catch (PDOException $pdoex) {
            trigger_error("Database connection failed: " . $pdoex->getMessage(), E_USER_WARNING);
            return false;
        } catch (Exception $ex) {
            trigger_error($ex->getMessage(), E_USER_WARNING);
            return false;
        }

        try {
            if (!$this->skip_table_check && !$this->checkTablesExist()) {
                // create tables...
                $this->createDatabaseTables();
            }
        } catch (Exception $ex) {
            trigger_error($ex->getMessage(), E_USER_WARNING);
            $this->pdo_conn = false;
            return false;
        }

        if (mt_rand(0, 100) / 100.0 == 1.0) {
            $this->purgeOldCodesFromDatabase();
        }

        return $this->pdo_conn;
    }
1124337
private function connect()
    {
        $port = isset($this->_args['port']) && $this->_args['port'] ? $this->_args['port'] : 3306;
        $dsn = "mysql:host={$this->_args['host']};port={$port};dbname={$this->_args['dbname']}";
        $username = $this->_args['username'];
        $password = $this->_args['password'];

        // TODO: Move to use the follow: PDO::ATTR_EMULATE_PREPARES to 'false'
        // For security reason
        $options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];

        /*\
         * The latter can be fixed by turning off emulation
         * and using the DSN charset attribute instead of SET NAMES.
         * The former is tricky, because you have no concept for safely
         * dealing with identifiers (they're just dumped straight into the query).
         * One possible approach would be to wrap all identifiers in backticks
         * while escaping all backticks within the identifiers (through doubling).
         * Whether this actually works in all cases is an open question, though.
        \*/

        try {
            $this->_pdo = new PDO($dsn, $username, $password, $options);
        } catch (PDOException $ex) {
            $this->_database->error('connect', $ex);
        }

        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
734709
public static function connect()
    {   
        self::getEnv();
        return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
    }
1087722
private function connect()
    {
        // Connecting with PDO.
        try {
            switch ($this->dbType) {
                case 'sqlite':
                    $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings);
                    break;
                case 'mysql':
                case 'pgsql':
                case 'dblib':
                    $this->dbHandler = @new PDO(
                        $this->dsn,
                        $this->user,
                        $this->pass,
                        $this->pdoSettings
                    );
                    // Execute init commands once connected
                    foreach ($this->dumpSettings['init_commands'] as $stmt) {
                        $this->dbHandler->exec($stmt);
                    }
                    // Store server version
                    $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
                    break;
                default:
                    throw new Exception("Unsupported database type (".$this->dbType.")");
            }
        } catch (PDOException $e) {
            throw new Exception(
                "Connection to ".$this->dbType." failed with message: ".
                $e->getMessage()
            );
        }

        if (is_null($this->dbHandler)) {
            throw new Exception("Connection to ".$this->dbType."failed");
        }

        $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
        $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings);
    }
498346
public function connect() {
		try {
			$this->_connect ();
			return true;
		} catch ( \PDOException $e ) {
			throw new DBException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
		}
	}
770946
private function _connect()
    {
        if (empty($this->_config))
            throw new \Exception('Empty connection settings provided'); 
        
        $port = $this->_config->getPort();
        $port = !empty($port) ? $port : 3306;
        $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName();
        // Create a PDO Instance for this user + database combination
        try {
            $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword());
        } catch(\PDOException $pe) {
            throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName().
                "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage());
        }

        $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false);
        $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'");
        $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING);
        $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
    }
956284
public function connectPDO($selectDb = true)
    {
        if (null !== self::$_linkId) {
            return true;
        }
        try {
            self::$_linkId = new PDO(
                'mysql:host=' . $this->_server,
                $this->_user,
                $this->_pass,
                array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')
            );
            self::$_linkId->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            if ($selectDb) {
                self::$_linkId->query('USE ' . $this->_database);
            }
        } catch (PDOException $e) {
            $this->_error = $e->getMessage();
            return false;
        }
        return true;
    }
125878
public function tryConnect() {
		if ($this->db_connected) {
			return TRUE;
		}
		if (!class_exists('mysqli')) {
			BLog::addToLog($this->logsuffix . ': MySQLi class not found', LL_ERROR);
			return FALSE;
		}
		$this->mysqli = new \mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name, $this->db_port);
		if ((empty($this->mysqli)) || (mysqli_connect_errno())) {
			BLog::addToLog($this->logsuffix . ': ' . mysqli_connect_error(), LL_ERROR);
			return FALSE;
		}
		if (!$this->mysqli->set_charset("utf8")) return FALSE;
		$this->db_connected = TRUE;
		return TRUE;
	}
34467
private function connect()
    {
        $username = $this->config->get('username');
        $password = $this->config->get('password');
        $host = $this->config->get('hostname');
        $database = $this->config->get('database');
        $schema = $this->config->get('schema');
        $this->dsn = $this->config->get('dsn');
        if (!$this->config->has('type', Type::STRING))
            throw new ConfigurationException("Please specify the database type in the configuration section [sql]");

        $type = $this->config->getString('type');

        // Set up the driver
        $this->driver = $this->setupDriver($type);
        $this->driver->setTablePrefix($this->config->dget('prefix', ''));
            
        if (!$this->dsn)
        {
            $this->dsn = $this->driver->generateDSN($this->config->toArray());
            self::$logger->debug("Generated DSN: {0}", [$this->dsn]);
            $this->config->set('dsn', $this->dsn);
        }
            
        // Create the PDO and connect it to the database, setting default options
        //$pdo = new PDO($this->dsn, $username, $password);
        $pdo = DI::getInjector()
            ->newInstance(
                PDO::class,
                ['dsn' => $this->dsn, 'username' => $username, 'passwd' => $password]
            )
        ;
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            
        $this->pdo = $pdo;
    }
831094
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Make sure the PDO extension for PHP is installed and enabled.
		if (!self::isSupported())
		{
			throw new \RuntimeException('PDO Extension is not available.', 1);
		}

		// Find the correct PDO DSN Format to use:
		switch ($this->options['driver'])
		{
			case 'cubrid':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 33000;

				$format = 'cubrid:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'dblib':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'dblib:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'firebird':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 3050;

				$format = 'firebird:dbname=#DBNAME#';

				$replace = array('#DBNAME#');
				$with = array($this->options['database']);

				break;

			case 'ibm':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 56789;

				if (!empty($this->options['dsn']))
				{
					$format = 'ibm:DSN=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'ibm:hostname=#HOST#;port=#PORT#;database=#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				break;

			case 'informix':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1526;
				$this->options['protocol'] = (isset($this->options['protocol'])) ? $this->options['protocol'] : 'onsoctcp';

				if (!empty($this->options['dsn']))
				{
					$format = 'informix:DSN=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'informix:host=#HOST#;service=#PORT#;database=#DBNAME#;server=#SERVER#;protocol=#PROTOCOL#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#SERVER#', '#PROTOCOL#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database'], $this->options['server'], $this->options['protocol']);
				}

				break;

			case 'mssql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'mysql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 3306;

				$format = 'mysql:host=#HOST#;port=#PORT#;dbname=#DBNAME#;charset=#CHARSET#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#CHARSET#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database'], $this->options['charset']);

				break;

			case 'oci':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1521;
				$this->options['charset'] = (isset($this->options['charset'])) ? $this->options['charset'] : 'AL32UTF8';

				if (!empty($this->options['dsn']))
				{
					$format = 'oci:dbname=#DSN#';

					$replace = array('#DSN#');
					$with = array($this->options['dsn']);
				}
				else
				{
					$format = 'oci:dbname=//#HOST#:#PORT#/#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				$format .= ';charset=' . $this->options['charset'];

				break;

			case 'odbc':
				$format = 'odbc:DSN=#DSN#;UID:#USER#;PWD=#PASSWORD#';

				$replace = array('#DSN#', '#USER#', '#PASSWORD#');
				$with = array($this->options['dsn'], $this->options['user'], $this->options['password']);

				break;

			case 'pgsql':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 5432;

				$format = 'pgsql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'sqlite':
				if (isset($this->options['version']) && $this->options['version'] == 2)
				{
					$format = 'sqlite2:#DBNAME#';
				}
				else
				{
					$format = 'sqlite:#DBNAME#';
				}

				$replace = array('#DBNAME#');
				$with = array($this->options['database']);

				break;

			case 'sybase':
				$this->options['port'] = (isset($this->options['port'])) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			default:
				throw new \UnexpectedValueException('The ' . $this->options['driver'] . ' driver is not supported.');
		}

		// Create the connection string:
		$connectionString = str_replace($replace, $with, $format);

		try
		{
			$this->connection = new \PDO(
				$connectionString,
				$this->options['user'],
				$this->options['password'],
				$this->options['driverOptions']
			);
		}
		catch (\PDOException $e)
		{
			throw new \RuntimeException('Could not connect to PDO' . ': ' . $e->getMessage(), 2, $e);
		}
	}
987387
public function connect()
    {
        $connection = null;

        /**
         * @todo we need a SQLLogger that logs to a (CSV?) file, as we probably do not want to log into the database.
         *
         * $configuration->setSQLLogger(new EchoSQLLogger());
         */

        try {
            $connection = $this->getConnectionFromDriverManager();
            $connection->connect();

            $this->setConnection($connection);

            $this->ensureConnectionIsEstablished($connection);
        } catch (DBALException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        } catch (PDOException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        }
    }
1139854
protected function _connect()
    {
        try {
            $this->_Redis = new Redis();
            if (!empty($this->_config['unix_socket'])) {
                $return = $this->_Redis->connect($this->_config['unix_socket']);
            } elseif (empty($this->_config['persistent'])) {
                $return = $this->_Redis->connect($this->_config['server'], $this->_config['port'], $this->_config['timeout']);
            } else {
                $persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database'];
                $return = $this->_Redis->pconnect($this->_config['server'], $this->_config['port'], $this->_config['timeout'], $persistentId);
            }
        } catch (RedisException $e) {
            return false;
        }
        if ($return && $this->_config['password']) {
            $return = $this->_Redis->auth($this->_config['password']);
        }
        if ($return) {
            $return = $this->_Redis->select($this->_config['database']);
        }

        return $return;
    }
1359554
private function connect() {
    // connect
    if (isset($this->connectionParams['dbType']) && isset($this->connectionParams['dbHostName']) &&
      isset($this->connectionParams['dbUserName']) && isset($this->connectionParams['dbPassword']) &&
      isset($this->connectionParams['dbName'])) {

      $dbType = strtolower($this->connectionParams['dbType']);
      $this->isFileDB = $dbType == 'sqlite' && strtolower($this->connectionParams['dbName']) != ':memory:';

      $this->connId = join(',', [$this->connectionParams['dbType'], $this->connectionParams['dbHostName'],
          $this->connectionParams['dbUserName'], $this->connectionParams['dbPassword'], $this->connectionParams['dbName'],
          // make sure that the sequence mapper uses it's own connection for separate transaction management
          (!$this->isFileDB && $this->getType() == $this->getSequenceMapper()->getType())
      ]);

      // reuse an existing adapter if possible
      if (isset(self::$adapters[$this->connId])) {
        $this->adapter = self::$adapters[$this->connId];
      }
      else {
        try {
          $charSet = isset($this->connectionParams['dbCharSet']) ?
                  $this->connectionParams['dbCharSet'] : 'utf8';

          // create new connection
          $pdoParams = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
          // driver specific
          switch ($dbType) {
            case 'mysql':
              $pdoParams[PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = true;
              $pdoParams[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES ".$charSet;
              break;
            case 'sqlite':
              if (!$this->isFileDB) {
                $pdoParams[PDO::ATTR_PERSISTENT] = true;
              }
              else {
                $this->connectionParams['dbName'] = FileUtil::realpath(WCMF_BASE.$this->connectionParams['dbName']);
              }
              break;
          }

          $params = [
            'hostname' => $this->connectionParams['dbHostName'],
            'username' => $this->connectionParams['dbUserName'],
            'password' => $this->connectionParams['dbPassword'],
            'database' => $this->connectionParams['dbName'],
            'driver' => 'Pdo_'.ucfirst($this->connectionParams['dbType']),
            'driver_options' => $pdoParams
          ];

          if (!empty($this->connectionParams['dbPort'])) {
            $params['port'] = $this->connectionParams['dbPort'];
          }
          $this->adapter = new Adapter($params);

          // store the connection for reuse
          self::$adapters[$this->connId] = $this->adapter;
        }
        catch(\Exception $ex) {
          throw new PersistenceException("Connection to ".$this->connectionParams['dbHostName'].".".
            $this->connectionParams['dbName']." failed: ".$ex->getMessage());
        }
      }
      // get database prefix if defined
      if (isset($this->connectionParams['dbPrefix'])) {
        $this->dbPrefix = $this->connectionParams['dbPrefix'];
      }
    }
    else {
      throw new IllegalArgumentException("Wrong parameters for constructor.");
    }
  }
395287
private static function createConnection()
    {
        // Validate if configuration has enough details.
        $driver = Configuration::get('database_driver');

        // Make DSN and options
        $dsn = "";
        $options = Configuration::get('database-options');
        $options = !is_array($options) ? array() : $options;

        $user = null;
        $password = null;

        if ($driver === 'pdo_sqlite') {
            // We will ignore this for now, as it's not tested with SQLite yet!
            // @codeCoverageIgnoreStart
            $path = Configuration::get('database_path');

            if (! $path || ! file_exists($path)) {
                throw new \Exception("SQLite Database File doesn't exists or not configured! '".$path."'");
            }

            $dsn = "sqlite:" . $path;
            // @codeCoverageIgnoreEnd
        }else if ($driver === 'pdo_mysql') {
            $host = Configuration::get('database_host');
            $database = Configuration::get('database_db');
            $user = Configuration::get('database_user');
            $password = Configuration::get('database_password');

            $port = Configuration::get('database_port');
            $port = !is_int($port) ? 3306 : $port;

            $encoding = Configuration::get('database_encoding');
            $encoding = $encoding == null ? 'utf8' : $encoding;

            if (is_null($host) || is_null($database) || is_null($user) || is_null($password)) {
                throw new \Exception("Please configure the ORM first. We can't get a connection now!");
            }

            $dsn = "mysql:host=" . $host . ";port=" . $port . ";dbname=" . $database . ";charset=" . $encoding;
        }else{
            throw new \Exception("Please configure the ORM first. We can't get a connection now! No driver given!");
        }

        // Make connection
        self::$connection = new \PDO($dsn, $user, $password, $options);
    }
1163073
public function connection()
    {
        // Build of the mysql dsn
        if (isset($this->config['socket']) && !is_null($this->config['socket']) && !empty($this->config['socket'])) {
            $hostname = $this->config['socket'];
        } else {
            $hostname = $this->config['hostname'];
        }

        $port = '';

        if ($hostname !== 'localhost' || $hostname == '127.0.0.1') {
            if (isset($this->config['port']) && !is_null($this->config['port']) && !empty($this->config['port'])) {
                $port = ':'.$this->config['port'];
            } else {
                $port = ':'.self::PORT;
            }
        }

        // Formatting connection parameters
        $host  = "mysql:host=".$hostname.$port;

        $database = "dbname=".$this->config['database'];

        $username = $this->config["username"];

        $password = $this->config["password"];

        // Configuration extra PDO side
        $options = [
            PDO::ATTR_DEFAULT_FETCH_MODE => isset($this->config['fetch']) ? $this->config['fetch'] : $this->fetch,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . Str::upper($this->config["charset"]),
            PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
        ];

        $this->pdo = new PDO($host.';'.$database, $username, $password, $options);
    }
455779
private function connect()
    {
        try {
            $this->db = new \PDO(
                $this->dbOptions['dsn'],
                $this->dbOptions['username'],
                $this->dbOptions['password'],
                $this->dbOptions['driver_options']
            );

        } catch (\Exception $e) {
            //Change to true to debug database connection
            if ($this->dbOptions['debug']) {
                // For debug purpose, shows all connection details
                throw $e;
            } else {
                // Hide connection details.
                throw new \PDOException("Could not connect to database, hiding connection details.");
            }
        }
        $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
    }
731385
public function connect() : bool
    {
        try {
            $connection_string = 'sqlsrv:SERVER=' . $this->configuration['server'] . ';DATABASE=' . $this->configuration['dbname'];
            if (isset($this->configuration['encrypt']) && true === $this->configuration['encrypt']) {
                $connection_string .= ';ENCRYPT=1';
            }
            $this->logger->debug('Connecting to database engine.');
            $this->dbconn = new PDO($connection_string, $this->configuration['username'],
                $this->configuration['password']);
            $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->logger->debug('Connected to database engine.');
            $this->is_connected = true;
        } catch (\Exception $e) {
            throw new DatabaseConnectionException('MSSQL Connection to <strong>' . $this->configuration['server'] . '</strong> failed!<br>' . $e->getMessage());
        }
        return true;
    }