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

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