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)
14 * Code for remove, add, modify, lookup by David Härdeman
15 * <david at 2gen.com> (#1495763)
17 * This backend uses LDAP person (RFC2256), organizationalPerson (RFC2256)
18 * and inetOrgPerson (RFC2798) objects and dn, description, sn, givenname,
19 * cn, mail attributes. Other attributes are ignored.
21 * @copyright © 1999-2006 The SquirrelMail Project Team
22 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
24 * @package squirrelmail
25 * @subpackage addressbook
29 * Address book backend for LDAP server
31 * An array with the following elements must be passed to
32 * the class constructor (elements marked ? are optional)
36 * host => LDAP server hostname, IP-address or any other URI compatible
37 * with used LDAP library.
38 * base => LDAP server root (base dn). Empty string allowed.
39 * ? port => LDAP server TCP port number (default: 389)
40 * ? charset => LDAP server charset (default: utf-8)
41 * ? name => Name for LDAP server (default "LDAP: hostname")
42 * Used to tag the result data
43 * ? maxrows => Maximum # of rows in search result
44 * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
45 * Might not work for all LDAP libraries or servers.
46 * ? binddn => LDAP Bind DN.
47 * ? bindpw => LDAP Bind Password.
48 * ? protocol => LDAP Bind protocol.
52 * ? filter => Filter expression to limit ldap searches
53 * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
54 * ? listing => Controls listing of LDAP directory.
55 * ? writeable => Controls write access to address book
56 * ? search_tree => Controls subtree or one level search.
57 * ? starttls => Controls use of StartTLS on LDAP connections
59 * NOTE. This class should not be used directly. Use addressbook_init()
61 * @package squirrelmail
62 * @subpackage addressbook
64 class abook_ldap_server
extends addressbook_backend
{
66 * @var string backend type
68 var $btype = 'remote';
70 * @var string backend name
72 var $bname = 'ldap_server';
74 /* Parameters changed by class */
76 * @var string displayed name
78 var $sname = 'LDAP'; /* Service name */
80 * @var string LDAP server name or address or url
84 * @var integer LDAP server port
88 * @var string LDAP base DN
92 * @var string charset used for entries in LDAP server
94 var $charset = 'utf-8';
96 * @var object PHP LDAP link ID
100 * @var bool True if LDAP server is bound
104 * @var integer max rows in result
108 * @var string ldap filter
113 * @var integer timeout of LDAP operations (in seconds)
117 * @var string DN to bind to (non-anonymous bind)
118 * @since 1.5.0 and 1.4.3
122 * @var string password to bind with (non-anonymous bind)
123 * @since 1.5.0 and 1.4.3
127 * @var integer protocol used to connect to ldap server
128 * @since 1.5.0 and 1.4.3
132 * @var boolean limits scope to base dn
135 var $limit_scope = false;
137 * @var boolean controls listing of directory
140 var $listing = false;
142 * @var boolean true if removing/adding/modifying entries is allowed
145 var $writeable = false;
147 * @var boolean controls ldap search type.
148 * only first level entries are displayed if set to false
151 var $search_tree = true;
153 * @var boolean controls use of StartTLS on ldap
154 * connections. Requires php 4.2+ and protocol >= 3
157 var $starttls = false;
160 * Constructor. Connects to database
161 * @param array connection options
163 function abook_ldap_server($param) {
164 if(!function_exists('ldap_connect')) {
165 $this->set_error(_("PHP install does not have LDAP support."));
168 if(is_array($param)) {
169 $this->server
= $param['host'];
170 // remove whitespace from basedn
171 $this->basedn
= preg_replace('/,\s*/',',',trim($param['base']));
173 if(!empty($param['port']))
174 $this->port
= $param['port'];
176 if(!empty($param['charset']))
177 $this->charset
= strtolower($param['charset']);
179 if(isset($param['maxrows']))
180 $this->maxrows
= $param['maxrows'];
182 if(isset($param['timeout']))
183 $this->timeout
= $param['timeout'];
185 if(isset($param['binddn']))
186 $this->binddn
= $param['binddn'];
188 if(isset($param['bindpw']))
189 $this->bindpw
= $param['bindpw'];
191 if(isset($param['protocol']))
192 $this->protocol
= (int) $param['protocol'];
194 if(isset($param['filter']))
195 $this->filter
= trim($param['filter']);
197 if(isset($param['limit_scope']))
198 $this->limit_scope
= (bool) $param['limit_scope'];
200 if(isset($param['listing']))
201 $this->listing
= (bool) $param['listing'];
203 if(isset($param['writeable'])) {
204 $this->writeable
= (bool) $param['writeable'];
205 // switch backend type to local, if it is writable
206 if($this->writeable
) $this->btype
= 'local';
209 if(isset($param['search_tree']))
210 $this->search_tree
= (bool) $param['search_tree'];
212 if(isset($param['starttls']))
213 $this->starttls
= (bool) $param['starttls'];
215 if(empty($param['name'])) {
216 $this->sname
= 'LDAP: ' . $param['host'];
218 $this->sname
= $param['name'];
222 * don't open LDAP server on addressbook_init(),
223 * open ldap connection only on search. Speeds up
224 * addressbook_init() call.
226 // $this->open(true);
228 $this->set_error('Invalid argument to constructor');
234 * Open the LDAP server.
235 * @param bool $new is it a new connection
238 function open($new = false) {
241 /* Connection is already open */
242 if($this->linkid
!= false && !$new) {
246 $this->linkid
= @ldap_connect
($this->server
, $this->port
);
248 * check if connection was successful
249 * It does not work with OpenLDAP 2.x libraries. Connect error will be
250 * displayed only on ldap command that tries to make connection
251 * (ldap_start_tls or ldap_bind).
254 return $this->set_error($this->ldap_error('ldap_connect failed'));
257 if(!empty($this->protocol
)) {
258 // make sure that ldap_set_option() is available before using it
259 if(! function_exists('ldap_set_option') ||
260 !@ldap_set_option
($this->linkid
, LDAP_OPT_PROTOCOL_VERSION
, $this->protocol
)) {
261 return $this->set_error('unable to set ldap protocol number');
266 * http://www.php.net/ldap-start-tls
267 * Check if v3 or newer protocol is used,
268 * check if ldap_start_tls function is available.
269 * Silently ignore setting, if these requirements are not satisfied.
270 * Break with error message if somebody tries to start TLS on
271 * ldaps or socket connection.
273 if($this->starttls
&&
274 !empty($this->protocol
) && $this->protocol
>= 3 &&
275 function_exists('ldap_start_tls') ) {
276 // make sure that $this->server is not ldaps:// or ldapi:// URL.
277 if (preg_match("/^ldap[si]:\/\/.+/i",$this->server
)) {
278 return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
282 if (! @ldap_start_tls
($this->linkid
)) {
283 // set error if call fails
284 return $this->set_error($this->ldap_error('ldap_start_tls failed'));
288 if(!empty($this->limit_scope
) && $this->limit_scope
) {
289 if(empty($this->protocol
) ||
intval($this->protocol
) < 3) {
290 return $this->set_error('limit_scope requires protocol >= 3');
292 // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
293 $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
295 * Option is set only during connection.
296 * It does not cause immediate errors with OpenLDAP 2.x libraries.
298 if(! function_exists('ldap_set_option') ||
299 !@ldap_set_option
($this->linkid
, LDAP_OPT_SERVER_CONTROLS
, array($ctrl))) {
300 return $this->set_error($this->ldap_error('limit domain scope failed'));
304 // authenticated bind
305 if(!empty($this->binddn
)) {
306 if(!@ldap_bind
($this->linkid
, $this->binddn
, $this->bindpw
)) {
307 return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
311 if(!@ldap_bind
($this->linkid
)) {
312 return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
322 * Encode string to the charset used by this LDAP server
323 * @param string string that has to be encoded
324 * @return string encoded string
326 function charset_encode($str) {
327 global $default_charset;
328 if($this->charset
!= $default_charset) {
329 return charset_convert($default_charset,$str,$this->charset
,false);
336 * Decode from charset used by this LDAP server to charset used by translation
338 * Uses SquirrelMail charset_decode functions
339 * @param string string that has to be decoded
340 * @return string decoded string
342 function charset_decode($str) {
343 global $default_charset;
344 if ($this->charset
!= $default_charset) {
345 return charset_convert($this->charset
,$str,$default_charset,false);
352 * Sanitizes ldap search strings.
354 * @link http://www.faqs.org/rfcs/rfc2254.html
355 * @since 1.5.1 and 1.4.5
356 * @param string $string
357 * @return string sanitized string
359 function ldapspecialchars($string) {
360 $sanitized=array('\\' => '\5c',
366 return str_replace(array_keys($sanitized),array_values($sanitized),$string);
370 * Prepares user input for use in a ldap query.
372 * Function converts input string to character set used in LDAP server
373 * (charset_encode() method) and sanitizes it (ldapspecialchars()).
375 * @param string $string string to encode
376 * @return string ldap encoded string
379 function quotevalue($string) {
380 $sanitized = $this->charset_encode($string);
381 return $this->ldapspecialchars($sanitized);
385 * Search LDAP server.
387 * Warning: You must make sure that ldap query is correctly formated and
388 * sanitize use of special ldap keywords.
389 * @param string $expression ldap query
390 * @param boolean $singleentry (since 1.5.2) whether we are looking for a
391 * single entry. Boolean true forces LDAP_SCOPE_BASE search.
392 * @return array search results (false on error)
395 function ldap_search($expression, $singleentry = false) {
396 /* Make sure connection is there */
401 $attributes = array('dn', 'description', 'sn', 'givenname', 'cn', 'mail');
404 // ldap_read - search for one single entry
405 $sret = @ldap_read
($this->linkid
, $expression, "objectClass=*",
406 $attributes, 0, $this->maxrows
, $this->timeout
);
407 } elseif ($this->search_tree
) {
408 // ldap_search - search subtree
409 $sret = @ldap_search
($this->linkid
, $this->basedn
, $expression,
410 $attributes, 0, $this->maxrows
, $this->timeout
);
412 // ldap_list - search one level
413 $sret = @ldap_list
($this->linkid
, $this->basedn
, $expression,
414 $attributes, 0, $this->maxrows
, $this->timeout
);
417 /* Return error if search failed */
419 // Check for LDAP_NO_SUCH_OBJECT (0x20 or 32) error
420 if (ldap_errno($this->linkid
)==32) {
423 return $this->set_error($this->ldap_error('ldap_search failed'));
427 if(@ldap_count_entries
($this->linkid
, $sret) <= 0) {
434 $res = @ldap_get_entries
($this->linkid
, $sret);
435 for($i = 0 ; $i < $res['count'] ; $i++
) {
438 /* Extract data common for all e-mail addresses
439 * of an object. Use only the first name */
440 $nickname = $this->charset_decode($row['dn']);
443 * remove trailing basedn
444 * remove whitespaces between RDNs
445 * remove leading "cn="
446 * which gives nicknames which are shorter while still unique
448 $nickname = preg_replace('/,\s*/',',', trim($nickname));
449 $offset = strlen($nickname) - strlen($this->basedn
);
451 if($offset > 0 && substr($nickname, $offset) == $this->basedn
) {
452 $nickname = substr($nickname, 0, $offset);
453 if(substr($nickname, -1) == ",")
454 $nickname = substr($nickname, 0, -1);
456 if(strncasecmp($nickname, "cn=", 3) == 0)
457 $nickname=substr($nickname, 3);
459 if(empty($row['description'][0])) {
462 $label = $this->charset_decode($row['description'][0]);
465 if(empty($row['givenname'][0])) {
468 $firstname = $this->charset_decode($row['givenname'][0]);
471 if(empty($row['sn'][0])) {
474 // remove whitespace in order to handle sn set to empty string
475 $surname = trim($this->charset_decode($row['sn'][0]));
478 // FIXME: Write generic function to handle name order
479 $fullname = trim($firstname . " " . $surname);
481 /* Add one row to result for each e-mail address */
482 if(isset($row['mail']['count'])) {
483 for($j = 0 ; $j < $row['mail']['count'] ; $j++
) {
484 array_push($ret, array('nickname' => $nickname,
486 'firstname' => $firstname,
487 'lastname' => $surname,
488 'email' => $row['mail'][$j],
490 'backend' => $this->bnum
,
491 'source' => &$this->sname
));
493 // Limit number of hits
495 if(($returned_rows >= $this->maxrows
) &&
496 ($this->maxrows
> 0) ) {
497 ldap_free_result($sret);
503 } // isset($row['mail']['count'])
507 ldap_free_result($sret);
512 * Add an entry to LDAP server.
514 * Warning: You must make sure that the arguments are correctly formated and
515 * sanitize use of special ldap keywords.
516 * @param string $dn the dn of the entry to be added
517 * @param array $data the values of the entry to be added
518 * @return boolean result (false on error)
521 function ldap_add($dn, $data) {
522 /* Make sure connection is there */
527 if(!@ldap_add
($this->linkid
, $dn, $data)) {
528 $this->set_error(_("Write to address book failed"));
536 * Remove an entry from LDAP server.
538 * Warning: You must make sure that the argument is correctly formated and
539 * sanitize use of special ldap keywords.
540 * @param string $dn the dn of the entry to remove
541 * @return boolean result (false on error)
544 function ldap_remove($dn) {
545 /* Make sure connection is there */
550 if(!@ldap_delete
($this->linkid
, $dn)) {
551 $this->set_error(_("Removing entry from address book failed"));
559 * Rename an entry on LDAP server.
561 * Warning: You must make sure that the arguments are correctly formated and
562 * sanitize use of special ldap keywords.
563 * @param string $sourcedn the dn of the entry to be renamed
564 * @param string $targetdn the dn which $sourcedn should be renamed to
565 * @param string $parent the dn of the parent entry
566 * @return boolean result (false on error)
569 function ldap_rename($sourcedn, $targetdn, $parent) {
570 /* Make sure connection is there */
575 /* Make sure that the protocol version supports rename */
576 if($this->protocol
< 3) {
577 $this->set_error(_("LDAP rename is not supported by used protocol version"));
581 * Function is available only in OpenLDAP 2.x.x or Netscape Directory
582 * SDK x.x, and was added in PHP 4.0.5
583 * @todo maybe we can use copy + delete instead of ldap_rename()
585 if(!function_exists('ldap_rename')) {
586 $this->set_error(_("LDAP rename is not supported by used LDAP library. You can't change nickname"));
591 if(!@ldap_rename
($this->linkid
, $sourcedn, $targetdn, $parent, true)) {
592 $this->set_error(_("LDAP rename failed"));
600 * Modify the values of an entry on LDAP server.
602 * Warning: You must make sure that the arguments are correctly formated and
603 * sanitize use of special ldap keywords.
604 * @param string $dn the dn of the entry to be modified
605 * @param array $data the new values of the entry
606 * @param array $deleted_attribs attributes that should be deleted.
607 * @return bool result (false on error)
610 function ldap_modify($dn, $data, $deleted_attribs) {
611 /* Make sure connection is there */
616 if(!@ldap_modify
($this->linkid
, $dn, $data)) {
617 $this->set_error(_("Write to address book failed"));
621 if (!@ldap_mod_del
($this->linkid
, $dn, $deleted_attribs)) {
622 $this->set_error(_("Unable to remove some field values"));
630 * Get error from LDAP resource if possible
632 * Should get error from server using the ldap_errno() and ldap_err2str() functions
633 * @param string $sError error message used when ldap error functions
634 * and connection resource are unavailable
635 * @return string error message
638 function ldap_error($sError) {
639 // it is possible that function_exists() tests are not needed
640 if(function_exists('ldap_err2str') &&
641 function_exists('ldap_errno') &&
642 is_resource($this->linkid
)) {
643 return ldap_err2str(ldap_errno($this->linkid
));
644 // return ldap_error($this->linkid);
650 /* ========================== Public ======================== */
653 * Search the LDAP server
654 * @param string $expr search expression
655 * @return array search results
657 function search($expr) {
658 /* To be replaced by advanded search expression parsing */
659 if(is_array($expr)) return false;
661 // don't allow wide search when listing is disabled.
662 if ($expr=='*' && ! $this->listing
) {
664 } elseif ($expr=='*') {
665 // allow use of wildcard when listing is enabled.
666 $expression = '(cn=*)';
668 /* Convert search from user's charset to the one used in ldap and sanitize */
669 $expr = $this->quotevalue($expr);
671 /* Search for same string in cn, main and sn */
672 $expression = '(|(cn=*'.$expr.'*)(mail=*'.$expr.'*)(sn=*'.$expr.'*))';
674 /* Undo sanitizing of * symbol */
675 $expression = str_replace('\2a','*',$expression);
678 /* Add search filtering */
679 if ($this->filter
!='')
680 $expression = '(&' . $this->filter
. $expression . ')';
682 /* Use internal search function and return search results */
683 return $this->ldap_search($expression);
688 * @param string $alias alias
689 * @return array search results
692 function lookup($alias) {
693 /* Generate the dn and try to retrieve that single entry */
694 $cn = $this->quotevalue($alias);
695 $dn = 'cn=' . $cn . ',' . $this->basedn
;
698 $result = $this->ldap_search($dn, true);
699 if (!is_array($result) ||
count($result) < 1)
706 * List all entries present in LDAP server
708 * maxrows setting might limit list of returned entries.
709 * Careful with this -- it could get quite large for big sites.
710 * @return array all entries in ldap server
712 function list_addr() {
713 if (! $this->listing
)
716 /* set wide search expression */
717 $expression = '(cn=*)';
720 if ($this->filter
!='')
721 $expression = '(&' . $this->filter
. $expression .')';
723 /* use internal search function and return search results */
724 return $this->ldap_search($expression);
729 * @param array $userdata new data
733 function add($userdata) {
734 if(!$this->writeable
) {
735 return $this->set_error(_("Address book is read-only"));
738 /* Convert search from user's charset to the one used in ldap and sanitize */
739 $cn = $this->quotevalue($userdata['nickname']);
740 $dn = 'cn=' . $cn . ',' . trim($this->basedn
);
742 /* See if user exists already */
743 $user = $this->ldap_search($dn, true);
744 if (!is_array($user)) {
746 } elseif (count($user) > 0) {
747 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
755 $data['mail'] = $this->quotevalue($userdata['email']);
756 $data["objectclass"][0] = "top";
757 $data["objectclass"][1] = "person";
758 $data["objectclass"][2] = "organizationalPerson";
759 $data["objectclass"][3] = "inetOrgPerson";
760 /* sn is required in person object */
761 if(!empty($userdata['lastname'])) {
762 $data['sn'] = $this->quotevalue($userdata['lastname']);
766 /* optional fields */
767 if(!empty($userdata['firstname']))
768 $data['givenName'] = $this->quotevalue($userdata['firstname']);
769 if(!empty($userdata['label'])) {
770 $data['description'] = $this->quotevalue($userdata['label']);
772 return $this->ldap_add($dn, $data);
777 * @param array $aliases array of entries that have to be removed.
781 function remove($aliases) {
782 if(!$this->writeable
) {
783 return $this->set_error(_("Address book is read-only"));
786 foreach ($aliases as $alias) {
787 /* Convert nickname from user's charset and derive cn/dn */
788 $cn = $this->quotevalue($alias);
789 $dn = 'cn=' . $cn . ',' . $this->basedn
;
791 if (!$this->ldap_remove($dn))
800 * @param string $alias modified alias
801 * @param array $userdata new data
805 function modify($alias, $userdata) {
806 if(!$this->writeable
) {
807 return $this->set_error(_("Address book is read-only"));
810 /* Convert search from user's charset to the one used in ldap and sanitize */
811 $sourcecn = $this->quotevalue($alias);
812 $sourcedn = 'cn=' . $sourcecn . ',' . trim($this->basedn
);
813 $targetcn = $this->quotevalue($userdata['nickname']);
814 $targetdn = 'cn=' . $targetcn . ',' . trim($this->basedn
);
816 /* Check that the dn to modify exists */
817 $sourceuser = $this->lookup($alias);
818 if (!is_array($sourceuser) ||
count($sourceuser) < 1)
821 /* Check if dn is going to change */
822 if ($alias != $userdata['nickname']) {
824 /* Check that the target dn doesn't exist */
825 $targetuser = $this->lookup($userdata['nickname']);
826 if (is_array($targetuser) && count($targetuser) > 0)
827 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
829 /* Rename from the source dn to target dn */
830 if (!$this->ldap_rename($sourcedn, 'cn=' . $targetcn, $this->basedn
))
831 return $this->set_error(sprintf(_("Unable to rename user \"%s\" to \"%s\""), $alias, $userdata['nickname']));
836 $deleted_attribs = array();
839 $data['cn'] = $this->quotevalue($targetcn);
840 $data['mail'] = $this->quotevalue($userdata['email']);
841 $data["objectclass"][0] = "top";
842 $data["objectclass"][1] = "person";
843 $data["objectclass"][2] = "organizationalPerson";
844 $data["objectclass"][3] = "inetOrgPerson";
846 if(!empty($userdata['firstname'])) {
847 $data['givenName'] = $this->quotevalue($userdata['firstname']);
848 } elseif (!empty($sourceuser['firstname'])) {
849 $deleted_attribs['givenName'] = $this->quotevalue($sourceuser['firstname']);
852 if(!empty($userdata['lastname'])) {
853 $data['sn'] = $this->quotevalue($userdata['lastname']);
855 // sn is required attribute in LDAP person object.
856 // SquirrelMail requires givenName or Surname
860 if(!empty($userdata['label'])) {
861 $data['description'] = $this->quotevalue($userdata['label']);
862 } elseif (!empty($sourceuser['label'])) {
863 $deleted_attribs['description'] = $this->quotevalue($sourceuser['label']);
866 return $this->ldap_modify($targetdn, $data, $deleted_attribs);