From 305b366bb0cc425e7feb817aca342b95fb17a716 Mon Sep 17 00:00:00 2001
From: alecpl <alec@alec.pl>
Date: Tue, 15 Nov 2011 04:22:13 -0500
Subject: [PATCH] - Fix commit r5424 + preformance microoptimizations

---
 program/include/rcube_ldap.php |  152 ++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 128 insertions(+), 24 deletions(-)

diff --git a/program/include/rcube_ldap.php b/program/include/rcube_ldap.php
index 1f03e15..e308ffd 100644
--- a/program/include/rcube_ldap.php
+++ b/program/include/rcube_ldap.php
@@ -107,7 +107,7 @@
             list($col, $type) = explode(':', $col);
             if (!is_array($this->coltypes[$col])) {
                 $subtypes = $type ? array($type) : null;
-                $this->coltypes[$col] = array('limit' => 2, 'subtypes' => $subtypes);
+                $this->coltypes[$col] = array('limit' => 1, 'subtypes' => $subtypes);
             }
             elseif ($type) {
                 $this->coltypes[$col]['subtypes'][] = $type;
@@ -117,8 +117,16 @@
                 $this->fieldmap[$col] = $lf;
         }
 
-        if ($this->fieldmap['street'] && $this->fieldmap['locality'])
-            $this->coltypes['address'] = array('limit' => 1);
+        // support for composite address
+        if ($this->fieldmap['street'] && $this->fieldmap['locality']) {
+            $this->coltypes['address'] = array('limit' => max(1, $this->coltypes['locality']['limit']), 'subtypes' => $this->coltypes['locality']['subtypes'], 'childs' => array());
+            foreach (array('street','locality','zipcode','region','country') as $childcol) {
+                if ($this->fieldmap[$childcol]) {
+                    $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
+                    unset($this->coltypes[$childcol]);  // remove address child col from global coltypes list
+                }
+            }
+        }
         else if ($this->coltypes['address'])
             $this->coltypes['address'] = array('type' => 'textarea', 'childs' => null, 'limit' => 1, 'size' => 40);
 
@@ -181,6 +189,9 @@
                 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
                 $this->prop['host'] = $host;
                 $this->conn = $lc;
+
+                if (isset($this->prop['referrals']))
+                    ldap_set_option($lc, LDAP_OPT_REFERRALS, $this->prop['referrals']);
                 break;
             }
             $this->_debug("S: NOT OK");
@@ -687,15 +698,20 @@
      *
      * @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 int     $mode     Matching mode:
+     *                          0 - partial (*abc*),
+     *                          1 - strict (=),
+     *                          2 - prefix (abc*)
      * @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())
+    function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
     {
+        $mode = intval($mode);
+
         // special treatment for ID-based search
         if ($fields == 'ID' || $fields == $this->primary_key)
         {
@@ -712,9 +728,62 @@
             return $result;
         }
 
+        // use VLV pseudo-search for autocompletion
+        if ($this->prop['vlv_search'] && $this->conn && join(',', (array)$fields) == 'email,name')
+        {
+            // add general filter to query
+            if (!empty($this->prop['filter']) && empty($this->filter))
+                $this->set_search_set($this->prop['filter']);
+
+            // set VLV controls with encoded search string
+            $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size, $value);
+
+            $function = $this->_scope2func($this->prop['scope']);
+            $this->ldap_result = @$function($this->conn, $this->base_dn, $this->filter ? $this->filter : '(objectclass=*)',
+                array_values($this->fieldmap), 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']);
+
+            // get all entries of this page and post-filter those that really match the query
+            $search = mb_strtolower($value);
+            $this->result = new rcube_result_set(0);
+            $entries = ldap_get_entries($this->conn, $this->ldap_result);
+
+            for ($i = 0; $i < $entries['count']; $i++) {
+                $rec = $this->_ldap2result($entries[$i]);
+                foreach (array('email', 'name') as $f) {
+                    $val = mb_strtolower($rec[$f]);
+                    switch ($mode) {
+                    case 1:
+                        $got = ($val == $search);
+                        break;
+                    case 2:
+                        $got = ($search == substr($val, 0, strlen($search)));
+                        break;
+                    default:
+                        $got = (strpos($val, $search) !== false);
+                        break;
+                    }
+
+                    if ($got) {
+                        $this->result->add($rec);
+                        $this->result->count++;
+                        break;
+                    }
+                }
+            }
+
+            return $this->result;
+        }
+
         // use AND operator for advanced searches
         $filter = is_array($value) ? '(&' : '(|';
-        $wc     = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
+        // set wildcards
+        $wp = $ws = '';
+        if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
+            $ws = '*';
+            if (!$mode) {
+                $wp = '*';
+            }
+        }
 
         if ($fields == '*')
         {
@@ -728,7 +797,7 @@
             if (is_array($this->prop['search_fields']))
             {
                 foreach ($this->prop['search_fields'] as $field) {
-                    $filter .= "($field=$wc" . $this->_quote_string($value) . "$wc)";
+                    $filter .= "($field=$wp" . $this->_quote_string($value) . "$ws)";
                 }
             }
         }
@@ -737,7 +806,7 @@
             foreach ((array)$fields as $idx => $field) {
                 $val = is_array($value) ? $value[$idx] : $value;
                 if ($f = $this->_map_field($field)) {
-                    $filter .= "($f=$wc" . $this->_quote_string($val) . "$wc)";
+                    $filter .= "($f=$wp" . $this->_quote_string($val) . "$ws)";
                 }
             }
         }
@@ -1151,7 +1220,7 @@
                         $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
+                else if (!function_exists('ldap_parse_virtuallist_control'))  // ...or by fetching all records dn and count them
                     $this->vlv_count = $this->_exec_search(true);
 
                 $this->vlv_active = $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size);
@@ -1162,9 +1231,17 @@
             if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
                 $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']))
             {
+                // when running on a patched PHP we can use the extended functions to retrieve the total count from the LDAP search result
+                if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control') &&
+                    ldap_parse_result($this->conn, $this->ldap_result, $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)) {
+                    ldap_parse_virtuallist_control($this->conn, $serverctrls, $last_offset, $this->vlv_count, $vresult);
+                    $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$this->vlv_count");
+                }
+
                 $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
                 if ($err = ldap_errno($this->conn))
                     $this->_debug("S: Error: " .ldap_err2str($err));
+
                 return $count ? ldap_count_entries($this->conn, $this->ldap_result) : true;
             }
             else
@@ -1200,10 +1277,10 @@
     /**
      * Set server controls for Virtual List View (paginated listing)
      */
-    private function _vlv_set_controls($prop, $list_page, $page_size)
+    private function _vlv_set_controls($prop, $list_page, $page_size, $search = null)
     {
         $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$prop['sort']));
-        $vlv_ctrl  = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($list_page-1) * $page_size + 1), $page_size), 'iscritical' => true);
+        $vlv_ctrl  = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($list_page-1) * $page_size + 1), $page_size, $search), 'iscritical' => true);
 
         $sort = (array)$prop['sort'];
         $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ($sort[0]);"
@@ -1311,6 +1388,18 @@
 
 
     /**
+     * Activate/deactivate debug mode
+     *
+     * @param boolean $dbg True if LDAP commands should be logged
+     * @access public
+     */
+    function set_debug($dbg = true)
+    {
+        $this->debug = $dbg;
+    }
+
+
+    /**
      * Quotes attribute value string
      *
      * @param string $str Attribute value
@@ -1374,9 +1463,9 @@
 
         $groups = array();
         if ($search) {
-            $search = strtolower($search);
+            $search = mb_strtolower($search);
             foreach ($group_cache as $group) {
-                if (strstr(strtolower($group['name']), $search))
+                if (strpos(mb_strtolower($group['name']), $search) !== false)
                     $groups[] = $group;
             }
         }
@@ -1452,7 +1541,7 @@
                     $groups[$group_id]['email'][] = $ldap_data[$i][$email_attr][$j];
             }
 
-            $group_sortnames[] = strtolower($ldap_data[$i][$sort_attr][0]);
+            $group_sortnames[] = mb_strtolower($ldap_data[$i][$sort_attr][0]);
         }
 
         // recursive call can exit here
@@ -1719,7 +1808,7 @@
      * @param integer Records per page
      * @return string BER encoded option value
      */
-    private function _vlv_ber_encode($offset, $rpp)
+    private function _vlv_ber_encode($offset, $rpp, $search = '')
     {
         # this string is ber-encoded, php will prefix this value with:
         # 04 (octet string) and 10 (length of 16 bytes)
@@ -1730,6 +1819,12 @@
         # a0 = type context-specific/constructed with a length of 06 (6) bytes following
         # 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
         # 02 = type integer with 2 bytes following (contentCount):  01 00
+        
+        # whith a search string present:
+        # 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
+        # 81 indicates a user string is present where as a a0 indicates just a offset search
+        # 81 = type context-specific/constructed with a length of 06 (6) bytes following
+        
         # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
         # encoding of integer values (note: these values are in
         # two-complement form so since offset will never be negative bit 8 of the
@@ -1739,18 +1834,27 @@
         # of the second (to the left of first octet) octet:
         # a) shall not all be ones; and
         # b) shall not all be zero
+        
+        if ($search)
+        {
+            $search = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
+            $ber_val = self::_string2hex($search);
+            $str = self::_ber_addseq($ber_val, '81');
+        }
+        else
+        {
+            # construct the string from right to left
+            $str = "020100"; # contentCount
 
-        # construct the string from right to left
-        $str = "020100"; # contentCount
+            $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
 
-        $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
+            // calculate octet length of $ber_val
+            $str = self::_ber_addseq($ber_val, '02') . $str;
 
-        // calculate octet length of $ber_val
-        $str = self::_ber_addseq($ber_val, '02') . $str;
-
-        // now compute length over $str
-        $str = self::_ber_addseq($str, 'a0');
-
+            // now compute length over $str
+            $str = self::_ber_addseq($str, 'a0');
+        }
+        
         // now tack on records per page
         $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;
 

--
Gitblit v1.9.1