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

Last change on this file since 4560 was 4560, checked in by alec, 2 years ago
  • Add LDAP SASL bind and proxy authentication (#1486692)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 37.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 | Licensed under the GNU GPL                                            |
9 |                                                                       |
10 | PURPOSE:                                                              |
11 |   Interface to an LDAP address directory                              |
12 |                                                                       |
13 +-----------------------------------------------------------------------+
14 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
15 |         Andreas Dick <andudi (at) gmx (dot) ch>                       |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22
23/**
24 * Model class to access an LDAP address directory
25 *
26 * @package Addressbook
27 */
28class rcube_ldap extends rcube_addressbook
29{
30    /** public properties */
31    public $primary_key = 'ID';
32    public $groups = false;
33    public $readonly = true;
34    public $ready = false;
35    public $group_id = 0;
36    public $list_page = 1;
37    public $page_size = 10;
38    public $coltypes = array();
39
40    /** private properties */
41    protected $conn;
42    protected $prop = array();
43    protected $fieldmap = array();
44
45    protected $filter = '';
46    protected $result = null;
47    protected $ldap_result = null;
48    protected $sort_col = '';
49    protected $mail_domain = '';
50    protected $debug = false;
51
52    private $group_cache = array();
53    private $group_members = array();
54
55
56    /**
57    * Object constructor
58    *
59    * @param array      LDAP connection properties
60    * @param boolean    Enables debug mode
61    * @param string     Current user mail domain name
62    * @param integer User-ID
63    */
64    function __construct($p, $debug=false, $mail_domain=NULL)
65    {
66        $this->prop = $p;
67
68        // check if groups are configured
69        if (is_array($p['groups']))
70            $this->groups = true;
71
72        // fieldmap property is given
73        if (is_array($p['fieldmap'])) {
74            foreach ($p['fieldmap'] as $rf => $lf)
75                $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
76        }
77        else {
78            // read deprecated *_field properties to remain backwards compatible
79            foreach ($p as $prop => $value)
80                if (preg_match('/^(.+)_field$/', $prop, $matches))
81                    $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
82        }
83
84        // use fieldmap to advertise supported coltypes to the application
85        foreach ($this->fieldmap as $col => $lf) {
86            list($col, $type) = explode(':', $col);
87            if (!is_array($this->coltypes[$col])) {
88                $subtypes = $type ? array($type) : null;
89                $this->coltypes[$col] = array('limit' => 2, 'subtypes' => $subtypes);
90            }
91            elseif ($type) {
92                $this->coltypes[$col]['subtypes'][] = $type;
93                $this->coltypes[$col]['limit']++;
94            }
95            if ($type && !$this->fieldmap[$col])
96                $this->fieldmap[$col] = $lf;
97        }
98
99        if ($this->fieldmap['street'] && $this->fieldmap['locality'])
100            $this->coltypes['address'] = array('limit' => 1);
101        else if ($this->coltypes['address'])
102            $this->coltypes['address'] = array('type' => 'textarea', 'childs' => null, 'limit' => 1, 'size' => 40);
103
104        // make sure 'required_fields' is an array
105        if (!is_array($this->prop['required_fields']))
106            $this->prop['required_fields'] = (array) $this->prop['required_fields'];
107
108        foreach ($this->prop['required_fields'] as $key => $val)
109            $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
110
111        $this->sort_col = $p['sort'];
112        $this->debug = $debug;
113        $this->mail_domain = $mail_domain;
114
115        $this->_connect();
116    }
117
118
119    /**
120    * Establish a connection to the LDAP server
121    */
122    private function _connect()
123    {
124        global $RCMAIL;
125
126        if (!function_exists('ldap_connect'))
127            raise_error(array('code' => 100, 'type' => 'ldap',
128            'file' => __FILE__, 'line' => __LINE__,
129            'message' => "No ldap support in this installation of PHP"), true);
130
131        if (is_resource($this->conn))
132            return true;
133
134        if (!is_array($this->prop['hosts']))
135            $this->prop['hosts'] = array($this->prop['hosts']);
136
137        if (empty($this->prop['ldap_version']))
138            $this->prop['ldap_version'] = 3;
139
140        foreach ($this->prop['hosts'] as $host)
141        {
142            $host = idn_to_ascii(rcube_parse_host($host));
143            $this->_debug("C: Connect [$host".($this->prop['port'] ? ':'.$this->prop['port'] : '')."]");
144
145            if ($lc = @ldap_connect($host, $this->prop['port']))
146            {
147                if ($this->prop['use_tls']===true)
148                    if (!ldap_start_tls($lc))
149                        continue;
150
151                $this->_debug("S: OK");
152
153                ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
154                $this->prop['host'] = $host;
155                $this->conn = $lc;
156                break;
157            }
158            $this->_debug("S: NOT OK");
159        }
160
161        if (is_resource($this->conn))
162        {
163            $this->ready = true;
164
165            $bind_pass = $this->prop['bind_pass'];
166            $bind_user = $this->prop['bind_user'];
167            $bind_dn   = $this->prop['bind_dn'];
168            $base_dn   = $this->prop['base_dn'];
169
170            // User specific access, generate the proper values to use.
171            if ($this->prop['user_specific']) {
172                // No password set, use the session password
173                if (empty($bind_pass)) {
174                    $bind_pass = $RCMAIL->decrypt($_SESSION['password']);
175                }
176
177                // Get the pieces needed for variable replacement.
178                $fu = $RCMAIL->user->get_username();
179                list($u, $d) = explode('@', $fu);
180                $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
181
182                $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
183
184                if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
185                    // Search for the dn to use to authenticate
186                    $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
187                    $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
188
189                    $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
190
191                    $res = ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
192                    if ($res && ($entry = ldap_first_entry($this->conn, $res))) {
193                        $bind_dn = ldap_get_dn($this->conn, $entry);
194
195                        $this->_debug("S: search returned dn: $bind_dn");
196
197                        if ($bind_dn) {
198                            $dn = ldap_explode_dn($bind_dn, 1);
199                            $replaces['%dn'] = $dn[0];
200                        }
201                    }
202                }
203                // Replace the bind_dn and base_dn variables.
204                $bind_dn   = strtr($bind_dn, $replaces);
205                $base_dn   = strtr($base_dn, $replaces);
206
207                if (empty($bind_user)) {
208                    $bind_user = $u;
209                }
210            }
211
212            if (!empty($bind_pass)) {
213                if (!empty($bind_dn)) {
214                    $this->ready = $this->_bind($bind_dn, $bind_pass);
215                }
216                else if (!empty($this->prop['auth_cid'])) {
217                    $this->ready = $this->_sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
218                }
219                else {
220                    $this->ready = $this->_sasl_bind($bind_user, $bind_pass);
221                }
222            }
223        }
224        else
225            raise_error(array('code' => 100, 'type' => 'ldap',
226                'file' => __FILE__, 'line' => __LINE__,
227                'message' => "Could not connect to any LDAP server, last tried $host:{$this->prop[port]}"), true);
228
229        // See if the directory is writeable.
230        if ($this->prop['writable']) {
231            $this->readonly = false;
232        } // end if
233    }
234
235
236    /**
237     * Bind connection with (SASL-) user and password
238     *
239     * @param string $authc Authentication user
240     * @param string $pass  Bind password
241     * @param string $authz Autorization user
242     *
243     * @return boolean True on success, False on error
244     */
245    private function _sasl_bind($authc, $pass, $authz=null)
246    {
247        if (!$this->conn) {
248            return false;
249        }
250
251        if (!function_exists('ldap_sasl_bind')) {
252            raise_error(array(
253                'code' => 100, 'type' => 'ldap',
254                'file' => __FILE__, 'line' => __LINE__,
255                'message' => "Unable to bind: ldap_sasl_bind() not exists"),
256            true, true);
257        }
258
259        if (!empty($authz)) {
260            $authz = 'u:' . $authz;
261        }
262
263        if (!empty($this->prop['auth_method'])) {
264            $method = $this->prop['auth_method'];
265        }
266        else {
267            $method = 'DIGEST-MD5';
268        }
269
270        $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz] [pass: $pass]");
271
272        if (ldap_sasl_bind($this->conn, NULL, $pass, $method, NULL, $authc, $authz)) {
273            $this->_debug("S: OK");
274            return true;
275        }
276
277        $this->_debug("S: ".ldap_error($this->conn));
278
279        raise_error(array(
280            'code' => ldap_errno($this->conn), 'type' => 'ldap',
281            'file' => __FILE__, 'line' => __LINE__,
282            'message' => "Bind failed for authcid=$authc ".ldap_error($this->conn)),
283            true);
284
285        return false;
286    }
287
288
289    /**
290    * Bind connection with DN and password
291    *
292    * @param string Bind DN
293    * @param string Bind password
294    * @return boolean True on success, False on error
295    */
296    private function _bind($dn, $pass)
297    {
298        if (!$this->conn) {
299            return false;
300        }
301
302        $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
303
304        if (@ldap_bind($this->conn, $dn, $pass)) {
305            $this->_debug("S: OK");
306            return true;
307        }
308
309        $this->_debug("S: ".ldap_error($this->conn));
310
311        $error =  array(
312                'code' => ldap_errno($this->conn), 'type' => 'ldap',
313                'file' => __FILE__, 'line' => __LINE__,
314                'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn));
315        raise_error($error,true);
316
317        return false;
318    }
319
320
321    /**
322    * Close connection to LDAP server
323    */
324    function close()
325    {
326        if ($this->conn)
327        {
328            $this->_debug("C: Close");
329            ldap_unbind($this->conn);
330            $this->conn = null;
331        }
332    }
333
334
335    /**
336    * Set internal list page
337    *
338    * @param  number  Page number to list
339    * @access public
340    */
341    function set_page($page)
342    {
343        $this->list_page = (int)$page;
344    }
345
346
347    /**
348    * Set internal page size
349    *
350    * @param  number  Number of messages to display on one page
351    * @access public
352    */
353    function set_pagesize($size)
354    {
355        $this->page_size = (int)$size;
356    }
357
358
359    /**
360    * Save a search string for future listings
361    *
362    * @param string Filter string
363    */
364    function set_search_set($filter)
365    {
366        $this->filter = $filter;
367    }
368
369
370    /**
371    * Getter for saved search properties
372    *
373    * @return mixed Search properties used by this class
374    */
375    function get_search_set()
376    {
377        return $this->filter;
378    }
379
380
381    /**
382    * Reset all saved results and search parameters
383    */
384    function reset()
385    {
386        $this->result = null;
387        $this->ldap_result = null;
388        $this->filter = '';
389    }
390
391
392    /**
393    * List the current set of contact records
394    *
395    * @param  array  List of cols to show
396    * @param  int    Only return this number of records
397    * @return array  Indexed list of contact records, each a hash array
398    */
399    function list_records($cols=null, $subset=0)
400    {
401        // add general filter to query
402        if (!empty($this->prop['filter']) && empty($this->filter))
403        {
404            $filter = $this->prop['filter'];
405            $this->set_search_set($filter);
406        }
407
408        // exec LDAP search if no result resource is stored
409        if ($this->conn && !$this->ldap_result)
410            $this->_exec_search();
411
412        // count contacts for this user
413        $this->result = $this->count();
414
415        // we have a search result resource
416        if ($this->ldap_result && $this->result->count > 0)
417        {
418            if ($this->sort_col && $this->prop['scope'] !== 'base')
419                ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
420
421            $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
422            $last_row = $this->result->first + $this->page_size;
423            $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
424
425            $entries = ldap_get_entries($this->conn, $this->ldap_result);
426            for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
427                $this->result->add($this->_ldap2result($entries[$i]));
428        }
429
430        // temp hack for filtering group members
431        if ($this->groups and $this->group_id)
432        {
433            $result = new rcube_result_set();
434            while ($record = $this->result->iterate())
435            {
436                if ($this->group_members[$record['ID']])
437                {
438                    $result->add($record);
439                    $result->count++;
440                }
441            }
442            $this->result = $result;
443        }
444
445        return $this->result;
446    }
447
448
449    /**
450    * Search contacts
451    *
452    * @param array   List of fields to search in
453    * @param string  Search value
454    * @param boolean True for strict, False for partial (fuzzy) matching
455    * @param boolean True if results are requested, False if count only
456    * @param boolean (Not used)
457    * @param array   List of fields that cannot be empty
458    * @return array  Indexed list of contact records and 'count' value
459    */
460    function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
461    {
462        // special treatment for ID-based search
463        if ($fields == 'ID' || $fields == $this->primary_key)
464        {
465            $ids = explode(',', $value);
466            $result = new rcube_result_set();
467            foreach ($ids as $id)
468            {
469                if ($rec = $this->get_record($id, true))
470                {
471                    $result->add($rec);
472                    $result->count++;
473                }
474            }
475            return $result;
476        }
477
478        $filter = '(|';
479        $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
480        if ($fields != '*')
481        {
482            // search_fields are required for fulltext search
483            if (!$this->prop['search_fields'])
484            {
485                $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
486                $this->result = new rcube_result_set();
487                return $this->result;
488            }
489        }
490       
491        if (is_array($this->prop['search_fields']))
492        {
493            foreach ($this->prop['search_fields'] as $k => $field)
494                $filter .= "($field=$wc" . $this->_quote_string($value) . "$wc)";
495        }
496        else
497        {
498            foreach ((array)$fields as $field)
499                if ($f = $this->_map_field($field))
500                    $filter .= "($f=$wc" . $this->_quote_string($value) . "$wc)";
501        }
502        $filter .= ')';
503
504        // add required (non empty) fields filter
505        $req_filter = '';
506        foreach ((array)$required as $field)
507            if ($f = $this->_map_field($field))
508                $req_filter .= "($f=*)";
509
510        if (!empty($req_filter))
511            $filter = '(&' . $req_filter . $filter . ')';
512
513        // avoid double-wildcard if $value is empty
514        $filter = preg_replace('/\*+/', '*', $filter);
515
516        // add general filter to query
517        if (!empty($this->prop['filter']))
518            $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
519
520        // set filter string and execute search
521        $this->set_search_set($filter);
522        $this->_exec_search();
523
524        if ($select)
525            $this->list_records();
526        else
527            $this->result = $this->count();
528
529        return $this->result;
530    }
531
532
533    /**
534    * Count number of available contacts in database
535    *
536    * @return object rcube_result_set Resultset with values for 'count' and 'first'
537    */
538    function count()
539    {
540        $count = 0;
541        if ($this->conn && $this->ldap_result) {
542            $count = ldap_count_entries($this->conn, $this->ldap_result);
543        } // end if
544        elseif ($this->conn) {
545            // We have a connection but no result set, attempt to get one.
546            if (empty($this->filter)) {
547                // The filter is not set, set it.
548                $this->filter = $this->prop['filter'];
549            } // end if
550            $this->_exec_search();
551            if ($this->ldap_result) {
552                $count = ldap_count_entries($this->conn, $this->ldap_result);
553            } // end if
554        } // end else
555
556        return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
557    }
558
559
560    /**
561    * Return the last result set
562    *
563    * @return object rcube_result_set Current resultset or NULL if nothing selected yet
564    */
565    function get_result()
566    {
567        return $this->result;
568    }
569
570
571    /**
572    * Get a specific contact record
573    *
574    * @param mixed   Record identifier
575    * @param boolean Return as associative array
576    * @return mixed  Hash array or rcube_result_set with all record fields
577    */
578    function get_record($dn, $assoc=false)
579    {
580        $res = null;
581        if ($this->conn && $dn)
582        {
583            $dn = base64_decode($dn);
584
585            $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
586
587            if ($this->ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap)))
588                $entry = ldap_first_entry($this->conn, $this->ldap_result);
589            else
590                $this->_debug("S: ".ldap_error($this->conn));
591
592            if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
593            {
594                $this->_debug("S: OK"/* . print_r($rec, true)*/);
595
596                $rec = array_change_key_case($rec, CASE_LOWER);
597
598                // Add in the dn for the entry.
599                $rec['dn'] = $dn;
600                $res = $this->_ldap2result($rec);
601                $this->result = new rcube_result_set(1);
602                $this->result->add($res);
603            }
604        }
605
606        return $assoc ? $res : $this->result;
607    }
608
609
610    /**
611    * Create a new contact record
612    *
613    * @param array    Hash array with save data
614    * @return encoded record ID on success, False on error
615    */
616    function insert($save_cols)
617    {
618        // Map out the column names to their LDAP ones to build the new entry.
619        $newentry = array();
620        $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
621        foreach ($this->fieldmap as $col => $fld) {
622            $val = $save_cols[$col];
623            if (is_array($val))
624                $val = array_filter($val);  // remove empty entries
625            if ($fld && $val) {
626                // The field does exist, add it to the entry.
627                $newentry[$fld] = $val;
628            } // end if
629        } // end foreach
630
631        // Verify that the required fields are set.
632        foreach ($this->prop['required_fields'] as $fld) {
633            $missing = null;
634            if (!isset($newentry[$fld])) {
635                $missing[] = $fld;
636            }
637        }
638
639        // abort process if requiered fields are missing
640        // TODO: generate message saying which fields are missing
641        if ($missing) {
642            $this->set_error(self::ERROR_INCOMPLETE, 'formincomplete');
643            return false;
644        }
645
646        // Build the new entries DN.
647        $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->prop['base_dn'];
648
649        $this->_debug("C: Add [dn: $dn]: ".print_r($newentry, true));
650
651        $res = ldap_add($this->conn, $dn, $newentry);
652        if ($res === FALSE) {
653            $this->_debug("S: ".ldap_error($this->conn));
654            $this->set_error(self::ERROR_SAVING, 'errorsaving');
655            return false;
656        } // end if
657
658        $this->_debug("S: OK");
659
660        // add new contact to the selected group
661        if ($this->groups)
662            $this->add_to_group($this->group_id, base64_encode($dn));
663
664        return base64_encode($dn);
665    }
666
667
668    /**
669    * Update a specific contact record
670    *
671    * @param mixed Record identifier
672    * @param array Hash array with save data
673    * @return boolean True on success, False on error
674    */
675    function update($id, $save_cols)
676    {
677        $record = $this->get_record($id, true);
678        $result = $this->get_result();
679        $record = $result->first();
680
681        $newdata = array();
682        $replacedata = array();
683        $deletedata = array();
684        foreach ($this->fieldmap as $col => $fld) {
685            $val = $save_cols[$col];
686            if ($fld) {
687                // remove empty array values
688                if (is_array($val))
689                    $val = array_filter($val);
690                // The field does exist compare it to the ldap record.
691                if ($record[$col] != $val) {
692                    // Changed, but find out how.
693                    if (!isset($record[$col])) {
694                        // Field was not set prior, need to add it.
695                        $newdata[$fld] = $val;
696                    } // end if
697                    elseif ($val == '') {
698                        // Field supplied is empty, verify that it is not required.
699                        if (!in_array($fld, $this->prop['required_fields'])) {
700                            // It is not, safe to clear.
701                            $deletedata[$fld] = $record[$col];
702                        } // end if
703                    } // end elseif
704                    else {
705                        // The data was modified, save it out.
706                        $replacedata[$fld] = $val;
707                    } // end else
708                } // end if
709            } // end if
710        } // end foreach
711
712        $dn = base64_decode($id);
713
714        // Update the entry as required.
715        if (!empty($deletedata)) {
716            // Delete the fields.
717            $this->_debug("C: Delete [dn: $dn]: ".print_r($deletedata, true));
718            if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
719                $this->_debug("S: ".ldap_error($this->conn));
720                $this->set_error(self::ERROR_SAVING, 'errorsaving');
721                return false;
722            }
723            $this->_debug("S: OK");
724        } // end if
725
726        if (!empty($replacedata)) {
727            // Handle RDN change
728            if ($replacedata[$this->prop['LDAP_rdn']]) {
729                $newdn = $this->prop['LDAP_rdn'].'='
730                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
731                    .','.$this->prop['base_dn'];
732                if ($dn != $newdn) {
733                    $newrdn = $this->prop['LDAP_rdn'].'='
734                    .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
735                    unset($replacedata[$this->prop['LDAP_rdn']]);
736                }
737            }
738            // Replace the fields.
739            if (!empty($replacedata)) {
740                $this->_debug("C: Replace [dn: $dn]: ".print_r($replacedata, true));
741                if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
742                    $this->_debug("S: ".ldap_error($this->conn));
743                    return false;
744                }
745                $this->_debug("S: OK");
746            } // end if
747        } // end if
748
749        if (!empty($newdata)) {
750            // Add the fields.
751            $this->_debug("C: Add [dn: $dn]: ".print_r($newdata, true));
752            if (!ldap_mod_add($this->conn, $dn, $newdata)) {
753                $this->_debug("S: ".ldap_error($this->conn));
754                $this->set_error(self::ERROR_SAVING, 'errorsaving');
755                return false;
756            }
757            $this->_debug("S: OK");
758        } // end if
759
760        // Handle RDN change
761        if (!empty($newrdn)) {
762            $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
763            if (!ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
764                $this->_debug("S: ".ldap_error($this->conn));
765                return false;
766            }
767            $this->_debug("S: OK");
768
769            // change the group membership of the contact
770            if ($this->groups)
771            {
772                $group_ids = $this->get_record_groups(base64_encode($dn));
773                foreach ($group_ids as $group_id)
774                {
775                    $this->remove_from_group($group_id, base64_encode($dn));
776                    $this->add_to_group($group_id, base64_encode($newdn));
777                }
778            }
779            return base64_encode($newdn);
780        }
781
782        return true;
783    }
784
785
786    /**
787    * Mark one or more contact records as deleted
788    *
789    * @param array  Record identifiers
790    * @return boolean True on success, False on error
791    */
792    function delete($ids)
793    {
794        if (!is_array($ids)) {
795            // Not an array, break apart the encoded DNs.
796            $dns = explode(',', $ids);
797        } // end if
798
799        foreach ($dns as $id) {
800            $dn = base64_decode($id);
801            $this->_debug("C: Delete [dn: $dn]");
802            // Delete the record.
803            $res = ldap_delete($this->conn, $dn);
804            if ($res === FALSE) {
805                $this->_debug("S: ".ldap_error($this->conn));
806                $this->set_error(self::ERROR_SAVING, 'errorsaving');
807                return false;
808            } // end if
809            $this->_debug("S: OK");
810
811            // remove contact from all groups where he was member
812            if ($this->groups)
813            {
814                $group_ids = $this->get_record_groups(base64_encode($dn));
815                foreach ($group_ids as $group_id)
816                {
817                    $this->remove_from_group($group_id, base64_encode($dn));
818                }
819            }
820        } // end foreach
821
822        return count($dns);
823    }
824
825
826    /**
827    * Execute the LDAP search based on the stored credentials
828    *
829    * @access private
830    */
831    private function _exec_search()
832    {
833        if ($this->ready)
834        {
835            $filter = $this->filter ? $this->filter : '(objectclass=*)';
836            $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
837
838            $this->_debug("C: Search [".$filter."]");
839
840            if ($this->ldap_result = @$function($this->conn, $this->prop['base_dn'], $filter,
841                array_values($this->fieldmap), 0, (int) $this->prop['sizelimit'], (int) $this->prop['timelimit']))
842            {
843                $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
844                return true;
845            }
846            else
847            {
848                $this->_debug("S: ".ldap_error($this->conn));
849            }
850        }
851
852        return false;
853    }
854
855
856    /**
857    * @access private
858    */
859    private function _ldap2result($rec)
860    {
861        $out = array();
862
863        if ($rec['dn'])
864            $out[$this->primary_key] = base64_encode($rec['dn']);
865
866        foreach ($this->fieldmap as $rf => $lf)
867        {
868            for ($i=0; $i < $rec[$lf]['count']; $i++) {
869                if (!($value = $rec[$lf][$i]))
870                    continue;
871                if ($rf == 'email' && $this->mail_domain && !strpos($value, '@'))
872                    $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
873                else if (in_array($rf, array('street','zipcode','locality','country','region')))
874                    $out['address'][$i][$rf] = $value;
875                else if ($rec[$lf]['count'] > 1)
876                    $out[$rf][] = $value;
877                else
878                    $out[$rf] = $value;
879            }
880        }
881
882        return $out;
883    }
884
885
886    /**
887    * @access private
888    */
889    private function _map_field($field)
890    {
891        return $this->fieldmap[$field];
892    }
893
894
895    /**
896    * @access private
897    */
898    private function _attr_name($name)
899    {
900        // list of known attribute aliases
901        $aliases = array(
902            'gn' => 'givenname',
903            'rfc822mailbox' => 'email',
904            'userid' => 'uid',
905            'emailaddress' => 'email',
906            'pkcs9email' => 'email',
907        );
908        return isset($aliases[$name]) ? $aliases[$name] : $name;
909    }
910
911
912    /**
913    * @access private
914    */
915    private function _debug($str)
916    {
917        if ($this->debug)
918            write_log('ldap', $str);
919    }
920
921
922    /**
923    * @static
924    */
925    private function _quote_string($str, $dn=false)
926    {
927        // take firt entry if array given
928        if (is_array($str))
929            $str = reset($str);
930
931        if ($dn)
932            $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
933                '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
934        else
935            $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
936                '/'=>'\2f');
937
938        return strtr($str, $replace);
939    }
940
941
942    /**
943     * Setter for the current group
944     * (empty, has to be re-implemented by extending class)
945     */
946    function set_group($group_id)
947    {
948        if ($group_id)
949        {
950            if (!$this->group_cache)
951                $this->list_groups();
952
953            $cache_members = $this->group_cache[$group_id]['members'];
954
955            $members = array();
956            for ($i=1; $i<$cache_members["count"]; $i++)
957            {
958                $members[base64_encode($cache_members[$i])] = 1;
959            }
960            $this->group_members = $members;
961            $this->group_id = $group_id;
962        }
963        else
964            $this->group_id = 0;
965    }
966
967    /**
968     * List all active contact groups of this source
969     *
970     * @param string  Optional search string to match group name
971     * @return array  Indexed list of contact groups, each a hash array
972     */
973    function list_groups($search = null)
974    {
975        if (!$this->groups)
976            return array();
977
978        $base_dn = $this->prop['groups']['base_dn'];
979        $filter = '(objectClass=groupOfNames)';
980
981        $res = ldap_search($this->conn, $base_dn, $filter, array('cn','member'));
982        if ($res === false)
983        {
984            $this->_debug("S: ".ldap_error($this->conn));
985            $this->set_error(self::ERROR_SAVING, 'errorsaving');
986            return array();
987        }
988        $ldap_data = ldap_get_entries($this->conn, $res);
989
990        $groups = array();
991        $group_sortnames = array();
992        for ($i=0; $i<$ldap_data["count"]; $i++)
993        {
994            $group_name = $ldap_data[$i]['cn'][0];
995            $group_id = base64_encode($group_name);
996            $groups[$group_id]['ID'] = $group_id;
997            $groups[$group_id]['name'] = $group_name;
998            $groups[$group_id]['members'] = $ldap_data[$i]['member'];
999            $group_sortnames[] = strtolower($group_name);
1000        }
1001        array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
1002        $this->group_cache = $groups;
1003
1004        return $groups;
1005    }
1006
1007    /**
1008     * Create a contact group with the given name
1009     *
1010     * @param string The group name
1011     * @return mixed False on error, array with record props in success
1012     */
1013    function create_group($group_name)
1014    {
1015        if (!$this->group_cache)
1016            $this->list_groups();
1017
1018        $base_dn = $this->prop['groups']['base_dn'];
1019        $new_dn = "cn=$group_name,$base_dn";
1020        $new_gid = base64_encode($group_name);
1021
1022        $new_entry = array(
1023            'objectClass' => array('top', 'groupOfNames'),
1024            'cn' => $group_name,
1025            'member' => '',
1026        );
1027
1028        $res = ldap_add($this->conn, $new_dn, $new_entry);
1029        if ($res === false)
1030        {
1031            $this->_debug("S: ".ldap_error($this->conn));
1032            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1033            return false;
1034        }
1035        return array('id' => $new_gid, 'name' => $group_name);
1036    }
1037
1038    /**
1039     * Delete the given group and all linked group members
1040     *
1041     * @param string Group identifier
1042     * @return boolean True on success, false if no data was changed
1043     */
1044    function delete_group($group_id)
1045    {
1046        if (!$this->group_cache)
1047            $this->list_groups();
1048
1049        $base_dn = $this->prop['groups']['base_dn'];
1050        $group_name = $this->group_cache[$group_id]['name'];
1051
1052        $del_dn = "cn=$group_name,$base_dn";
1053        $res = ldap_delete($this->conn, $del_dn);
1054        if ($res === false)
1055        {
1056            $this->_debug("S: ".ldap_error($this->conn));
1057            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1058            return false;
1059        }
1060        return true;
1061    }
1062
1063    /**
1064     * Rename a specific contact group
1065     *
1066     * @param string Group identifier
1067     * @param string New name to set for this group
1068     * @param string New group identifier (if changed, otherwise don't set)
1069     * @return boolean New name on success, false if no data was changed
1070     */
1071    function rename_group($group_id, $new_name, &$new_id)
1072    {
1073        if (!$this->group_cache)
1074            $this->list_groups();
1075
1076        $base_dn = $this->prop['groups']['base_dn'];
1077        $group_name = $this->group_cache[$group_id]['name'];
1078        $old_dn = "cn=$group_name,$base_dn";
1079        $new_rdn = "cn=$new_name";
1080        $new_id = base64_encode($new_rdn . ",$base_dn");
1081
1082        $res = ldap_rename($this->conn, $old_dn, $new_rdn, NULL, TRUE);
1083        if ($res === false)
1084        {
1085            $this->_debug("S: ".ldap_error($this->conn));
1086            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1087            return false;
1088        }
1089        return $new_name;
1090    }
1091
1092    /**
1093     * Add the given contact records the a certain group
1094     *
1095     * @param string  Group identifier
1096     * @param array   List of contact identifiers to be added
1097     * @return int    Number of contacts added
1098     */
1099    function add_to_group($group_id, $contact_ids)
1100    {
1101        if (!$this->group_cache)
1102            $this->list_groups();
1103
1104        $base_dn = $this->prop['groups']['base_dn'];
1105        $group_name = $this->group_cache[$group_id]['name'];
1106        $group_dn = "cn=$group_name,$base_dn";
1107
1108        $new_attrs = array();
1109        foreach (explode(",", $contact_ids) as $id)
1110            $new_attrs['member'][] = base64_decode($id);
1111
1112        $res = ldap_mod_add($this->conn, $group_dn, $new_attrs);
1113        if ($res === false)
1114        {
1115            $this->_debug("S: ".ldap_error($this->conn));
1116            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1117            return 0;
1118        }
1119        return count($new_attrs['member']);
1120    }
1121
1122    /**
1123     * Remove the given contact records from a certain group
1124     *
1125     * @param string  Group identifier
1126     * @param array   List of contact identifiers to be removed
1127     * @return int    Number of deleted group members
1128     */
1129    function remove_from_group($group_id, $contact_ids)
1130    {
1131        if (!$this->group_cache)
1132            $this->list_groups();
1133
1134        $base_dn = $this->prop['groups']['base_dn'];
1135        $group_name = $this->group_cache[$group_id]['name'];
1136        $group_dn = "cn=$group_name,$base_dn";
1137
1138        $del_attrs = array();
1139        foreach (explode(",", $contact_ids) as $id)
1140            $del_attrs['member'][] = base64_decode($id);
1141
1142        $res = ldap_mod_del($this->conn, $group_dn, $del_attrs);
1143        if ($res === false)
1144        {
1145            $this->_debug("S: ".ldap_error($this->conn));
1146            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1147            return 0;
1148        }
1149        return count($del_attrs['member']);
1150    }
1151
1152    /**
1153     * Get group assignments of a specific contact record
1154     *
1155     * @param mixed Record identifier
1156     *
1157     * @return array List of assigned groups as ID=>Name pairs
1158     * @since 0.5-beta
1159     */
1160    function get_record_groups($contact_id)
1161    {
1162        if (!$this->groups)
1163            return array();
1164
1165        $base_dn = $this->prop['groups']['base_dn'];
1166        $contact_dn = base64_decode($contact_id);
1167        $filter = "(member=$contact_dn)";
1168
1169        $res = ldap_search($this->conn, $base_dn, $filter, array('cn'));
1170        if ($res === false)
1171        {
1172            $this->_debug("S: ".ldap_error($this->conn));
1173            $this->set_error(self::ERROR_SAVING, 'errorsaving');
1174            return array();
1175        }
1176        $ldap_data = ldap_get_entries($this->conn, $res);
1177
1178        $groups = array();
1179        for ($i=0; $i<$ldap_data["count"]; $i++)
1180        {
1181            $group_name = $ldap_data[$i]['cn'][0];
1182            $group_id = base64_encode($group_name);
1183            $groups[$group_id] = $group_id;
1184        }
1185        return $groups;
1186    }
1187}
Note: See TracBrowser for help on using the repository browser.