Adding write support to address book ldap backend. Patch by David Hardeman
authortokul <tokul@7612ce4b-ef26-0410-bec9-ea0150e637f0>
Sat, 3 Jun 2006 17:14:49 +0000 (17:14 +0000)
committertokul <tokul@7612ce4b-ef26-0410-bec9-ea0150e637f0>
Sat, 3 Jun 2006 17:14:49 +0000 (17:14 +0000)
(#1495763).

git-svn-id: https://svn.code.sf.net/p/squirrelmail/code/trunk/squirrelmail@11176 7612ce4b-ef26-0410-bec9-ea0150e637f0

ChangeLog
config/conf.pl
functions/abook_ldap_server.php
functions/addressbook.php

index e915990..24ac9be 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -69,6 +69,8 @@ Version 1.5.2 - CVS
     case insensitive in search() method.
   - Added special folder (Drafts, Sent, Trash) translations in mailbox 
     tree and folder selection boxes.
+  - Added write support to address book LDAP backend. Patch by David 
+    Hardeman (#1495763).
 
 Version 1.5.1 (branched on 2006-02-12)
 --------------------------------------
index 348feca..4ca3a08 100755 (executable)
@@ -286,6 +286,11 @@ while ( $line = <FILE> ) {
                     $tmp =~ s/[\'\"]?,?\s*$//;
                     $tmp =~ s/[\'\"]?\);\s*$//;
                     $listing = $tmp;
+                } elsif ( $tmp =~ /^\s*[\'\"]writeable[\'\"]/i ) {
+                    $tmp =~ s/^\s*[\'\"]writeable[\'\"]\s*=>\s*[\'\"]?//i;
+                    $tmp =~ s/[\'\"]?,?\s*$//;
+                    $tmp =~ s/[\'\"]?\);\s*$//;
+                    $writeable = $tmp;
                 } elsif ( $tmp =~ /^\s*[\'\"]search_tree[\'\"]/i ) {
                     $tmp =~ s/^\s*[\'\"]search_tree[\'\"]\s*=>\s*[\'\"]?//i;
                     $tmp =~ s/[\'\"]?,?\s*$//;
@@ -310,6 +315,7 @@ while ( $line = <FILE> ) {
             $ldap_protocol[$sub] = $protocol;
             $ldap_limit_scope[$sub] = $limit_scope;
             $ldap_listing[$sub] = $listing;
+            $ldap_writeable[$sub] = $writeable;
             $ldap_search_tree[$sub] = $search_tree;
             $ldap_starttls[$sub] = $starttls;
         } elsif ( $options[0] =~ /^(data_dir|attachment_dir|theme_css|org_logo|signout_page)$/ ) {
@@ -2929,6 +2935,9 @@ sub command61 {
                 if ( $ldap_listing[$count] ) {
                     print "     listing: $ldap_listing[$count]\n";
                 }
+                if ( $ldap_writeable[$count] ) {
+                    print "   writeable: $ldap_writeable[$count]\n";
+                }
                 if ( $ldap_search_tree[$count] ) {
                     print " search_tree: $ldap_search_tree[$count]\n";
                 }
@@ -3048,7 +3057,6 @@ sub command61 {
               print "Number of displayed entries is limited by maxrows setting.\n";
               print "\n";
               print "Don't enable this option for public LDAP directories.\n";
-              print "This feature is experimental.\n";
               print "\n";
               print "Allow listing of LDAP directory? (y/N):";
               $name = <STDIN>;
@@ -3061,6 +3069,23 @@ sub command61 {
 
               print "\n";
 
+              print "You can control write access to LDAP address book here. This option can\n";
+              print "be useful if you run small LDAP server and want to provide writable\n";
+              print "shared address book stored in LDAP to users of webmail interface.\n";
+              print "\n";
+              print "Don't enable this option for public LDAP directories.\n";
+              print "\n";
+              print "Allow writing to LDAP directory? (y/N):";
+              $name = <STDIN>;
+              if ( $name =~ /^y\n/i ) {
+                $name = 'true';
+              } else {
+                $name = 'false';
+              }
+              $ldap_writeable[$sub] = $name;
+
+              print "\n";
+
               print "You can specify an additional search filter.\n";
               print "This could be something like \"(objectclass=posixAccount)\".\n";
               print "No filtering is performed by default. Press ENTER for default.\n";
@@ -3137,6 +3162,7 @@ sub command61 {
             @new_ldap_protocol = ();
             @new_ldap_limit_scope = ();
             @new_ldap_listing = ();
+            @new_ldap_writeable = ();
             @new_ldap_search_tree = ();
             @new_ldap_starttls = ();
 
@@ -3154,6 +3180,7 @@ sub command61 {
                     @new_ldap_protocol  = ( @new_ldap_protocol,  $ldap_protocol[$count] );
                     @new_ldap_limit_scope = ( @new_ldap_limit_scope,  $ldap_limit_scope[$count] );
                     @new_ldap_listing = ( @new_ldap_listing, $ldap_listing[$count] );
+                    @new_ldap_writeable = ( @new_ldap_writeable, $ldap_writeable[$count] );
                     @new_ldap_search_tree = ( @new_ldap_search_tree, $ldap_search_tree[$count] );
                     @new_ldap_starttls = ( @new_ldap_starttls, $ldap_starttls[$count] );
                 }
@@ -3171,6 +3198,7 @@ sub command61 {
             @ldap_protocol = @new_ldap_protocol;
             @ldap_limit_scope = @new_ldap_limit_scope;
             @ldap_listing = @new_ldap_listing;
+            @ldap_writeable = @new_ldap_writeable;
             @ldap_search_tree = @new_ldap_search_tree;
             @ldap_starttls = @new_ldap_starttls;
 
@@ -3992,6 +4020,11 @@ sub save_data {
                 # boolean
                 print CF "    'listing' => $ldap_listing[$count]";
             }
+           if ( $ldap_writeable[$count] ) {
+                print CF ",\n";
+                # boolean
+                print CF "    'writeable' => $ldap_writeable[$count]";
+            }
             if ( $ldap_search_tree[$count] ) {
                 print CF ",\n";
                 # integer
index 87bacd9..212b105 100644 (file)
  *   <mcb30 at users.sourceforge.net> (#1035454)
  * StartTLS code by John Lane
  *   <starfry at users.sourceforge.net> (#1197703)
+ * Code for remove, add, modify, lookup by David Härdeman
+ *   <david at 2gen.com> (#1495763)
  *
+ * This backend uses LDAP person (RFC2256), organizationalPerson (RFC2256)
+ * and inetOrgPerson (RFC2798) objects and dn, description, sn, givenname,
+ * cn, mail attributes. Other attributes are ignored.
+ * 
  * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  * @version $Id$
@@ -27,7 +33,8 @@
  *
  * Main settings:
  * <pre>
- *    host      => LDAP server hostname/IP-address
+ *    host      => LDAP server hostname, IP-address or any other URI compatible
+ *                 with used LDAP library.
  *    base      => LDAP server root (base dn). Empty string allowed.
  *  ? port      => LDAP server TCP port number (default: 389)
  *  ? charset   => LDAP server charset (default: utf-8)
  *  ? filter    => Filter expression to limit ldap searches
  *  ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
  *  ? listing   => Controls listing of LDAP directory.
+ *  ? writeable => Controls write access to address book
  *  ? search_tree => Controls subtree or one level search.
  *  ? starttls  => Controls use of StartTLS on LDAP connections
  * </pre>
- * NOTE. This class should not be used directly. Use the
- *       "AddressBook" class instead.
+ * NOTE. This class should not be used directly. Use addressbook_init()
+ *       function instead.
  * @package squirrelmail
  * @subpackage addressbook
  */
@@ -131,6 +139,11 @@ class abook_ldap_server extends addressbook_backend {
      */
     var $listing = false;
     /**
+     * @var boolean true if removing/adding/modifying entries is allowed
+     * @since 1.5.2
+     */
+    var $writeable = true;
+    /**
      * @var boolean controls ldap search type.
      * only first level entries are displayed if set to false
      * @since 1.5.1
@@ -154,7 +167,8 @@ class abook_ldap_server extends addressbook_backend {
         }
         if(is_array($param)) {
             $this->server = $param['host'];
-            $this->basedn = $param['base'];
+            // remove whitespace from basedn
+            $this->basedn = preg_replace('/,\s*/',',',trim($param['base']));
 
             if(!empty($param['port']))
                 $this->port = $param['port'];
@@ -186,6 +200,12 @@ class abook_ldap_server extends addressbook_backend {
             if(isset($param['listing']))
                 $this->listing = (bool) $param['listing'];
 
+            if(isset($param['writeable'])) {
+                $this->writeable = (bool) $param['writeable'];
+                // switch backend type to local, if it is writable
+                if($this->writeable) $this->btype = 'local';
+            }
+
             if(isset($param['search_tree']))
                 $this->search_tree = (bool) $param['search_tree'];
 
@@ -347,35 +367,61 @@ class abook_ldap_server extends addressbook_backend {
     }
 
     /**
+     * Prepares user input for use in a ldap query.
+     *
+     * Function converts input string to character set used in LDAP server 
+     * (charset_encode() method) and sanitizes it (ldapspecialchars()).
+     *
+     * @param string $string string to encode
+     * @return string ldap encoded string
+     * @since 1.5.2
+     */
+    function quotevalue($string) {
+        $sanitized = $this->charset_encode($string);
+        return $this->ldapspecialchars($sanitized);
+    }
+
+    /**
      * Search LDAP server.
      *
      * Warning: You must make sure that ldap query is correctly formated and 
      * sanitize use of special ldap keywords.
      * @param string $expression ldap query
+     * @param boolean $singleentry (since 1.5.2) whether we are looking for a 
+     *  single entry. Boolean true forces LDAP_SCOPE_BASE search.
      * @return array search results (false on error)
      * @since 1.5.1
      */
-    function ldap_search($expression) {
+    function ldap_search($expression, $singleentry = false) {
         /* Make sure connection is there */
         if(!$this->open()) {
             return false;
         }
 
-        if ($this->search_tree) {
+        $attributes = array('dn', 'description', 'sn', 'givenname', 'cn', 'mail');
+
+        if ($singleentry) {
+            // ldap_read - search for one single entry
+            $sret = @ldap_read($this->linkid, $expression, "objectClass=*",
+                               $attributes, 0, $this->maxrows, $this->timeout);
+        } elseif ($this->search_tree) {
             // ldap_search - search subtree
             $sret = @ldap_search($this->linkid, $this->basedn, $expression,
-                array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
-                0, $this->maxrows, $this->timeout);
+                $attributes, 0, $this->maxrows, $this->timeout);
         } else {
             // ldap_list - search one level
             $sret = @ldap_list($this->linkid, $this->basedn, $expression,
-                array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
-                0, $this->maxrows, $this->timeout);
+                $attributes, 0, $this->maxrows, $this->timeout);
         }
 
         /* Return error if search failed */
         if(!$sret) {
-            return $this->set_error($this->ldap_error('ldap_search failed'));
+            // Check for LDAP_NO_SUCH_OBJECT (0x20 or 32) error
+            if (ldap_errno($this->linkid)==32) {
+                return array();
+            } else {
+                return $this->set_error($this->ldap_error('ldap_search failed'));
+            }
         }
 
         if(@ldap_count_entries($this->linkid, $sret) <= 0) {
@@ -394,22 +440,26 @@ class abook_ldap_server extends addressbook_backend {
             $nickname = $this->charset_decode($row['dn']);
 
             /**
-             * calculate length of basedn and remove it from nickname
-             * ignore whitespaces between RDNs
-             * Nicknames are shorter and still unique
-             */ 
-            $basedn_len=strlen(preg_replace('/,\s*/',',',trim($this->basedn)));
-            $nickname=substr(preg_replace('/,\s*/',',',$nickname),0,(-1 - $basedn_len));
-
-            $fullname = $this->charset_decode($row['cn'][0]);
-
-            if(!empty($row['ou'][0])) {
-                $label = $this->charset_decode($row['ou'][0]);
+             * remove trailing basedn
+             * remove whitespaces between RDNs
+             * remove leading "cn="
+             * which gives nicknames which are shorter while still unique
+             */
+            $nickname = preg_replace('/,\s*/',',', trim($nickname));
+            $offset = strlen($nickname) - strlen($this->basedn);
+            if($offset > 0 && substr($nickname, $offset) == $this->basedn) {
+                $nickname = substr($nickname, 0, $offset);
+                if(substr($nickname, -1) == ",")
+                    $nickname = substr($nickname, 0, -1);
             }
-            else if(!empty($row['o'][0])) {
-                $label = $this->charset_decode($row['o'][0]);
-            } else {
+            if(strncasecmp($nickname, "cn=", 3) == 0)
+                $nickname=substr($nickname, 3);         
+
+            if(empty($row['description'][0])) {
                 $label = '';
+            } else {
+                $label = $this->charset_decode($row['description'][0]);
             }
 
             if(empty($row['givenname'][0])) {
@@ -421,9 +471,13 @@ class abook_ldap_server extends addressbook_backend {
             if(empty($row['sn'][0])) {
                 $surname = '';
             } else {
-                $surname = $this->charset_decode($row['sn'][0]);
+                // remove whitespace in order to handle sn set to empty string
+                $surname = trim($this->charset_decode($row['sn'][0]));
             }
 
+            // FIXME: Write generic function to handle name order 
+            $fullname = trim($firstname . " " . $surname);
+
             /* Add one row to result for each e-mail address */
             if(isset($row['mail']['count'])) {
                 for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
@@ -455,6 +509,124 @@ class abook_ldap_server extends addressbook_backend {
     }
 
     /**
+     * Add an entry to LDAP server.
+     *
+     * Warning: You must make sure that the arguments are correctly formated and 
+     * sanitize use of special ldap keywords.
+     * @param string $dn the dn of the entry to be added
+     * @param array $data the values of the entry to be added
+     * @return boolean result (false on error)
+     * @since 1.5.2
+     */
+    function ldap_add($dn, $data) {
+        /* Make sure connection is there */
+        if(!$this->open()) {
+            return false;
+        }
+
+        if(!@ldap_add($this->linkid, $dn, $data)) {
+            $this->set_error(_("Write to address book failed"));
+            return false;
+        }
+        
+        return true;
+    }
+
+    /**
+     * Remove an entry from LDAP server.
+     *
+     * Warning: You must make sure that the argument is correctly formated and 
+     * sanitize use of special ldap keywords.
+     * @param string $dn the dn of the entry to remove
+     * @return boolean result (false on error)
+     * @since 1.5.2
+     */
+    function ldap_remove($dn) {
+        /* Make sure connection is there */
+        if(!$this->open()) {
+            return false;
+        }
+
+        if(!@ldap_delete($this->linkid, $dn)) {
+            $this->set_error(_("Removing entry from address book failed"));
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Rename an entry on LDAP server.
+     *
+     * Warning: You must make sure that the arguments are correctly formated and 
+     * sanitize use of special ldap keywords.
+     * @param string $sourcedn the dn of the entry to be renamed
+     * @param string $targetdn the dn which $sourcedn should be renamed to
+     * @param string $parent the dn of the parent entry
+     * @return boolean result (false on error)
+     * @since 1.5.2
+     */
+    function ldap_rename($sourcedn, $targetdn, $parent) {
+        /* Make sure connection is there */
+        if(!$this->open()) {
+            return false;
+        }
+
+        /* Make sure that the protocol version supports rename */
+        if($this->protocol < 3) {
+            $this->set_error(_("LDAP rename is not supported by used protocol version"));
+            return false;
+        }
+        /**
+         * Function is available only in OpenLDAP 2.x.x or Netscape Directory 
+         * SDK x.x, and was added in PHP 4.0.5
+         * @todo maybe we can use copy + delete instead of ldap_rename()
+         */
+        if(!function_exists('ldap_rename')) {
+            $this->set_error(_("LDAP rename is not supported by used LDAP library. You can't change nickname"));
+            return false;
+        }
+
+        /* OK, go for it */
+        if(!@ldap_rename($this->linkid, $sourcedn, $targetdn, $parent, true)) {
+            $this->set_error(_("LDAP rename failed"));
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Modify the values of an entry on LDAP server.
+     *
+     * Warning: You must make sure that the arguments are correctly formated and 
+     * sanitize use of special ldap keywords.
+     * @param string $dn the dn of the entry to be modified
+     * @param array $data the new values of the entry
+     * @param array $deleted_attribs attributes that should be deleted.
+     * @return bool result (false on error)
+     * @since 1.5.2
+     */
+    function ldap_modify($dn, $data, $deleted_attribs) {
+        /* Make sure connection is there */
+        if(!$this->open()) {
+            return false;
+        }
+
+        if(!@ldap_modify($this->linkid, $dn, $data)) {
+            $this->set_error(_("Write to address book failed"));
+            return false;
+        }
+
+        if (!@ldap_mod_del($this->linkid, $dn, $deleted_attribs)) {
+            $this->set_error(_("Unable to remove some field values"));
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
      * Get error from LDAP resource if possible
      *
      * Should get error from server using the ldap_errno() and ldap_err2str() functions
@@ -493,11 +665,8 @@ class abook_ldap_server extends addressbook_backend {
             // allow use of wildcard when listing is enabled.
             $expression = '(cn=*)';
         } else {
-            /* Convert search from user's charset to the one used in ldap */
-            $expr = $this->charset_encode($expr);
-
-            /* sanitize search string */
-            $expr = $this->ldapspecialchars($expr);
+            /* Convert search from user's charset to the one used in ldap and sanitize */
+            $expr = $this->quotevalue($expr);
 
             /* Search for same string in cn, main and sn */
             $expression = '(|(cn=*'.$expr.'*)(mail=*'.$expr.'*)(sn=*'.$expr.'*))';
@@ -514,6 +683,24 @@ class abook_ldap_server extends addressbook_backend {
         return $this->ldap_search($expression);
     }
 
+    /**
+     * Lookup an alias
+     * @param string $alias alias
+     * @return array search results
+     * @since 1.5.2
+     */
+    function lookup($alias) {
+        /* Generate the dn and try to retrieve that single entry */
+        $cn = $this->quotevalue($alias);
+        $dn = 'cn=' . $cn . ',' . $this->basedn;
+
+        /* Do the search */
+        $result = $this->ldap_search($dn, true);
+        if (!is_array($result) || count($result) < 1)
+            return array();
+
+        return $result[0];
+    }
 
     /**
      * List all entries present in LDAP server
@@ -536,5 +723,146 @@ class abook_ldap_server extends addressbook_backend {
          /* use internal search function and return search results */
          return $this->ldap_search($expression);
      }
+
+    /**
+     * Add address
+     * @param array $userdata new data
+     * @return boolean
+     * @since 1.5.2
+     */
+    function add($userdata) {
+        if(!$this->writeable) {
+            return $this->set_error(_("Address book is read-only"));
+        }
+
+        /* Convert search from user's charset to the one used in ldap and sanitize */
+        $cn = $this->quotevalue($userdata['nickname']);
+        $dn = 'cn=' . $cn . ',' . trim($this->basedn);
+
+        /* See if user exists already */
+        $user = $this->ldap_search($dn, true);
+        if (!is_array($user)) {
+            return false;
+        } elseif (count($user) > 0) {
+            return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
+        }
+
+        /* init variable */
+        $data = array();
+
+        /* Prepare data */
+        $data['cn'] = $cn;
+        $data['mail'] = $this->quotevalue($userdata['email']);
+        $data["objectclass"][0] = "top";
+        $data["objectclass"][1] = "person";
+        $data["objectclass"][2] = "organizationalPerson";
+        $data["objectclass"][3] = "inetOrgPerson";
+        /* sn is required in person object */
+        if(!empty($userdata['lastname'])) {
+            $data['sn'] = $this->quotevalue($userdata['lastname']);
+        } else {
+            $data['sn'] = ' ';
+        }
+        /* optional fields */
+        if(!empty($userdata['firstname']))
+            $data['givenName'] = $this->quotevalue($userdata['firstname']);
+        if(!empty($userdata['label'])) {
+            $data['description'] = $this->quotevalue($userdata['label']);
+        }
+        return $this->ldap_add($dn, $data);
+    }
+
+    /**
+     * Delete address
+     * @param array $aliases array of entries that have to be removed.
+     * @return boolean
+     * @since 1.5.2
+     */
+    function remove($aliases) {
+        if(!$this->writeable) {
+            return $this->set_error(_("Address book is read-only"));
+        }
+
+        foreach ($aliases as $alias) {
+            /* Convert nickname from user's charset and derive cn/dn */
+            $cn = $this->quotevalue($alias);
+            $dn = 'cn=' . $cn . ',' . $this->basedn;
+
+            if (!$this->ldap_remove($dn))
+                return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Modify address
+     * @param string $alias modified alias
+     * @param array $userdata new data
+     * @return boolean
+     * @since 1.5.2
+     */
+    function modify($alias, $userdata) {
+        if(!$this->writeable) {
+            return $this->set_error(_("Address book is read-only"));
+        }
+
+        /* Convert search from user's charset to the one used in ldap and sanitize */
+        $sourcecn = $this->quotevalue($alias);
+        $sourcedn = 'cn=' . $sourcecn . ',' . trim($this->basedn);
+        $targetcn = $this->quotevalue($userdata['nickname']);
+        $targetdn = 'cn=' . $targetcn . ',' . trim($this->basedn);
+
+        /* Check that the dn to modify exists */
+        $sourceuser = $this->lookup($alias);
+        if (!is_array($sourceuser) || count($sourceuser) < 1)
+            return false;
+
+        /* Check if dn is going to change */
+        if ($alias != $userdata['nickname']) {
+
+            /* Check that the target dn doesn't exist */
+            $targetuser = $this->lookup($userdata['nickname']);
+            if (is_array($targetuser) && count($targetuser) > 0)
+                return $this->set_error(sprintf(_("User \"%s\" already exists"), $userdata['nickname']));
+
+            /* Rename from the source dn to target dn */
+            if (!$this->ldap_rename($sourcedn, 'cn=' . $targetcn, $this->basedn))
+                    return $this->set_error(sprintf(_("Unable to rename user \"%s\" to \"%s\""), $alias, $userdata['nickname']));
+        }
+
+        // initial vars
+        $data = array();
+        $deleted_attribs = array();
+
+        /* Prepare data */
+        $data['cn'] = $this->quotevalue($targetcn);
+        $data['mail'] = $this->quotevalue($userdata['email']);
+        $data["objectclass"][0] = "top";
+        $data["objectclass"][1] = "person";
+        $data["objectclass"][2] = "organizationalPerson";
+        $data["objectclass"][3] = "inetOrgPerson";
+
+        if(!empty($userdata['firstname'])) {
+            $data['givenName'] = $this->quotevalue($userdata['firstname']);
+        } elseif (!empty($sourceuser['firstname'])) {
+            $deleted_attribs['givenName'] = $this->quotevalue($sourceuser['firstname']);
+        }
+
+        if(!empty($userdata['lastname'])) {
+            $data['sn'] = $this->quotevalue($userdata['lastname']);
+        } else {
+            // sn is required attribute in LDAP person object.
+            // SquirrelMail requires givenName or Surname 
+            $data['sn'] = ' ';
+        }
+
+        if(!empty($userdata['label'])) {
+            $data['description'] = $this->quotevalue($userdata['label']);
+        } elseif (!empty($sourceuser['label'])) {
+            $deleted_attribs['description'] = $this->quotevalue($sourceuser['label']);
+        }
+
+        return $this->ldap_modify($targetdn, $data, $deleted_attribs);
+    }
 }
-?>
\ No newline at end of file
index e487244..ba9c6b0 100644 (file)
@@ -136,23 +136,27 @@ function addressbook_init($showerr = true, $onlylocal = false) {
         $abook_init_error.=_("Error initializing other address books.") . "<br />\n" . $abook->error;
     }
 
-    if (! $onlylocal) {
-        /* Load configured LDAP servers (if PHP has LDAP support) */
-        if (isset($ldap_server) && is_array($ldap_server)) {
-            reset($ldap_server);
-            while (list($undef,$param) = each($ldap_server)) {
-                if (is_array($param)) {
-                    $r = $abook->add_backend('ldap_server', $param);
-                    if (!$r && $showerr) {
-                        if ($abook_init_error!='') $abook_init_error.="<br />\n";
-                        $abook_init_error.=sprintf(_("Error initializing LDAP server %s:") .
-                                "<br />\n", $param['host']);
-                        $abook_init_error.= $abook->error;
-                    }
-                }
+
+    /* Load configured LDAP servers (if PHP has LDAP support) */
+    if (isset($ldap_server) && is_array($ldap_server)) {
+        reset($ldap_server);
+        while (list($undef,$param) = each($ldap_server)) {
+            if (!is_array($param))
+                continue;
+
+            /* if onlylocal is true, we only add writeable ldap servers */
+            if ($onlylocal && (!isset($param['writeable']) || $param['writeable'] != true))
+                continue;
+
+            $r = $abook->add_backend('ldap_server', $param);
+            if (!$r && $showerr) {
+                if ($abook_init_error!='') $abook_init_error.="<br />\n";
+                $abook_init_error.=sprintf(_("Error initializing LDAP server %s:") .
+                                           "<br />\n", $param['host']);
+                $abook_init_error.= $abook->error;
             }
-        } // end of ldap server init
-    } // end of remote abook backend init
+        }
+    } // end of ldap server init
 
     /**
      * display address book init errors.
@@ -969,4 +973,3 @@ class addressbook_backend {
         return false;
     }
 }
-?>
\ No newline at end of file