* sync matches and replacement arrays again in magicHtml()
[squirrelmail.git] / functions / abook_ldap_server.php
1 <?php
2 /**
3 * abook_ldap_server.php
4 *
5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 *
8 * Address book backend for LDAP server
9 *
10 * LDAP filtering code by Tim Bell
11 * <bhat at users.sourceforge.net> (#539534)
12 * ADS limit_scope code by Michael Brown
13 * <mcb30 at users.sourceforge.net> (#1035454)
14 * StartTLS code by John Lane
15 * <starfry at users.sourceforge.net> (#1197703)
16 *
17 * @version $Id$
18 * @package squirrelmail
19 * @subpackage addressbook
20 */
21
22 /**
23 * Address book backend for LDAP server
24 *
25 * An array with the following elements must be passed to
26 * the class constructor (elements marked ? are optional)
27 *
28 * Main settings:
29 * <pre>
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.
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.
48 * ? search_tree => Controls subtree or one level search.
49 * ? starttls => Controls use of StartTLS on LDAP connections
50 * </pre>
51 * NOTE. This class should not be used directly. Use the
52 * "AddressBook" class instead.
53 * @package squirrelmail
54 * @subpackage addressbook
55 */
56 class abook_ldap_server extends addressbook_backend {
57 /**
58 * @var string backend type
59 */
60 var $btype = 'remote';
61 /**
62 * @var string backend name
63 */
64 var $bname = 'ldap_server';
65
66 /* Parameters changed by class */
67 /**
68 * @var string displayed name
69 */
70 var $sname = 'LDAP'; /* Service name */
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;
99 /**
100 * @var string ldap filter
101 * @since 1.5.1
102 */
103 var $filter = '';
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 = '';
123 /**
124 * @var boolean limits scope to base dn
125 * @since 1.5.1
126 */
127 var $limit_scope = false;
128 /**
129 * @var boolean controls listing of directory
130 * @since 1.5.1
131 */
132 var $listing = false;
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;
145
146 /**
147 * Constructor. Connects to database
148 * @param array connection options
149 */
150 function abook_ldap_server($param) {
151 if(!function_exists('ldap_connect')) {
152 $this->set_error(_("PHP install does not have LDAP support."));
153 return;
154 }
155 if(is_array($param)) {
156 $this->server = $param['host'];
157 $this->basedn = $param['base'];
158
159 if(!empty($param['port']))
160 $this->port = $param['port'];
161
162 if(!empty($param['charset']))
163 $this->charset = strtolower($param['charset']);
164
165 if(isset($param['maxrows']))
166 $this->maxrows = $param['maxrows'];
167
168 if(isset($param['timeout']))
169 $this->timeout = $param['timeout'];
170
171 if(isset($param['binddn']))
172 $this->binddn = $param['binddn'];
173
174 if(isset($param['bindpw']))
175 $this->bindpw = $param['bindpw'];
176
177 if(isset($param['protocol']))
178 $this->protocol = (int) $param['protocol'];
179
180 if(isset($param['filter']))
181 $this->filter = trim($param['filter']);
182
183 if(isset($param['limit_scope']))
184 $this->limit_scope = (bool) $param['limit_scope'];
185
186 if(isset($param['listing']))
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'];
194
195 if(empty($param['name'])) {
196 $this->sname = 'LDAP: ' . $param['host'];
197 } else {
198 $this->sname = $param['name'];
199 }
200
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);
207 } else {
208 $this->set_error('Invalid argument to constructor');
209 }
210 }
211
212
213 /**
214 * Open the LDAP server.
215 * @param bool $new is it a new connection
216 * @return bool
217 */
218 function open($new = false) {
219 $this->error = '';
220
221 /* Connection is already open */
222 if($this->linkid != false && !$new) {
223 return true;
224 }
225
226 $this->linkid = @ldap_connect($this->server, $this->port);
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 */
233 if(!$this->linkid) {
234 return $this->set_error($this->ldap_error('ldap_connect failed'));
235 }
236
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');
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'));
264 }
265 }
266
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 );
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'));
280 }
281 }
282
283 // authenticated bind
284 if(!empty($this->binddn)) {
285 if(!@ldap_bind($this->linkid, $this->binddn, $this->bindpw)) {
286 return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
287 }
288 } else {
289 // anonymous bind
290 if(!@ldap_bind($this->linkid)) {
291 return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
292 }
293 }
294
295 $this->bound = true;
296
297 return true;
298 }
299
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 */
305 function charset_encode($str) {
306 global $default_charset;
307 if($this->charset != $default_charset) {
308 return charset_convert($default_charset,$str,$this->charset,false);
309 } else {
310 return $str;
311 }
312 }
313
314 /**
315 * Decode from charset used by this LDAP server to charset used by translation
316 *
317 * Uses SquirrelMail charset_decode functions
318 * @param string string that has to be decoded
319 * @return string decoded string
320 */
321 function charset_decode($str) {
322 global $default_charset;
323 if ($this->charset != $default_charset) {
324 return charset_convert($this->charset,$str,$default_charset,false);
325 } else {
326 return $str;
327 }
328 }
329
330 /**
331 * Sanitizes ldap search strings.
332 * See rfc2254
333 * @link http://www.faqs.org/rfcs/rfc2254.html
334 * @since 1.5.1 and 1.4.5
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 }
347
348 /**
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
356 */
357 function ldap_search($expression) {
358 /* Make sure connection is there */
359 if(!$this->open()) {
360 return false;
361 }
362
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 }
374
375 /* Return error if search failed */
376 if(!$sret) {
377 return $this->set_error($this->ldap_error('ldap_search failed'));
378 }
379
380 if(@ldap_count_entries($this->linkid, $sret) <= 0) {
381 return array();
382 }
383
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];
390
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']);
394
395 /**
396 * calculate length of basedn and remove it from nickname
397 * ignore whitespaces between RDNs
398 * Nicknames are shorter and still unique
399 */
400 $basedn_len=strlen(preg_replace('/,\s*/',',',trim($this->basedn)));
401 $nickname=substr(preg_replace('/,\s*/',',',$nickname),0,(-1 - $basedn_len));
402
403 $fullname = $this->charset_decode($row['cn'][0]);
404
405 if(!empty($row['ou'][0])) {
406 $label = $this->charset_decode($row['ou'][0]);
407 }
408 else if(!empty($row['o'][0])) {
409 $label = $this->charset_decode($row['o'][0]);
410 } else {
411 $label = '';
412 }
413
414 if(empty($row['givenname'][0])) {
415 $firstname = '';
416 } else {
417 $firstname = $this->charset_decode($row['givenname'][0]);
418 }
419
420 if(empty($row['sn'][0])) {
421 $surname = '';
422 } else {
423 $surname = $this->charset_decode($row['sn'][0]);
424 }
425
426 /* Add one row to result for each e-mail address */
427 if(isset($row['mail']['count'])) {
428 for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
429 array_push($ret, array('nickname' => $nickname,
430 'name' => $fullname,
431 'firstname' => $firstname,
432 'lastname' => $surname,
433 'email' => $row['mail'][$j],
434 'label' => $label,
435 'backend' => $this->bnum,
436 'source' => &$this->sname));
437
438 // Limit number of hits
439 $returned_rows++;
440 if(($returned_rows >= $this->maxrows) &&
441 ($this->maxrows > 0) ) {
442 ldap_free_result($sret);
443 return $ret;
444 }
445
446 } // for($j ...)
447
448 } // isset($row['mail']['count'])
449
450 }
451
452 ldap_free_result($sret);
453 return $ret;
454 }
455
456 /**
457 * Get error from LDAP resource if possible
458 *
459 * Should get error from server using the ldap_errno() and ldap_err2str() functions
460 * @param string $sError error message used when ldap error functions
461 * and connection resource are unavailable
462 * @return string error message
463 * @since 1.5.1
464 */
465 function ldap_error($sError) {
466 // it is possible that function_exists() tests are not needed
467 if(function_exists('ldap_err2str') &&
468 function_exists('ldap_errno') &&
469 is_resource($this->linkid)) {
470 return ldap_err2str(ldap_errno($this->linkid));
471 // return ldap_error($this->linkid);
472 } else {
473 return $sError;
474 }
475 }
476
477 /* ========================== Public ======================== */
478
479 /**
480 * Search the LDAP server
481 * @param string $expr search expression
482 * @return array search results
483 */
484 function search($expr) {
485 /* To be replaced by advanded search expression parsing */
486 if(is_array($expr)) return false;
487
488 // don't allow wide search when listing is disabled.
489 if ($expr=='*' && ! $this->listing) {
490 return array();
491 } elseif ($expr=='*') {
492 // allow use of wildcard when listing is enabled.
493 $expression = '(cn=*)';
494 } else {
495 /* Convert search from user's charset to the one used in ldap */
496 $expr = $this->charset_encode($expr);
497
498 /* Make sure that search does not contain ldap special chars */
499 $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
500
501 /* Undo sanitizing of * symbol */
502 $expression = str_replace('\2a','*',$expression);
503 /* TODO: implement any single character (?) matching */
504 }
505
506 /* Add search filtering */
507 if ($this->filter!='')
508 $expression = '(&' . $this->filter . $expression . ')';
509
510 /* Use internal search function and return search results */
511 return $this->ldap_search($expression);
512 }
513
514
515 /**
516 * List all entries present in LDAP server
517 *
518 * maxrows setting might limit list of returned entries.
519 * Careful with this -- it could get quite large for big sites.
520 * @return array all entries in ldap server
521 */
522 function list_addr() {
523 if (! $this->listing)
524 return array();
525
526 /* set wide search expression */
527 $expression = '(cn=*)';
528
529 /* add filtering */
530 if ($this->filter!='')
531 $expression = '(&' . $this->filter . $expression .')';
532
533 /* use internal search function and return search results */
534 return $this->ldap_search($expression);
535 }
536 }
537 ?>