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-2007 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 search results.
53 * You can use this to *limit* the result set, based on specific
54 * requirements. The filter must be enclosed in parentheses, e.g.:
55 * '(objectclass=mailRecipient)'
56 * or '(&(objectclass=mailRecipient)(obectclass=myCustomClass))'
57 * The default value is empty.
59 * ? search_expression => Custom expression to expand ldap searches.
60 * This can help *expand* the result set, because of hits in more
61 * LDAP attributes. It must be a printf()-style string with either
62 * one placeholder '%s', or, if you want to repeat the expression
63 * many times, '%1$s'. The default value is:
64 * '(|(cn=*%1$s*)(mail=*%1$s*)(sn=*%1$s*))'
65 * that is, the search expression is search in the fields cn (common
66 * name), sn (surname) and mail.
68 * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
69 * ? listing => Controls listing of LDAP directory.
70 * ? writeable => Controls write access to address book
71 * ? search_tree => Controls subtree or one level search.
72 * ? starttls => Controls use of StartTLS on LDAP connections
74 * NOTE. This class should not be used directly. Use addressbook_init()
76 * @package squirrelmail
77 * @subpackage addressbook
79 class abook_ldap_server
extends addressbook_backend
{
81 * @var string backend type
83 var $btype = 'remote';
85 * @var string backend name
87 var $bname = 'ldap_server';
89 /* Parameters changed by class */
91 * @var string displayed name
93 var $sname = 'LDAP'; /* Service name */
95 * @var string LDAP server name or address or url
99 * @var integer LDAP server port
103 * @var string LDAP base DN
107 * @var string charset used for entries in LDAP server
109 var $charset = 'utf-8';
111 * @var object PHP LDAP link ID
115 * @var bool True if LDAP server is bound
119 * @var integer max rows in result
123 * @var string ldap filter
128 * @var string printf()-style ldap search expression.
129 * The default is to search for same string in cn, mail and sn.
132 var $search_expression = '(|(cn=*%1$s*)(mail=*%1$s*)(sn=*%1$s*))';
134 * @var integer timeout of LDAP operations (in seconds)
138 * @var string DN to bind to (non-anonymous bind)
139 * @since 1.5.0 and 1.4.3
143 * @var string password to bind with (non-anonymous bind)
144 * @since 1.5.0 and 1.4.3
148 * @var integer protocol used to connect to ldap server
149 * @since 1.5.0 and 1.4.3
153 * @var boolean limits scope to base dn
156 var $limit_scope = false;
158 * @var boolean controls listing of directory
161 var $listing = false;
163 * @var boolean true if removing/adding/modifying entries is allowed
166 var $writeable = false;
168 * @var boolean controls ldap search type.
169 * only first level entries are displayed if set to false
172 var $search_tree = true;
174 * @var boolean controls use of StartTLS on ldap
175 * connections. Requires php 4.2+ and protocol >= 3
178 var $starttls = false;
181 * Constructor. Connects to database
182 * @param array connection options
184 function abook_ldap_server($param) {
185 if(!function_exists('ldap_connect')) {
186 $this->set_error(_("PHP install does not have LDAP support."));
189 if(is_array($param)) {
190 $this->server
= $param['host'];
191 // remove whitespace from basedn
192 $this->basedn
= preg_replace('/,\s*/',',',trim($param['base']));
194 if(!empty($param['port']))
195 $this->port
= $param['port'];
197 if(!empty($param['charset']))
198 $this->charset
= strtolower($param['charset']);
200 if(isset($param['maxrows']))
201 $this->maxrows
= $param['maxrows'];
203 if(isset($param['timeout']))
204 $this->timeout
= $param['timeout'];
206 if(isset($param['binddn']))
207 $this->binddn
= $param['binddn'];
209 if(isset($param['bindpw']))
210 $this->bindpw
= $param['bindpw'];
212 if(isset($param['protocol']))
213 $this->protocol
= (int) $param['protocol'];
215 if(isset($param['filter']))
216 $this->filter
= trim($param['filter']);
218 if(isset($param['search_expression']) &&
219 (strstr($param['search_expression'], '%s') ||
strstr($param['search_expression'], '%1$s'))) {
220 $this->search_expression
= trim($param['search_expression']);
223 if(isset($param['limit_scope']))
224 $this->limit_scope
= (bool) $param['limit_scope'];
226 if(isset($param['listing']))
227 $this->listing
= (bool) $param['listing'];
229 if(isset($param['writeable'])) {
230 $this->writeable
= (bool) $param['writeable'];
231 // switch backend type to local, if it is writable
232 if($this->writeable
) $this->btype
= 'local';
235 if(isset($param['search_tree']))
236 $this->search_tree
= (bool) $param['search_tree'];
238 if(isset($param['starttls']))
239 $this->starttls
= (bool) $param['starttls'];
241 if(empty($param['name'])) {
242 $this->sname
= 'LDAP: ' . $param['host'];
244 $this->sname
= $param['name'];
248 * don't open LDAP server on addressbook_init(),
249 * open ldap connection only on search. Speeds up
250 * addressbook_init() call.
252 // $this->open(true);
254 $this->set_error('Invalid argument to constructor');
260 * Open the LDAP server.
261 * @param bool $new is it a new connection
264 function open($new = false) {
267 /* Connection is already open */
268 if($this->linkid
!= false && !$new) {
272 $this->linkid
= @ldap_connect
($this->server
, $this->port
);
274 * check if connection was successful
275 * It does not work with OpenLDAP 2.x libraries. Connect error will be
276 * displayed only on ldap command that tries to make connection
277 * (ldap_start_tls or ldap_bind).
280 return $this->set_error($this->ldap_error('ldap_connect failed'));
283 if(!empty($this->protocol
)) {
284 // make sure that ldap_set_option() is available before using it
285 if(! function_exists('ldap_set_option') ||
286 !@ldap_set_option
($this->linkid
, LDAP_OPT_PROTOCOL_VERSION
, $this->protocol
)) {
287 return $this->set_error('unable to set ldap protocol number');
292 * http://www.php.net/ldap-start-tls
293 * Check if v3 or newer protocol is used,
294 * check if ldap_start_tls function is available.
295 * Silently ignore setting, if these requirements are not satisfied.
296 * Break with error message if somebody tries to start TLS on
297 * ldaps or socket connection.
299 if($this->starttls
&&
300 !empty($this->protocol
) && $this->protocol
>= 3 &&
301 function_exists('ldap_start_tls') ) {
302 // make sure that $this->server is not ldaps:// or ldapi:// URL.
303 if (preg_match("/^ldap[si]:\/\/.+/i",$this->server
)) {
304 return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
308 if (! @ldap_start_tls
($this->linkid
)) {
309 // set error if call fails
310 return $this->set_error($this->ldap_error('ldap_start_tls failed'));
314 if(!empty($this->limit_scope
) && $this->limit_scope
) {
315 if(empty($this->protocol
) ||
intval($this->protocol
) < 3) {
316 return $this->set_error('limit_scope requires protocol >= 3');
318 // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
319 $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
321 * Option is set only during connection.
322 * It does not cause immediate errors with OpenLDAP 2.x libraries.
324 if(! function_exists('ldap_set_option') ||
325 !@ldap_set_option
($this->linkid
, LDAP_OPT_SERVER_CONTROLS
, array($ctrl))) {
326 return $this->set_error($this->ldap_error('limit domain scope failed'));
330 // authenticated bind
331 if(!empty($this->binddn
)) {
332 if(!@ldap_bind
($this->linkid
, $this->binddn
, $this->bindpw
)) {
333 return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
337 if(!@ldap_bind
($this->linkid
)) {
338 return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
348 * Encode string to the charset used by this LDAP server
349 * @param string string that has to be encoded
350 * @return string encoded string
352 function charset_encode($str) {
353 global $default_charset;
354 if($this->charset
!= $default_charset) {
355 return charset_convert($default_charset,$str,$this->charset
,false);
362 * Decode from charset used by this LDAP server to charset used by translation
364 * Uses SquirrelMail charset_decode functions
365 * @param string string that has to be decoded
366 * @return string decoded string
368 function charset_decode($str) {
369 global $default_charset;
370 if ($this->charset
!= $default_charset) {
371 return charset_convert($this->charset
,$str,$default_charset,false);
378 * Sanitizes ldap search strings.
380 * @link http://www.faqs.org/rfcs/rfc2254.html
381 * @since 1.5.1 and 1.4.5
382 * @param string $string
383 * @return string sanitized string
385 function ldapspecialchars($string) {
386 $sanitized=array('\\' => '\5c',
392 return str_replace(array_keys($sanitized),array_values($sanitized),$string);
396 * Prepares user input for use in a ldap query.
398 * Function converts input string to character set used in LDAP server
399 * (charset_encode() method) and sanitizes it (ldapspecialchars()).
401 * @param string $string string to encode
402 * @return string ldap encoded string
405 function quotevalue($string) {
406 $sanitized = $this->charset_encode($string);
407 return $this->ldapspecialchars($sanitized);
411 * Search LDAP server.
413 * Warning: You must make sure that ldap query is correctly formated and
414 * sanitize use of special ldap keywords.
415 * @param string $expression ldap query
416 * @param boolean $singleentry (since 1.5.2) whether we are looking for a
417 * single entry. Boolean true forces LDAP_SCOPE_BASE search.
418 * @return array search results (false on error)
421 function ldap_search($expression, $singleentry = false) {
422 /* Make sure connection is there */
427 $attributes = array('dn', 'description', 'sn', 'givenname', 'cn', 'mail');
430 // ldap_read - search for one single entry
431 $sret = @ldap_read
($this->linkid
, $expression, "objectClass=*",
432 $attributes, 0, $this->maxrows
, $this->timeout
);
433 } elseif ($this->search_tree
) {
434 // ldap_search - search subtree
435 $sret = @ldap_search
($this->linkid
, $this->basedn
, $expression,
436 $attributes, 0, $this->maxrows
, $this->timeout
);
438 // ldap_list - search one level
439 $sret = @ldap_list
($this->linkid
, $this->basedn
, $expression,
440 $attributes, 0, $this->maxrows
, $this->timeout
);
443 /* Return error if search failed */
445 // Check for LDAP_NO_SUCH_OBJECT (0x20 or 32) error
446 if (ldap_errno($this->linkid
)==32) {
449 return $this->set_error($this->ldap_error('ldap_search failed'));
453 if(@ldap_count_entries
($this->linkid
, $sret) <= 0) {
460 $res = @ldap_get_entries
($this->linkid
, $sret);
461 for($i = 0 ; $i < $res['count'] ; $i++
) {
464 /* Extract data common for all e-mail addresses
465 * of an object. Use only the first name */
466 $nickname = $this->charset_decode($row['dn']);
469 * remove trailing basedn
470 * remove whitespaces between RDNs
471 * remove leading "cn="
472 * which gives nicknames which are shorter while still unique
474 $nickname = preg_replace('/,\s*/',',', trim($nickname));
475 $offset = strlen($nickname) - strlen($this->basedn
);
477 if($offset > 0 && substr($nickname, $offset) == $this->basedn
) {
478 $nickname = substr($nickname, 0, $offset);
479 if(substr($nickname, -1) == ",")
480 $nickname = substr($nickname, 0, -1);
482 if(strncasecmp($nickname, "cn=", 3) == 0)
483 $nickname=substr($nickname, 3);
485 if(empty($row['description'][0])) {
488 $label = $this->charset_decode($row['description'][0]);
491 if(empty($row['givenname'][0])) {
494 $firstname = $this->charset_decode($row['givenname'][0]);
497 if(empty($row['sn'][0])) {
500 // remove whitespace in order to handle sn set to empty string
501 $surname = trim($this->charset_decode($row['sn'][0]));
504 $fullname = $this->fullname($firstname,$surname);
506 /* Add one row to result for each e-mail address */
507 if(isset($row['mail']['count'])) {
508 for($j = 0 ; $j < $row['mail']['count'] ; $j++
) {
509 array_push($ret, array('nickname' => $nickname,
511 'firstname' => $firstname,
512 'lastname' => $surname,
513 'email' => $row['mail'][$j],
515 'backend' => $this->bnum
,
516 'source' => &$this->sname
));
518 // Limit number of hits
520 if(($returned_rows >= $this->maxrows
) &&
521 ($this->maxrows
> 0) ) {
522 ldap_free_result($sret);
528 } // isset($row['mail']['count'])
532 ldap_free_result($sret);
537 * Add an entry to LDAP server.
539 * Warning: You must make sure that the arguments are correctly formated and
540 * sanitize use of special ldap keywords.
541 * @param string $dn the dn of the entry to be added
542 * @param array $data the values of the entry to be added
543 * @return boolean result (false on error)
546 function ldap_add($dn, $data) {
547 /* Make sure connection is there */
552 if(!@ldap_add
($this->linkid
, $dn, $data)) {
553 $this->set_error(_("Write to address book failed"));
561 * Remove an entry from LDAP server.
563 * Warning: You must make sure that the argument is correctly formated and
564 * sanitize use of special ldap keywords.
565 * @param string $dn the dn of the entry to remove
566 * @return boolean result (false on error)
569 function ldap_remove($dn) {
570 /* Make sure connection is there */
575 if(!@ldap_delete
($this->linkid
, $dn)) {
576 $this->set_error(_("Removing entry from address book failed"));
584 * Rename an entry on LDAP server.
586 * Warning: You must make sure that the arguments are correctly formated and
587 * sanitize use of special ldap keywords.
588 * @param string $sourcedn the dn of the entry to be renamed
589 * @param string $targetdn the dn which $sourcedn should be renamed to
590 * @param string $parent the dn of the parent entry
591 * @return boolean result (false on error)
594 function ldap_rename($sourcedn, $targetdn, $parent) {
595 /* Make sure connection is there */
600 /* Make sure that the protocol version supports rename */
601 if($this->protocol
< 3) {
602 $this->set_error(_("LDAP rename is not supported by used protocol version"));
606 * Function is available only in OpenLDAP 2.x.x or Netscape Directory
607 * SDK x.x, and was added in PHP 4.0.5
608 * @todo maybe we can use copy + delete instead of ldap_rename()
610 if(!function_exists('ldap_rename')) {
611 $this->set_error(_("LDAP rename is not supported by used LDAP library. You can't change nickname"));
616 if(!@ldap_rename
($this->linkid
, $sourcedn, $targetdn, $parent, true)) {
617 $this->set_error(_("LDAP rename failed"));
625 * Modify the values of an entry on LDAP server.
627 * Warning: You must make sure that the arguments are correctly formated and
628 * sanitize use of special ldap keywords.
629 * @param string $dn the dn of the entry to be modified
630 * @param array $data the new values of the entry
631 * @param array $deleted_attribs attributes that should be deleted.
632 * @return bool result (false on error)
635 function ldap_modify($dn, $data, $deleted_attribs) {
636 /* Make sure connection is there */
641 if(!@ldap_modify
($this->linkid
, $dn, $data)) {
642 $this->set_error(_("Write to address book failed"));
646 if (!@ldap_mod_del
($this->linkid
, $dn, $deleted_attribs)) {
647 $this->set_error(_("Unable to remove some field values"));
655 * Get error from LDAP resource if possible
657 * Should get error from server using the ldap_errno() and ldap_err2str() functions
658 * @param string $sError error message used when ldap error functions
659 * and connection resource are unavailable
660 * @return string error message
663 function ldap_error($sError) {
664 // it is possible that function_exists() tests are not needed
665 if(function_exists('ldap_err2str') &&
666 function_exists('ldap_errno') &&
667 is_resource($this->linkid
)) {
668 return ldap_err2str(ldap_errno($this->linkid
));
669 // return ldap_error($this->linkid);
675 /* ========================== Public ======================== */
678 * Search the LDAP server
679 * @param string $expr search expression
680 * @return array search results
682 function search($expr) {
683 /* To be replaced by advanded search expression parsing */
684 if(is_array($expr)) return false;
686 // don't allow wide search when listing is disabled.
687 if ($expr=='*' && ! $this->listing
) {
689 } elseif ($expr=='*') {
690 // allow use of wildcard when listing is enabled.
691 $expression = '(cn=*)';
693 /* Convert search from user's charset to the one used in ldap and sanitize */
694 $expr = $this->quotevalue($expr);
696 /* If search expr contains %s or %1$s, replace them with escaped values,
697 * so that a wrong printf()-style string is not created by mistake.
698 * (Probably overkill but who knows...) */
699 $expr = str_replace('%s', '\\25s', $expr);
700 $expr = str_replace('%1$s', '\\251$s', $expr);
702 /* Substitute %s or %1$s in printf()-formatted search_expresison with
703 * the value that the user searches for. */
704 $expression = sprintf($this->search_expression
, $expr);
706 /* Undo sanitizing of * symbol */
707 $expression = str_replace('\2a','*',$expression);
709 /* Replace '**', '***' etc. with '*' in case it occurs in final
710 * search expression */
711 while(strstr($expression, '**')) {
712 $expression = str_replace('**', '*', $expression);
716 /* Add search filtering */
717 if ($this->filter
!='')
718 $expression = '(&' . $this->filter
. $expression . ')';
720 /* Use internal search function and return search results */
721 return $this->ldap_search($expression);
726 * @param string $alias alias
727 * @return array search results
730 function lookup($alias) {
731 /* Generate the dn and try to retrieve that single entry */
732 $cn = $this->quotevalue($alias);
733 $dn = 'cn=' . $cn . ',' . $this->basedn
;
736 $result = $this->ldap_search($dn, true);
737 if (!is_array($result) ||
count($result) < 1)
744 * List all entries present in LDAP server
746 * maxrows setting might limit list of returned entries.
747 * Careful with this -- it could get quite large for big sites.
748 * @return array all entries in ldap server
750 function list_addr() {
751 if (! $this->listing
)
754 /* set wide search expression */
755 $expression = '(cn=*)';
758 if ($this->filter
!='')
759 $expression = '(&' . $this->filter
. $expression .')';
761 /* use internal search function and return search results */
762 return $this->ldap_search($expression);
767 * @param array $userdata new data
771 function add($userdata) {
772 if(!$this->writeable
) {
773 return $this->set_error(_("Address book is read-only"));
776 /* Convert search from user's charset to the one used in ldap and sanitize */
777 $cn = $this->quotevalue($userdata['nickname']);
778 $dn = 'cn=' . $cn . ',' . trim($this->basedn
);
780 /* See if user exists already */
781 $user = $this->ldap_search($dn, true);
782 if (!is_array($user)) {
784 } elseif (count($user) > 0) {
785 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
793 $data['mail'] = $this->quotevalue($userdata['email']);
794 $data["objectclass"][0] = "top";
795 $data["objectclass"][1] = "person";
796 $data["objectclass"][2] = "organizationalPerson";
797 $data["objectclass"][3] = "inetOrgPerson";
798 /* sn is required in person object */
799 if(!empty($userdata['lastname'])) {
800 $data['sn'] = $this->quotevalue($userdata['lastname']);
804 /* optional fields */
805 if(!empty($userdata['firstname']))
806 $data['givenName'] = $this->quotevalue($userdata['firstname']);
807 if(!empty($userdata['label'])) {
808 $data['description'] = $this->quotevalue($userdata['label']);
810 return $this->ldap_add($dn, $data);
815 * @param array $aliases array of entries that have to be removed.
819 function remove($aliases) {
820 if(!$this->writeable
) {
821 return $this->set_error(_("Address book is read-only"));
824 foreach ($aliases as $alias) {
825 /* Convert nickname from user's charset and derive cn/dn */
826 $cn = $this->quotevalue($alias);
827 $dn = 'cn=' . $cn . ',' . $this->basedn
;
829 if (!$this->ldap_remove($dn))
838 * @param string $alias modified alias
839 * @param array $userdata new data
843 function modify($alias, $userdata) {
844 if(!$this->writeable
) {
845 return $this->set_error(_("Address book is read-only"));
848 /* Convert search from user's charset to the one used in ldap and sanitize */
849 $sourcecn = $this->quotevalue($alias);
850 $sourcedn = 'cn=' . $sourcecn . ',' . trim($this->basedn
);
851 $targetcn = $this->quotevalue($userdata['nickname']);
852 $targetdn = 'cn=' . $targetcn . ',' . trim($this->basedn
);
854 /* Check that the dn to modify exists */
855 $sourceuser = $this->lookup($alias);
856 if (!is_array($sourceuser) ||
count($sourceuser) < 1)
859 /* Check if dn is going to change */
860 if ($alias != $userdata['nickname']) {
862 /* Check that the target dn doesn't exist */
863 $targetuser = $this->lookup($userdata['nickname']);
864 if (is_array($targetuser) && count($targetuser) > 0)
865 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
867 /* Rename from the source dn to target dn */
868 if (!$this->ldap_rename($sourcedn, 'cn=' . $targetcn, $this->basedn
))
869 return $this->set_error(sprintf(_("Unable to rename user \"%s\" to \"%s\""), $alias, $userdata['nickname']));
874 $deleted_attribs = array();
877 $data['cn'] = $this->quotevalue($targetcn);
878 $data['mail'] = $this->quotevalue($userdata['email']);
879 $data["objectclass"][0] = "top";
880 $data["objectclass"][1] = "person";
881 $data["objectclass"][2] = "organizationalPerson";
882 $data["objectclass"][3] = "inetOrgPerson";
884 if(!empty($userdata['firstname'])) {
885 $data['givenName'] = $this->quotevalue($userdata['firstname']);
886 } elseif (!empty($sourceuser['firstname'])) {
887 $deleted_attribs['givenName'] = $this->quotevalue($sourceuser['firstname']);
890 if(!empty($userdata['lastname'])) {
891 $data['sn'] = $this->quotevalue($userdata['lastname']);
893 // sn is required attribute in LDAP person object.
894 // SquirrelMail requires givenName or Surname
898 if(!empty($userdata['label'])) {
899 $data['description'] = $this->quotevalue($userdata['label']);
900 } elseif (!empty($sourceuser['label'])) {
901 $deleted_attribs['description'] = $this->quotevalue($sourceuser['label']);
904 return $this->ldap_modify($targetdn, $data, $deleted_attribs);