alecpl
2011-10-07 b1f0846727331f58342e9cfdd02df03ea8f15181
program/include/rcube_ldap.php
@@ -5,6 +5,7 @@
 |                                                                       |
 | This file is part of the Roundcube Webmail client                     |
 | Copyright (C) 2006-2011, The Roundcube Dev Team                       |
 | Copyright (C) 2011, Kolab Systems AG                                  |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
@@ -13,6 +14,7 @@
 +-----------------------------------------------------------------------+
 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
 |         Andreas Dick <andudi (at) gmx (dot) ch>                       |
 |         Aleksander Machniak <machniak@kolabsys.com>                   |
 +-----------------------------------------------------------------------+
 $Id$
@@ -51,8 +53,9 @@
    private $base_dn = '';
    private $groups_base_dn = '';
    private $group_cache = array();
    private $group_url = null;
    private $group_members = array();
    private $cache;
    private $vlv_active = false;
    private $vlv_count = 0;
@@ -70,9 +73,21 @@
    {
        $this->prop = $p;
        if (isset($p['searchonly']))
            $this->searchonly = $p['searchonly'];
        // check if groups are configured
        if (is_array($p['groups']) and count($p['groups']))
        if (is_array($p['groups']) && count($p['groups'])) {
            $this->groups = true;
            // set member field
            if (!empty($p['groups']['member_attr']))
                $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
            else if (empty($p['member_attr']))
                $this->prop['member_attr'] = 'member';
            // set default name attribute to cn
            if (empty($this->prop['groups']['name_attr']))
                $this->prop['groups']['name_attr'] = 'cn';
        }
        // fieldmap property is given
        if (is_array($p['fieldmap'])) {
@@ -113,9 +128,14 @@
        foreach ($this->prop['required_fields'] as $key => $val)
            $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
        $this->sort_col = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
        $this->debug = $debug;
        $this->sort_col    = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
        $this->debug       = $debug;
        $this->mail_domain = $mail_domain;
        // initialize cache
        $rcmail = rcmail::get_instance();
        $this->cache = $rcmail->get_cache('LDAP.' . asciiwords($this->prop['name']), 'db', 600);
        $this->cache->expunge();
        $this->_connect();
    }
@@ -171,7 +191,10 @@
            $bind_pass = $this->prop['bind_pass'];
            $bind_user = $this->prop['bind_user'];
            $bind_dn   = $this->prop['bind_dn'];
            $this->base_dn   = $this->prop['base_dn'];
            $this->base_dn        = $this->prop['base_dn'];
            $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
                $this->prop['groups']['base_dn'] : $this->base_dn;
            // User specific access, generate the proper values to use.
            if ($this->prop['user_specific']) {
@@ -185,7 +208,7 @@
                  list($u, $d) = explode('@', $fu);
                else
                  $d = $this->mail_domain;
                $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
                $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
@@ -197,7 +220,7 @@
                    $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
                    $res = ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
                    $res = @ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
                    if ($res && ($entry = ldap_first_entry($this->conn, $res))) {
                        $bind_dn = ldap_get_dn($this->conn, $entry);
@@ -210,8 +233,9 @@
                    }
                }
                // Replace the bind_dn and base_dn variables.
                $bind_dn   = strtr($bind_dn, $replaces);
                $this->base_dn   = strtr($this->base_dn, $replaces);
                $bind_dn              = strtr($bind_dn, $replaces);
                $this->base_dn        = strtr($this->base_dn, $replaces);
                $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
                if (empty($bind_user)) {
                    $bind_user = $u;
@@ -220,13 +244,13 @@
            if (!empty($bind_pass)) {
                if (!empty($bind_dn)) {
                    $this->ready = $this->_bind($bind_dn, $bind_pass);
                    $this->ready = $this->bind($bind_dn, $bind_pass);
                }
                else if (!empty($this->prop['auth_cid'])) {
                    $this->ready = $this->_sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
                    $this->ready = $this->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
                }
                else {
                    $this->ready = $this->_sasl_bind($bind_user, $bind_pass);
                    $this->ready = $this->sasl_bind($bind_user, $bind_pass);
                }
            }
        }
@@ -251,7 +275,7 @@
     *
     * @return boolean True on success, False on error
     */
    private function _sasl_bind($authc, $pass, $authz=null)
    public function sasl_bind($authc, $pass, $authz=null)
    {
        if (!$this->conn) {
            return false;
@@ -302,7 +326,7 @@
     *
     * @return boolean True on success, False on error
     */
    private function _bind($dn, $pass)
    public function bind($dn, $pass)
    {
        if (!$this->conn) {
            return false;
@@ -417,11 +441,30 @@
     */
    function list_records($cols=null, $subset=0)
    {
        if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id)
        {
            $this->result = new rcube_result_set(0);
            $this->result->searchonly = true;
            return $this->result;
        }
        // add general filter to query
        if (!empty($this->prop['filter']) && empty($this->filter))
        {
            $filter = $this->prop['filter'];
            $this->set_search_set($filter);
        }
        // query URL is given by the selected group
        if ($this->group_id && $this->group_url)
        {
            // extract components from url
            if (preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $this->group_url, $m))
            {
                $this->base_dn = $m[1];
                $this->prop['scope'] = $m[2];
                $this->filter = $m[3];
            }
        }
        // exec LDAP search if no result resource is stored
@@ -448,13 +491,13 @@
            $entries = ldap_get_entries($this->conn, $this->ldap_result);
            // filtering for group members
            if ($this->groups and $this->group_id)
            if ($this->groups && $this->group_id && !$this->group_url)
            {
                $count = 0;
                $members = array();
                foreach ($entries as $entry)
                {
                    if ($this->group_members[base64_encode($entry['dn'])])
                    if ($this->group_members[self::dn_encode($entry['dn'])])
                    {
                        $members[] = $entry;
                        $count++;
@@ -614,7 +657,7 @@
        $res = null;
        if ($this->conn && $dn)
        {
            $dn = base64_decode($dn);
            $dn = self::dn_decode($dn);
            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
@@ -685,8 +728,8 @@
        } // end foreach
        // Verify that the required fields are set.
        $missing = null;
        foreach ($this->prop['required_fields'] as $fld) {
            $missing = null;
            if (!isset($newentry[$fld])) {
                $missing[] = $fld;
            }
@@ -713,11 +756,13 @@
        $this->_debug("S: OK");
        $dn = self::dn_encode($dn);
        // add new contact to the selected group
        if ($this->groups)
            $this->add_to_group($this->group_id, base64_encode($dn));
            $this->add_to_group($this->group_id, $dn);
        return base64_encode($dn);
        return $dn;
    }
@@ -738,7 +783,7 @@
        $newdata = array();
        $replacedata = array();
        $deletedata = array();
        // flatten composite fields in $record
        if (is_array($record['address'])) {
          foreach ($record['address'] as $i => $struct) {
@@ -776,7 +821,7 @@
            } // end if
        } // end foreach
        $dn = base64_decode($id);
        $dn = self::dn_decode($id);
        // Update the entry as required.
        if (!empty($deletedata)) {
@@ -833,17 +878,21 @@
            }
            $this->_debug("S: OK");
            $dn    = self::dn_encode($dn);
            $newdn = self::dn_encode($newdn);
            // change the group membership of the contact
            if ($this->groups)
            {
                $group_ids = $this->get_record_groups(base64_encode($dn));
                $group_ids = $this->get_record_groups($dn);
                foreach ($group_ids as $group_id)
                {
                    $this->remove_from_group($group_id, base64_encode($dn));
                    $this->add_to_group($group_id, base64_encode($newdn));
                    $this->remove_from_group($group_id, $dn);
                    $this->add_to_group($group_id, $newdn);
                }
            }
            return base64_encode($newdn);
            return $newdn;
        }
        return true;
@@ -866,7 +915,7 @@
        } // end if
        foreach ($ids as $id) {
            $dn = base64_decode($id);
            $dn = self::dn_decode($id);
            $this->_debug("C: Delete [dn: $dn]");
            // Delete the record.
            $res = ldap_delete($this->conn, $dn);
@@ -878,12 +927,11 @@
            $this->_debug("S: OK");
            // remove contact from all groups where he was member
            if ($this->groups)
            {
                $group_ids = $this->get_record_groups(base64_encode($dn));
                foreach ($group_ids as $group_id)
                {
                    $this->remove_from_group($group_id, base64_encode($dn));
            if ($this->groups) {
                $dn = self::dn_encode($dn);
                $group_ids = $this->get_record_groups($dn);
                foreach ($group_ids as $group_id) {
                    $this->remove_from_group($group_id, $dn);
                }
            }
        } // end foreach
@@ -905,7 +953,7 @@
            $this->_debug("C: Search [$filter]");
            // when using VLV, we get the total count by...
            if (!$count && $function != 'ldap_read' && $this->prop['vlv']) {
            if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
                // ...either reading numSubOrdinates attribute
                if ($this->prop['numsub_filter'] && ($result_count = @$function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
                    $counts = ldap_get_entries($this->conn, $result_count);
@@ -967,7 +1015,7 @@
        $out = array();
        if ($rec['dn'])
            $out[$this->primary_key] = base64_encode($rec['dn']);
            $out[$this->primary_key] = self::dn_encode($rec['dn']);
        foreach ($this->fieldmap as $rf => $lf)
        {
@@ -982,6 +1030,11 @@
                    $out[$rf][] = $value;
                else
                    $out[$rf] = $value;
            }
            // Make sure name fields aren't arrays (#1488108)
            if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
                $out[$rf] = $out[$rf][0];
            }
        }
@@ -1058,22 +1111,27 @@
    {
        if ($group_id)
        {
            if (!$this->group_cache)
                $this->list_groups();
            if (!($group_cache = $this->cache->get('groups')))
                $group_cache = $this->list_groups();
            $cache_members = $this->group_cache[$group_id]['members'];
            $cache_members = $group_cache[$group_id]['members'];
            $members = array();
            for ($i=0; $i<$cache_members["count"]; $i++)
            {
                if (!empty($cache_members[$i]))
                    $members[base64_encode($cache_members[$i])] = 1;
                    $members[self::dn_encode($cache_members[$i])] = 1;
            }
            $this->group_members = $members;
            $this->group_url = $group_cache[$group_id]['member_url'];
            $this->group_id = $group_id;
        }
        else
        {
            $this->group_id = 0;
            $this->group_url = null;
            $this->group_members = array();
        }
    }
    /**
@@ -1084,35 +1142,19 @@
     */
    function list_groups($search = null)
    {
        global $RCMAIL;
        if (!$this->groups)
            return array();
        $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
                $this->prop['groups']['base_dn'] : $this->base_dn;
        // replace user specific dn
        if ($this->prop['user_specific'])
        {
            $fu = $RCMAIL->user->get_username();
            list($u, $d) = explode('@', $fu);
            $dc = 'dc='.strtr($d, array('.' => ',dc='));
            $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
            $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
        }
        $base_dn = $this->groups_base_dn;
        $filter = $this->prop['groups']['filter'];
        $name_attr = $this->prop['groups']['name_attr'];
        $this->_debug("C: Search [$filter][dn: $base_dn]");
        $res = ldap_search($this->conn, $base_dn, $filter, array('cn','member'));
        $res = @ldap_search($this->conn, $base_dn, $filter);
        if ($res === false)
        {
            $this->_debug("S: ".ldap_error($this->conn));
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return array();
        }
@@ -1123,18 +1165,45 @@
        $group_sortnames = array();
        for ($i=0; $i<$ldap_data["count"]; $i++)
        {
            $group_name = $ldap_data[$i]['cn'][0];
            $group_name = $ldap_data[$i][$name_attr][0];
            if (!$search || strstr(strtolower($group_name), strtolower($search)))
            {
                $group_id = base64_encode($group_name);
                $group_id = self::dn_encode($group_name);
                $groups[$group_id]['ID'] = $group_id;
                $groups[$group_id]['name'] = $group_name;
                $groups[$group_id]['members'] = $ldap_data[$i]['member'];
                // default behavior: check members attribute
                if ($this->prop['member_attr']) {
                    $groups[$group_id]['members'] = $ldap_data[$i][$this->prop['member_attr']];
                    $groups[$group_id]['member_attr'] = $this->prop['member_attr'];
                }
                // check objectClass attributes of group and act accordingly
                for ($j=0; $j < $ldap_data[$i]['objectclass']['count']; $j++) {
                    switch (strtolower($ldap_data[$i]['objectclass'][$j])) {
                        case 'groupofnames':
                            $groups[$group_id]['members'] = $ldap_data[$i]['members'];
                            $groups[$group_id]['member_attr'] = 'member';
                            break;
                        case 'groupofuniquenames':
                            $groups[$group_id]['members'] = $ldap_data[$i]['uniqueMember'];
                            $groups[$group_id]['member_attr'] = 'uniqueMember';
                            break;
                        case 'groupofurls':
                            $groups[$group_id]['member_url'] = $ldap_data[$i]['memberurl'][0];
                            break;
                    }
                }
                $group_sortnames[] = strtolower($group_name);
            }
        }
        array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
        $this->group_cache = $groups;
        // cache this
        $this->cache->set('groups', $groups);
        return $groups;
    }
@@ -1147,17 +1216,14 @@
     */
    function create_group($group_name)
    {
        if (!$this->group_cache)
            $this->list_groups();
        $base_dn = $this->groups_base_dn;
        $new_dn = "cn=$group_name,$base_dn";
        $new_gid = base64_encode($group_name);
        $new_gid = self::dn_encode($group_name);
        $name_attr = $this->prop['groups']['name_attr'];
        $new_entry = array(
            'objectClass' => $this->prop['groups']['object_classes'],
            'cn' => $group_name,
            'member' => '',
            $name_attr => $group_name,
        );
        $this->_debug("C: Add [dn: $new_dn]: ".print_r($new_entry, true));
@@ -1171,6 +1237,7 @@
        }
        $this->_debug("S: OK");
        $this->cache->remove('groups');
        return array('id' => $new_gid, 'name' => $group_name);
    }
@@ -1183,11 +1250,11 @@
     */
    function delete_group($group_id)
    {
        if (!$this->group_cache)
            $this->list_groups();
        if (!($group_cache = $this->cache->get('groups')))
            $group_cache = $this->list_groups();
        $base_dn = $this->groups_base_dn;
        $group_name = $this->group_cache[$group_id]['name'];
        $group_name = $group_cache[$group_id]['name'];
        $del_dn = "cn=$group_name,$base_dn";
        $this->_debug("C: Delete [dn: $del_dn]");
@@ -1201,6 +1268,7 @@
        }
        $this->_debug("S: OK");
        $this->cache->remove('groups');
        return true;
    }
@@ -1215,14 +1283,14 @@
     */
    function rename_group($group_id, $new_name, &$new_gid)
    {
        if (!$this->group_cache)
            $this->list_groups();
        if (!($group_cache = $this->cache->get('groups')))
            $group_cache = $this->list_groups();
        $base_dn = $this->groups_base_dn;
        $group_name = $this->group_cache[$group_id]['name'];
        $group_name = $group_cache[$group_id]['name'];
        $old_dn = "cn=$group_name,$base_dn";
        $new_rdn = "cn=$new_name";
        $new_gid = base64_encode($new_name);
        $new_gid = self::dn_encode($new_name);
        $this->_debug("C: Rename [dn: $old_dn] [dn: $new_rdn]");
@@ -1235,6 +1303,7 @@
        }
        $this->_debug("S: OK");
        $this->cache->remove('groups');
        return $new_name;
    }
@@ -1248,16 +1317,17 @@
     */
    function add_to_group($group_id, $contact_ids)
    {
        if (!$this->group_cache)
            $this->list_groups();
        if (!($group_cache = $this->cache->get('groups')))
            $group_cache = $this->list_groups();
        $base_dn = $this->groups_base_dn;
        $group_name = $this->group_cache[$group_id]['name'];
        $group_dn = "cn=$group_name,$base_dn";
        $base_dn     = $this->groups_base_dn;
        $group_name  = $group_cache[$group_id]['name'];
        $member_attr = $group_cache[$group_id]['member_attr'];
        $group_dn    = "cn=$group_name,$base_dn";
        $new_attrs = array();
        foreach (explode(",", $contact_ids) as $id)
            $new_attrs['member'][] = base64_decode($id);
            $new_attrs[$member_attr][] = self::dn_decode($id);
        $this->_debug("C: Add [dn: $group_dn]: ".print_r($new_attrs, true));
@@ -1270,6 +1340,7 @@
        }
        $this->_debug("S: OK");
        $this->cache->remove('groups');
        return count($new_attrs['member']);
    }
@@ -1283,16 +1354,17 @@
     */
    function remove_from_group($group_id, $contact_ids)
    {
        if (!$this->group_cache)
            $this->list_groups();
        if (!($group_cache = $this->cache->get('groups')))
            $group_cache = $this->list_groups();
        $base_dn = $this->groups_base_dn;
        $group_name = $this->group_cache[$group_id]['name'];
        $group_dn = "cn=$group_name,$base_dn";
        $base_dn     = $this->groups_base_dn;
        $group_name  = $group_cache[$group_id]['name'];
        $member_attr = $group_cache[$group_id]['member_attr'];
        $group_dn    = "cn=$group_name,$base_dn";
        $del_attrs = array();
        foreach (explode(",", $contact_ids) as $id)
            $del_attrs['member'][] = base64_decode($id);
            $del_attrs[$member_attr][] = self::dn_decode($id);
        $this->_debug("C: Delete [dn: $group_dn]: ".print_r($del_attrs, true));
@@ -1305,6 +1377,7 @@
        }
        $this->_debug("S: OK");
        $this->cache->remove('groups');
        return count($del_attrs['member']);
    }
@@ -1322,17 +1395,21 @@
        if (!$this->groups)
            return array();
        $base_dn = $this->groups_base_dn;
        $contact_dn = base64_decode($contact_id);
        $filter = strtr("(member=$contact_dn)", array('\\' => '\\\\'));
        $base_dn     = $this->groups_base_dn;
        $contact_dn  = self::dn_decode($contact_id);
        $name_attr   = $this->prop['groups']['name_attr'];
        $member_attr = $this->prop['member_attr'];
        $add_filter  = '';
        if ($member_attr != 'member' && $member_attr != 'uniqueMember')
            $add_filter = "($member_attr=$contact_dn)";
        $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
        $this->_debug("C: Search [$filter][dn: $base_dn]");
        $res = ldap_search($this->conn, $base_dn, $filter, array('cn'));
        $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
        if ($res === false)
        {
            $this->_debug("S: ".ldap_error($this->conn));
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return array();
        }
        $ldap_data = ldap_get_entries($this->conn, $res);
@@ -1341,8 +1418,8 @@
        $groups = array();
        for ($i=0; $i<$ldap_data["count"]; $i++)
        {
            $group_name = $ldap_data[$i]['cn'][0];
            $group_id = base64_encode($group_name);
            $group_name = $ldap_data[$i][$name_attr][0];
            $group_id = self::dn_encode($group_name);
            $groups[$group_id] = $group_id;
        }
        return $groups;
@@ -1401,7 +1478,7 @@
    /**
     * create ber encoding for sort control
     *
     * @pararm array List of cols to sort by
     * @param array List of cols to sort by
     * @return string BER encoded option value
     */
    private function _sort_ber_encode($sortcols)
@@ -1455,11 +1532,38 @@
    /**
     * Returns ascii string encoded in hex
     */
    private static function _string2hex($str) {
    private static function _string2hex($str)
    {
        $hex = '';
        for ($i=0; $i < strlen($str); $i++)
            $hex .= dechex(ord($str[$i]));
        return $hex;
    }
    /**
     * HTML-safe DN string encoding
     *
     * @param string $str DN string
     *
     * @return string Encoded HTML identifier string
     */
    static function dn_encode($str)
    {
        // @TODO: to make output string shorter we could probably
        //        remove dc=* items from it
        return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
    }
    /**
     * Decodes DN string encoded with _dn_encode()
     *
     * @param string $str Encoded HTML identifier string
     *
     * @return string DN string
     */
    static function dn_decode($str)
    {
        $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
        return base64_decode($str);
    }
}