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

Last change on this file since 5162 was 5162, checked in by thomasb, 21 months ago

Fallback to mail_domain in LDAP variable replacements; add 'host' to 'user_create' hook arguments (#1488024)

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