moving to documentation module
[squirrelmail.git] / functions / abook_ldap_server.php
CommitLineData
5100704d 1<?php
35586184 2/**
3 * abook_ldap_server.php
4 *
6c84ba1e 5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
35586184 6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
981681d5 8 * Address book backend for LDAP server
9 *
ae4d36f7 10 * LDAP filtering code by Tim Bell
11 * <bhat at users.sourceforge.net> (#539534)
f8a1ed5a 12 * ADS limit_scope code by Michael Brown
ae4d36f7 13 * <mcb30 at users.sourceforge.net> (#1035454)
593370a4 14 * StartTLS code by John Lane
15 * <starfry at users.sourceforge.net> (#1197703)
ae4d36f7 16 *
981681d5 17 * @version $Id$
18 * @package squirrelmail
19 * @subpackage addressbook
20 */
21
22/**
35586184 23 * Address book backend for LDAP server
24 *
25 * An array with the following elements must be passed to
3d1fa376 26 * the class constructor (elements marked ? are optional)
27 *
28 * Main settings:
981681d5 29 * <pre>
35586184 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.
30e9932c 39 * ? binddn => LDAP Bind DN.
40 * ? bindpw => LDAP Bind Password.
41 * ? protocol => LDAP Bind protocol.
3d1fa376 42 * </pre>
43 * Advanced settings:
44 * <pre>
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.
593370a4 48 * ? search_tree => Controls subtree or one level search.
49 * ? starttls => Controls use of StartTLS on LDAP connections
981681d5 50 * </pre>
35586184 51 * NOTE. This class should not be used directly. Use the
52 * "AddressBook" class instead.
d6c32258 53 * @package squirrelmail
a9d318b0 54 * @subpackage addressbook
35586184 55 */
35586184 56class abook_ldap_server extends addressbook_backend {
981681d5 57 /**
58 * @var string backend type
59 */
06b4facd 60 var $btype = 'remote';
981681d5 61 /**
62 * @var string backend name
63 */
06b4facd 64 var $bname = 'ldap_server';
65
66 /* Parameters changed by class */
981681d5 67 /**
68 * @var string displayed name
69 */
06b4facd 70 var $sname = 'LDAP'; /* Service name */
981681d5 71 /**
72 * @var string LDAP server name or address or url
73 */
74 var $server = '';
75 /**
76 * @var integer LDAP server port
77 */
78 var $port = 389;
79 /**
80 * @var string LDAP base DN
81 */
82 var $basedn = '';
83 /**
84 * @var string charset used for entries in LDAP server
85 */
86 var $charset = 'utf-8';
87 /**
88 * @var object PHP LDAP link ID
89 */
90 var $linkid = false;
91 /**
92 * @var bool True if LDAP server is bound
93 */
94 var $bound = false;
95 /**
96 * @var integer max rows in result
97 */
98 var $maxrows = 250;
ae4d36f7 99 /**
100 * @var string ldap filter
101 * @since 1.5.1
102 */
103 var $filter = '';
981681d5 104 /**
105 * @var integer timeout of LDAP operations (in seconds)
106 */
107 var $timeout = 30;
108 /**
109 * @var string DN to bind to (non-anonymous bind)
110 * @since 1.5.0 and 1.4.3
111 */
112 var $binddn = '';
113 /**
114 * @var string password to bind with (non-anonymous bind)
115 * @since 1.5.0 and 1.4.3
116 */
117 var $bindpw = '';
118 /**
119 * @var integer protocol used to connect to ldap server
120 * @since 1.5.0 and 1.4.3
121 */
122 var $protocol = '';
ae4d36f7 123 /**
124 * @var boolean limits scope to base dn
125 * @since 1.5.1
126 */
127 var $limit_scope = false;
3d1fa376 128 /**
129 * @var boolean controls listing of directory
130 * @since 1.5.1
131 */
132 var $listing = false;
593370a4 133 /**
134 * @var boolean controls ldap search type.
135 * only first level entries are displayed if set to false
136 * @since 1.5.1
137 */
138 var $search_tree = true;
139 /**
140 * @var boolean controls use of StartTLS on ldap
141 * connections. Requires php 4.2+ and protocol >= 3
142 * @since 1.5.1
143 */
144 var $starttls = false;
981681d5 145
146 /**
147 * Constructor. Connects to database
148 * @param array connection options
149 */
06b4facd 150 function abook_ldap_server($param) {
151 if(!function_exists('ldap_connect')) {
ae4d36f7 152 $this->set_error(_("PHP install does not have LDAP support."));
06b4facd 153 return;
154 }
155 if(is_array($param)) {
156 $this->server = $param['host'];
157 $this->basedn = $param['base'];
ae4d36f7 158
159 if(!empty($param['port']))
06b4facd 160 $this->port = $param['port'];
ae4d36f7 161
162 if(!empty($param['charset']))
06b4facd 163 $this->charset = strtolower($param['charset']);
ae4d36f7 164
165 if(isset($param['maxrows']))
06b4facd 166 $this->maxrows = $param['maxrows'];
ae4d36f7 167
168 if(isset($param['timeout']))
06b4facd 169 $this->timeout = $param['timeout'];
ae4d36f7 170
171 if(isset($param['binddn']))
30e9932c 172 $this->binddn = $param['binddn'];
ae4d36f7 173
174 if(isset($param['bindpw']))
30e9932c 175 $this->bindpw = $param['bindpw'];
ae4d36f7 176
177 if(isset($param['protocol']))
593370a4 178 $this->protocol = (int) $param['protocol'];
ae4d36f7 179
180 if(isset($param['filter']))
181 $this->filter = trim($param['filter']);
182
183 if(isset($param['limit_scope']))
593370a4 184 $this->limit_scope = (bool) $param['limit_scope'];
ae4d36f7 185
3d1fa376 186 if(isset($param['listing']))
593370a4 187 $this->listing = (bool) $param['listing'];
188
189 if(isset($param['search_tree']))
190 $this->search_tree = (bool) $param['search_tree'];
191
192 if(isset($param['starttls']))
193 $this->starttls = (bool) $param['starttls'];
3d1fa376 194
06b4facd 195 if(empty($param['name'])) {
196 $this->sname = 'LDAP: ' . $param['host'];
ae4d36f7 197 } else {
06b4facd 198 $this->sname = $param['name'];
199 }
62f7daa5 200
ae4d36f7 201 /*
202 * don't open LDAP server on addressbook_init(),
203 * open ldap connection only on search. Speeds up
204 * addressbook_init() call.
205 */
206 // $this->open(true);
06b4facd 207 } else {
208 $this->set_error('Invalid argument to constructor');
209 }
210 }
211
212
981681d5 213 /**
214 * Open the LDAP server.
215 * @param bool $new is it a new connection
216 * @return bool
217 */
06b4facd 218 function open($new = false) {
219 $this->error = '';
62f7daa5 220
06b4facd 221 /* Connection is already open */
222 if($this->linkid != false && !$new) {
223 return true;
224 }
62f7daa5 225
06b4facd 226 $this->linkid = @ldap_connect($this->server, $this->port);
593370a4 227 /**
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).
232 */
06b4facd 233 if(!$this->linkid) {
593370a4 234 return $this->set_error($this->ldap_error('ldap_connect failed'));
06b4facd 235 }
62f7daa5 236
981681d5 237 if(!empty($this->protocol)) {
593370a4 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');
242 }
243 }
244
245 /**
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 requirements are not satisfied
250 */
251 if($this->starttls &&
252 !empty($this->protocol) && $this->protocol >= 3 &&
253 function_exists('ldap_start_tls') ) {
254 // make sure that $this->host is not ldaps:// URL.
255 if (preg_match("/^ldaps:\/\/.+/i",$this->server)) {
256 return $this->set_error("you can't enable starttls on ldaps connection.");
257 }
258 // TODO: starttls and ldapi:// tests are needed
259
260 // try starting tls
261 if (! @ldap_start_tls($this->linkid)) {
262 // set error if call fails
263 return $this->set_error($this->ldap_error('ldap_start_tls failed'));
981681d5 264 }
265 }
30e9932c 266
ae4d36f7 267 if(!empty($this->limit_scope) && $this->limit_scope) {
268 if(empty($this->protocol) || intval($this->protocol) < 3) {
269 return $this->set_error('limit_scope requires protocol >= 3');
270 }
271 // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
272 $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
593370a4 273 /*
274 * Option is set only during connection.
275 * It does not cause immediate errors with OpenLDAP 2.x libraries.
276 */
277 if(! function_exists('ldap_set_option') ||
278 !@ldap_set_option($this->linkid, LDAP_OPT_SERVER_CONTROLS, array($ctrl))) {
279 return $this->set_error($this->ldap_error('limit domain scope failed'));
ae4d36f7 280 }
281 }
282
593370a4 283 // authenticated bind
30e9932c 284 if(!empty($this->binddn)) {
285 if(!@ldap_bind($this->linkid, $this->binddn, $this->bindpw)) {
593370a4 286 return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
287 }
30e9932c 288 } else {
593370a4 289 // anonymous bind
981681d5 290 if(!@ldap_bind($this->linkid)) {
593370a4 291 return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
981681d5 292 }
06b4facd 293 }
30e9932c 294
06b4facd 295 $this->bound = true;
62f7daa5 296
06b4facd 297 return true;
298 }
299
981681d5 300 /**
301 * Encode string to the charset used by this LDAP server
302 * @param string string that has to be encoded
303 * @return string encoded string
304 */
06b4facd 305 function charset_encode($str) {
b64dd897 306 global $default_charset;
307 if($this->charset != $default_charset) {
308 return charset_convert($default_charset,$str,$this->charset,false);
06b4facd 309 } else {
310 return $str;
311 }
312 }
313
981681d5 314 /**
b64dd897 315 * Decode from charset used by this LDAP server to charset used by translation
981681d5 316 *
598294a7 317 * Uses SquirrelMail charset_decode functions
981681d5 318 * @param string string that has to be decoded
319 * @return string decoded string
320 */
06b4facd 321 function charset_decode($str) {
981681d5 322 global $default_charset;
323 if ($this->charset != $default_charset) {
b64dd897 324 return charset_convert($this->charset,$str,$default_charset,false);
06b4facd 325 } else {
326 return $str;
327 }
328 }
329
d58ed98f 330 /**
331 * Sanitizes ldap search strings.
332 * See rfc2254
333 * @link http://www.faqs.org/rfcs/rfc2254.html
ae4d36f7 334 * @since 1.5.1 and 1.4.5
d58ed98f 335 * @param string $string
336 * @return string sanitized string
337 */
338 function ldapspecialchars($string) {
339 $sanitized=array('\\' => '\5c',
340 '*' => '\2a',
341 '(' => '\28',
342 ')' => '\29',
343 "\x00" => '\00');
344
345 return str_replace(array_keys($sanitized),array_values($sanitized),$string);
346 }
62f7daa5 347
981681d5 348 /**
3d1fa376 349 * Search LDAP server.
350 *
351 * Warning: You must make sure that ldap query is correctly formated and
352 * sanitize use of special ldap keywords.
353 * @param string $expression ldap query
354 * @return array search results (false on error)
355 * @since 1.5.1
981681d5 356 */
3d1fa376 357 function ldap_search($expression) {
06b4facd 358 /* Make sure connection is there */
359 if(!$this->open()) {
360 return false;
361 }
62f7daa5 362
593370a4 363 if ($this->search_tree) {
364 // ldap_search - search subtree
365 $sret = @ldap_search($this->linkid, $this->basedn, $expression,
366 array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
367 0, $this->maxrows, $this->timeout);
368 } else {
369 // ldap_list - search one level
370 $sret = @ldap_list($this->linkid, $this->basedn, $expression,
371 array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
372 0, $this->maxrows, $this->timeout);
373 }
62f7daa5 374
593370a4 375 /* Return error if search failed */
06b4facd 376 if(!$sret) {
593370a4 377 return $this->set_error($this->ldap_error('ldap_search failed'));
06b4facd 378 }
62f7daa5 379
06b4facd 380 if(@ldap_count_entries($this->linkid, $sret) <= 0) {
381 return array();
382 }
62f7daa5 383
06b4facd 384 /* Get results */
385 $ret = array();
386 $returned_rows = 0;
387 $res = @ldap_get_entries($this->linkid, $sret);
388 for($i = 0 ; $i < $res['count'] ; $i++) {
389 $row = $res[$i];
62f7daa5 390
06b4facd 391 /* Extract data common for all e-mail addresses
392 * of an object. Use only the first name */
393 $nickname = $this->charset_decode($row['dn']);
3d1fa376 394 // TODO: remove basedn from $nickname
395
06b4facd 396 $fullname = $this->charset_decode($row['cn'][0]);
62f7daa5 397
06b4facd 398 if(!empty($row['ou'][0])) {
399 $label = $this->charset_decode($row['ou'][0]);
400 }
401 else if(!empty($row['o'][0])) {
402 $label = $this->charset_decode($row['o'][0]);
403 } else {
404 $label = '';
405 }
62f7daa5 406
06b4facd 407 if(empty($row['givenname'][0])) {
408 $firstname = '';
409 } else {
410 $firstname = $this->charset_decode($row['givenname'][0]);
411 }
62f7daa5 412
06b4facd 413 if(empty($row['sn'][0])) {
414 $surname = '';
415 } else {
416 $surname = $this->charset_decode($row['sn'][0]);
417 }
62f7daa5 418
06b4facd 419 /* Add one row to result for each e-mail address */
420 if(isset($row['mail']['count'])) {
421 for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
422 array_push($ret, array('nickname' => $nickname,
423 'name' => $fullname,
424 'firstname' => $firstname,
425 'lastname' => $surname,
426 'email' => $row['mail'][$j],
427 'label' => $label,
06b4facd 428 'backend' => $this->bnum,
429 'source' => &$this->sname));
62f7daa5 430
06b4facd 431 // Limit number of hits
432 $returned_rows++;
62f7daa5 433 if(($returned_rows >= $this->maxrows) &&
06b4facd 434 ($this->maxrows > 0) ) {
435 ldap_free_result($sret);
436 return $ret;
437 }
438
439 } // for($j ...)
440
441 } // isset($row['mail']['count'])
62f7daa5 442
06b4facd 443 }
62f7daa5 444
06b4facd 445 ldap_free_result($sret);
446 return $ret;
3d1fa376 447 }
448
593370a4 449 /**
450 * Get error from LDAP resource if possible
451 *
452 * Should get error from server using the ldap_errno() and ldap_err2str() functions
453 * @param string $sError error message used when ldap error functions
454 * and connection resource are unavailable
455 * @return string error message
456 * @since 1.5.1
457 */
458 function ldap_error($sError) {
459 // it is possible that function_exists() tests are not needed
460 if(function_exists('ldap_err2str') &&
461 function_exists('ldap_errno') &&
462 is_resource($this->linkid)) {
463 return ldap_err2str(ldap_errno($this->linkid));
464 // return ldap_error($this->linkid);
465 } else {
466 return $sError;
467 }
468 }
469
3d1fa376 470 /* ========================== Public ======================== */
471
472 /**
473 * Search the LDAP server
474 * @param string $expr search expression
475 * @return array search results
476 */
477 function search($expr) {
478 /* To be replaced by advanded search expression parsing */
479 if(is_array($expr)) return false;
480
481 // don't allow wide search when listing is disabled.
327e2d96 482 if ($expr=='*' && ! $this->listing) {
483 return array();
484 } elseif ($expr=='*') {
485 // allow use of wildcard when listing is enabled.
486 $expression = '(cn=*)';
487 } else {
488 /* Convert search from user's charset to the one used in ldap */
489 $expr = $this->charset_encode($expr);
3d1fa376 490
327e2d96 491 /* Make sure that search does not contain ldap special chars */
492 $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
3d1fa376 493
327e2d96 494 /* Undo sanitizing of * symbol */
495 $expression = str_replace('\2a','*',$expression);
496 /* TODO: implement any single character (?) matching */
497 }
3d1fa376 498
499 /* Add search filtering */
500 if ($this->filter!='')
501 $expression = '(&' . $this->filter . $expression . ')';
502
503 /* Use internal search function and return search results */
504 return $this->ldap_search($expression);
505 }
06b4facd 506
507
981681d5 508 /**
509 * List all entries present in LDAP server
06b4facd 510 *
3d1fa376 511 * maxrows setting might limit list of returned entries.
981681d5 512 * Careful with this -- it could get quite large for big sites.
513 * @return array all entries in ldap server
514 */
515 function list_addr() {
3d1fa376 516 if (! $this->listing)
517 return array();
518
519 /* set wide search expression */
520 $expression = '(cn=*)';
521
522 /* add filtering */
523 if ($this->filter!='')
524 $expression = '(&' . $this->filter . $expression .')';
525
526 /* use internal search function and return search results */
527 return $this->ldap_search($expression);
981681d5 528 }
06b4facd 529}
62f7daa5 530?>