You are here

public function Server::connect in Lightweight Directory Access Protocol (LDAP) 8.3

Connects to the LDAP server.

Return value

int LDAP_SUCCESS or the relevant error.

1 call to Server::connect()
Server::connectAndBindIfNotAlready in ldap_servers/src/Entity/Server.php
Checks if connected and connects and binds otherwise.

File

ldap_servers/src/Entity/Server.php, line 166

Class

Server
Defines the Server entity.

Namespace

Drupal\ldap_servers\Entity

Code

public function connect() {
  if (!function_exists('ldap_connect')) {
    $this->logger
      ->error('PHP LDAP extension not found, aborting.');
    return self::LDAP_NOT_SUPPORTED;
  }
  $this->connection = ldap_connect(self::get('address'), self::get('port'));
  if (!$this->connection) {
    $this->logger
      ->notice('LDAP Connect failure to @address on port @port.', [
      '@address' => self::get('address'),
      '@port' => self::get('port'),
    ]);
    return self::LDAP_CONNECT_ERROR;
  }
  ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
  ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
  ldap_set_option($this->connection, LDAP_OPT_NETWORK_TIMEOUT, self::get('timeout'));

  // Use TLS if we are configured and able to.
  if (self::get('tls')) {
    ldap_get_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $protocolVersion);
    if ($protocolVersion == -1) {
      $this->logger
        ->notice('Could not get LDAP protocol version.');
      return self::LDAP_PROTOCOL_ERROR;
    }
    if ($protocolVersion != 3) {
      $this->logger
        ->notice('Could not start TLS, only supported by LDAP v3.');
      return self::LDAP_CONNECT_ERROR;
    }
    elseif (!function_exists('ldap_start_tls')) {
      $this->logger
        ->notice('Could not start TLS. It does not seem to be supported by this PHP setup.');
      return self::LDAP_CONNECT_ERROR;
    }
    elseif (!ldap_start_tls($this->connection)) {
      $this->logger
        ->notice('Could not start TLS. (Error @errno: @error).', [
        '@errno' => ldap_errno($this->connection),
        '@error' => ldap_error($this->connection),
      ]);
      return self::LDAP_CONNECT_ERROR;
    }
  }
  return self::LDAP_SUCCESS;
}