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

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