source: subversion/trunk/roundcubemail/program/include/rcube_ldap.php @ 6047

Last change on this file since 6047 was 6047, checked in by alec, 14 months ago
  • Improved validation and forced RDN in required_fields (#1488254)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 73.1 KB
Line 
1<?php
2/*
3 +-----------------------------------------------------------------------+
4 | program/include/rcube_ldap.php                                        |
5 |                                                                       |
6 | This file is part of the Roundcube Webmail client                     |
7 | Copyright (C) 2006-2012, The Roundcube Dev Team                       |
8 | Copyright (C) 2011, Kolab Systems AG                                  |
9 |                                                                       |
10 | Licensed under the GNU General Public License version 3 or            |
11 | any later version with exceptions for skins & plugins.                |
12 | See the README file for a full license statement.                     |
13 |                                                                       |
14 | PURPOSE:                                                              |
15 |   Interface to an LDAP address directory                              |
16 |                                                                       |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19 |         Andreas Dick <andudi (at) gmx (dot) ch>                       |
20 |         Aleksander Machniak <machniak@kolabsys.com>                   |
21 +-----------------------------------------------------------------------+
22
23 $Id$
24
25*/
26
27
28/**
29 * Model class to access an LDAP address directory
30 *
31 * @package Addressbook
32 */
33class rcube_ldap extends rcube_addressbook
34{
35    /** public properties */
36    public $primary_key = 'ID';
37    public $groups = false;
38    public $readonly = true;
39    public $ready = false;
40    public $group_id = 0;
41    public $coltypes = array();
42
43    /** private properties */
44    protected $conn;
45    protected $prop = array();
46    protected $fieldmap = array();
47    protected $sub_filter;
48    protected $filter = '';
49    protected $result = null;
50    protected $ldap_result = null;
51    protected $mail_domain = '';
52    protected $debug = false;
53
54    private $base_dn = '';
55    private $groups_base_dn = '';
56    private $group_url = null;
57    private $cache;
58
59    private $vlv_active = false;
60    private $vlv_count = 0;
61
62
63    /**
64    * Object constructor
65    *
66    * @param array          LDAP connection properties
67    * @param boolean    Enables debug mode
68    * @param string     Current user mail domain name
69    * @param integer User-ID
70    */
71    function __construct($p, $debug=false, $mail_domain=NULL)
72    {
73        $this->prop = $p;
74
75        if (isset($p['searchonly']))
76            $this->searchonly = $p['searchonly'];
77
78        // check if groups are configured
79        if (is_array($p['groups']) && count($p['groups'])) {
80            $this->groups = true;
81            // set member field
82            if (!empty($p['groups']['member_attr']))
83                $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
84            else if (empty($p['member_attr']))
85                $this->prop['member_attr'] = 'member';
86            // set default name attribute to cn
87            if (empty($this->prop['groups']['name_attr']))
88                $this->prop['groups']['name_attr'] = 'cn';
89            if (empty($this->prop['groups']['scope']))
90                $this->prop['groups']['scope'] = 'sub';
91        }
92
93        // fieldmap property is given
94        if (is_array($p['fieldmap'])) {
95            foreach ($p['fieldmap'] as $rf => $lf)
96                $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
97        }
98        else if (!empty($p)) {
99            // read deprecated *_field properties to remain backwards compatible
100            foreach ($p as $prop => $value)
101                if (preg_match('/^(.+)_field$/', $prop, $matches))
102                    $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
103        }
104
105        // use fieldmap to advertise supported coltypes to the application
106        foreach ($this->fieldmap as $col => $lf) {
107            list($col, $type) = explode(':', $col);
108            if (!is_array($this->coltypes[$col])) {
109                $subtypes = $type ? array($type) : null;
110                $this->coltypes[$col] = array('limit' => 1, 'subtypes' => $subtypes);
111            }
112            elseif ($type) {
113                $this->coltypes[$col]['subtypes'][] = $type;
114                $this->coltypes[$col]['limit']++;
115            }
116            if ($type && !$this->fieldmap[$col])
117                $this->fieldmap[$col] = $lf;
118        }
119
120        // support for composite address
121        if ($this->fieldmap['street'] && $this->fieldmap['locality']) {
122            $this->coltypes['address'] = array('limit' => max(1, $this->coltypes['locality']['limit']), 'subtypes' => $this->coltypes['locality']['subtypes'], 'childs' => array());
123            foreach (array('street','locality','zipcode','region','country') as $childcol) {
124                if ($this->fieldmap[$childcol]) {
125                    $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
126                    unset($this->coltypes[$childcol]);  // remove address child col from global coltypes list
127                }
128            }
129        }
130        else if ($this->coltypes['address']) {
131            $this->coltypes['address'] = array('type' => 'textarea', 'childs' => null, 'limit' => 1, 'size' => 40);
132        }
133
134        // make sure 'required_fields' is an array
135        if (!is_array($this->prop['required_fields'])) {
136            $this->prop['required_fields'] = (array) $this->prop['required_fields'];
137        }
138
139        // make sure LDAP_rdn field is required
140        if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])) {
141            $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
142        }
143
144        foreach ($this->prop['required_fields'] as $key => $val) {
145            $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
146        }
147
148        // Build sub_fields filter
149        if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
150            $this->sub_filter = '';
151            foreach ($this->prop['sub_fields'] as $attr => $class) {
152                if (!empty($class)) {
153                    $class = is_array($class) ? array_pop($class) : $class;
154                    $this->sub_filter .= '(objectClass=' . $class . ')';
155                }
156            }
157            if (count($this->prop['sub_fields']) > 1) {
158                $this->sub_filter = '(|' . $this->sub_filter . ')';
159            }
160        }
161
162        $this->sort_col    = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
163        $this->debug       = $debug;
164        $this->mail_domain = $mail_domain;
165
166        // initialize cache
167        $rcmail = rcmail::get_instance();
168        $this->cache = $rcmail->get_cache('LDAP.' . asciiwords($this->prop['name']), 'db', 600);
169
170        $this->_connect();
171    }
172
173
174    /**
175    * Establish a connection to the LDAP server
176    */
177    private function _connect()
178    {
179        global $RCMAIL;
180
181        if (!function_exists('ldap_connect'))
182            raise_error(array('code' => 100, 'type' => 'ldap',
183                'file' => __FILE__, 'line' => __LINE__,
184                'message' => "No ldap support in this installation of PHP"),
185                true, true);
186
187        if (is_resource($this->conn))
188            return true;
189
190        if (!is_array($this->prop['hosts']))
191            $this->prop['hosts'] = array($this->prop['hosts']);
192
193        if (empty($this->prop['ldap_version']))
194            $this->prop['ldap_version'] = 3;
195
196        foreach ($this->prop['hosts'] as $host)
197        {
198            $host     = idn_to_ascii(rcube_parse_host($host));
199            $hostname = $host.($this->prop['port'] ? ':'.$this->prop['port'] : '');
200
201            $this->_debug("C: Connect [$hostname] [{$this->prop['name']}]");
202
203            if ($lc = @ldap_connect($host, $this->prop['port']))
204            {
205                if ($this->prop['use_tls'] === true)
206                    if (!ldap_start_tls($lc))
207                        continue;
208
209                $this->_debug("S: OK");
210
211                ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
212                $this->prop['host'] = $host;
213                $this->conn = $lc;
214
215                if (isset($this->prop['referrals']))
216                    ldap_set_option($lc, LDAP_OPT_REFERRALS, $this->prop['referrals']);
217                break;
218            }
219            $this->_debug("S: NOT OK");
220        }
221
222        // See if the directory is writeable.
223        if ($this->prop['writable']) {
224            $this->readonly = false;
225        }
226
227        if (!is_resource($this->conn)) {
228            raise_error(array('code' => 100, 'type' => 'ldap',
229                'file' => __FILE__, 'line' => __LINE__,
230                'message' => "Could not connect to any LDAP server, last tried $hostname"), true);
231
232            return false;
233        }
234
235        $bind_pass = $this->prop['bind_pass'];
236        $bind_user = $this->prop['bind_user'];
237        $bind_dn   = $this->prop['bind_dn'];
238
239        $this->base_dn        = $this->prop['base_dn'];
240        $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
241        $this->prop['groups']['base_dn'] : $this->base_dn;
242
243        // User specific access, generate the proper values to use.
244        if ($this->prop['user_specific']) {
245            // No password set, use the session password
246            if (empty($bind_pass)) {
247                $bind_pass = $RCMAIL->decrypt($_SESSION['password']);
248            }
249
250            // Get the pieces needed for variable replacement.
251            if ($fu = $RCMAIL->user->get_username())
252                list($u, $d) = explode('@', $fu);
253            else
254                $d = $this->mail_domain;
255
256            $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
257
258            $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
259
260            if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
261                if (!empty($this->prop['search_bind_dn']) && !empty($this->prop['search_bind_pw'])) {
262                    $this->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
263                }
264
265                // Search for the dn to use to authenticate
266                $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
267                $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
268
269                $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
270
271                $res = @ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
272                if ($res) {
273                    if (($entry = ldap_first_entry($this->conn, $res))
274                        && ($bind_dn = ldap_get_dn($this->conn, $entry))
275                    ) {
276                        $this->_debug("S: search returned dn: $bind_dn");
277                        $dn = ldap_explode_dn($bind_dn, 1);
278                        $replaces['%dn'] = $dn[0];
279                    }
280                }
281                else {
282                    $this->_debug("S: ".ldap_error($this->conn));
283                }
284
285                // DN not found
286                if (empty($replaces['%dn'])) {
287                    if (!empty($this->prop['search_dn_default']))
288                        $replaces['%dn'] = $this->prop['search_dn_default'];
289                    else {
290                        raise_error(array(
291                            'code' => 100, 'type' => 'ldap',
292                            'file' => __FILE__, 'line' => __LINE__,
293                            'message' => "DN not found using LDAP search."), true);
294                        return false;
295                    }
296                }
297            }
298
299            // Replace the bind_dn and base_dn variables.
300            $bind_dn              = strtr($bind_dn, $replaces);
301            $this->base_dn        = strtr($this->base_dn, $replaces);
302            $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
303
304            if (empty($bind_user)) {
305                $bind_user = $u;
306            }
307        }
308
309        if (empty($bind_pass)) {
310            $this->ready = true;
311        }
312        else {
313            if (!empty($bind_dn)) {
314                $this->ready = $this->bind($bind_dn, $bind_pass);
315            }
316            else if (!empty($this->prop['auth_cid'])) {
317                $this->ready = $this->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
318            }
319            else {
320                $this->ready = $this->sasl_bind($bind_user, $bind_pass);
321            }
322        }
323
324        return $this->ready;
325    }
326
327
328    /**
329     * Bind connection with (SASL-) user and password
330     *
331     * @param string $authc Authentication user
332     * @param string $pass  Bind password
333     * @param string $authz Autorization user
334     *
335     * @return boolean True on success, False on error
336     */
337    public function sasl_bind($authc, $pass, $authz=null)
338    {
339        if (!$this->conn) {
340            return false;
341        }
342
343        if (!function_exists('ldap_sasl_bind')) {
344            raise_error(array('code' => 100, 'type' => 'ldap',
345                'file' => __FILE__, 'line' => __LINE__,
346                'message' => "Unable to bind: ldap_sasl_bind() not exists"),
347                true, true);
348        }
349
350        if (!empty($authz)) {
351            $authz = 'u:' . $authz;
352        }
353
354        if (!empty($this->prop['auth_method'])) {
355            $method = $this->prop['auth_method'];
356        }
357        else {
358            $method = 'DIGEST-MD5';
359        }
360
361        $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz] [pass: $pass]");
362
363        if (ldap_sasl_bind($this->conn, NULL, $pass, $method, NULL, $authc, $authz)) {
364            $this->_debug("S: OK");
365            return true;
366        }
367
368        $this->_debug("S: ".ldap_error($this->conn));
369
370        raise_error(array(
371            'code' => ldap_errno($this->conn), 'type' => 'ldap',
372            'file' => __FILE__, 'line' => __LINE__,
373            'message' => "Bind failed for authcid=$authc ".ldap_error($this->conn)),
374            true);
375
376        return false;
377    }
378
379
380    /**
381     * Bind connection with DN and password
382     *
383     * @param string Bind DN
384     * @param string Bind password
385     *
386     * @return boolean True on success, False on error
387     */
388    public function bind($dn, $pass)
389    {
390        if (!$this->conn) {
391            return false;
392        }
393
394        $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
395
396        if (@ldap_bind($this->conn, $dn, $pass)) {
397            $this->_debug("S: OK");
398            return true;
399        }
400
401        $this->_debug("S: ".ldap_error($this->conn));
402
403        raise_error(array(
404            'code' => ldap_errno($this->conn), 'type' => 'ldap',
405            'file' => __FILE__, 'line' => __LINE__,
406            'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
407            true);
408
409        return false;
410    }
411
412
413    /**
414     * Close connection to LDAP server
415     */
416    function close()
417    {
418        if ($this->conn)
419        {
420            $this->_debug("C: Close");
421            ldap_unbind($this->conn);
422            $this->conn = null;
423        }
424    }
425
426
427    /**
428     * Returns address book name
429     *
430     * @return string Address book name
431     */
432    function get_name()
433    {
434        return $this->prop['name'];
435    }
436
437
438    /**
439     * Set internal sort settings
440     *
441     * @param string $sort_col Sort column
442     * @param string $sort_order Sort order
443     */
444    function set_sort_order($sort_col, $sort_order = null)
445    {
446        if ($this->fieldmap[$sort_col])
447            $this->sort_col = $this->fieldmap[$sort_col];
448    }
449
450
451    /**
452     * Save a search string for future listings
453     *
454     * @param string $filter Filter string
455     */
456    function set_search_set($filter)
457    {
458        $this->filter = $filter;
459    }
460
461
462    /**
463     * Getter for saved search properties
464     *
465     * @return mixed Search properties used by this class
466     */
467    function get_search_set()
468    {
469        return $this->filter;
470    }
471
472
473    /**
474     * Reset all saved results and search parameters
475     */
476    function reset()
477    {
478        $this->result = null;
479        $this->ldap_result = null;
480        $this->filter = '';
481    }
482
483
484    /**
485     * List the current set of contact records
486     *
487     * @param  array  List of cols to show
488     * @param  int    Only return this number of records
489     *
490     * @return array  Indexed list of contact records, each a hash array
491     */
492    function list_records($cols=null, $subset=0)
493    {
494        if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id)
495        {
496            $this->result = new rcube_result_set(0);
497            $this->result->searchonly = true;
498            return $this->result;
499        }
500
501        // fetch group members recursively
502        if ($this->group_id && $this->group_data['dn'])
503        {
504            $entries = $this->list_group_members($this->group_data['dn']);
505
506            // make list of entries unique and sort it
507            $seen = array();
508            foreach ($entries as $i => $rec) {
509                if ($seen[$rec['dn']]++)
510                    unset($entries[$i]);
511            }
512            usort($entries, array($this, '_entry_sort_cmp'));
513
514            $entries['count'] = count($entries);
515            $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
516        }
517        else
518        {
519            // add general filter to query
520            if (!empty($this->prop['filter']) && empty($this->filter))
521                $this->set_search_set($this->prop['filter']);
522
523            // exec LDAP search if no result resource is stored
524            if ($this->conn && !$this->ldap_result)
525                $this->_exec_search();
526
527            // count contacts for this user
528            $this->result = $this->count();
529
530            // we have a search result resource
531            if ($this->ldap_result && $this->result->count > 0)
532            {
533                // sorting still on the ldap server
534                if ($this->sort_col && $this->prop['scope'] !== 'base' && !$this->vlv_active)
535                    ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
536
537                // get all entries from the ldap server
538                $entries = ldap_get_entries($this->conn, $this->ldap_result);
539            }
540
541        }  // end else
542
543        // start and end of the page
544        $start_row = $this->vlv_active ? 0 : $this->result->first;
545        $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
546        $last_row = $this->result->first + $this->page_size;
547        $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
548
549        // filter entries for this page
550        for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
551            $this->result->add($this->_ldap2result($entries[$i]));
552
553        return $this->result;
554    }
555
556    /**
557     * Get all members of the given group
558     *
559     * @param string Group DN
560     * @param array  Group entries (if called recursively)
561     * @return array Accumulated group members
562     */
563    function list_group_members($dn, $count = false, $entries = null)
564    {
565        $group_members = array();
566
567        // fetch group object
568        if (empty($entries)) {
569            $result = @ldap_read($this->conn, $dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL'));
570            if ($result === false)
571            {
572                $this->_debug("S: ".ldap_error($this->conn));
573                return $group_members;
574            }
575
576            $entries = @ldap_get_entries($this->conn, $result);
577        }
578
579        for ($i=0; $i < $entries['count']; $i++)
580        {
581            $entry = $entries[$i];
582
583            if (empty($entry['objectclass']))
584                continue;
585
586            foreach ((array)$entry['objectclass'] as $objectclass)
587            {
588                switch (strtolower($objectclass)) {
589                    case "group":
590                    case "groupofnames":
591                    case "kolabgroupofnames":
592                        $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'member', $count));
593                        break;
594                    case "groupofuniquenames":
595                    case "kolabgroupofuniquenames":
596                        $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'uniquemember', $count));
597                        break;
598                    case "groupofurls":
599                        $group_members = array_merge($group_members, $this->_list_group_memberurl($dn, $entry, $count));
600                        break;
601                }
602            }
603
604            if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit'])
605              break;
606        }
607
608        return array_filter($group_members);
609    }
610
611    /**
612     * Fetch members of the given group entry from server
613     *
614     * @param string Group DN
615     * @param array  Group entry
616     * @param string Member attribute to use
617     * @return array Accumulated group members
618     */
619    private function _list_group_members($dn, $entry, $attr, $count)
620    {
621        // Use the member attributes to return an array of member ldap objects
622        // NOTE that the member attribute is supposed to contain a DN
623        $group_members = array();
624        if (empty($entry[$attr]))
625            return $group_members;
626
627        // read these attributes for all members
628        $attrib = $count ? array('dn') : array_values($this->fieldmap);
629        $attrib[] = 'objectClass';
630        $attrib[] = 'member';
631        $attrib[] = 'uniqueMember';
632        $attrib[] = 'memberURL';
633
634        for ($i=0; $i < $entry[$attr]['count']; $i++)
635        {
636            if (empty($entry[$attr][$i]))
637                continue;
638
639            $result = @ldap_read($this->conn, $entry[$attr][$i], '(objectclass=*)',
640                $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']);
641
642            $members = @ldap_get_entries($this->conn, $result);
643            if ($members == false)
644            {
645                $this->_debug("S: ".ldap_error($this->conn));
646                $members = array();
647            }
648
649            // for nested groups, call recursively
650            $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
651
652            unset($members['count']);
653            $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
654        }
655
656        return $group_members;
657    }
658
659    /**
660     * List members of group class groupOfUrls
661     *
662     * @param string Group DN
663     * @param array  Group entry
664     * @param boolean True if only used for counting
665     * @return array Accumulated group members
666     */
667    private function _list_group_memberurl($dn, $entry, $count)
668    {
669        $group_members = array();
670
671        for ($i=0; $i < $entry['memberurl']['count']; $i++)
672        {
673            // extract components from url
674            if (!preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m))
675                continue;
676
677            // add search filter if any
678            $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
679            $func = $m[2] == 'sub' ? 'ldap_search' : ($m[2] == 'base' ? 'ldap_read' : 'ldap_list');
680
681            $attrib = $count ? array('dn') : array_values($this->fieldmap);
682            if ($result = @$func($this->conn, $m[1], $filter,
683                $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
684            ) {
685                $this->_debug("S: ".ldap_count_entries($this->conn, $result)." record(s) for ".$m[1]);
686            }
687            else {
688                $this->_debug("S: ".ldap_error($this->conn));
689                return $group_members;
690            }
691
692            $entries = @ldap_get_entries($this->conn, $result);
693            for ($j = 0; $j < $entries['count']; $j++)
694            {
695                if ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count))
696                    $group_members = array_merge($group_members, $nested_group_members);
697                else
698                    $group_members[] = $entries[$j];
699            }
700        }
701
702        return $group_members;
703    }
704
705    /**
706     * Callback for sorting entries
707     */
708    function _entry_sort_cmp($a, $b)
709    {
710        return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
711    }
712
713
714    /**
715     * Search contacts
716     *
717     * @param mixed   $fields   The field name of array of field names to search in
718     * @param mixed   $value    Search value (or array of values when $fields is array)
719     * @param int     $mode     Matching mode:
720     *                          0 - partial (*abc*),
721     *                          1 - strict (=),
722     *                          2 - prefix (abc*)
723     * @param boolean $select   True if results are requested, False if count only
724     * @param boolean $nocount  (Not used)
725     * @param array   $required List of fields that cannot be empty
726     *
727     * @return array  Indexed list of contact records and 'count' value
728     */
729    function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
730    {
731        $mode = intval($mode);
732
733        // special treatment for ID-based search
734        if ($fields == 'ID' || $fields == $this->primary_key)
735        {
736            $ids = !is_array($value) ? explode(',', $value) : $value;
737            $result = new rcube_result_set();
738            foreach ($ids as $id)
739            {
740                if ($rec = $this->get_record($id, true))
741                {
742                    $result->add($rec);
743                    $result->count++;
744                }
745            }
746            return $result;
747        }
748
749        // use VLV pseudo-search for autocompletion
750        if ($this->prop['vlv_search'] && $this->conn && join(',', (array)$fields) == 'email,name')
751        {
752            // add general filter to query
753            if (!empty($this->prop['filter']) && empty($this->filter))
754                $this->set_search_set($this->prop['filter']);
755
756            // set VLV controls with encoded search string
757            $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size, $value);
758
759            $function = $this->_scope2func($this->prop['scope']);
760            $this->ldap_result = @$function($this->conn, $this->base_dn, $this->filter ? $this->filter : '(objectclass=*)',
761                array_values($this->fieldmap), 0, $this->page_size, (int)$this->prop['timelimit']);
762
763            $this->result = new rcube_result_set(0);
764
765            if (!$this->ldap_result) {
766                $this->_debug("S: ".ldap_error($this->conn));
767                return $this->result;
768            }
769
770            $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
771
772            // get all entries of this page and post-filter those that really match the query
773            $search = mb_strtolower($value);
774            $entries = ldap_get_entries($this->conn, $this->ldap_result);
775
776            for ($i = 0; $i < $entries['count']; $i++) {
777                $rec = $this->_ldap2result($entries[$i]);
778                foreach (array('email', 'name') as $f) {
779                    $val = mb_strtolower($rec[$f]);
780                    switch ($mode) {
781                    case 1:
782                        $got = ($val == $search);
783                        break;
784                    case 2:
785                        $got = ($search == substr($val, 0, strlen($search)));
786                        break;
787                    default:
788                        $got = (strpos($val, $search) !== false);
789                        break;
790                    }
791
792                    if ($got) {
793                        $this->result->add($rec);
794                        $this->result->count++;
795                        break;
796                    }
797                }
798            }
799
800            return $this->result;
801        }
802
803        // use AND operator for advanced searches
804        $filter = is_array($value) ? '(&' : '(|';
805        // set wildcards
806        $wp = $ws = '';
807        if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
808            $ws = '*';
809            if (!$mode) {
810                $wp = '*';
811            }
812        }
813
814        if ($fields == '*')
815        {
816            // search_fields are required for fulltext search
817            if (empty($this->prop['search_fields']))
818            {
819                $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
820                $this->result = new rcube_result_set();
821                return $this->result;
822            }
823            if (is_array($this->prop['search_fields']))
824            {
825                foreach ($this->prop['search_fields'] as $field) {
826                    $filter .= "($field=$wp" . $this->_quote_string($value) . "$ws)";
827                }
828            }
829        }
830        else
831        {
832            foreach ((array)$fields as $idx => $field) {
833                $val = is_array($value) ? $value[$idx] : $value;
834                if ($f = $this->_map_field($field)) {
835                    $filter .= "($f=$wp" . $this->_quote_string($val) . "$ws)";
836                }
837            }
838        }
839        $filter .= ')';
840
841        // add required (non empty) fields filter
842        $req_filter = '';
843        foreach ((array)$required as $field)
844            if ($f = $this->_map_field($field))
845                $req_filter .= "($f=*)";
846
847        if (!empty($req_filter))
848            $filter = '(&' . $req_filter . $filter . ')';
849
850        // avoid double-wildcard if $value is empty
851        $filter = preg_replace('/\*+/', '*', $filter);
852
853        // add general filter to query
854        if (!empty($this->prop['filter']))
855            $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
856
857        // set filter string and execute search
858        $this->set_search_set($filter);
859        $this->_exec_search();
860
861        if ($select)
862            $this->list_records();
863        else
864            $this->result = $this->count();
865
866        return $this->result;
867    }
868
869
870    /**
871     * Count number of available contacts in database
872     *
873     * @return object rcube_result_set Resultset with values for 'count' and 'first'
874     */
875    function count()
876    {
877        $count = 0;
878        if ($this->conn && $this->ldap_result) {
879            $count = $this->vlv_active ? $this->vlv_count : ldap_count_entries($this->conn, $this->ldap_result);
880        }
881        else if ($this->group_id && $this->group_data['dn']) {
882            $count = count($this->list_group_members($this->group_data['dn'], true));
883        }
884        else if ($this->conn) {
885            // We have a connection but no result set, attempt to get one.
886            if (empty($this->filter)) {
887                // The filter is not set, set it.
888                $this->filter = $this->prop['filter'];
889            }
890
891            $count = (int) $this->_exec_search(true);
892        }
893
894        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
895    }
896
897
898    /**
899     * Return the last result set
900     *
901     * @return object rcube_result_set Current resultset or NULL if nothing selected yet
902     */
903    function get_result()
904    {
905        return $this->result;
906    }
907
908
909    /**
910     * Get a specific contact record
911     *
912     * @param mixed   Record identifier
913     * @param boolean Return as associative array
914     *
915     * @return mixed  Hash array or rcube_result_set with all record fields
916     */
917    function get_record($dn, $assoc=false)
918    {
919        $res = $this->result = null;
920
921        if ($this->conn && $dn)
922        {
923            $dn = self::dn_decode($dn);
924
925            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
926
927            if ($ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap))) {
928                $this->_debug("S: OK");
929
930                $entry = ldap_first_entry($this->conn, $ldap_result);
931
932                if ($entry && ($rec = ldap_get_attributes($this->conn, $entry))) {
933                    $rec = array_change_key_case($rec, CASE_LOWER);
934                }
935            }
936            else {
937                $this->_debug("S: ".ldap_error($this->conn));
938            }
939
940            // Use ldap_list to get subentries like country (c) attribute (#1488123)
941            if (!empty($rec) && $this->sub_filter) {
942                if ($entries = $this->ldap_list($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
943                    foreach ($entries as $entry) {
944                        $lrec = array_change_key_case($entry, CASE_LOWER);
945                        $rec  = array_merge($lrec, $rec);
946                    }
947                }
948            }
949
950            if (!empty($rec)) {
951                // Add in the dn for the entry.
952                $rec['dn'] = $dn;
953                $res = $this->_ldap2result($rec);
954                $this->result = new rcube_result_set();
955                $this->result->add($res);
956            }
957        }
958
959        return $assoc ? $res : $this->result;
960    }
961
962
963    /**
964     * Check the given data before saving.
965     * If input not valid, the message to display can be fetched using get_error()
966     *
967     * @param array Assoziative array with data to save
968     * @param boolean Try to fix/complete record automatically
969     * @return boolean True if input is valid, False if not.
970     */
971    public function validate(&$save_data, $autofix = false)
972    {
973        // validate e-mail addresses
974        if (!parent::validate($save_data, $autofix)) {
975            return false;
976        }
977
978        // check for name input
979        if (empty($save_data['name'])) {
980            $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
981            return false;
982        }
983
984        // Verify that the required fields are set.
985        $missing = null;
986        $ldap_data = $this->_map_data($save_data);
987        foreach ($this->prop['required_fields'] as $fld) {
988            if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
989                $missing[$fld] = 1;
990            }
991        }
992
993        if ($missing) {
994            // try to complete record automatically
995            if ($autofix) {
996                $reverse_map = array_flip($this->fieldmap);
997                $name_parts  = preg_split('/[\s,.]+/', $save_data['name']);
998                $sn_field    = $this->fieldmap['surname'];
999                $fn_field    = $this->fieldmap['firstname'];
1000
1001                if ($sn_field && $missing[$sn_field]) {
1002                    $save_data['surname'] = array_pop($name_parts);
1003                    unset($missing[$sn_field]);
1004                }
1005
1006                if ($fn_field && $missing[$fn_field]) {
1007                    $save_data['firstname'] = array_shift($name_parts);
1008                    unset($missing[$fn_field]);
1009                }
1010            }
1011
1012            // TODO: generate message saying which fields are missing
1013            if (!empty($missing)) {
1014                $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
1015                return false;
1016            }
1017        }
1018
1019        return true;
1020    }
1021
1022
1023    /**
1024     * Create a new contact record
1025     *
1026     * @param array    Hash array with save data
1027     *
1028     * @return encoded record ID on success, False on error
1029     */
1030    function insert($save_cols)
1031    {
1032        // Map out the column names to their LDAP ones to build the new entry.
1033        $newentry = $this->_map_data($save_cols);
1034        $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
1035
1036        // Verify that the required fields are set.
1037        $missing = null;
1038        foreach ($this->prop['required_fields'] as $fld) {
1039            if (!isset($newentry[$fld])) {
1040                $missing[] = $fld;
1041            }
1042        }
1043
1044        // abort process if requiered fields are missing
1045        // TODO: generate message saying which fields are missing
1046        if ($missing) {
1047            $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
1048            return false;
1049        }
1050
1051        // Build the new entries DN.
1052        $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
1053
1054        // Remove attributes that need to be added separately (child objects)
1055        $xfields = array();
1056        if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
1057            foreach ($this->prop['sub_fields'] as $xf => $xclass) {
1058                if (!empty($newentry[$xf])) {
1059                    $xfields[$xf] = $newentry[$xf];
1060                    unset($newentry[$xf]);
1061                }
1062            }
1063        }
1064
1065        if (!$this->ldap_add($dn, $newentry)) {
1066            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1067            return false;
1068        }
1069
1070        foreach ($xfields as $xidx => $xf) {
1071            $xdn = $xidx.'='.$this->_quote_string($xf).','.$dn;
1072            $xf = array(
1073                $xidx => $xf,
1074                'objectClass' => (array) $this->prop['sub_fields'][$xidx],
1075            );
1076
1077            $this->ldap_add($xdn, $xf);
1078        }
1079
1080        $dn = self::dn_encode($dn);
1081
1082        // add new contact to the selected group
1083        if ($this->group_id)
1084            $this->add_to_group($this->group_id, $dn);
1085
1086        return $dn;
1087    }
1088
1089
1090    /**
1091     * Update a specific contact record
1092     *
1093     * @param mixed Record identifier
1094     * @param array Hash array with save data
1095     *
1096     * @return boolean True on success, False on error
1097     */
1098    function update($id, $save_cols)
1099    {
1100        $record = $this->get_record($id, true);
1101
1102        $newdata     = array();
1103        $replacedata = array();
1104        $deletedata  = array();
1105        $subdata     = array();
1106        $subdeldata  = array();
1107        $subnewdata  = array();
1108
1109        $ldap_data = $this->_map_data($save_cols);
1110        $old_data  = $record['_raw_attrib'];
1111
1112        foreach ($this->fieldmap as $col => $fld) {
1113            if ($fld) {
1114                $val = $ldap_data[$fld];
1115                $old = $old_data[$fld];
1116                // remove empty array values
1117                if (is_array($val))
1118                    $val = array_filter($val);
1119                // $this->_map_data() result and _raw_attrib use different format
1120                // make sure comparing array with one element with a string works as expected
1121                if (is_array($old) && count($old) == 1 && !is_array($val)) {
1122                    $old = array_pop($old);
1123                }
1124                // Subentries must be handled separately
1125                if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
1126                    if ($old != $val) {
1127                        if ($old !== null) {
1128                            $subdeldata[$fld] = $old;
1129                        }
1130                        if ($val) {
1131                            $subnewdata[$fld] = $val;
1132                        }
1133                    }
1134                    else if ($old !== null) {
1135                        $subdata[$fld] = $old;
1136                    }
1137                    continue;
1138                }
1139                // The field does exist compare it to the ldap record.
1140                if ($old != $val) {
1141                    // Changed, but find out how.
1142                    if ($old === null) {
1143                        // Field was not set prior, need to add it.
1144                        $newdata[$fld] = $val;
1145                    }
1146                    else if ($val == '') {
1147                        // Field supplied is empty, verify that it is not required.
1148                        if (!in_array($fld, $this->prop['required_fields'])) {
1149                            // It is not, safe to clear.
1150                            $deletedata[$fld] = $old_data[$fld];
1151                        }
1152                    }
1153                    else {
1154                        // The data was modified, save it out.
1155                        $replacedata[$fld] = $val;
1156                    }
1157                } // end if
1158            } // end if
1159        } // end foreach
1160/*
1161        console($old_data);
1162        console($ldap_data);
1163        console('----');
1164        console($newdata);
1165        console($replacedata);
1166        console($deletedata);
1167        console('----');
1168        console($subdata);
1169        console($subnewdata);
1170        console($subdeldata);
1171*/
1172        $dn = self::dn_decode($id);
1173
1174        // Update the entry as required.
1175        if (!empty($deletedata)) {
1176            // Delete the fields.
1177            if (!$this->ldap_mod_del($dn, $deletedata)) {
1178                $this->set_error(self::ERROR_SAVING, 'errorsaving');
1179                return false;
1180            }
1181        } // end if
1182
1183        if (!empty($replacedata)) {
1184            // Handle RDN change
1185            if ($replacedata[$this->prop['LDAP_rdn']]) {
1186                $newdn = $this->prop['LDAP_rdn'].'='
1187                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
1188                    .','.$this->base_dn;
1189                if ($dn != $newdn) {
1190                    $newrdn = $this->prop['LDAP_rdn'].'='
1191                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
1192                    unset($replacedata[$this->prop['LDAP_rdn']]);
1193                }
1194            }
1195            // Replace the fields.
1196            if (!empty($replacedata)) {
1197                if (!$this->ldap_mod_replace($dn, $replacedata)) {
1198                    $this->set_error(self::ERROR_SAVING, 'errorsaving');
1199                    return false;
1200                }
1201            }
1202        } // end if
1203
1204        // RDN change, we need to remove all sub-entries
1205        if (!empty($newrdn)) {
1206            $subdeldata = array_merge($subdeldata, $subdata);
1207            $subnewdata = array_merge($subnewdata, $subdata);
1208        }
1209
1210        // remove sub-entries
1211        if (!empty($subdeldata)) {
1212            foreach ($subdeldata as $fld => $val) {
1213                $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
1214                if (!$this->ldap_delete($subdn)) {
1215                    return false;
1216                }
1217            }
1218        }
1219
1220        if (!empty($newdata)) {
1221            // Add the fields.
1222            if (!$this->ldap_mod_add($dn, $newdata)) {
1223                $this->set_error(self::ERROR_SAVING, 'errorsaving');
1224                return false;
1225            }
1226        } // end if
1227
1228        // Handle RDN change
1229        if (!empty($newrdn)) {
1230            if (!$this->ldap_rename($dn, $newrdn, null, true)) {
1231                $this->set_error(self::ERROR_SAVING, 'errorsaving');
1232                return false;
1233            }
1234
1235            $dn    = self::dn_encode($dn);
1236            $newdn = self::dn_encode($newdn);
1237
1238            // change the group membership of the contact
1239            if ($this->groups) {
1240                $group_ids = $this->get_record_groups($dn);
1241                foreach ($group_ids as $group_id)
1242                {
1243                    $this->remove_from_group($group_id, $dn);
1244                    $this->add_to_group($group_id, $newdn);
1245                }
1246            }
1247
1248            $dn = self::dn_decode($newdn);
1249        }
1250
1251        // add sub-entries
1252        if (!empty($subnewdata)) {
1253            foreach ($subnewdata as $fld => $val) {
1254                $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
1255                $xf = array(
1256                    $fld => $val,
1257                    'objectClass' => (array) $this->prop['sub_fields'][$fld],
1258                );
1259                $this->ldap_add($subdn, $xf);
1260            }
1261        }
1262
1263        return $newdn ? $newdn : true;
1264    }
1265
1266
1267    /**
1268     * Mark one or more contact records as deleted
1269     *
1270     * @param array   Record identifiers
1271     * @param boolean Remove record(s) irreversible (unsupported)
1272     *
1273     * @return boolean True on success, False on error
1274     */
1275    function delete($ids, $force=true)
1276    {
1277        if (!is_array($ids)) {
1278            // Not an array, break apart the encoded DNs.
1279            $ids = explode(',', $ids);
1280        } // end if
1281
1282        foreach ($ids as $id) {
1283            $dn = self::dn_decode($id);
1284
1285            // Need to delete all sub-entries first
1286            if ($this->sub_filter) {
1287                if ($entries = $this->ldap_list($dn, $this->sub_filter, array_keys($this->props['sub_fields']))) {
1288                    foreach ($entries as $entry) {
1289                        if (!$this->ldap_delete($entry['dn'])) {
1290                            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1291                            return false;
1292                        }
1293                    }
1294                }
1295            }
1296
1297            // Delete the record.
1298            if (!$this->ldap_delete($dn)) {
1299                $this->set_error(self::ERROR_SAVING, 'errorsaving');
1300                return false;
1301            }
1302
1303            // remove contact from all groups where he was member
1304            if ($this->groups) {
1305                $dn = self::dn_encode($dn);
1306                $group_ids = $this->get_record_groups($dn);
1307                foreach ($group_ids as $group_id) {
1308                    $this->remove_from_group($group_id, $dn);
1309                }
1310            }
1311        } // end foreach
1312
1313        return count($ids);
1314    }
1315
1316
1317    /**
1318     * Execute the LDAP search based on the stored credentials
1319     */
1320    private function _exec_search($count = false)
1321    {
1322        if ($this->ready)
1323        {
1324            $filter = $this->filter ? $this->filter : '(objectclass=*)';
1325            $function = $this->_scope2func($this->prop['scope'], $ns_function);
1326
1327            $this->_debug("C: Search [$filter][dn: $this->base_dn]");
1328
1329            // when using VLV, we get the total count by...
1330            if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
1331                // ...either reading numSubOrdinates attribute
1332                if ($this->prop['numsub_filter'] && ($result_count = @$ns_function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
1333                    $counts = ldap_get_entries($this->conn, $result_count);
1334                    for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
1335                        $this->vlv_count += $counts[$j]['numsubordinates'][0];
1336                    $this->_debug("D: total numsubordinates = " . $this->vlv_count);
1337                }
1338                else if (!function_exists('ldap_parse_virtuallist_control'))  // ...or by fetching all records dn and count them
1339                    $this->vlv_count = $this->_exec_search(true);
1340
1341                $this->vlv_active = $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size);
1342            }
1343
1344            // only fetch dn for count (should keep the payload low)
1345            $attrs = $count ? array('dn') : array_values($this->fieldmap);
1346            if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
1347                $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
1348            ) {
1349                // when running on a patched PHP we can use the extended functions to retrieve the total count from the LDAP search result
1350                if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control')) {
1351                    if (ldap_parse_result($this->conn, $this->ldap_result,
1352                        $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)
1353                    ) {
1354                        ldap_parse_virtuallist_control($this->conn, $serverctrls,
1355                            $last_offset, $this->vlv_count, $vresult);
1356                        $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$this->vlv_count");
1357                    }
1358                    else {
1359                        $this->_debug("S: ".($errmsg ? $errmsg : ldap_error($this->conn)));
1360                    }
1361                }
1362
1363                $entries_count = ldap_count_entries($this->conn, $this->ldap_result);
1364                $this->_debug("S: $entries_count record(s)");
1365
1366                return $count ? $entries_count : true;
1367            }
1368            else {
1369                $this->_debug("S: ".ldap_error($this->conn));
1370            }
1371        }
1372
1373        return false;
1374    }
1375
1376    /**
1377     * Choose the right PHP function according to scope property
1378     */
1379    private function _scope2func($scope, &$ns_function = null)
1380    {
1381        switch ($scope) {
1382          case 'sub':
1383            $function = $ns_function  = 'ldap_search';
1384            break;
1385          case 'base':
1386            $function = $ns_function = 'ldap_read';
1387            break;
1388          default:
1389            $function = 'ldap_list';
1390            $ns_function = 'ldap_read';
1391            break;
1392        }
1393
1394        return $function;
1395    }
1396
1397    /**
1398     * Set server controls for Virtual List View (paginated listing)
1399     */
1400    private function _vlv_set_controls($prop, $list_page, $page_size, $search = null)
1401    {
1402        $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$prop['sort']));
1403        $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);
1404
1405        $sort = (array)$prop['sort'];
1406        $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ($sort[0]);"
1407            . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset/$page_size)");
1408
1409        if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
1410            $this->_debug("S: ".ldap_error($this->conn));
1411            $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');
1412            return false;
1413        }
1414
1415        return true;
1416    }
1417
1418
1419    /**
1420     * Converts LDAP entry into an array
1421     */
1422    private function _ldap2result($rec)
1423    {
1424        $out = array();
1425
1426        if ($rec['dn'])
1427            $out[$this->primary_key] = self::dn_encode($rec['dn']);
1428
1429        foreach ($this->fieldmap as $rf => $lf)
1430        {
1431            for ($i=0; $i < $rec[$lf]['count']; $i++) {
1432                if (!($value = $rec[$lf][$i]))
1433                    continue;
1434
1435                list($col, $subtype) = explode(':', $rf);
1436                $out['_raw_attrib'][$lf][$i] = $value;
1437
1438                if ($rf == 'email' && $this->mail_domain && !strpos($value, '@'))
1439                    $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
1440                else if (in_array($col, array('street','zipcode','locality','country','region')))
1441                    $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
1442                else if ($rec[$lf]['count'] > 1)
1443                    $out[$rf][] = $value;
1444                else
1445                    $out[$rf] = $value;
1446            }
1447
1448            // Make sure name fields aren't arrays (#1488108)
1449            if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
1450                $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
1451            }
1452        }
1453
1454        return $out;
1455    }
1456
1457
1458    /**
1459     * Return real field name (from fields map)
1460     */
1461    private function _map_field($field)
1462    {
1463        return $this->fieldmap[$field];
1464    }
1465
1466
1467    /**
1468     * Convert a record data set into LDAP field attributes
1469     */
1470    private function _map_data($save_cols)
1471    {
1472        // flatten composite fields first
1473        foreach ($this->coltypes as $col => $colprop) {
1474            if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
1475                foreach ($values as $subtype => $childs) {
1476                    $subtype = $subtype ? ':'.$subtype : '';
1477                    foreach ($childs as $i => $child_values) {
1478                        foreach ((array)$child_values as $childcol => $value) {
1479                            $save_cols[$childcol.$subtype][$i] = $value;
1480                        }
1481                    }
1482                }
1483            }
1484        }
1485
1486        $ldap_data = array();
1487        foreach ($this->fieldmap as $col => $fld) {
1488            $val = $save_cols[$col];
1489            if (is_array($val))
1490                $val = array_filter($val);  // remove empty entries
1491            if ($fld && $val) {
1492                // The field does exist, add it to the entry.
1493                $ldap_data[$fld] = $val;
1494            }
1495        }
1496
1497        return $ldap_data;
1498    }
1499
1500
1501    /**
1502     * Returns unified attribute name (resolving aliases)
1503     */
1504    private static function _attr_name($name)
1505    {
1506        // list of known attribute aliases
1507        $aliases = array(
1508            'gn' => 'givenname',
1509            'rfc822mailbox' => 'email',
1510            'userid' => 'uid',
1511            'emailaddress' => 'email',
1512            'pkcs9email' => 'email',
1513        );
1514        return isset($aliases[$name]) ? $aliases[$name] : $name;
1515    }
1516
1517
1518    /**
1519     * Prints debug info to the log
1520     */
1521    private function _debug($str)
1522    {
1523        if ($this->debug)
1524            write_log('ldap', $str);
1525    }
1526
1527
1528    /**
1529     * Activate/deactivate debug mode
1530     *
1531     * @param boolean $dbg True if LDAP commands should be logged
1532     * @access public
1533     */
1534    function set_debug($dbg = true)
1535    {
1536        $this->debug = $dbg;
1537    }
1538
1539
1540    /**
1541     * Quotes attribute value string
1542     *
1543     * @param string $str Attribute value
1544     * @param bool   $dn  True if the attribute is a DN
1545     *
1546     * @return string Quoted string
1547     */
1548    private static function _quote_string($str, $dn=false)
1549    {
1550        // take firt entry if array given
1551        if (is_array($str))
1552            $str = reset($str);
1553
1554        if ($dn)
1555            $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
1556                '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
1557        else
1558            $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
1559                '/'=>'\2f');
1560
1561        return strtr($str, $replace);
1562    }
1563
1564
1565    /**
1566     * Setter for the current group
1567     * (empty, has to be re-implemented by extending class)
1568     */
1569    function set_group($group_id)
1570    {
1571        if ($group_id)
1572        {
1573            if (($group_cache = $this->cache->get('groups')) === null)
1574                $group_cache = $this->_fetch_groups();
1575
1576            $this->group_id = $group_id;
1577            $this->group_data = $group_cache[$group_id];
1578        }
1579        else
1580        {
1581            $this->group_id = 0;
1582            $this->group_data = null;
1583        }
1584    }
1585
1586    /**
1587     * List all active contact groups of this source
1588     *
1589     * @param string  Optional search string to match group name
1590     * @return array  Indexed list of contact groups, each a hash array
1591     */
1592    function list_groups($search = null)
1593    {
1594        if (!$this->groups)
1595            return array();
1596
1597        // use cached list for searching
1598        $this->cache->expunge();
1599        if (!$search || ($group_cache = $this->cache->get('groups')) === null)
1600            $group_cache = $this->_fetch_groups();
1601
1602        $groups = array();
1603        if ($search) {
1604            $search = mb_strtolower($search);
1605            foreach ($group_cache as $group) {
1606                if (strpos(mb_strtolower($group['name']), $search) !== false)
1607                    $groups[] = $group;
1608            }
1609        }
1610        else
1611            $groups = $group_cache;
1612
1613        return array_values($groups);
1614    }
1615
1616    /**
1617     * Fetch groups from server
1618     */
1619    private function _fetch_groups($vlv_page = 0)
1620    {
1621        $base_dn = $this->groups_base_dn;
1622        $filter = $this->prop['groups']['filter'];
1623        $name_attr = $this->prop['groups']['name_attr'];
1624        $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
1625        $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
1626        $sort_attr = $sort_attrs[0];
1627
1628        $this->_debug("C: Search [$filter][dn: $base_dn]");
1629
1630        // use vlv to list groups
1631        if ($this->prop['groups']['vlv']) {
1632            $page_size = 200;
1633            if (!$this->prop['groups']['sort'])
1634                $this->prop['groups']['sort'] = $sort_attrs;
1635            $vlv_active = $this->_vlv_set_controls($this->prop['groups'], $vlv_page+1, $page_size);
1636        }
1637
1638        $function = $this->_scope2func($this->prop['groups']['scope'], $ns_function);
1639        $res = @$function($this->conn, $base_dn, $filter, array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr)));
1640        if ($res === false)
1641        {
1642            $this->_debug("S: ".ldap_error($this->conn));
1643            return array();
1644        }
1645
1646        $ldap_data = ldap_get_entries($this->conn, $res);
1647        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1648
1649        $groups = array();
1650        $group_sortnames = array();
1651        $group_count = $ldap_data["count"];
1652        for ($i=0; $i < $group_count; $i++)
1653        {
1654            $group_name = is_array($ldap_data[$i][$name_attr]) ? $ldap_data[$i][$name_attr][0] : $ldap_data[$i][$name_attr];
1655            $group_id = self::dn_encode($group_name);
1656            $groups[$group_id]['ID'] = $group_id;
1657            $groups[$group_id]['dn'] = $ldap_data[$i]['dn'];
1658            $groups[$group_id]['name'] = $group_name;
1659            $groups[$group_id]['member_attr'] = $this->prop['member_attr'];
1660
1661            // check objectClass attributes of group and act accordingly
1662            for ($j=0; $j < $ldap_data[$i]['objectclass']['count']; $j++) {
1663                switch (strtolower($ldap_data[$i]['objectclass'][$j])) {
1664                    case 'group':
1665                    case 'groupofnames':
1666                    case 'kolabgroupofnames':
1667                        $groups[$group_id]['member_attr'] = 'member';
1668                        break;
1669
1670                    case 'groupofuniquenames':
1671                    case 'kolabgroupofuniquenames':
1672                        $groups[$group_id]['member_attr'] = 'uniqueMember';
1673                        break;
1674                }
1675            }
1676
1677            // list email attributes of a group
1678            for ($j=0; $ldap_data[$i][$email_attr] && $j < $ldap_data[$i][$email_attr]['count']; $j++) {
1679                if (strpos($ldap_data[$i][$email_attr][$j], '@') > 0)
1680                    $groups[$group_id]['email'][] = $ldap_data[$i][$email_attr][$j];
1681            }
1682
1683            $group_sortnames[] = mb_strtolower($ldap_data[$i][$sort_attr][0]);
1684        }
1685
1686        // recursive call can exit here
1687        if ($vlv_page > 0)
1688            return $groups;
1689
1690        // call recursively until we have fetched all groups
1691        while ($vlv_active && $group_count == $page_size)
1692        {
1693            $next_page = $this->_fetch_groups(++$vlv_page);
1694            $groups = array_merge($groups, $next_page);
1695            $group_count = count($next_page);
1696        }
1697
1698        // when using VLV the list of groups is already sorted
1699        if (!$this->prop['groups']['vlv'])
1700            array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
1701
1702        // cache this
1703        $this->cache->set('groups', $groups);
1704
1705        return $groups;
1706    }
1707
1708    /**
1709     * Get group properties such as name and email address(es)
1710     *
1711     * @param string Group identifier
1712     * @return array Group properties as hash array
1713     */
1714    function get_group($group_id)
1715    {
1716        if (($group_cache = $this->cache->get('groups')) === null)
1717            $group_cache = $this->_fetch_groups();
1718
1719        $group_data = $group_cache[$group_id];
1720        unset($group_data['dn'], $group_data['member_attr']);
1721
1722        return $group_data;
1723    }
1724
1725    /**
1726     * Create a contact group with the given name
1727     *
1728     * @param string The group name
1729     * @return mixed False on error, array with record props in success
1730     */
1731    function create_group($group_name)
1732    {
1733        $base_dn = $this->groups_base_dn;
1734        $new_dn = "cn=$group_name,$base_dn";
1735        $new_gid = self::dn_encode($group_name);
1736        $member_attr = $this->prop['groups']['member_attr'];
1737        $name_attr = $this->prop['groups']['name_attr'];
1738
1739        $new_entry = array(
1740            'objectClass' => $this->prop['groups']['object_classes'],
1741            $name_attr => $group_name,
1742            $member_attr => '',
1743        );
1744
1745        if (!$this->ldap_add($new_dn, $new_entry)) {
1746            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1747            return false;
1748        }
1749
1750        $this->cache->remove('groups');
1751
1752        return array('id' => $new_gid, 'name' => $group_name);
1753    }
1754
1755    /**
1756     * Delete the given group and all linked group members
1757     *
1758     * @param string Group identifier
1759     * @return boolean True on success, false if no data was changed
1760     */
1761    function delete_group($group_id)
1762    {
1763        if (($group_cache = $this->cache->get('groups')) === null)
1764            $group_cache = $this->_fetch_groups();
1765
1766        $base_dn = $this->groups_base_dn;
1767        $group_name = $group_cache[$group_id]['name'];
1768        $del_dn = "cn=$group_name,$base_dn";
1769
1770        if (!$this->ldap_delete($del_dn)) {
1771            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1772            return false;
1773        }
1774
1775        $this->cache->remove('groups');
1776
1777        return true;
1778    }
1779
1780    /**
1781     * Rename a specific contact group
1782     *
1783     * @param string Group identifier
1784     * @param string New name to set for this group
1785     * @param string New group identifier (if changed, otherwise don't set)
1786     * @return boolean New name on success, false if no data was changed
1787     */
1788    function rename_group($group_id, $new_name, &$new_gid)
1789    {
1790        if (($group_cache = $this->cache->get('groups')) === null)
1791            $group_cache = $this->_fetch_groups();
1792
1793        $base_dn = $this->groups_base_dn;
1794        $group_name = $group_cache[$group_id]['name'];
1795        $old_dn = "cn=$group_name,$base_dn";
1796        $new_rdn = "cn=$new_name";
1797        $new_gid = self::dn_encode($new_name);
1798
1799        if (!$this->ldap_rename($old_dn, $new_rdn, null, true)) {
1800            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1801            return false;
1802        }
1803
1804        $this->cache->remove('groups');
1805
1806        return $new_name;
1807    }
1808
1809    /**
1810     * Add the given contact records the a certain group
1811     *
1812     * @param string  Group identifier
1813     * @param array   List of contact identifiers to be added
1814     * @return int    Number of contacts added
1815     */
1816    function add_to_group($group_id, $contact_ids)
1817    {
1818        if (($group_cache = $this->cache->get('groups')) === null)
1819            $group_cache = $this->_fetch_groups();
1820
1821        if (!is_array($contact_ids))
1822            $contact_ids = explode(',', $contact_ids);
1823
1824        $base_dn     = $this->groups_base_dn;
1825        $group_name  = $group_cache[$group_id]['name'];
1826        $member_attr = $group_cache[$group_id]['member_attr'];
1827        $group_dn    = "cn=$group_name,$base_dn";
1828
1829        $new_attrs = array();
1830        foreach ($contact_ids as $id)
1831            $new_attrs[$member_attr][] = self::dn_decode($id);
1832
1833        if (!$this->ldap_mod_add($group_dn, $new_attrs)) {
1834            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1835            return 0;
1836        }
1837
1838        $this->cache->remove('groups');
1839
1840        return count($new_attrs['member']);
1841    }
1842
1843    /**
1844     * Remove the given contact records from a certain group
1845     *
1846     * @param string  Group identifier
1847     * @param array   List of contact identifiers to be removed
1848     * @return int    Number of deleted group members
1849     */
1850    function remove_from_group($group_id, $contact_ids)
1851    {
1852        if (($group_cache = $this->cache->get('groups')) === null)
1853            $group_cache = $this->_fetch_groups();
1854
1855        $base_dn     = $this->groups_base_dn;
1856        $group_name  = $group_cache[$group_id]['name'];
1857        $member_attr = $group_cache[$group_id]['member_attr'];
1858        $group_dn    = "cn=$group_name,$base_dn";
1859
1860        $del_attrs = array();
1861        foreach (explode(",", $contact_ids) as $id)
1862            $del_attrs[$member_attr][] = self::dn_decode($id);
1863
1864        if (!$this->ldap_mod_del($group_dn, $del_attrs)) {
1865            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1866            return 0;
1867        }
1868
1869        $this->cache->remove('groups');
1870
1871        return count($del_attrs['member']);
1872    }
1873
1874    /**
1875     * Get group assignments of a specific contact record
1876     *
1877     * @param mixed Record identifier
1878     *
1879     * @return array List of assigned groups as ID=>Name pairs
1880     * @since 0.5-beta
1881     */
1882    function get_record_groups($contact_id)
1883    {
1884        if (!$this->groups)
1885            return array();
1886
1887        $base_dn     = $this->groups_base_dn;
1888        $contact_dn  = self::dn_decode($contact_id);
1889        $name_attr   = $this->prop['groups']['name_attr'];
1890        $member_attr = $this->prop['member_attr'];
1891        $add_filter  = '';
1892        if ($member_attr != 'member' && $member_attr != 'uniqueMember')
1893            $add_filter = "($member_attr=$contact_dn)";
1894        $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
1895
1896        $this->_debug("C: Search [$filter][dn: $base_dn]");
1897
1898        $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
1899        if ($res === false)
1900        {
1901            $this->_debug("S: ".ldap_error($this->conn));
1902            return array();
1903        }
1904        $ldap_data = ldap_get_entries($this->conn, $res);
1905        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1906
1907        $groups = array();
1908        for ($i=0; $i<$ldap_data["count"]; $i++)
1909        {
1910            $group_name = $ldap_data[$i][$name_attr][0];
1911            $group_id = self::dn_encode($group_name);
1912            $groups[$group_id] = $group_id;
1913        }
1914        return $groups;
1915    }
1916
1917
1918    /**
1919     * Generate BER encoded string for Virtual List View option
1920     *
1921     * @param integer List offset (first record)
1922     * @param integer Records per page
1923     * @return string BER encoded option value
1924     */
1925    private function _vlv_ber_encode($offset, $rpp, $search = '')
1926    {
1927        # this string is ber-encoded, php will prefix this value with:
1928        # 04 (octet string) and 10 (length of 16 bytes)
1929        # the code behind this string is broken down as follows:
1930        # 30 = ber sequence with a length of 0e (14) bytes following
1931        # 02 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
1932        # 02 = type integer (in two's complement form) with 2 bytes following (afterCount):  01 18 (ie 25-1=24)
1933        # a0 = type context-specific/constructed with a length of 06 (6) bytes following
1934        # 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
1935        # 02 = type integer with 2 bytes following (contentCount):  01 00
1936       
1937        # whith a search string present:
1938        # 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
1939        # 81 indicates a user string is present where as a a0 indicates just a offset search
1940        # 81 = type context-specific/constructed with a length of 06 (6) bytes following
1941       
1942        # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
1943        # encoding of integer values (note: these values are in
1944        # two-complement form so since offset will never be negative bit 8 of the
1945        # leftmost octet should never by set to 1):
1946        # 8.3.2: If the contents octets of an integer value encoding consist
1947        # of more than one octet, then the bits of the first octet (rightmost) and bit 8
1948        # of the second (to the left of first octet) octet:
1949        # a) shall not all be ones; and
1950        # b) shall not all be zero
1951       
1952        if ($search)
1953        {
1954            $search = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
1955            $ber_val = self::_string2hex($search);
1956            $str = self::_ber_addseq($ber_val, '81');
1957        }
1958        else
1959        {
1960            # construct the string from right to left
1961            $str = "020100"; # contentCount
1962
1963            $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
1964
1965            // calculate octet length of $ber_val
1966            $str = self::_ber_addseq($ber_val, '02') . $str;
1967
1968            // now compute length over $str
1969            $str = self::_ber_addseq($str, 'a0');
1970        }
1971       
1972        // now tack on records per page
1973        $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;
1974
1975        // now tack on sequence identifier and length
1976        $str = self::_ber_addseq($str, '30');
1977
1978        return pack('H'.strlen($str), $str);
1979    }
1980
1981
1982    /**
1983     * create ber encoding for sort control
1984     *
1985     * @param array List of cols to sort by
1986     * @return string BER encoded option value
1987     */
1988    private function _sort_ber_encode($sortcols)
1989    {
1990        $str = '';
1991        foreach (array_reverse((array)$sortcols) as $col) {
1992            $ber_val = self::_string2hex($col);
1993
1994            # 30 = ber sequence with a length of octet value
1995            # 04 = octet string with a length of the ascii value
1996            $oct = self::_ber_addseq($ber_val, '04');
1997            $str = self::_ber_addseq($oct, '30') . $str;
1998        }
1999
2000        // now tack on sequence identifier and length
2001        $str = self::_ber_addseq($str, '30');
2002
2003        return pack('H'.strlen($str), $str);
2004    }
2005
2006    /**
2007     * Add BER sequence with correct length and the given identifier
2008     */
2009    private static function _ber_addseq($str, $identifier)
2010    {
2011        $len = dechex(strlen($str)/2);
2012        if (strlen($len) % 2 != 0)
2013            $len = '0'.$len;
2014
2015        return $identifier . $len . $str;
2016    }
2017
2018    /**
2019     * Returns BER encoded integer value in hex format
2020     */
2021    private static function _ber_encode_int($offset)
2022    {
2023        $val = dechex($offset);
2024        $prefix = '';
2025
2026        // check if bit 8 of high byte is 1
2027        if (preg_match('/^[89abcdef]/', $val))
2028            $prefix = '00';
2029
2030        if (strlen($val)%2 != 0)
2031            $prefix .= '0';
2032
2033        return $prefix . $val;
2034    }
2035
2036    /**
2037     * Returns ascii string encoded in hex
2038     */
2039    private static function _string2hex($str)
2040    {
2041        $hex = '';
2042        for ($i=0; $i < strlen($str); $i++)
2043            $hex .= dechex(ord($str[$i]));
2044        return $hex;
2045    }
2046
2047    /**
2048     * HTML-safe DN string encoding
2049     *
2050     * @param string $str DN string
2051     *
2052     * @return string Encoded HTML identifier string
2053     */
2054    static function dn_encode($str)
2055    {
2056        // @TODO: to make output string shorter we could probably
2057        //        remove dc=* items from it
2058        return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
2059    }
2060
2061    /**
2062     * Decodes DN string encoded with _dn_encode()
2063     *
2064     * @param string $str Encoded HTML identifier string
2065     *
2066     * @return string DN string
2067     */
2068    static function dn_decode($str)
2069    {
2070        $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
2071        return base64_decode($str);
2072    }
2073
2074    /**
2075     * Wrapper for ldap_add()
2076     */
2077    protected function ldap_add($dn, $entry)
2078    {
2079        $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2080
2081        $res = ldap_add($this->conn, $dn, $entry);
2082        if ($res === false) {
2083            $this->_debug("S: ".ldap_error($this->conn));
2084            return false;
2085        }
2086
2087        $this->_debug("S: OK");
2088        return true;
2089    }
2090
2091    /**
2092     * Wrapper for ldap_delete()
2093     */
2094    protected function ldap_delete($dn)
2095    {
2096        $this->_debug("C: Delete [dn: $dn]");
2097
2098        $res = ldap_delete($this->conn, $dn);
2099        if ($res === false) {
2100            $this->_debug("S: ".ldap_error($this->conn));
2101            return false;
2102        }
2103
2104        $this->_debug("S: OK");
2105        return true;
2106    }
2107
2108    /**
2109     * Wrapper for ldap_mod_replace()
2110     */
2111    protected function ldap_mod_replace($dn, $entry)
2112    {
2113        $this->_debug("C: Replace [dn: $dn]: ".print_r($entry, true));
2114
2115        if (!ldap_mod_replace($this->conn, $dn, $entry)) {
2116            $this->_debug("S: ".ldap_error($this->conn));
2117            return false;
2118        }
2119
2120        $this->_debug("S: OK");
2121        return true;
2122    }
2123
2124    /**
2125     * Wrapper for ldap_mod_add()
2126     */
2127    protected function ldap_mod_add($dn, $entry)
2128    {
2129        $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2130
2131        if (!ldap_mod_add($this->conn, $dn, $entry)) {
2132            $this->_debug("S: ".ldap_error($this->conn));
2133            return false;
2134        }
2135
2136        $this->_debug("S: OK");
2137        return true;
2138    }
2139
2140    /**
2141     * Wrapper for ldap_mod_del()
2142     */
2143    protected function ldap_mod_del($dn, $entry)
2144    {
2145        $this->_debug("C: Delete [dn: $dn]: ".print_r($entry, true));
2146
2147        if (!ldap_mod_del($this->conn, $dn, $entry)) {
2148            $this->_debug("S: ".ldap_error($this->conn));
2149            return false;
2150        }
2151
2152        $this->_debug("S: OK");
2153        return true;
2154    }
2155
2156    /**
2157     * Wrapper for ldap_rename()
2158     */
2159    protected function ldap_rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
2160    {
2161        $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
2162
2163        if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
2164            $this->_debug("S: ".ldap_error($this->conn));
2165            return false;
2166        }
2167
2168        $this->_debug("S: OK");
2169        return true;
2170    }
2171
2172    /**
2173     * Wrapper for ldap_list()
2174     */
2175    protected function ldap_list($dn, $filter, $attrs)
2176    {
2177        $list = array();
2178        $this->_debug("C: List [dn: $dn] [{$filter}]");
2179
2180        if ($result = ldap_list($this->conn, $dn, $filter, $attrs)) {
2181            $list = ldap_get_entries($this->conn, $result);
2182
2183            if ($list === false) {
2184                $this->_debug("S: ".ldap_error($this->conn));
2185                return array();
2186            }
2187
2188            $count = $list['count'];
2189            unset($list['count']);
2190
2191            $this->_debug("S: $count record(s)");
2192        }
2193        else {
2194            $this->_debug("S: ".ldap_error($this->conn));
2195        }
2196
2197        return $list;
2198    }
2199
2200}
Note: See TracBrowser for help on using the repository browser.