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 $fullname = $this->fullname($firstname,$surname);
480 /* Add one row to result for each e-mail address */
481 if(isset($row['mail']['count'])) {
482 for($j = 0 ; $j < $row['mail']['count'] ; $j++
) {
483 array_push($ret, array('nickname' => $nickname,
485 'firstname' => $firstname,
486 'lastname' => $surname,
487 'email' => $row['mail'][$j],
489 'backend' => $this->bnum
,
490 'source' => &$this->sname
));
492 // Limit number of hits
494 if(($returned_rows >= $this->maxrows
) &&
495 ($this->maxrows
> 0) ) {
496 ldap_free_result($sret);
502 } // isset($row['mail']['count'])
506 ldap_free_result($sret);
511 * Add an entry to LDAP server.
513 * Warning: You must make sure that the arguments are correctly formated and
514 * sanitize use of special ldap keywords.
515 * @param string $dn the dn of the entry to be added
516 * @param array $data the values of the entry to be added
517 * @return boolean result (false on error)
520 function ldap_add($dn, $data) {
521 /* Make sure connection is there */
526 if(!@ldap_add
($this->linkid
, $dn, $data)) {
527 $this->set_error(_("Write to address book failed"));
535 * Remove an entry from LDAP server.
537 * Warning: You must make sure that the argument is correctly formated and
538 * sanitize use of special ldap keywords.
539 * @param string $dn the dn of the entry to remove
540 * @return boolean result (false on error)
543 function ldap_remove($dn) {
544 /* Make sure connection is there */
549 if(!@ldap_delete
($this->linkid
, $dn)) {
550 $this->set_error(_("Removing entry from address book failed"));
558 * Rename an entry on LDAP server.
560 * Warning: You must make sure that the arguments are correctly formated and
561 * sanitize use of special ldap keywords.
562 * @param string $sourcedn the dn of the entry to be renamed
563 * @param string $targetdn the dn which $sourcedn should be renamed to
564 * @param string $parent the dn of the parent entry
565 * @return boolean result (false on error)
568 function ldap_rename($sourcedn, $targetdn, $parent) {
569 /* Make sure connection is there */
574 /* Make sure that the protocol version supports rename */
575 if($this->protocol
< 3) {
576 $this->set_error(_("LDAP rename is not supported by used protocol version"));
580 * Function is available only in OpenLDAP 2.x.x or Netscape Directory
581 * SDK x.x, and was added in PHP 4.0.5
582 * @todo maybe we can use copy + delete instead of ldap_rename()
584 if(!function_exists('ldap_rename')) {
585 $this->set_error(_("LDAP rename is not supported by used LDAP library. You can't change nickname"));
590 if(!@ldap_rename
($this->linkid
, $sourcedn, $targetdn, $parent, true)) {
591 $this->set_error(_("LDAP rename failed"));
599 * Modify the values of an entry on LDAP server.
601 * Warning: You must make sure that the arguments are correctly formated and
602 * sanitize use of special ldap keywords.
603 * @param string $dn the dn of the entry to be modified
604 * @param array $data the new values of the entry
605 * @param array $deleted_attribs attributes that should be deleted.
606 * @return bool result (false on error)
609 function ldap_modify($dn, $data, $deleted_attribs) {
610 /* Make sure connection is there */
615 if(!@ldap_modify
($this->linkid
, $dn, $data)) {
616 $this->set_error(_("Write to address book failed"));
620 if (!@ldap_mod_del
($this->linkid
, $dn, $deleted_attribs)) {
621 $this->set_error(_("Unable to remove some field values"));
629 * Get error from LDAP resource if possible
631 * Should get error from server using the ldap_errno() and ldap_err2str() functions
632 * @param string $sError error message used when ldap error functions
633 * and connection resource are unavailable
634 * @return string error message
637 function ldap_error($sError) {
638 // it is possible that function_exists() tests are not needed
639 if(function_exists('ldap_err2str') &&
640 function_exists('ldap_errno') &&
641 is_resource($this->linkid
)) {
642 return ldap_err2str(ldap_errno($this->linkid
));
643 // return ldap_error($this->linkid);
649 /* ========================== Public ======================== */
652 * Search the LDAP server
653 * @param string $expr search expression
654 * @return array search results
656 function search($expr) {
657 /* To be replaced by advanded search expression parsing */
658 if(is_array($expr)) return false;
660 // don't allow wide search when listing is disabled.
661 if ($expr=='*' && ! $this->listing
) {
663 } elseif ($expr=='*') {
664 // allow use of wildcard when listing is enabled.
665 $expression = '(cn=*)';
667 /* Convert search from user's charset to the one used in ldap and sanitize */
668 $expr = $this->quotevalue($expr);
670 /* Search for same string in cn, main and sn */
671 $expression = '(|(cn=*'.$expr.'*)(mail=*'.$expr.'*)(sn=*'.$expr.'*))';
673 /* Undo sanitizing of * symbol */
674 $expression = str_replace('\2a','*',$expression);
677 /* Add search filtering */
678 if ($this->filter
!='')
679 $expression = '(&' . $this->filter
. $expression . ')';
681 /* Use internal search function and return search results */
682 return $this->ldap_search($expression);
687 * @param string $alias alias
688 * @return array search results
691 function lookup($alias) {
692 /* Generate the dn and try to retrieve that single entry */
693 $cn = $this->quotevalue($alias);
694 $dn = 'cn=' . $cn . ',' . $this->basedn
;
697 $result = $this->ldap_search($dn, true);
698 if (!is_array($result) ||
count($result) < 1)
705 * List all entries present in LDAP server
707 * maxrows setting might limit list of returned entries.
708 * Careful with this -- it could get quite large for big sites.
709 * @return array all entries in ldap server
711 function list_addr() {
712 if (! $this->listing
)
715 /* set wide search expression */
716 $expression = '(cn=*)';
719 if ($this->filter
!='')
720 $expression = '(&' . $this->filter
. $expression .')';
722 /* use internal search function and return search results */
723 return $this->ldap_search($expression);
728 * @param array $userdata new data
732 function add($userdata) {
733 if(!$this->writeable
) {
734 return $this->set_error(_("Address book is read-only"));
737 /* Convert search from user's charset to the one used in ldap and sanitize */
738 $cn = $this->quotevalue($userdata['nickname']);
739 $dn = 'cn=' . $cn . ',' . trim($this->basedn
);
741 /* See if user exists already */
742 $user = $this->ldap_search($dn, true);
743 if (!is_array($user)) {
745 } elseif (count($user) > 0) {
746 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
754 $data['mail'] = $this->quotevalue($userdata['email']);
755 $data["objectclass"][0] = "top";
756 $data["objectclass"][1] = "person";
757 $data["objectclass"][2] = "organizationalPerson";
758 $data["objectclass"][3] = "inetOrgPerson";
759 /* sn is required in person object */
760 if(!empty($userdata['lastname'])) {
761 $data['sn'] = $this->quotevalue($userdata['lastname']);
765 /* optional fields */
766 if(!empty($userdata['firstname']))
767 $data['givenName'] = $this->quotevalue($userdata['firstname']);
768 if(!empty($userdata['label'])) {
769 $data['description'] = $this->quotevalue($userdata['label']);
771 return $this->ldap_add($dn, $data);
776 * @param array $aliases array of entries that have to be removed.
780 function remove($aliases) {
781 if(!$this->writeable
) {
782 return $this->set_error(_("Address book is read-only"));
785 foreach ($aliases as $alias) {
786 /* Convert nickname from user's charset and derive cn/dn */
787 $cn = $this->quotevalue($alias);
788 $dn = 'cn=' . $cn . ',' . $this->basedn
;
790 if (!$this->ldap_remove($dn))
799 * @param string $alias modified alias
800 * @param array $userdata new data
804 function modify($alias, $userdata) {
805 if(!$this->writeable
) {
806 return $this->set_error(_("Address book is read-only"));
809 /* Convert search from user's charset to the one used in ldap and sanitize */
810 $sourcecn = $this->quotevalue($alias);
811 $sourcedn = 'cn=' . $sourcecn . ',' . trim($this->basedn
);
812 $targetcn = $this->quotevalue($userdata['nickname']);
813 $targetdn = 'cn=' . $targetcn . ',' . trim($this->basedn
);
815 /* Check that the dn to modify exists */
816 $sourceuser = $this->lookup($alias);
817 if (!is_array($sourceuser) ||
count($sourceuser) < 1)
820 /* Check if dn is going to change */
821 if ($alias != $userdata['nickname']) {
823 /* Check that the target dn doesn't exist */
824 $targetuser = $this->lookup($userdata['nickname']);
825 if (is_array($targetuser) && count($targetuser) > 0)
826 return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
828 /* Rename from the source dn to target dn */
829 if (!$this->ldap_rename($sourcedn, 'cn=' . $targetcn, $this->basedn
))
830 return $this->set_error(sprintf(_("Unable to rename user \"%s\" to \"%s\""), $alias, $userdata['nickname']));
835 $deleted_attribs = array();
838 $data['cn'] = $this->quotevalue($targetcn);
839 $data['mail'] = $this->quotevalue($userdata['email']);
840 $data["objectclass"][0] = "top";
841 $data["objectclass"][1] = "person";
842 $data["objectclass"][2] = "organizationalPerson";
843 $data["objectclass"][3] = "inetOrgPerson";
845 if(!empty($userdata['firstname'])) {
846 $data['givenName'] = $this->quotevalue($userdata['firstname']);
847 } elseif (!empty($sourceuser['firstname'])) {
848 $deleted_attribs['givenName'] = $this->quotevalue($sourceuser['firstname']);
851 if(!empty($userdata['lastname'])) {
852 $data['sn'] = $this->quotevalue($userdata['lastname']);
854 // sn is required attribute in LDAP person object.
855 // SquirrelMail requires givenName or Surname
859 if(!empty($userdata['label'])) {
860 $data['description'] = $this->quotevalue($userdata['label']);
861 } elseif (!empty($sourceuser['label'])) {
862 $deleted_attribs['description'] = $this->quotevalue($sourceuser['label']);
865 return $this->ldap_modify($targetdn, $data, $deleted_attribs);