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

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