source: github/program/include/rcube_ldap.php @ 2a3e0276

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