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