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

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