source: github/program/include/rcube_ldap.php @ 6f3fa96

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 6f3fa96 was 6f3fa96, checked in by thomascube <thomas@…>, 2 years ago

Use dechex() instead of sprintf() for base conversion

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