3 * abook_ldap_server.php
5 * Copyright (c) 1999-2005 The SquirrelMail Project Team
6 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 * Address book backend for LDAP server
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)
16 * @package squirrelmail
17 * @subpackage addressbook
21 * Address book backend for LDAP server
23 * An array with the following elements must be passed to
24 * the class constructor (elements marked ? are optional)
28 * host => LDAP server hostname/IP-address
29 * base => LDAP server root (base dn). Empty string allowed.
30 * ? port => LDAP server TCP port number (default: 389)
31 * ? charset => LDAP server charset (default: utf-8)
32 * ? name => Name for LDAP server (default "LDAP: hostname")
33 * Used to tag the result data
34 * ? maxrows => Maximum # of rows in search result
35 * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
36 * Might not work for all LDAP libraries or servers.
37 * ? binddn => LDAP Bind DN.
38 * ? bindpw => LDAP Bind Password.
39 * ? protocol => LDAP Bind protocol.
43 * ? filter => Filter expression to limit ldap searches
44 * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
45 * ? listing => Controls listing of LDAP directory.
47 * NOTE. This class should not be used directly. Use the
48 * "AddressBook" class instead.
49 * @package squirrelmail
50 * @subpackage addressbook
52 class abook_ldap_server
extends addressbook_backend
{
54 * @var string backend type
56 var $btype = 'remote';
58 * @var string backend name
60 var $bname = 'ldap_server';
62 /* Parameters changed by class */
64 * @var string displayed name
66 var $sname = 'LDAP'; /* Service name */
68 * @var string LDAP server name or address or url
72 * @var integer LDAP server port
76 * @var string LDAP base DN
80 * @var string charset used for entries in LDAP server
82 var $charset = 'utf-8';
84 * @var object PHP LDAP link ID
88 * @var bool True if LDAP server is bound
92 * @var integer max rows in result
96 * @var string ldap filter
101 * @var integer timeout of LDAP operations (in seconds)
105 * @var string DN to bind to (non-anonymous bind)
106 * @since 1.5.0 and 1.4.3
110 * @var string password to bind with (non-anonymous bind)
111 * @since 1.5.0 and 1.4.3
115 * @var integer protocol used to connect to ldap server
116 * @since 1.5.0 and 1.4.3
120 * @var boolean limits scope to base dn
123 var $limit_scope = false;
125 * @var boolean controls listing of directory
128 var $listing = false;
131 * Constructor. Connects to database
132 * @param array connection options
134 function abook_ldap_server($param) {
135 if(!function_exists('ldap_connect')) {
136 $this->set_error(_("PHP install does not have LDAP support."));
139 if(is_array($param)) {
140 $this->server
= $param['host'];
141 $this->basedn
= $param['base'];
143 if(!empty($param['port']))
144 $this->port
= $param['port'];
146 if(!empty($param['charset']))
147 $this->charset
= strtolower($param['charset']);
149 if(isset($param['maxrows']))
150 $this->maxrows
= $param['maxrows'];
152 if(isset($param['timeout']))
153 $this->timeout
= $param['timeout'];
155 if(isset($param['binddn']))
156 $this->binddn
= $param['binddn'];
158 if(isset($param['bindpw']))
159 $this->bindpw
= $param['bindpw'];
161 if(isset($param['protocol']))
162 $this->protocol
= $param['protocol'];
164 if(isset($param['filter']))
165 $this->filter
= trim($param['filter']);
167 if(isset($param['limit_scope']))
168 $this->limit_scope
= $param['limit_scope'];
170 if(isset($param['listing']))
171 $this->listing
= $param['listing'];
173 if(empty($param['name'])) {
174 $this->sname
= 'LDAP: ' . $param['host'];
176 $this->sname
= $param['name'];
180 * don't open LDAP server on addressbook_init(),
181 * open ldap connection only on search. Speeds up
182 * addressbook_init() call.
184 // $this->open(true);
186 $this->set_error('Invalid argument to constructor');
192 * Open the LDAP server.
193 * @param bool $new is it a new connection
196 function open($new = false) {
199 /* Connection is already open */
200 if($this->linkid
!= false && !$new) {
204 $this->linkid
= @ldap_connect
($this->server
, $this->port
);
206 if(function_exists('ldap_error') && is_resource($this->linkid
)) {
207 return $this->set_error(ldap_error($this->linkid
));
209 return $this->set_error('ldap_connect failed');
213 if(!empty($this->protocol
)) {
214 if(!@ldap_set_option
($this->linkid
, LDAP_OPT_PROTOCOL_VERSION
, $this->protocol
)) {
215 if(function_exists('ldap_error')) {
216 return $this->set_error(ldap_error($this->linkid
));
218 return $this->set_error('ldap_set_option failed');
223 if(!empty($this->limit_scope
) && $this->limit_scope
) {
224 if(empty($this->protocol
) ||
intval($this->protocol
) < 3) {
225 return $this->set_error('limit_scope requires protocol >= 3');
227 // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
228 $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
229 if(!@ldap_set_option
($this->linkid
, LDAP_OPT_SERVER_CONTROLS
, array($ctrl))) {
230 if(function_exists('ldap_error')) {
231 return $this->set_error(ldap_error($this->linkid
));
233 return $this->set_error('limit domain scope failed');
238 if(!empty($this->binddn
)) {
239 if(!@ldap_bind
($this->linkid
, $this->binddn
, $this->bindpw
)) {
240 if(function_exists('ldap_error')) {
241 return $this->set_error(ldap_error($this->linkid
));
243 return $this->set_error('authenticated ldap_bind failed');
247 if(!@ldap_bind
($this->linkid
)) {
248 if(function_exists('ldap_error')) {
249 return $this->set_error(ldap_error($this->linkid
));
251 return $this->set_error('anonymous ldap_bind failed');
262 * Encode string to the charset used by this LDAP server
263 * @param string string that has to be encoded
264 * @return string encoded string
266 function charset_encode($str) {
267 global $default_charset;
268 if($this->charset
!= $default_charset) {
269 return charset_convert($default_charset,$str,$this->charset
,false);
276 * Decode from charset used by this LDAP server to charset used by translation
278 * Uses SquirrelMail charset_decode functions
279 * @param string string that has to be decoded
280 * @return string decoded string
282 function charset_decode($str) {
283 global $default_charset;
284 if ($this->charset
!= $default_charset) {
285 return charset_convert($this->charset
,$str,$default_charset,false);
292 * Sanitizes ldap search strings.
294 * @link http://www.faqs.org/rfcs/rfc2254.html
295 * @since 1.5.1 and 1.4.5
296 * @param string $string
297 * @return string sanitized string
299 function ldapspecialchars($string) {
300 $sanitized=array('\\' => '\5c',
306 return str_replace(array_keys($sanitized),array_values($sanitized),$string);
310 * Search LDAP server.
312 * Warning: You must make sure that ldap query is correctly formated and
313 * sanitize use of special ldap keywords.
314 * @param string $expression ldap query
315 * @return array search results (false on error)
318 function ldap_search($expression) {
319 /* Make sure connection is there */
324 // TODO: ldap_search() | ldap_list() | ldap_read() option
325 $sret = @ldap_search
($this->linkid
, $this->basedn
, $expression,
326 array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
327 0, $this->maxrows
, $this->timeout
);
329 /* Should get error from server using the ldap_error() function,
330 * but it only exist in the PHP LDAP documentation. */
332 if(function_exists('ldap_error')) {
333 return $this->set_error(ldap_error($this->linkid
));
335 return $this->set_error('ldap_search failed');
339 if(@ldap_count_entries
($this->linkid
, $sret) <= 0) {
346 $res = @ldap_get_entries
($this->linkid
, $sret);
347 for($i = 0 ; $i < $res['count'] ; $i++
) {
350 /* Extract data common for all e-mail addresses
351 * of an object. Use only the first name */
352 $nickname = $this->charset_decode($row['dn']);
353 // TODO: remove basedn from $nickname
355 $fullname = $this->charset_decode($row['cn'][0]);
357 if(!empty($row['ou'][0])) {
358 $label = $this->charset_decode($row['ou'][0]);
360 else if(!empty($row['o'][0])) {
361 $label = $this->charset_decode($row['o'][0]);
366 if(empty($row['givenname'][0])) {
369 $firstname = $this->charset_decode($row['givenname'][0]);
372 if(empty($row['sn'][0])) {
375 $surname = $this->charset_decode($row['sn'][0]);
378 /* Add one row to result for each e-mail address */
379 if(isset($row['mail']['count'])) {
380 for($j = 0 ; $j < $row['mail']['count'] ; $j++
) {
381 array_push($ret, array('nickname' => $nickname,
383 'firstname' => $firstname,
384 'lastname' => $surname,
385 'email' => $row['mail'][$j],
387 'backend' => $this->bnum
,
388 'source' => &$this->sname
));
390 // Limit number of hits
392 if(($returned_rows >= $this->maxrows
) &&
393 ($this->maxrows
> 0) ) {
394 ldap_free_result($sret);
400 } // isset($row['mail']['count'])
404 ldap_free_result($sret);
408 /* ========================== Public ======================== */
411 * Search the LDAP server
412 * @param string $expr search expression
413 * @return array search results
415 function search($expr) {
416 /* To be replaced by advanded search expression parsing */
417 if(is_array($expr)) return false;
419 // don't allow wide search when listing is disabled.
420 if ($expr=='*' && ! $this->listing
) {
422 } elseif ($expr=='*') {
423 // allow use of wildcard when listing is enabled.
424 $expression = '(cn=*)';
426 /* Convert search from user's charset to the one used in ldap */
427 $expr = $this->charset_encode($expr);
429 /* Make sure that search does not contain ldap special chars */
430 $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
432 /* Undo sanitizing of * symbol */
433 $expression = str_replace('\2a','*',$expression);
434 /* TODO: implement any single character (?) matching */
437 /* Add search filtering */
438 if ($this->filter
!='')
439 $expression = '(&' . $this->filter
. $expression . ')';
441 /* Use internal search function and return search results */
442 return $this->ldap_search($expression);
447 * List all entries present in LDAP server
449 * maxrows setting might limit list of returned entries.
450 * Careful with this -- it could get quite large for big sites.
451 * @return array all entries in ldap server
453 function list_addr() {
454 if (! $this->listing
)
457 /* set wide search expression */
458 $expression = '(cn=*)';
461 if ($this->filter
!='')
462 $expression = '(&' . $this->filter
. $expression .')';
464 /* use internal search function and return search results */
465 return $this->ldap_search($expression);