alecpl
2011-09-19 9eeb14699f8f9bc2904fde07e967fb458664c85c
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$
@@ -113,7 +115,7 @@
        foreach ($this->prop['required_fields'] as $key => $val)
            $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
        $this->sort_col = $p['sort'];
        $this->sort_col = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
        $this->debug = $debug;
        $this->mail_domain = $mail_domain;
@@ -181,8 +183,11 @@
                }
                // Get the pieces needed for variable replacement.
                $fu = $RCMAIL->user->get_username();
                list($u, $d) = explode('@', $fu);
                if ($fu = $RCMAIL->user->get_username())
                  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);
@@ -217,13 +222,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);
                }
            }
        }
@@ -248,7 +253,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;
@@ -292,13 +297,14 @@
    /**
    * Bind connection with DN and password
    *
    * @param string Bind DN
    * @param string Bind password
    * @return boolean True on success, False on error
    */
    private function _bind($dn, $pass)
     * Bind connection with DN and password
     *
     * @param string Bind DN
     * @param string Bind password
     *
     * @return boolean True on success, False on error
     */
    public function bind($dn, $pass)
    {
        if (!$this->conn) {
            return false;
@@ -324,8 +330,8 @@
    /**
    * Close connection to LDAP server
    */
     * Close connection to LDAP server
     */
    function close()
    {
        if ($this->conn)
@@ -338,11 +344,21 @@
    /**
    * Set internal list page
    *
    * @param  number  Page number to list
    * @access public
    */
     * Returns address book name
     *
     * @return string Address book name
     */
    function get_name()
    {
        return $this->prop['name'];
    }
    /**
     * Set internal list page
     *
     * @param number $page Page number to list
     */
    function set_page($page)
    {
        $this->list_page = (int)$page;
@@ -350,11 +366,10 @@
    /**
    * Set internal page size
    *
    * @param  number  Number of messages to display on one page
    * @access public
    */
     * Set internal page size
     *
     * @param number $size Number of messages to display on one page
     */
    function set_pagesize($size)
    {
        $this->page_size = (int)$size;
@@ -362,10 +377,10 @@
    /**
    * Save a search string for future listings
    *
    * @param string Filter string
    */
     * Save a search string for future listings
     *
     * @param string $filter Filter string
     */
    function set_search_set($filter)
    {
        $this->filter = $filter;
@@ -373,10 +388,10 @@
    /**
    * Getter for saved search properties
    *
    * @return mixed Search properties used by this class
    */
     * Getter for saved search properties
     *
     * @return mixed Search properties used by this class
     */
    function get_search_set()
    {
        return $this->filter;
@@ -384,8 +399,8 @@
    /**
    * Reset all saved results and search parameters
    */
     * Reset all saved results and search parameters
     */
    function reset()
    {
        $this->result = null;
@@ -395,12 +410,13 @@
    /**
    * List the current set of contact records
    *
    * @param  array  List of cols to show
    * @param  int    Only return this number of records
    * @return array  Indexed list of contact records, each a hash array
    */
     * List the current set of contact records
     *
     * @param  array  List of cols to show
     * @param  int    Only return this number of records
     *
     * @return array  Indexed list of contact records, each a hash array
     */
    function list_records($cols=null, $subset=0)
    {
        // add general filter to query
@@ -420,50 +436,57 @@
        // we have a search result resource
        if ($this->ldap_result && $this->result->count > 0)
        {
            // sorting still on the ldap server
            if ($this->sort_col && $this->prop['scope'] !== 'base' && !$this->vlv_active)
                ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
            // start and end of the page
            $start_row = $this->vlv_active ? 0 : $this->result->first;
            $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
            $last_row = $this->result->first + $this->page_size;
            $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
            // get all entries from the ldap server
            $entries = ldap_get_entries($this->conn, $this->ldap_result);
            // filtering for group members
            if ($this->groups and $this->group_id)
            {
                $count = 0;
                $members = array();
                foreach ($entries as $entry)
                {
                    if ($this->group_members[self::dn_encode($entry['dn'])])
                    {
                        $members[] = $entry;
                        $count++;
                    }
                }
                $entries = $members;
                $entries['count'] = $count;
                $this->result->count = $count;
            }
            // filter entries for this page
            for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
                $this->result->add($this->_ldap2result($entries[$i]));
        }
        // temp hack for filtering group members
        if ($this->groups and $this->group_id)
        {
            $result = new rcube_result_set();
            while ($record = $this->result->iterate())
            {
                if ($this->group_members[$record['ID']])
                {
                    $result->add($record);
                    $result->count++;
                }
            }
            $this->result = $result;
        }
        return $this->result;
    }
    /**
    * Search contacts
    *
    * @param mixed   $fields   The field name of array of field names to search in
    * @param mixed   $value    Search value (or array of values when $fields is array)
    * @param boolean $strict   True for strict, False for partial (fuzzy) matching
    * @param boolean $select   True if results are requested, False if count only
    * @param boolean $nocount  (Not used)
    * @param array   $required List of fields that cannot be empty
    *
    * @return array  Indexed list of contact records and 'count' value
    */
     * Search contacts
     *
     * @param mixed   $fields   The field name of array of field names to search in
     * @param mixed   $value    Search value (or array of values when $fields is array)
     * @param boolean $strict   True for strict, False for partial (fuzzy) matching
     * @param boolean $select   True if results are requested, False if count only
     * @param boolean $nocount  (Not used)
     * @param array   $required List of fields that cannot be empty
     *
     * @return array  Indexed list of contact records and 'count' value
     */
    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
    {
        // special treatment for ID-based search
@@ -543,10 +566,10 @@
    /**
    * Count number of available contacts in database
    *
    * @return object rcube_result_set Resultset with values for 'count' and 'first'
    */
     * Count number of available contacts in database
     *
     * @return object rcube_result_set Resultset with values for 'count' and 'first'
     */
    function count()
    {
        $count = 0;
@@ -570,10 +593,10 @@
    /**
    * Return the last result set
    *
    * @return object rcube_result_set Current resultset or NULL if nothing selected yet
    */
     * Return the last result set
     *
     * @return object rcube_result_set Current resultset or NULL if nothing selected yet
     */
    function get_result()
    {
        return $this->result;
@@ -581,18 +604,19 @@
    /**
    * Get a specific contact record
    *
    * @param mixed   Record identifier
    * @param boolean Return as associative array
    * @return mixed  Hash array or rcube_result_set with all record fields
    */
     * Get a specific contact record
     *
     * @param mixed   Record identifier
     * @param boolean Return as associative array
     *
     * @return mixed  Hash array or rcube_result_set with all record fields
     */
    function get_record($dn, $assoc=false)
    {
        $res = null;
        if ($this->conn && $dn)
        {
            $dn = base64_decode($dn);
            $dn = self::dn_decode($dn);
            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
@@ -624,6 +648,7 @@
     * If input not valid, the message to display can be fetched using get_error()
     *
     * @param array Assoziative array with data to save
     *
     * @return boolean True if input is valid, False if not.
     */
    public function validate($save_data)
@@ -633,18 +658,19 @@
            $this->set_error('warning', 'nonamewarning');
            return false;
        }
        // validate e-mail addresses
        return parent::validate($save_data);
    }
    /**
    * Create a new contact record
    *
    * @param array    Hash array with save data
    * @return encoded record ID on success, False on error
    */
     * Create a new contact record
     *
     * @param array    Hash array with save data
     *
     * @return encoded record ID on success, False on error
     */
    function insert($save_cols)
    {
        // Map out the column names to their LDAP ones to build the new entry.
@@ -661,8 +687,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;
            }
@@ -689,21 +715,24 @@
        $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;
    }
    /**
    * Update a specific contact record
    *
    * @param mixed Record identifier
    * @param array Hash array with save data
    * @return boolean True on success, False on error
    */
     * Update a specific contact record
     *
     * @param mixed Record identifier
     * @param array Hash array with save data
     *
     * @return boolean True on success, False on error
     */
    function update($id, $save_cols)
    {
        $record = $this->get_record($id, true);
@@ -713,6 +742,16 @@
        $newdata = array();
        $replacedata = array();
        $deletedata = array();
        // flatten composite fields in $record
        if (is_array($record['address'])) {
          foreach ($record['address'] as $i => $struct) {
            foreach ($struct as $col => $val) {
              $record[$col][$i] = $val;
            }
          }
        }
        foreach ($this->fieldmap as $col => $fld) {
            $val = $save_cols[$col];
            if ($fld) {
@@ -741,7 +780,7 @@
            } // end if
        } // end foreach
        $dn = base64_decode($id);
        $dn = self::dn_decode($id);
        // Update the entry as required.
        if (!empty($deletedata)) {
@@ -798,17 +837,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;
@@ -816,20 +859,22 @@
    /**
    * Mark one or more contact records as deleted
    *
    * @param array  Record identifiers
    * @return boolean True on success, False on error
    */
    function delete($ids)
     * Mark one or more contact records as deleted
     *
     * @param array   Record identifiers
     * @param boolean Remove record(s) irreversible (unsupported)
     *
     * @return boolean True on success, False on error
     */
    function delete($ids, $force=true)
    {
        if (!is_array($ids)) {
            // Not an array, break apart the encoded DNs.
            $dns = explode(',', $ids);
            $ids = explode(',', $ids);
        } // end if
        foreach ($dns as $id) {
            $dn = base64_decode($id);
        foreach ($ids as $id) {
            $dn = self::dn_decode($id);
            $this->_debug("C: Delete [dn: $dn]");
            // Delete the record.
            $res = ldap_delete($this->conn, $dn);
@@ -841,25 +886,22 @@
            $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
        return count($dns);
        return count($ids);
    }
    /**
    * Execute the LDAP search based on the stored credentials
    *
    * @access private
    */
     * Execute the LDAP search based on the stored credentials
     */
    private function _exec_search($count = false)
    {
        if ($this->ready)
@@ -867,12 +909,20 @@
            $filter = $this->filter ? $this->filter : '(objectclass=*)';
            $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
            $this->_debug("C: Search [".$filter."]");
            $this->_debug("C: Search [$filter]");
            // when using VLV, we need to issue listing command first in order to get the full count
            // when using VLV, we get the total count by...
            if (!$count && $function != 'ldap_read' && $this->prop['vlv']) {
                if ($this->_exec_search(true))
                    $this->vlv_count = ldap_count_entries($this->conn, $this->ldap_result);
                // ...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);
                    for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
                        $this->vlv_count += $counts[$j]['numsubordinates'][0];
                    $this->_debug("D: total numsubordinates = " . $this->vlv_count);
                }
                else  // ...or by fetching all records dn and count them
                    $this->vlv_count = $this->_exec_search(true);
                $this->vlv_active = $this->_vlv_set_controls();
            }
@@ -894,13 +944,13 @@
        return false;
    }
    /**
     * Set server controls for Virtual List View (paginated listing)
     */
    private function _vlv_set_controls()
    {
        $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode(array($this->sort_col)));
        $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$this->prop['sort']));
        $vlv_ctrl  = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($this->list_page-1) * $this->page_size + 1), $this->page_size), 'iscritical' => true);
        $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ({$this->sort_col});"
@@ -917,14 +967,14 @@
    /**
    * @access private
    */
     * Converts LDAP entry into an array
     */
    private function _ldap2result($rec)
    {
        $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)
        {
@@ -947,8 +997,8 @@
    /**
    * @access private
    */
     * Return real field name (from fields map)
     */
    private function _map_field($field)
    {
        return $this->fieldmap[$field];
@@ -956,9 +1006,9 @@
    /**
    * @access private
    */
    private function _attr_name($name)
     * Returns unified attribute name (resolving aliases)
     */
    private static function _attr_name($name)
    {
        // list of known attribute aliases
        $aliases = array(
@@ -973,8 +1023,8 @@
    /**
    * @access private
    */
     * Prints debug info to the log
     */
    private function _debug($str)
    {
        if ($this->debug)
@@ -983,9 +1033,14 @@
    /**
    * @static
    */
    private function _quote_string($str, $dn=false)
     * Quotes attribute value string
     *
     * @param string $str Attribute value
     * @param bool   $dn  True if the attribute is a DN
     *
     * @return string Quoted string
     */
    private static function _quote_string($str, $dn=false)
    {
        // take firt entry if array given
        if (is_array($str))
@@ -1016,9 +1071,10 @@
            $cache_members = $this->group_cache[$group_id]['members'];
            $members = array();
            for ($i=1; $i<$cache_members["count"]; $i++)
            for ($i=0; $i<$cache_members["count"]; $i++)
            {
                $members[base64_encode($cache_members[$i])] = 1;
                if (!empty($cache_members[$i]))
                    $members[self::dn_encode($cache_members[$i])] = 1;
            }
            $this->group_members = $members;
            $this->group_id = $group_id;
@@ -1051,11 +1107,13 @@
            $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);;
            $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
        }
        $base_dn = $this->groups_base_dn;
        $filter = $this->prop['groups']['filter'];
        $this->_debug("C: Search [$filter][dn: $base_dn]");
        $res = ldap_search($this->conn, $base_dn, $filter, array('cn','member'));
        if ($res === false)
@@ -1064,18 +1122,23 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return array();
        }
        $ldap_data = ldap_get_entries($this->conn, $res);
        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
        $groups = array();
        $group_sortnames = array();
        for ($i=0; $i<$ldap_data["count"]; $i++)
        {
            $group_name = $ldap_data[$i]['cn'][0];
            $group_id = base64_encode($group_name);
            $groups[$group_id]['ID'] = $group_id;
            $groups[$group_id]['name'] = $group_name;
            $groups[$group_id]['members'] = $ldap_data[$i]['member'];
            $group_sortnames[] = strtolower($group_name);
            if (!$search || strstr(strtolower($group_name), strtolower($search)))
            {
                $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'];
                $group_sortnames[] = strtolower($group_name);
            }
        }
        array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
        $this->group_cache = $groups;
@@ -1096,13 +1159,15 @@
        $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);
        $new_entry = array(
            'objectClass' => $this->prop['groups']['object_classes'],
            'cn' => $group_name,
            'member' => '',
        );
        $this->_debug("C: Add [dn: $new_dn]: ".print_r($new_entry, true));
        $res = ldap_add($this->conn, $new_dn, $new_entry);
        if ($res === false)
@@ -1111,6 +1176,9 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return false;
        }
        $this->_debug("S: OK");
        return array('id' => $new_gid, 'name' => $group_name);
    }
@@ -1127,8 +1195,10 @@
        $base_dn = $this->groups_base_dn;
        $group_name = $this->group_cache[$group_id]['name'];
        $del_dn = "cn=$group_name,$base_dn";
        $this->_debug("C: Delete [dn: $del_dn]");
        $res = ldap_delete($this->conn, $del_dn);
        if ($res === false)
        {
@@ -1136,6 +1206,9 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return false;
        }
        $this->_debug("S: OK");
        return true;
    }
@@ -1156,7 +1229,9 @@
        $group_name = $this->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]");
        $res = ldap_rename($this->conn, $old_dn, $new_rdn, NULL, TRUE);
        if ($res === false)
@@ -1165,6 +1240,9 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return false;
        }
        $this->_debug("S: OK");
        return $new_name;
    }
@@ -1186,7 +1264,9 @@
        $new_attrs = array();
        foreach (explode(",", $contact_ids) as $id)
            $new_attrs['member'][] = base64_decode($id);
            $new_attrs['member'][] = self::dn_decode($id);
        $this->_debug("C: Add [dn: $group_dn]: ".print_r($new_attrs, true));
        $res = ldap_mod_add($this->conn, $group_dn, $new_attrs);
        if ($res === false)
@@ -1195,6 +1275,9 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return 0;
        }
        $this->_debug("S: OK");
        return count($new_attrs['member']);
    }
@@ -1216,7 +1299,9 @@
        $del_attrs = array();
        foreach (explode(",", $contact_ids) as $id)
            $del_attrs['member'][] = base64_decode($id);
            $del_attrs['member'][] = self::dn_decode($id);
        $this->_debug("C: Delete [dn: $group_dn]: ".print_r($del_attrs, true));
        $res = ldap_mod_del($this->conn, $group_dn, $del_attrs);
        if ($res === false)
@@ -1225,6 +1310,9 @@
            $this->set_error(self::ERROR_SAVING, 'errorsaving');
            return 0;
        }
        $this->_debug("S: OK");
        return count($del_attrs['member']);
    }
@@ -1242,8 +1330,10 @@
            return array();
        $base_dn = $this->groups_base_dn;
        $contact_dn = base64_decode($contact_id);
        $filter = "(member=$contact_dn)";
        $contact_dn = self::dn_decode($contact_id);
        $filter = strtr("(member=$contact_dn)", array('\\' => '\\\\'));
        $this->_debug("C: Search [$filter][dn: $base_dn]");
        $res = ldap_search($this->conn, $base_dn, $filter, array('cn'));
        if ($res === false)
@@ -1253,12 +1343,13 @@
            return array();
        }
        $ldap_data = ldap_get_entries($this->conn, $res);
        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
        $groups = array();
        for ($i=0; $i<$ldap_data["count"]; $i++)
        {
            $group_name = $ldap_data[$i]['cn'][0];
            $group_id = base64_encode($group_name);
            $group_id = self::dn_encode($group_name);
            $groups[$group_id] = $group_id;
        }
        return $groups;
@@ -1295,7 +1386,7 @@
        # construct the string from right to left
        $str = "020100"; # contentCount
        $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
        // calculate octet length of $ber_val
@@ -1317,7 +1408,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)
@@ -1357,7 +1448,7 @@
    {
        $val = dechex($offset);
        $prefix = '';
        // check if bit 8 of high byte is 1
        if (preg_match('/^[89abcdef]/', $val))
            $prefix = '00';
@@ -1371,11 +1462,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);
    }
}