4 * abook_ldap_server.php
6 * Address book backend for LDAP server
8 * LDAP filtering code by Tim Bell
9 * <bhat at users.sourceforge.net> (#539534)
10 * ADS limit_scope code by Michael Brown
11 * <mcb30 at users.sourceforge.net> (#1035454)
12 * StartTLS code by John Lane
13 * <starfry at users.sourceforge.net> (#1197703)
15 * @copyright © 1999-2005 The SquirrelMail Project Team
16 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
18 * @package squirrelmail
19 * @subpackage addressbook
23 * Address book backend for LDAP server
25 * An array with the following elements must be passed to
26 * the class constructor (elements marked ? are optional)
30 * host => LDAP server hostname/IP-address
31 * base => LDAP server root (base dn). Empty string allowed.
32 * ? port => LDAP server TCP port number (default: 389)
33 * ? charset => LDAP server charset (default: utf-8)
34 * ? name => Name for LDAP server (default "LDAP: hostname")
35 * Used to tag the result data
36 * ? maxrows => Maximum # of rows in search result
37 * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
38 * Might not work for all LDAP libraries or servers.
39 * ? binddn => LDAP Bind DN.
40 * ? bindpw => LDAP Bind Password.
41 * ? protocol => LDAP Bind protocol.
45 * ? filter => Filter expression to limit ldap searches
46 * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
47 * ? listing => Controls listing of LDAP directory.
48 * ? search_tree => Controls subtree or one level search.
49 * ? starttls => Controls use of StartTLS on LDAP connections
51 * NOTE. This class should not be used directly. Use the
52 * "AddressBook" class instead.
53 * @package squirrelmail
54 * @subpackage addressbook
56 class abook_ldap_server
extends addressbook_backend
{
58 * @var string backend type
60 var $btype = 'remote';
62 * @var string backend name
64 var $bname = 'ldap_server';
66 /* Parameters changed by class */
68 * @var string displayed name
70 var $sname = 'LDAP'; /* Service name */
72 * @var string LDAP server name or address or url
76 * @var integer LDAP server port
80 * @var string LDAP base DN
84 * @var string charset used for entries in LDAP server
86 var $charset = 'utf-8';
88 * @var object PHP LDAP link ID
92 * @var bool True if LDAP server is bound
96 * @var integer max rows in result
100 * @var string ldap filter
105 * @var integer timeout of LDAP operations (in seconds)
109 * @var string DN to bind to (non-anonymous bind)
110 * @since 1.5.0 and 1.4.3
114 * @var string password to bind with (non-anonymous bind)
115 * @since 1.5.0 and 1.4.3
119 * @var integer protocol used to connect to ldap server
120 * @since 1.5.0 and 1.4.3
124 * @var boolean limits scope to base dn
127 var $limit_scope = false;
129 * @var boolean controls listing of directory
132 var $listing = false;
134 * @var boolean controls ldap search type.
135 * only first level entries are displayed if set to false
138 var $search_tree = true;
140 * @var boolean controls use of StartTLS on ldap
141 * connections. Requires php 4.2+ and protocol >= 3
144 var $starttls = false;
147 * Constructor. Connects to database
148 * @param array connection options
150 function abook_ldap_server($param) {
151 if(!function_exists('ldap_connect')) {
152 $this->set_error(_("PHP install does not have LDAP support."));
155 if(is_array($param)) {
156 $this->server
= $param['host'];
157 $this->basedn
= $param['base'];
159 if(!empty($param['port']))
160 $this->port
= $param['port'];
162 if(!empty($param['charset']))
163 $this->charset
= strtolower($param['charset']);
165 if(isset($param['maxrows']))
166 $this->maxrows
= $param['maxrows'];
168 if(isset($param['timeout']))
169 $this->timeout
= $param['timeout'];
171 if(isset($param['binddn']))
172 $this->binddn
= $param['binddn'];
174 if(isset($param['bindpw']))
175 $this->bindpw
= $param['bindpw'];
177 if(isset($param['protocol']))
178 $this->protocol
= (int) $param['protocol'];
180 if(isset($param['filter']))
181 $this->filter
= trim($param['filter']);
183 if(isset($param['limit_scope']))
184 $this->limit_scope
= (bool) $param['limit_scope'];
186 if(isset($param['listing']))
187 $this->listing
= (bool) $param['listing'];
189 if(isset($param['search_tree']))
190 $this->search_tree
= (bool) $param['search_tree'];
192 if(isset($param['starttls']))
193 $this->starttls
= (bool) $param['starttls'];
195 if(empty($param['name'])) {
196 $this->sname
= 'LDAP: ' . $param['host'];
198 $this->sname
= $param['name'];
202 * don't open LDAP server on addressbook_init(),
203 * open ldap connection only on search. Speeds up
204 * addressbook_init() call.
206 // $this->open(true);
208 $this->set_error('Invalid argument to constructor');
214 * Open the LDAP server.
215 * @param bool $new is it a new connection
218 function open($new = false) {
221 /* Connection is already open */
222 if($this->linkid
!= false && !$new) {
226 $this->linkid
= @ldap_connect
($this->server
, $this->port
);
228 * check if connection was successful
229 * It does not work with OpenLDAP 2.x libraries. Connect error will be
230 * displayed only on ldap command that tries to make connection
231 * (ldap_start_tls or ldap_bind).
234 return $this->set_error($this->ldap_error('ldap_connect failed'));
237 if(!empty($this->protocol
)) {
238 // make sure that ldap_set_option() is available before using it
239 if(! function_exists('ldap_set_option') ||
240 !@ldap_set_option
($this->linkid
, LDAP_OPT_PROTOCOL_VERSION
, $this->protocol
)) {
241 return $this->set_error('unable to set ldap protocol number');
246 * http://www.php.net/ldap-start-tls
247 * Check if v3 or newer protocol is used,
248 * check if ldap_start_tls function is available.
249 * Silently ignore setting, if these requirements are not satisfied.
250 * Break with error message if somebody tries to start TLS on
251 * ldaps or socket connection.
253 if($this->starttls
&&
254 !empty($this->protocol
) && $this->protocol
>= 3 &&
255 function_exists('ldap_start_tls') ) {
256 // make sure that $this->server is not ldaps:// or ldapi:// URL.
257 if (preg_match("/^ldap[si]:\/\/.+/i",$this->server
)) {
258 return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
262 if (! @ldap_start_tls
($this->linkid
)) {
263 // set error if call fails
264 return $this->set_error($this->ldap_error('ldap_start_tls failed'));
268 if(!empty($this->limit_scope
) && $this->limit_scope
) {
269 if(empty($this->protocol
) ||
intval($this->protocol
) < 3) {
270 return $this->set_error('limit_scope requires protocol >= 3');
272 // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
273 $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
275 * Option is set only during connection.
276 * It does not cause immediate errors with OpenLDAP 2.x libraries.
278 if(! function_exists('ldap_set_option') ||
279 !@ldap_set_option
($this->linkid
, LDAP_OPT_SERVER_CONTROLS
, array($ctrl))) {
280 return $this->set_error($this->ldap_error('limit domain scope failed'));
284 // authenticated bind
285 if(!empty($this->binddn
)) {
286 if(!@ldap_bind
($this->linkid
, $this->binddn
, $this->bindpw
)) {
287 return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
291 if(!@ldap_bind
($this->linkid
)) {
292 return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
302 * Encode string to the charset used by this LDAP server
303 * @param string string that has to be encoded
304 * @return string encoded string
306 function charset_encode($str) {
307 global $default_charset;
308 if($this->charset
!= $default_charset) {
309 return charset_convert($default_charset,$str,$this->charset
,false);
316 * Decode from charset used by this LDAP server to charset used by translation
318 * Uses SquirrelMail charset_decode functions
319 * @param string string that has to be decoded
320 * @return string decoded string
322 function charset_decode($str) {
323 global $default_charset;
324 if ($this->charset
!= $default_charset) {
325 return charset_convert($this->charset
,$str,$default_charset,false);
332 * Sanitizes ldap search strings.
334 * @link http://www.faqs.org/rfcs/rfc2254.html
335 * @since 1.5.1 and 1.4.5
336 * @param string $string
337 * @return string sanitized string
339 function ldapspecialchars($string) {
340 $sanitized=array('\\' => '\5c',
346 return str_replace(array_keys($sanitized),array_values($sanitized),$string);
350 * Search LDAP server.
352 * Warning: You must make sure that ldap query is correctly formated and
353 * sanitize use of special ldap keywords.
354 * @param string $expression ldap query
355 * @return array search results (false on error)
358 function ldap_search($expression) {
359 /* Make sure connection is there */
364 if ($this->search_tree
) {
365 // ldap_search - search subtree
366 $sret = @ldap_search
($this->linkid
, $this->basedn
, $expression,
367 array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
368 0, $this->maxrows
, $this->timeout
);
370 // ldap_list - search one level
371 $sret = @ldap_list
($this->linkid
, $this->basedn
, $expression,
372 array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
373 0, $this->maxrows
, $this->timeout
);
376 /* Return error if search failed */
378 return $this->set_error($this->ldap_error('ldap_search failed'));
381 if(@ldap_count_entries
($this->linkid
, $sret) <= 0) {
388 $res = @ldap_get_entries
($this->linkid
, $sret);
389 for($i = 0 ; $i < $res['count'] ; $i++
) {
392 /* Extract data common for all e-mail addresses
393 * of an object. Use only the first name */
394 $nickname = $this->charset_decode($row['dn']);
397 * calculate length of basedn and remove it from nickname
398 * ignore whitespaces between RDNs
399 * Nicknames are shorter and still unique
401 $basedn_len=strlen(preg_replace('/,\s*/',',',trim($this->basedn
)));
402 $nickname=substr(preg_replace('/,\s*/',',',$nickname),0,(-1 - $basedn_len));
404 $fullname = $this->charset_decode($row['cn'][0]);
406 if(!empty($row['ou'][0])) {
407 $label = $this->charset_decode($row['ou'][0]);
409 else if(!empty($row['o'][0])) {
410 $label = $this->charset_decode($row['o'][0]);
415 if(empty($row['givenname'][0])) {
418 $firstname = $this->charset_decode($row['givenname'][0]);
421 if(empty($row['sn'][0])) {
424 $surname = $this->charset_decode($row['sn'][0]);
427 /* Add one row to result for each e-mail address */
428 if(isset($row['mail']['count'])) {
429 for($j = 0 ; $j < $row['mail']['count'] ; $j++
) {
430 array_push($ret, array('nickname' => $nickname,
432 'firstname' => $firstname,
433 'lastname' => $surname,
434 'email' => $row['mail'][$j],
436 'backend' => $this->bnum
,
437 'source' => &$this->sname
));
439 // Limit number of hits
441 if(($returned_rows >= $this->maxrows
) &&
442 ($this->maxrows
> 0) ) {
443 ldap_free_result($sret);
449 } // isset($row['mail']['count'])
453 ldap_free_result($sret);
458 * Get error from LDAP resource if possible
460 * Should get error from server using the ldap_errno() and ldap_err2str() functions
461 * @param string $sError error message used when ldap error functions
462 * and connection resource are unavailable
463 * @return string error message
466 function ldap_error($sError) {
467 // it is possible that function_exists() tests are not needed
468 if(function_exists('ldap_err2str') &&
469 function_exists('ldap_errno') &&
470 is_resource($this->linkid
)) {
471 return ldap_err2str(ldap_errno($this->linkid
));
472 // return ldap_error($this->linkid);
478 /* ========================== Public ======================== */
481 * Search the LDAP server
482 * @param string $expr search expression
483 * @return array search results
485 function search($expr) {
486 /* To be replaced by advanded search expression parsing */
487 if(is_array($expr)) return false;
489 // don't allow wide search when listing is disabled.
490 if ($expr=='*' && ! $this->listing
) {
492 } elseif ($expr=='*') {
493 // allow use of wildcard when listing is enabled.
494 $expression = '(cn=*)';
496 /* Convert search from user's charset to the one used in ldap */
497 $expr = $this->charset_encode($expr);
499 /* Make sure that search does not contain ldap special chars */
500 $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
502 /* Undo sanitizing of * symbol */
503 $expression = str_replace('\2a','*',$expression);
504 /* TODO: implement any single character (?) matching */
507 /* Add search filtering */
508 if ($this->filter
!='')
509 $expression = '(&' . $this->filter
. $expression . ')';
511 /* Use internal search function and return search results */
512 return $this->ldap_search($expression);
517 * List all entries present in LDAP server
519 * maxrows setting might limit list of returned entries.
520 * Careful with this -- it could get quite large for big sites.
521 * @return array all entries in ldap server
523 function list_addr() {
524 if (! $this->listing
)
527 /* set wide search expression */
528 $expression = '(cn=*)';
531 if ($this->filter
!='')
532 $expression = '(&' . $this->filter
. $expression .')';
534 /* use internal search function and return search results */
535 return $this->ldap_search($expression);