source: subversion/branches/release-0.7/program/include/rcube_ldap.php @ 5351

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