]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Ldap/LdapConfig.php
Added more complexity in an attempt to make ldap host failover fit
[bookstack] / app / Auth / Access / Ldap / LdapConfig.php
1 <?php
2
3 namespace BookStack\Auth\Access\Ldap;
4
5 class LdapConfig
6 {
7     /**
8      * App provided config array.
9      * @var array
10      */
11     protected array $config;
12
13     public function __construct(array $config)
14     {
15         $this->config = $config;
16     }
17
18     /**
19      * Get a value from the config.
20      */
21     public function get(string $key)
22     {
23         return $this->config[$key] ?? null;
24     }
25
26     /**
27      * Parse the potentially multi-value LDAP server host string and return an array of host/port detail pairs.
28      * Multiple hosts are separated with a semicolon, for example: 'ldap.example.com:8069;ldaps://ldap.example.com'
29      *
30      * @return array<array{host: string, port: int}>
31      */
32     public function getServers(): array
33     {
34         $serverStringList = explode(';', $this->get('server'));
35
36         return array_map(fn ($serverStr) => $this->parseSingleServerString($serverStr), $serverStringList);
37     }
38
39     /**
40      * Parse an LDAP server string and return the host and port for a connection.
41      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
42      *
43      * @return array{host: string, port: int}
44      */
45     protected function parseSingleServerString(string $serverString): array
46     {
47         $serverNameParts = explode(':', trim($serverString));
48
49         // If we have a protocol just return the full string since PHP will ignore a separate port.
50         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
51             return ['host' => $serverString, 'port' => 389];
52         }
53
54         // Otherwise, extract the port out
55         $hostName = $serverNameParts[0];
56         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
57
58         return ['host' => $hostName, 'port' => $ldapPort];
59     }
60 }