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

Last change on this file since 6055 was 6055, checked in by alec, 13 months ago
  • Fix removing all folders on import to LDAP addressbook (added rcube_ldap::delete_all())
  • Fix removing sub-entries in delete()
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 73.5 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)) {
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     * Remove all contact records
1319     */
1320    function delete_all()
1321    {
1322        //searching for contact entries
1323        $dn_list = $this->ldap_list($this->base_dn, $this->prop['filter'] ? $this->prop['filter'] : '(objectclass=*)');
1324
1325        if (!empty($dn_list)) {
1326            foreach ($dn_list as $idx => $entry) {
1327                $dn_list[$idx] = self::dn_encode($entry['dn']);
1328            }
1329            $this->delete($dn_list);
1330        }
1331    }
1332
1333
1334    /**
1335     * Execute the LDAP search based on the stored credentials
1336     */
1337    private function _exec_search($count = false)
1338    {
1339        if ($this->ready)
1340        {
1341            $filter = $this->filter ? $this->filter : '(objectclass=*)';
1342            $function = $this->_scope2func($this->prop['scope'], $ns_function);
1343
1344            $this->_debug("C: Search [$filter][dn: $this->base_dn]");
1345
1346            // when using VLV, we get the total count by...
1347            if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
1348                // ...either reading numSubOrdinates attribute
1349                if ($this->prop['numsub_filter'] && ($result_count = @$ns_function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
1350                    $counts = ldap_get_entries($this->conn, $result_count);
1351                    for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
1352                        $this->vlv_count += $counts[$j]['numsubordinates'][0];
1353                    $this->_debug("D: total numsubordinates = " . $this->vlv_count);
1354                }
1355                else if (!function_exists('ldap_parse_virtuallist_control'))  // ...or by fetching all records dn and count them
1356                    $this->vlv_count = $this->_exec_search(true);
1357
1358                $this->vlv_active = $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size);
1359            }
1360
1361            // only fetch dn for count (should keep the payload low)
1362            $attrs = $count ? array('dn') : array_values($this->fieldmap);
1363            if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
1364                $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
1365            ) {
1366                // when running on a patched PHP we can use the extended functions to retrieve the total count from the LDAP search result
1367                if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control')) {
1368                    if (ldap_parse_result($this->conn, $this->ldap_result,
1369                        $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)
1370                    ) {
1371                        ldap_parse_virtuallist_control($this->conn, $serverctrls,
1372                            $last_offset, $this->vlv_count, $vresult);
1373                        $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$this->vlv_count");
1374                    }
1375                    else {
1376                        $this->_debug("S: ".($errmsg ? $errmsg : ldap_error($this->conn)));
1377                    }
1378                }
1379
1380                $entries_count = ldap_count_entries($this->conn, $this->ldap_result);
1381                $this->_debug("S: $entries_count record(s)");
1382
1383                return $count ? $entries_count : true;
1384            }
1385            else {
1386                $this->_debug("S: ".ldap_error($this->conn));
1387            }
1388        }
1389
1390        return false;
1391    }
1392
1393    /**
1394     * Choose the right PHP function according to scope property
1395     */
1396    private function _scope2func($scope, &$ns_function = null)
1397    {
1398        switch ($scope) {
1399          case 'sub':
1400            $function = $ns_function  = 'ldap_search';
1401            break;
1402          case 'base':
1403            $function = $ns_function = 'ldap_read';
1404            break;
1405          default:
1406            $function = 'ldap_list';
1407            $ns_function = 'ldap_read';
1408            break;
1409        }
1410
1411        return $function;
1412    }
1413
1414    /**
1415     * Set server controls for Virtual List View (paginated listing)
1416     */
1417    private function _vlv_set_controls($prop, $list_page, $page_size, $search = null)
1418    {
1419        $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$prop['sort']));
1420        $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);
1421
1422        $sort = (array)$prop['sort'];
1423        $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ($sort[0]);"
1424            . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset/$page_size)");
1425
1426        if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
1427            $this->_debug("S: ".ldap_error($this->conn));
1428            $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');
1429            return false;
1430        }
1431
1432        return true;
1433    }
1434
1435
1436    /**
1437     * Converts LDAP entry into an array
1438     */
1439    private function _ldap2result($rec)
1440    {
1441        $out = array();
1442
1443        if ($rec['dn'])
1444            $out[$this->primary_key] = self::dn_encode($rec['dn']);
1445
1446        foreach ($this->fieldmap as $rf => $lf)
1447        {
1448            for ($i=0; $i < $rec[$lf]['count']; $i++) {
1449                if (!($value = $rec[$lf][$i]))
1450                    continue;
1451
1452                list($col, $subtype) = explode(':', $rf);
1453                $out['_raw_attrib'][$lf][$i] = $value;
1454
1455                if ($rf == 'email' && $this->mail_domain && !strpos($value, '@'))
1456                    $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
1457                else if (in_array($col, array('street','zipcode','locality','country','region')))
1458                    $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
1459                else if ($rec[$lf]['count'] > 1)
1460                    $out[$rf][] = $value;
1461                else
1462                    $out[$rf] = $value;
1463            }
1464
1465            // Make sure name fields aren't arrays (#1488108)
1466            if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
1467                $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
1468            }
1469        }
1470
1471        return $out;
1472    }
1473
1474
1475    /**
1476     * Return real field name (from fields map)
1477     */
1478    private function _map_field($field)
1479    {
1480        return $this->fieldmap[$field];
1481    }
1482
1483
1484    /**
1485     * Convert a record data set into LDAP field attributes
1486     */
1487    private function _map_data($save_cols)
1488    {
1489        // flatten composite fields first
1490        foreach ($this->coltypes as $col => $colprop) {
1491            if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
1492                foreach ($values as $subtype => $childs) {
1493                    $subtype = $subtype ? ':'.$subtype : '';
1494                    foreach ($childs as $i => $child_values) {
1495                        foreach ((array)$child_values as $childcol => $value) {
1496                            $save_cols[$childcol.$subtype][$i] = $value;
1497                        }
1498                    }
1499                }
1500            }
1501        }
1502
1503        $ldap_data = array();
1504        foreach ($this->fieldmap as $col => $fld) {
1505            $val = $save_cols[$col];
1506            if (is_array($val))
1507                $val = array_filter($val);  // remove empty entries
1508            if ($fld && $val) {
1509                // The field does exist, add it to the entry.
1510                $ldap_data[$fld] = $val;
1511            }
1512        }
1513
1514        return $ldap_data;
1515    }
1516
1517
1518    /**
1519     * Returns unified attribute name (resolving aliases)
1520     */
1521    private static function _attr_name($name)
1522    {
1523        // list of known attribute aliases
1524        $aliases = array(
1525            'gn' => 'givenname',
1526            'rfc822mailbox' => 'email',
1527            'userid' => 'uid',
1528            'emailaddress' => 'email',
1529            'pkcs9email' => 'email',
1530        );
1531        return isset($aliases[$name]) ? $aliases[$name] : $name;
1532    }
1533
1534
1535    /**
1536     * Prints debug info to the log
1537     */
1538    private function _debug($str)
1539    {
1540        if ($this->debug)
1541            write_log('ldap', $str);
1542    }
1543
1544
1545    /**
1546     * Activate/deactivate debug mode
1547     *
1548     * @param boolean $dbg True if LDAP commands should be logged
1549     * @access public
1550     */
1551    function set_debug($dbg = true)
1552    {
1553        $this->debug = $dbg;
1554    }
1555
1556
1557    /**
1558     * Quotes attribute value string
1559     *
1560     * @param string $str Attribute value
1561     * @param bool   $dn  True if the attribute is a DN
1562     *
1563     * @return string Quoted string
1564     */
1565    private static function _quote_string($str, $dn=false)
1566    {
1567        // take firt entry if array given
1568        if (is_array($str))
1569            $str = reset($str);
1570
1571        if ($dn)
1572            $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
1573                '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
1574        else
1575            $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
1576                '/'=>'\2f');
1577
1578        return strtr($str, $replace);
1579    }
1580
1581
1582    /**
1583     * Setter for the current group
1584     * (empty, has to be re-implemented by extending class)
1585     */
1586    function set_group($group_id)
1587    {
1588        if ($group_id)
1589        {
1590            if (($group_cache = $this->cache->get('groups')) === null)
1591                $group_cache = $this->_fetch_groups();
1592
1593            $this->group_id = $group_id;
1594            $this->group_data = $group_cache[$group_id];
1595        }
1596        else
1597        {
1598            $this->group_id = 0;
1599            $this->group_data = null;
1600        }
1601    }
1602
1603    /**
1604     * List all active contact groups of this source
1605     *
1606     * @param string  Optional search string to match group name
1607     * @return array  Indexed list of contact groups, each a hash array
1608     */
1609    function list_groups($search = null)
1610    {
1611        if (!$this->groups)
1612            return array();
1613
1614        // use cached list for searching
1615        $this->cache->expunge();
1616        if (!$search || ($group_cache = $this->cache->get('groups')) === null)
1617            $group_cache = $this->_fetch_groups();
1618
1619        $groups = array();
1620        if ($search) {
1621            $search = mb_strtolower($search);
1622            foreach ($group_cache as $group) {
1623                if (strpos(mb_strtolower($group['name']), $search) !== false)
1624                    $groups[] = $group;
1625            }
1626        }
1627        else
1628            $groups = $group_cache;
1629
1630        return array_values($groups);
1631    }
1632
1633    /**
1634     * Fetch groups from server
1635     */
1636    private function _fetch_groups($vlv_page = 0)
1637    {
1638        $base_dn = $this->groups_base_dn;
1639        $filter = $this->prop['groups']['filter'];
1640        $name_attr = $this->prop['groups']['name_attr'];
1641        $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
1642        $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
1643        $sort_attr = $sort_attrs[0];
1644
1645        $this->_debug("C: Search [$filter][dn: $base_dn]");
1646
1647        // use vlv to list groups
1648        if ($this->prop['groups']['vlv']) {
1649            $page_size = 200;
1650            if (!$this->prop['groups']['sort'])
1651                $this->prop['groups']['sort'] = $sort_attrs;
1652            $vlv_active = $this->_vlv_set_controls($this->prop['groups'], $vlv_page+1, $page_size);
1653        }
1654
1655        $function = $this->_scope2func($this->prop['groups']['scope'], $ns_function);
1656        $res = @$function($this->conn, $base_dn, $filter, array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr)));
1657        if ($res === false)
1658        {
1659            $this->_debug("S: ".ldap_error($this->conn));
1660            return array();
1661        }
1662
1663        $ldap_data = ldap_get_entries($this->conn, $res);
1664        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1665
1666        $groups = array();
1667        $group_sortnames = array();
1668        $group_count = $ldap_data["count"];
1669        for ($i=0; $i < $group_count; $i++)
1670        {
1671            $group_name = is_array($ldap_data[$i][$name_attr]) ? $ldap_data[$i][$name_attr][0] : $ldap_data[$i][$name_attr];
1672            $group_id = self::dn_encode($group_name);
1673            $groups[$group_id]['ID'] = $group_id;
1674            $groups[$group_id]['dn'] = $ldap_data[$i]['dn'];
1675            $groups[$group_id]['name'] = $group_name;
1676            $groups[$group_id]['member_attr'] = $this->prop['member_attr'];
1677
1678            // check objectClass attributes of group and act accordingly
1679            for ($j=0; $j < $ldap_data[$i]['objectclass']['count']; $j++) {
1680                switch (strtolower($ldap_data[$i]['objectclass'][$j])) {
1681                    case 'group':
1682                    case 'groupofnames':
1683                    case 'kolabgroupofnames':
1684                        $groups[$group_id]['member_attr'] = 'member';
1685                        break;
1686
1687                    case 'groupofuniquenames':
1688                    case 'kolabgroupofuniquenames':
1689                        $groups[$group_id]['member_attr'] = 'uniqueMember';
1690                        break;
1691                }
1692            }
1693
1694            // list email attributes of a group
1695            for ($j=0; $ldap_data[$i][$email_attr] && $j < $ldap_data[$i][$email_attr]['count']; $j++) {
1696                if (strpos($ldap_data[$i][$email_attr][$j], '@') > 0)
1697                    $groups[$group_id]['email'][] = $ldap_data[$i][$email_attr][$j];
1698            }
1699
1700            $group_sortnames[] = mb_strtolower($ldap_data[$i][$sort_attr][0]);
1701        }
1702
1703        // recursive call can exit here
1704        if ($vlv_page > 0)
1705            return $groups;
1706
1707        // call recursively until we have fetched all groups
1708        while ($vlv_active && $group_count == $page_size)
1709        {
1710            $next_page = $this->_fetch_groups(++$vlv_page);
1711            $groups = array_merge($groups, $next_page);
1712            $group_count = count($next_page);
1713        }
1714
1715        // when using VLV the list of groups is already sorted
1716        if (!$this->prop['groups']['vlv'])
1717            array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
1718
1719        // cache this
1720        $this->cache->set('groups', $groups);
1721
1722        return $groups;
1723    }
1724
1725    /**
1726     * Get group properties such as name and email address(es)
1727     *
1728     * @param string Group identifier
1729     * @return array Group properties as hash array
1730     */
1731    function get_group($group_id)
1732    {
1733        if (($group_cache = $this->cache->get('groups')) === null)
1734            $group_cache = $this->_fetch_groups();
1735
1736        $group_data = $group_cache[$group_id];
1737        unset($group_data['dn'], $group_data['member_attr']);
1738
1739        return $group_data;
1740    }
1741
1742    /**
1743     * Create a contact group with the given name
1744     *
1745     * @param string The group name
1746     * @return mixed False on error, array with record props in success
1747     */
1748    function create_group($group_name)
1749    {
1750        $base_dn = $this->groups_base_dn;
1751        $new_dn = "cn=$group_name,$base_dn";
1752        $new_gid = self::dn_encode($group_name);
1753        $member_attr = $this->prop['groups']['member_attr'];
1754        $name_attr = $this->prop['groups']['name_attr'];
1755
1756        $new_entry = array(
1757            'objectClass' => $this->prop['groups']['object_classes'],
1758            $name_attr => $group_name,
1759            $member_attr => '',
1760        );
1761
1762        if (!$this->ldap_add($new_dn, $new_entry)) {
1763            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1764            return false;
1765        }
1766
1767        $this->cache->remove('groups');
1768
1769        return array('id' => $new_gid, 'name' => $group_name);
1770    }
1771
1772    /**
1773     * Delete the given group and all linked group members
1774     *
1775     * @param string Group identifier
1776     * @return boolean True on success, false if no data was changed
1777     */
1778    function delete_group($group_id)
1779    {
1780        if (($group_cache = $this->cache->get('groups')) === null)
1781            $group_cache = $this->_fetch_groups();
1782
1783        $base_dn = $this->groups_base_dn;
1784        $group_name = $group_cache[$group_id]['name'];
1785        $del_dn = "cn=$group_name,$base_dn";
1786
1787        if (!$this->ldap_delete($del_dn)) {
1788            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1789            return false;
1790        }
1791
1792        $this->cache->remove('groups');
1793
1794        return true;
1795    }
1796
1797    /**
1798     * Rename a specific contact group
1799     *
1800     * @param string Group identifier
1801     * @param string New name to set for this group
1802     * @param string New group identifier (if changed, otherwise don't set)
1803     * @return boolean New name on success, false if no data was changed
1804     */
1805    function rename_group($group_id, $new_name, &$new_gid)
1806    {
1807        if (($group_cache = $this->cache->get('groups')) === null)
1808            $group_cache = $this->_fetch_groups();
1809
1810        $base_dn = $this->groups_base_dn;
1811        $group_name = $group_cache[$group_id]['name'];
1812        $old_dn = "cn=$group_name,$base_dn";
1813        $new_rdn = "cn=$new_name";
1814        $new_gid = self::dn_encode($new_name);
1815
1816        if (!$this->ldap_rename($old_dn, $new_rdn, null, true)) {
1817            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1818            return false;
1819        }
1820
1821        $this->cache->remove('groups');
1822
1823        return $new_name;
1824    }
1825
1826    /**
1827     * Add the given contact records the a certain group
1828     *
1829     * @param string  Group identifier
1830     * @param array   List of contact identifiers to be added
1831     * @return int    Number of contacts added
1832     */
1833    function add_to_group($group_id, $contact_ids)
1834    {
1835        if (($group_cache = $this->cache->get('groups')) === null)
1836            $group_cache = $this->_fetch_groups();
1837
1838        if (!is_array($contact_ids))
1839            $contact_ids = explode(',', $contact_ids);
1840
1841        $base_dn     = $this->groups_base_dn;
1842        $group_name  = $group_cache[$group_id]['name'];
1843        $member_attr = $group_cache[$group_id]['member_attr'];
1844        $group_dn    = "cn=$group_name,$base_dn";
1845
1846        $new_attrs = array();
1847        foreach ($contact_ids as $id)
1848            $new_attrs[$member_attr][] = self::dn_decode($id);
1849
1850        if (!$this->ldap_mod_add($group_dn, $new_attrs)) {
1851            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1852            return 0;
1853        }
1854
1855        $this->cache->remove('groups');
1856
1857        return count($new_attrs['member']);
1858    }
1859
1860    /**
1861     * Remove the given contact records from a certain group
1862     *
1863     * @param string  Group identifier
1864     * @param array   List of contact identifiers to be removed
1865     * @return int    Number of deleted group members
1866     */
1867    function remove_from_group($group_id, $contact_ids)
1868    {
1869        if (($group_cache = $this->cache->get('groups')) === null)
1870            $group_cache = $this->_fetch_groups();
1871
1872        $base_dn     = $this->groups_base_dn;
1873        $group_name  = $group_cache[$group_id]['name'];
1874        $member_attr = $group_cache[$group_id]['member_attr'];
1875        $group_dn    = "cn=$group_name,$base_dn";
1876
1877        $del_attrs = array();
1878        foreach (explode(",", $contact_ids) as $id)
1879            $del_attrs[$member_attr][] = self::dn_decode($id);
1880
1881        if (!$this->ldap_mod_del($group_dn, $del_attrs)) {
1882            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1883            return 0;
1884        }
1885
1886        $this->cache->remove('groups');
1887
1888        return count($del_attrs['member']);
1889    }
1890
1891    /**
1892     * Get group assignments of a specific contact record
1893     *
1894     * @param mixed Record identifier
1895     *
1896     * @return array List of assigned groups as ID=>Name pairs
1897     * @since 0.5-beta
1898     */
1899    function get_record_groups($contact_id)
1900    {
1901        if (!$this->groups)
1902            return array();
1903
1904        $base_dn     = $this->groups_base_dn;
1905        $contact_dn  = self::dn_decode($contact_id);
1906        $name_attr   = $this->prop['groups']['name_attr'];
1907        $member_attr = $this->prop['member_attr'];
1908        $add_filter  = '';
1909        if ($member_attr != 'member' && $member_attr != 'uniqueMember')
1910            $add_filter = "($member_attr=$contact_dn)";
1911        $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
1912
1913        $this->_debug("C: Search [$filter][dn: $base_dn]");
1914
1915        $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
1916        if ($res === false)
1917        {
1918            $this->_debug("S: ".ldap_error($this->conn));
1919            return array();
1920        }
1921        $ldap_data = ldap_get_entries($this->conn, $res);
1922        $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
1923
1924        $groups = array();
1925        for ($i=0; $i<$ldap_data["count"]; $i++)
1926        {
1927            $group_name = $ldap_data[$i][$name_attr][0];
1928            $group_id = self::dn_encode($group_name);
1929            $groups[$group_id] = $group_id;
1930        }
1931        return $groups;
1932    }
1933
1934
1935    /**
1936     * Generate BER encoded string for Virtual List View option
1937     *
1938     * @param integer List offset (first record)
1939     * @param integer Records per page
1940     * @return string BER encoded option value
1941     */
1942    private function _vlv_ber_encode($offset, $rpp, $search = '')
1943    {
1944        # this string is ber-encoded, php will prefix this value with:
1945        # 04 (octet string) and 10 (length of 16 bytes)
1946        # the code behind this string is broken down as follows:
1947        # 30 = ber sequence with a length of 0e (14) bytes following
1948        # 02 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
1949        # 02 = type integer (in two's complement form) with 2 bytes following (afterCount):  01 18 (ie 25-1=24)
1950        # a0 = type context-specific/constructed with a length of 06 (6) bytes following
1951        # 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
1952        # 02 = type integer with 2 bytes following (contentCount):  01 00
1953       
1954        # whith a search string present:
1955        # 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
1956        # 81 indicates a user string is present where as a a0 indicates just a offset search
1957        # 81 = type context-specific/constructed with a length of 06 (6) bytes following
1958       
1959        # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
1960        # encoding of integer values (note: these values are in
1961        # two-complement form so since offset will never be negative bit 8 of the
1962        # leftmost octet should never by set to 1):
1963        # 8.3.2: If the contents octets of an integer value encoding consist
1964        # of more than one octet, then the bits of the first octet (rightmost) and bit 8
1965        # of the second (to the left of first octet) octet:
1966        # a) shall not all be ones; and
1967        # b) shall not all be zero
1968       
1969        if ($search)
1970        {
1971            $search = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
1972            $ber_val = self::_string2hex($search);
1973            $str = self::_ber_addseq($ber_val, '81');
1974        }
1975        else
1976        {
1977            # construct the string from right to left
1978            $str = "020100"; # contentCount
1979
1980            $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
1981
1982            // calculate octet length of $ber_val
1983            $str = self::_ber_addseq($ber_val, '02') . $str;
1984
1985            // now compute length over $str
1986            $str = self::_ber_addseq($str, 'a0');
1987        }
1988       
1989        // now tack on records per page
1990        $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;
1991
1992        // now tack on sequence identifier and length
1993        $str = self::_ber_addseq($str, '30');
1994
1995        return pack('H'.strlen($str), $str);
1996    }
1997
1998
1999    /**
2000     * create ber encoding for sort control
2001     *
2002     * @param array List of cols to sort by
2003     * @return string BER encoded option value
2004     */
2005    private function _sort_ber_encode($sortcols)
2006    {
2007        $str = '';
2008        foreach (array_reverse((array)$sortcols) as $col) {
2009            $ber_val = self::_string2hex($col);
2010
2011            # 30 = ber sequence with a length of octet value
2012            # 04 = octet string with a length of the ascii value
2013            $oct = self::_ber_addseq($ber_val, '04');
2014            $str = self::_ber_addseq($oct, '30') . $str;
2015        }
2016
2017        // now tack on sequence identifier and length
2018        $str = self::_ber_addseq($str, '30');
2019
2020        return pack('H'.strlen($str), $str);
2021    }
2022
2023    /**
2024     * Add BER sequence with correct length and the given identifier
2025     */
2026    private static function _ber_addseq($str, $identifier)
2027    {
2028        $len = dechex(strlen($str)/2);
2029        if (strlen($len) % 2 != 0)
2030            $len = '0'.$len;
2031
2032        return $identifier . $len . $str;
2033    }
2034
2035    /**
2036     * Returns BER encoded integer value in hex format
2037     */
2038    private static function _ber_encode_int($offset)
2039    {
2040        $val = dechex($offset);
2041        $prefix = '';
2042
2043        // check if bit 8 of high byte is 1
2044        if (preg_match('/^[89abcdef]/', $val))
2045            $prefix = '00';
2046
2047        if (strlen($val)%2 != 0)
2048            $prefix .= '0';
2049
2050        return $prefix . $val;
2051    }
2052
2053    /**
2054     * Returns ascii string encoded in hex
2055     */
2056    private static function _string2hex($str)
2057    {
2058        $hex = '';
2059        for ($i=0; $i < strlen($str); $i++)
2060            $hex .= dechex(ord($str[$i]));
2061        return $hex;
2062    }
2063
2064    /**
2065     * HTML-safe DN string encoding
2066     *
2067     * @param string $str DN string
2068     *
2069     * @return string Encoded HTML identifier string
2070     */
2071    static function dn_encode($str)
2072    {
2073        // @TODO: to make output string shorter we could probably
2074        //        remove dc=* items from it
2075        return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
2076    }
2077
2078    /**
2079     * Decodes DN string encoded with _dn_encode()
2080     *
2081     * @param string $str Encoded HTML identifier string
2082     *
2083     * @return string DN string
2084     */
2085    static function dn_decode($str)
2086    {
2087        $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
2088        return base64_decode($str);
2089    }
2090
2091    /**
2092     * Wrapper for ldap_add()
2093     */
2094    protected function ldap_add($dn, $entry)
2095    {
2096        $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2097
2098        $res = ldap_add($this->conn, $dn, $entry);
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_delete()
2110     */
2111    protected function ldap_delete($dn)
2112    {
2113        $this->_debug("C: Delete [dn: $dn]");
2114
2115        $res = ldap_delete($this->conn, $dn);
2116        if ($res === false) {
2117            $this->_debug("S: ".ldap_error($this->conn));
2118            return false;
2119        }
2120
2121        $this->_debug("S: OK");
2122        return true;
2123    }
2124
2125    /**
2126     * Wrapper for ldap_mod_replace()
2127     */
2128    protected function ldap_mod_replace($dn, $entry)
2129    {
2130        $this->_debug("C: Replace [dn: $dn]: ".print_r($entry, true));
2131
2132        if (!ldap_mod_replace($this->conn, $dn, $entry)) {
2133            $this->_debug("S: ".ldap_error($this->conn));
2134            return false;
2135        }
2136
2137        $this->_debug("S: OK");
2138        return true;
2139    }
2140
2141    /**
2142     * Wrapper for ldap_mod_add()
2143     */
2144    protected function ldap_mod_add($dn, $entry)
2145    {
2146        $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2147
2148        if (!ldap_mod_add($this->conn, $dn, $entry)) {
2149            $this->_debug("S: ".ldap_error($this->conn));
2150            return false;
2151        }
2152
2153        $this->_debug("S: OK");
2154        return true;
2155    }
2156
2157    /**
2158     * Wrapper for ldap_mod_del()
2159     */
2160    protected function ldap_mod_del($dn, $entry)
2161    {
2162        $this->_debug("C: Delete [dn: $dn]: ".print_r($entry, true));
2163
2164        if (!ldap_mod_del($this->conn, $dn, $entry)) {
2165            $this->_debug("S: ".ldap_error($this->conn));
2166            return false;
2167        }
2168
2169        $this->_debug("S: OK");
2170        return true;
2171    }
2172
2173    /**
2174     * Wrapper for ldap_rename()
2175     */
2176    protected function ldap_rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
2177    {
2178        $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
2179
2180        if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
2181            $this->_debug("S: ".ldap_error($this->conn));
2182            return false;
2183        }
2184
2185        $this->_debug("S: OK");
2186        return true;
2187    }
2188
2189    /**
2190     * Wrapper for ldap_list()
2191     */
2192    protected function ldap_list($dn, $filter, $attrs = array(''))
2193    {
2194        $list = array();
2195        $this->_debug("C: List [dn: $dn] [{$filter}]");
2196
2197        if ($result = ldap_list($this->conn, $dn, $filter, $attrs)) {
2198            $list = ldap_get_entries($this->conn, $result);
2199
2200            if ($list === false) {
2201                $this->_debug("S: ".ldap_error($this->conn));
2202                return array();
2203            }
2204
2205            $count = $list['count'];
2206            unset($list['count']);
2207
2208            $this->_debug("S: $count record(s)");
2209        }
2210        else {
2211            $this->_debug("S: ".ldap_error($this->conn));
2212        }
2213
2214        return $list;
2215    }
2216
2217}
Note: See TracBrowser for help on using the repository browser.