@param string $dsn

@return array
435305
private function parseDsn($dsn)
    {
        $dsn = Dsn::parseFirst($dsn);

        $supportedSchemes = $this->supportedSchemes;
        if (false == in_array($dsn->getSchemeProtocol(), $supportedSchemes, true)) {
            throw new \LogicException(sprintf(
                'The given scheme protocol "%s" is not supported. It must be one of "%s".',
                $dsn->getSchemeProtocol(),
                implode('", "', $supportedSchemes)
            ));
        }

        $sslOn = false;
        $isAmqps = 'amqps' === $dsn->getSchemeProtocol();
        $isTls = in_array('tls', $dsn->getSchemeExtensions(), true);
        $isSsl = in_array('ssl', $dsn->getSchemeExtensions(), true);
        if ($isAmqps || $isTls || $isSsl) {
            $sslOn = true;
        }

        $this->schemeExtensions = $dsn->getSchemeExtensions();

        $config = array_filter(array_replace($dsn->getQuery(), [
            'host' => $dsn->getHost(),
            'port' => $dsn->getPort(),
            'user' => $dsn->getUser(),
            'pass' => $dsn->getPassword(),
            'vhost' => null !== ($path = $dsn->getPath()) ?
                (0 === strpos($path, '/') ? substr($path, 1) : $path)
                : null,
            'read_timeout' => $dsn->getFloat('read_timeout'),
            'write_timeout' => $dsn->getFloat('write_timeout'),
            'connection_timeout' => $dsn->getFloat('connection_timeout'),
            'heartbeat' => $dsn->getFloat('heartbeat'),
            'persisted' => $dsn->getBool('persisted'),
            'lazy' => $dsn->getBool('lazy'),
            'qos_global' => $dsn->getBool('qos_global'),
            'qos_prefetch_size' => $dsn->getDecimal('qos_prefetch_size'),
            'qos_prefetch_count' => $dsn->getDecimal('qos_prefetch_count'),
            'ssl_on' => $sslOn,
            'ssl_verify' => $dsn->getBool('ssl_verify'),
            'ssl_cacert' => $dsn->getString('ssl_cacert'),
            'ssl_cert' => $dsn->getString('ssl_cert'),
            'ssl_key' => $dsn->getString('ssl_key'),
            'ssl_passphrase' => $dsn->getString('ssl_passphrase'),
        ]), function ($value) { return null !== $value; });

        return array_map(function ($value) {
            return is_string($value) ? rawurldecode($value) : $value;
        }, $config);
    }
780788
private function scanAsn($asns)
    {
        $netblocks = [];

        foreach ($asns as $asn) {
            $dns = dns_get_record("as{$asn}.ascc.dnsbl.bit.nl", DNS_TXT);
            foreach ($dns as $key => $entry) {
                if (!in_array($entry, $netblocks)) {
                    $this->scanNetblock($netblocks);

                    $netblocks[] = $entry['txt'];
                }
            }
        }

        return true;
    }
1132927
public static function parse(string $dsn): array
    {
        if (false === strpos($dsn, ':')) {
            throw new \LogicException(sprintf('The DSN is invalid. It does not have scheme separator ":".'));
        }

        list($scheme, $dsnWithoutScheme) = explode(':', $dsn, 2);

        $scheme = strtolower($scheme);
        if (false == preg_match('/^[a-z\d+-.]*$/', $scheme)) {
            throw new \LogicException('The DSN is invalid. Scheme contains illegal symbols.');
        }

        $schemeParts = explode('+', $scheme);
        $schemeProtocol = $schemeParts[0];

        unset($schemeParts[0]);
        $schemeExtensions = array_values($schemeParts);

        $user = parse_url($dsn, PHP_URL_USER) ?: null;
        if (is_string($user)) {
            $user = rawurldecode($user);
        }

        $password = parse_url($dsn, PHP_URL_PASS) ?: null;
        if (is_string($password)) {
            $password = rawurldecode($password);
        }

        $path = parse_url($dsn, PHP_URL_PATH) ?: null;
        if ($path) {
            $path = rawurldecode($path);
        }

        $query = [];
        $queryString = parse_url($dsn, PHP_URL_QUERY) ?: null;
        if (is_string($queryString)) {
            $query = self::httpParseQuery($queryString, '&', PHP_QUERY_RFC3986);
        }
        $hostsPorts = '';
        if (0 === strpos($dsnWithoutScheme, '//')) {
            $dsnWithoutScheme = substr($dsnWithoutScheme, 2);
            $dsnWithoutUserPassword = explode('@', $dsnWithoutScheme, 2);
            $dsnWithoutUserPassword = 2 === count($dsnWithoutUserPassword) ?
                $dsnWithoutUserPassword[1] :
                $dsnWithoutUserPassword[0]
            ;

            list($hostsPorts) = explode('#', $dsnWithoutUserPassword, 2);
            list($hostsPorts) = explode('?', $hostsPorts, 2);
            list($hostsPorts) = explode('/', $hostsPorts, 2);
        }

        if (empty($hostsPorts)) {
            return [
                new self(
                    $scheme,
                    $schemeProtocol,
                    $schemeExtensions,
                    null,
                    null,
                    null,
                    null,
                    $path,
                    $queryString,
                    $query
                ),
            ];
        }

        $dsns = [];
        $hostParts = explode(',', $hostsPorts);
        foreach ($hostParts as $key => $hostPart) {
            unset($hostParts[$key]);

            $parts = explode(':', $hostPart, 2);
            $host = $parts[0];

            $port = null;
            if (isset($parts[1])) {
                $port = (int) $parts[1];
            }

            $dsns[] = new self(
                $scheme,
                $schemeProtocol,
                $schemeExtensions,
                $user,
                $password,
                $host,
                $port,
                $path,
                $queryString,
                $query
            );
        }

        return $dsns;
    }
902456
protected function getGroupsByNames(array $dns = [], $fields = [])
    {
        $query = $this->query->newInstance();

        return $query->newCollection($dns)->map(function ($dn) use ($query, $fields) {
            return $query->select($fields)->findByDn($dn);
        })->filter(function ($group) {
            return $group instanceof Group;
        });
    }
274141
private function parseDsn(string $dsn, array $config = null): array
    {
        if (false === strpos($dsn, ':')) {
            throw new \LogicException(sprintf('The DSN is invalid. It does not have scheme separator ":".'));
        }

        if (false === parse_url($dsn)) {
            throw new \LogicException(sprintf('Failed to parse DSN "%s"', $dsn));
        }

        list($scheme) = explode(':', $dsn, 2);

        $scheme = strtolower($scheme);
        if (false == preg_match('/^[a-z\d+-.]*$/', $scheme)) {
            throw new \LogicException('The DSN is invalid. Scheme contains illegal symbols.');
        }

        $supported = [
            'db2' => 'db2',
            'ibm-db2' => 'ibm-db2',
            'mssql' => 'mssql',
            'sqlsrv+pdo' => 'pdo_sqlsrv',
            'mysql' => 'mysql',
            'mysql2' => 'mysql2',
            'mysql+pdo' => 'pdo_mysql',
            'pgsql' => 'pgsql',
            'postgres' => 'postgres',
            'pgsql+pdo' => 'pdo_pgsql',
            'sqlite' => 'sqlite',
            'sqlite3' => 'sqlite3',
            'sqlite+pdo' => 'pdo_sqlite',
        ];

        if (false == isset($supported[$scheme])) {
            throw new \LogicException(sprintf(
                'The given DSN schema "%s" is not supported. There are supported schemes: "%s".',
                $scheme,
                implode('", "', array_keys($supported))
            ));
        }

        $doctrineScheme = $supported[$scheme];

        if ($scheme.':' === $dsn && is_array($config) && array_key_exists('connection', $config)) {
            $default = [
                'driver' => $doctrineScheme,
                'host' => 'localhost',
                'port' => '3306',
                'user' => 'root',
                'password' => '',
            ];

            return [
                'lazy' => true,
                'connection' => array_replace_recursive($default, $config['connection']),
            ];
        }

        return [
            'lazy' => true,
            'connection' => [
                'url' => $scheme.':' === $dsn ?
                    $doctrineScheme.'://root@localhost' :
                    str_replace($scheme, $doctrineScheme, $dsn),
            ],
        ];
    }
315809
public function dnExists($dn)
    {
        if (PEAR::isError($dn)) {
            return $dn;
        }
        if ($dn instanceof Net_LDAP2_Entry) {
             $dn = $dn->dn();
        }
        if (false === is_string($dn)) {
            return PEAR::raiseError('Parameter $dn is not a string nor an entry object!');
        }

        // search LDAP for that DN by performing a baselevel search for any
        // object. We can only find the DN in question this way, or nothing.
        $s_opts = array(
            'scope'      => 'base',
            'sizelimit'  => 1,
            'attributes' => '1.1' // select no attrs
        );
        $search = $this->search($dn, '(objectClass=*)', $s_opts);

        if (self::isError($search)) {
            return $search;
        }

        // retun wehter the DN exists; that is, we found an entry
        return ($search->count() == 0)? false : true;
    }
1340086
static function getGroupNameByDN( $ds, $groupDN )
    {
        $LDAPIni = eZINI::instance( 'ldap.ini' );
        $LDAPGroupNameAttribute = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupNameAttribute' );

        // First, try to see if the $LDAPGroupNameAttribute is contained within the DN, in that case we can read it directly
        $groupDNParts = ldap_explode_dn( $groupDN, 0 );
        list( $firstName, $firstValue ) = explode( '=', $groupDNParts[0] );

        if ( $firstName = $LDAPGroupNameAttribute ) // Read the group name attribute directly from the group DN
        {
            $groupName = $firstValue;
        }
        else // Read the LDAP group object, get the group name attribute from it
        {
            $sr = ldap_read( $ds, $groupDN, "($LDAPGroupNameAttribute=*)", array( $LDAPGroupNameAttribute ) );
            $info = ldap_get_entries( $ds, $sr );

            if ( $info['count'] < 1 or $info[0]['count'] < 1 )
            {
                eZDebug::writeWarning( 'LDAP group not found, tried DN: ' . $groupDN, __METHOD__ );
                return false;
            }

            $groupName = $info[0][$LDAPGroupNameAttribute];
            if ( is_array( $groupName ) ) // This may be a string or an array of strings, depending on LDAP setup
                $groupName = $groupName[0]; // At least one must exist, since we specified it in the search filter
        }

        return $groupName;
    }
245642
public function setDsn(Dsn $dsn)
    {
        $this->dsn = $dsn;
        $cell = $dsn->getConfig()->getCell();

        if (!$cell) {
            throw new Exception("Cell missing.");
        }

        $this->set(self::PARAM_CELL, new Parameter(self::PARAM_CELL, $cell));

        return $this;
    }
241456
function load($dsn) {
		$fw=Base::instance();
		if ($dsn=trim($dsn)) {
			if (preg_match('/^redis=(.+)/',$dsn,$parts) &&
				extension_loaded('redis')) {
				$port=6379;
				$parts=explode(':',$parts[1],2);
				if (count($parts)>1)
					list($host,$port)=$parts;
				else
					$host=$parts[0];
				$this->ref=new Redis;
				if(!$this->ref->connect($host,$port,2))
					$this->ref=NULL;
			}
			elseif (preg_match('/^memcache=(.+)/',$dsn,$parts) &&
				extension_loaded('memcache'))
				foreach ($fw->split($parts[1]) as $server) {
					$port=11211;
					$parts=explode(':',$server,2);
					if (count($parts)>1)
						list($host,$port)=$parts;
					else
						$host=$parts[0];
					if (empty($this->ref))
						$this->ref=@memcache_connect($host,$port)?:NULL;
					else
						memcache_add_server($this->ref,$host,$port);
				}
			if (empty($this->ref) && !preg_match('/^folder\h*=/',$dsn))
				$dsn=($grep=preg_grep('/^(apc|wincache|xcache)/',
					array_map('strtolower',get_loaded_extensions())))?
						// Auto-detect
						current($grep):
						// Use filesystem as fallback
						('folder='.$fw->get('TEMP').'cache/');
			if (preg_match('/^folder\h*=\h*(.+)/',$dsn,$parts) &&
				!is_dir($parts[1]))
				mkdir($parts[1],Base::MODE,TRUE);
		}
		$this->prefix=$fw->hash($_SERVER['SERVER_NAME'].$fw->get('BASE'));
		return $this->dsn=$dsn;
	}
970916
function _connect($dsn)
    {
        if (is_string($dsn) || is_array($dsn)) {
        	if(!$this->db) {
	        	$this->db = ADONewConnection($dsn);
	    		if( $err = ADODB_Pear_error() ) {
	   	    		return PEAR::raiseError($err);
	    		}
        	}

        } else {
            return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__,
                                    41,
                                    PEAR_ERROR_RETURN,
                                    null,
                                    null
                                    );
        }

        if(!$this->db) {
        	return PEAR::raiseError(ADODB_Pear_error());
        } else {
        	return true;
        }
    }
1228575
public static function ds(array $dsn)
	{
		static $list = [];
		$dsn = SqlDataSource::dsn($dsn);
		$id = $dsn['id'];
		if ( empty( $list[$id] ) )
		{
			$list[$id] = new SqlDataSource($dsn);
		}
		return $list[$id];
	}
907134
public static function getRdnFromDn($dn)
    {
        $rdn = self::explodeDn($dn, 0)[0];
        $rdn = explode('=', $rdn, 2);

        return $rdn[0].'='.self::escapeValue($rdn[1], null, LDAP_ESCAPE_DN);
    }
804196
private static function parseDsn($dsnStr)
    {
        $info = parse_url($dsnStr);
        if (!$info) {
            return [];
        }
        $dsn = [
            'type'     => $info['scheme'],
            'username' => isset($info['user']) ? $info['user'] : '',
            'password' => isset($info['pass']) ? $info['pass'] : '',
            'hostname' => isset($info['host']) ? $info['host'] : '',
            'hostport' => isset($info['port']) ? $info['port'] : '',
            'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
            'charset'  => isset($info['fragment']) ? $info['fragment'] : 'utf8',
        ];

        if (isset($info['query'])) {
            parse_str($info['query'], $dsn['params']);
        } else {
            $dsn['params'] = [];
        }
        return $dsn;
    }
174262
protected function parseCommonDirectives($dn)
    {
        $changeType = null;
        $controls = [];

        $this->nextLine();
        while ($this->isCommonDirective()) {
            if ($this->isComment()) {
                $this->nextLine();
                continue;
            // We need to exit the loop completely in this case...
            } elseif ($this->isEndOfLdif() || $this->isStartOfEntry()) {
                break;
            } elseif ($this->isCommonDirective()) {
                list($key, $value) = $this->getKeyAndValue($this->currentLine());

                if ($key == Ldif::DIRECTIVE_CHANGETYPE && is_null($changeType)) {
                    $changeType = $value;
                } elseif ($key == Ldif::DIRECTIVE_CHANGETYPE && !is_null($changeType)) {
                    $this->throwException('The changetype directive has already been defined');
                } else {
                    $controls[] = $this->getLdapControl($value);
                }
            }
            $this->nextLine();
        }
        $changeType = $changeType ?: LdifEntryInterface::TYPE_ADD;
        $entry = $this->getLdifEntryObject($dn, $changeType);

        foreach ($controls as $control) {
            $entry->addControl($control);
        }

        return $entry;
    }
79635
public static function dsn(array $dsn)
    {
    	foreach (array('type','dbpath','login','password') as $key)
        {
        	if ( empty($dsn[$key]) )
        	{
        		throw new SqlError("db config invalid: {$key}");
        	}
        }

        if ( empty( $dsn['attr'] ) || !is_array( $dsn['attr'] ) )
    	{
    		$dsn['attr'] = [];
    	}

    	# force use ASSOC array
    	$dsn['attr'][PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;

    	if ( empty( $dsn['initcmd'] ) || !is_array( $dsn['initcmd'] ) )
    	{
    		$dsn['initcmd'] = [];
    	}
    	
    	# sql monitor
    	$dsn['monitor'] = empty( $dsn['monitor'] ) || !is_callable( $dsn['monitor'] ) ? false : $dsn['monitor'];

    	$dsn['id'] = "{$dsn['dbpath']}@{$dsn['login']}";

        return $dsn;
    }
1169658
public function getDsn()
    {
        if (!$this->config) {
            return '';
        }
        $dsn = array();
        $path = null;

        if ($this->config->getName()) {
            $path = $this->config->getName();
        }

        if ($this->config->getPath()) {
            $path = $this->config->getPath();
        }

        if ($path) {
            if (!file_exists($path)) {
                @touch($path);
            }
            $dsn[] = $path;
        } else {
            $dsn[] = ':memory:';
        }

        return $this->getPrefix().implode(';', $dsn);
    }
852467
private function _buildConnection(Dsn $dsn)
    {
        if (isset($this->_drivers[$dsn->scheme])) {
            $driver = $this->_drivers[$dsn->scheme];

            return is_string($driver)
                ? new $driver($dsn) : call_user_func($driver, $dsn);
        }

        // check built in drivers
        switch ($dsn->scheme) {
            case 'mysql':
            case 'mysqli':
                return new Mysqli\Connection($dsn);
        }

        throw new \Pheasant\Exception("Unknown driver $driver");
    }