alecpl
2011-05-21 bc8c2c57880523472b30f475d566a8133e2d2e20
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'] ? '*' : '';
3e2637 482         if ($fields != '*')
T 483         {
484             // search_fields are required for fulltext search
485             if (!$this->prop['search_fields'])
486             {
487                 $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
488                 $this->result = new rcube_result_set();
489                 return $this->result;
490             }
491         }
492         
a97937 493         if (is_array($this->prop['search_fields']))
T 494         {
495             foreach ($this->prop['search_fields'] as $k => $field)
496                 $filter .= "($field=$wc" . $this->_quote_string($value) . "$wc)";
497         }
498         else
499         {
500             foreach ((array)$fields as $field)
501                 if ($f = $this->_map_field($field))
502                     $filter .= "($f=$wc" . $this->_quote_string($value) . "$wc)";
503         }
504         $filter .= ')';
505
506         // add required (non empty) fields filter
507         $req_filter = '';
508         foreach ((array)$required as $field)
509             if ($f = $this->_map_field($field))
510                 $req_filter .= "($f=*)";
511
512         if (!empty($req_filter))
513             $filter = '(&' . $req_filter . $filter . ')';
514
515         // avoid double-wildcard if $value is empty
516         $filter = preg_replace('/\*+/', '*', $filter);
517
518         // add general filter to query
519         if (!empty($this->prop['filter']))
520             $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
521
522         // set filter string and execute search
523         $this->set_search_set($filter);
524         $this->_exec_search();
525
526         if ($select)
527             $this->list_records();
528         else
529             $this->result = $this->count();
530
531         return $this->result;
532     }
533
534
535     /**
536     * Count number of available contacts in database
537     *
538     * @return object rcube_result_set Resultset with values for 'count' and 'first'
539     */
540     function count()
541     {
542         $count = 0;
543         if ($this->conn && $this->ldap_result) {
544             $count = ldap_count_entries($this->conn, $this->ldap_result);
545         } // end if
546         elseif ($this->conn) {
547             // We have a connection but no result set, attempt to get one.
548             if (empty($this->filter)) {
549                 // The filter is not set, set it.
550                 $this->filter = $this->prop['filter'];
551             } // end if
552             $this->_exec_search();
553             if ($this->ldap_result) {
554                 $count = ldap_count_entries($this->conn, $this->ldap_result);
555             } // end if
556         } // end else
557
558         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
559     }
560
561
562     /**
563     * Return the last result set
564     *
565     * @return object rcube_result_set Current resultset or NULL if nothing selected yet
566     */
567     function get_result()
568     {
569         return $this->result;
570     }
571
572
573     /**
574     * Get a specific contact record
575     *
576     * @param mixed   Record identifier
577     * @param boolean Return as associative array
578     * @return mixed  Hash array or rcube_result_set with all record fields
579     */
580     function get_record($dn, $assoc=false)
581     {
582         $res = null;
583         if ($this->conn && $dn)
584         {
585             $dn = base64_decode($dn);
586
587             $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
588
589             if ($this->ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap)))
590                 $entry = ldap_first_entry($this->conn, $this->ldap_result);
591             else
592                 $this->_debug("S: ".ldap_error($this->conn));
593
594             if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
595             {
596                 $this->_debug("S: OK"/* . print_r($rec, true)*/);
597
598                 $rec = array_change_key_case($rec, CASE_LOWER);
599
600                 // Add in the dn for the entry.
601                 $rec['dn'] = $dn;
602                 $res = $this->_ldap2result($rec);
603                 $this->result = new rcube_result_set(1);
604                 $this->result->add($res);
6039aa 605             }
T 606         }
a97937 607
T 608         return $assoc ? $res : $this->result;
f11541 609     }
T 610
611
a97937 612     /**
e84818 613      * Check the given data before saving.
T 614      * If input not valid, the message to display can be fetched using get_error()
615      *
616      * @param array Assoziative array with data to save
617      * @return boolean True if input is valid, False if not.
618      */
619     public function validate($save_data)
620     {
621         // check for name input
622         if (empty($save_data['name'])) {
623             $this->set_error('warning', 'nonamewarning');
624             return false;
625         }
626         
627         // validate e-mail addresses
628         return parent::validate($save_data);
629     }
630
631
632     /**
a97937 633     * Create a new contact record
T 634     *
635     * @param array    Hash array with save data
636     * @return encoded record ID on success, False on error
637     */
638     function insert($save_cols)
f11541 639     {
a97937 640         // Map out the column names to their LDAP ones to build the new entry.
T 641         $newentry = array();
642         $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
643         foreach ($this->fieldmap as $col => $fld) {
644             $val = $save_cols[$col];
645             if (is_array($val))
646                 $val = array_filter($val);  // remove empty entries
647             if ($fld && $val) {
648                 // The field does exist, add it to the entry.
649                 $newentry[$fld] = $val;
4f9c83 650             } // end if
a97937 651         } // end foreach
T 652
653         // Verify that the required fields are set.
654         foreach ($this->prop['required_fields'] as $fld) {
655             $missing = null;
656             if (!isset($newentry[$fld])) {
657                 $missing[] = $fld;
658             }
659         }
660
661         // abort process if requiered fields are missing
662         // TODO: generate message saying which fields are missing
663         if ($missing) {
664             $this->set_error(self::ERROR_INCOMPLETE, 'formincomplete');
665             return false;
666         }
667
668         // Build the new entries DN.
d1e08f 669         $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
a97937 670
T 671         $this->_debug("C: Add [dn: $dn]: ".print_r($newentry, true));
672
673         $res = ldap_add($this->conn, $dn, $newentry);
674         if ($res === FALSE) {
675             $this->_debug("S: ".ldap_error($this->conn));
676             $this->set_error(self::ERROR_SAVING, 'errorsaving');
677             return false;
4f9c83 678         } // end if
S 679
010274 680         $this->_debug("S: OK");
4f9c83 681
a97937 682         // add new contact to the selected group
T 683         if ($this->groups)
684             $this->add_to_group($this->group_id, base64_encode($dn));
4f9c83 685
a97937 686         return base64_encode($dn);
e83f03 687     }
A 688
4f9c83 689
a97937 690     /**
T 691     * Update a specific contact record
692     *
693     * @param mixed Record identifier
694     * @param array Hash array with save data
695     * @return boolean True on success, False on error
696     */
697     function update($id, $save_cols)
f11541 698     {
a97937 699         $record = $this->get_record($id, true);
T 700         $result = $this->get_result();
701         $record = $result->first();
4aaecb 702
a97937 703         $newdata = array();
T 704         $replacedata = array();
705         $deletedata = array();
706         foreach ($this->fieldmap as $col => $fld) {
707             $val = $save_cols[$col];
708             if ($fld) {
709                 // remove empty array values
710                 if (is_array($val))
711                     $val = array_filter($val);
712                 // The field does exist compare it to the ldap record.
713                 if ($record[$col] != $val) {
714                     // Changed, but find out how.
715                     if (!isset($record[$col])) {
716                         // Field was not set prior, need to add it.
717                         $newdata[$fld] = $val;
718                     } // end if
719                     elseif ($val == '') {
720                         // Field supplied is empty, verify that it is not required.
721                         if (!in_array($fld, $this->prop['required_fields'])) {
722                             // It is not, safe to clear.
723                             $deletedata[$fld] = $record[$col];
724                         } // end if
725                     } // end elseif
726                     else {
727                         // The data was modified, save it out.
728                         $replacedata[$fld] = $val;
729                     } // end else
730                 } // end if
731             } // end if
732         } // end foreach
010274 733
a97937 734         $dn = base64_decode($id);
T 735
736         // Update the entry as required.
737         if (!empty($deletedata)) {
738             // Delete the fields.
739             $this->_debug("C: Delete [dn: $dn]: ".print_r($deletedata, true));
740             if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
741                 $this->_debug("S: ".ldap_error($this->conn));
742                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
743                 return false;
744             }
745             $this->_debug("S: OK");
746         } // end if
747
748         if (!empty($replacedata)) {
749             // Handle RDN change
750             if ($replacedata[$this->prop['LDAP_rdn']]) {
751                 $newdn = $this->prop['LDAP_rdn'].'='
752                     .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
d1e08f 753                     .','.$this->base_dn;
a97937 754                 if ($dn != $newdn) {
T 755                     $newrdn = $this->prop['LDAP_rdn'].'='
756                     .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
757                     unset($replacedata[$this->prop['LDAP_rdn']]);
758                 }
759             }
760             // Replace the fields.
761             if (!empty($replacedata)) {
762                 $this->_debug("C: Replace [dn: $dn]: ".print_r($replacedata, true));
763                 if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
764                     $this->_debug("S: ".ldap_error($this->conn));
765                     return false;
766                 }
767                 $this->_debug("S: OK");
768             } // end if
769         } // end if
770
771         if (!empty($newdata)) {
772             // Add the fields.
773             $this->_debug("C: Add [dn: $dn]: ".print_r($newdata, true));
774             if (!ldap_mod_add($this->conn, $dn, $newdata)) {
775                 $this->_debug("S: ".ldap_error($this->conn));
776                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
777                 return false;
778             }
779             $this->_debug("S: OK");
780         } // end if
781
782         // Handle RDN change
783         if (!empty($newrdn)) {
784             $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
785             if (!ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
786                 $this->_debug("S: ".ldap_error($this->conn));
787                 return false;
788             }
789             $this->_debug("S: OK");
790
791             // change the group membership of the contact
792             if ($this->groups)
793             {
794                 $group_ids = $this->get_record_groups(base64_encode($dn));
795                 foreach ($group_ids as $group_id)
796                 {
797                     $this->remove_from_group($group_id, base64_encode($dn));
798                     $this->add_to_group($group_id, base64_encode($newdn));
799                 }
800             }
801             return base64_encode($newdn);
802         }
803
4aaecb 804         return true;
f11541 805     }
a97937 806
T 807
808     /**
809     * Mark one or more contact records as deleted
810     *
811     * @param array  Record identifiers
812     * @return boolean True on success, False on error
813     */
814     function delete($ids)
f11541 815     {
a97937 816         if (!is_array($ids)) {
T 817             // Not an array, break apart the encoded DNs.
818             $dns = explode(',', $ids);
819         } // end if
820
821         foreach ($dns as $id) {
822             $dn = base64_decode($id);
823             $this->_debug("C: Delete [dn: $dn]");
824             // Delete the record.
825             $res = ldap_delete($this->conn, $dn);
826             if ($res === FALSE) {
827                 $this->_debug("S: ".ldap_error($this->conn));
828                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
829                 return false;
830             } // end if
831             $this->_debug("S: OK");
832
833             // remove contact from all groups where he was member
834             if ($this->groups)
835             {
836                 $group_ids = $this->get_record_groups(base64_encode($dn));
837                 foreach ($group_ids as $group_id)
838                 {
839                     $this->remove_from_group($group_id, base64_encode($dn));
840                 }
841             }
842         } // end foreach
843
844         return count($dns);
f11541 845     }
4368a0 846
A 847
a97937 848     /**
T 849     * Execute the LDAP search based on the stored credentials
850     *
851     * @access private
852     */
853     private function _exec_search()
854     {
855         if ($this->ready)
856         {
857             $filter = $this->filter ? $this->filter : '(objectclass=*)';
858             $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
010274 859
a97937 860             $this->_debug("C: Search [".$filter."]");
100440 861
d1e08f 862             if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
a97937 863                 array_values($this->fieldmap), 0, (int) $this->prop['sizelimit'], (int) $this->prop['timelimit']))
T 864             {
865                 $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
866                 return true;
867             }
868             else
869             {
870                 $this->_debug("S: ".ldap_error($this->conn));
871             }
872         }
873
874         return false;
875     }
876
877
878     /**
879     * @access private
880     */
881     private function _ldap2result($rec)
882     {
883         $out = array();
884
885         if ($rec['dn'])
886             $out[$this->primary_key] = base64_encode($rec['dn']);
887
888         foreach ($this->fieldmap as $rf => $lf)
889         {
890             for ($i=0; $i < $rec[$lf]['count']; $i++) {
891                 if (!($value = $rec[$lf][$i]))
892                     continue;
893                 if ($rf == 'email' && $this->mail_domain && !strpos($value, '@'))
894                     $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
895                 else if (in_array($rf, array('street','zipcode','locality','country','region')))
896                     $out['address'][$i][$rf] = $value;
897                 else if ($rec[$lf]['count'] > 1)
898                     $out[$rf][] = $value;
899                 else
900                     $out[$rf] = $value;
901             }
902         }
903
904         return $out;
905     }
906
907
908     /**
909     * @access private
910     */
911     private function _map_field($field)
912     {
913         return $this->fieldmap[$field];
914     }
915
916
917     /**
918     * @access private
919     */
920     private function _attr_name($name)
921     {
922         // list of known attribute aliases
923         $aliases = array(
924             'gn' => 'givenname',
925             'rfc822mailbox' => 'email',
926             'userid' => 'uid',
927             'emailaddress' => 'email',
928             'pkcs9email' => 'email',
929         );
930         return isset($aliases[$name]) ? $aliases[$name] : $name;
931     }
932
933
934     /**
935     * @access private
936     */
937     private function _debug($str)
938     {
939         if ($this->debug)
940             write_log('ldap', $str);
941     }
942
943
944     /**
945     * @static
946     */
947     private function _quote_string($str, $dn=false)
948     {
949         // take firt entry if array given
950         if (is_array($str))
951             $str = reset($str);
952
953         if ($dn)
954             $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
955                 '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
956         else
957             $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
958                 '/'=>'\2f');
959
960         return strtr($str, $replace);
961     }
f11541 962
6039aa 963
T 964     /**
965      * Setter for the current group
966      * (empty, has to be re-implemented by extending class)
967      */
968     function set_group($group_id)
969     {
970         if ($group_id)
971         {
a97937 972             if (!$this->group_cache)
T 973                 $this->list_groups();
974
975             $cache_members = $this->group_cache[$group_id]['members'];
6039aa 976
T 977             $members = array();
a97937 978             for ($i=1; $i<$cache_members["count"]; $i++)
6039aa 979             {
a97937 980                 $members[base64_encode($cache_members[$i])] = 1;
6039aa 981             }
T 982             $this->group_members = $members;
983             $this->group_id = $group_id;
984         }
a97937 985         else
T 986             $this->group_id = 0;
6039aa 987     }
T 988
989     /**
990      * List all active contact groups of this source
991      *
992      * @param string  Optional search string to match group name
993      * @return array  Indexed list of contact groups, each a hash array
994      */
995     function list_groups($search = null)
996     {
d1e08f 997         global $RCMAIL;
T 998
a97937 999         if (!$this->groups)
T 1000             return array();
6039aa 1001
d1e08f 1002         $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
T 1003                 $this->prop['groups']['base_dn'] : $this->base_dn;
1004
1005         // replace user specific dn
1006         if ($this->prop['user_specific'])
1007         {
1008             $fu = $RCMAIL->user->get_username();
1009             list($u, $d) = explode('@', $fu);
1010             $dc = 'dc='.strtr($d, array('.' => ',dc='));
1011             $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
1012
1013             $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);;
1014         }
1015
1016         $base_dn = $this->groups_base_dn;
1017         $filter = $this->prop['groups']['filter'];
6039aa 1018
T 1019         $res = ldap_search($this->conn, $base_dn, $filter, array('cn','member'));
1020         if ($res === false)
1021         {
1022             $this->_debug("S: ".ldap_error($this->conn));
1023             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1024             return array();
1025         }
1026         $ldap_data = ldap_get_entries($this->conn, $res);
1027
1028         $groups = array();
1029         $group_sortnames = array();
1030         for ($i=0; $i<$ldap_data["count"]; $i++)
1031         {
1032             $group_name = $ldap_data[$i]['cn'][0];
1033             $group_id = base64_encode($group_name);
1034             $groups[$group_id]['ID'] = $group_id;
1035             $groups[$group_id]['name'] = $group_name;
1036             $groups[$group_id]['members'] = $ldap_data[$i]['member'];
1037             $group_sortnames[] = strtolower($group_name);
1038         }
1039         array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
1040         $this->group_cache = $groups;
a97937 1041
6039aa 1042         return $groups;
T 1043     }
1044
1045     /**
1046      * Create a contact group with the given name
1047      *
1048      * @param string The group name
1049      * @return mixed False on error, array with record props in success
1050      */
1051     function create_group($group_name)
1052     {
1053         if (!$this->group_cache)
1054             $this->list_groups();
1055
d1e08f 1056         $base_dn = $this->groups_base_dn;
6039aa 1057         $new_dn = "cn=$group_name,$base_dn";
T 1058         $new_gid = base64_encode($group_name);
1059
1060         $new_entry = array(
d1e08f 1061             'objectClass' => $this->prop['groups']['object_classes'],
6039aa 1062             'cn' => $group_name,
T 1063             'member' => '',
1064         );
1065
1066         $res = ldap_add($this->conn, $new_dn, $new_entry);
1067         if ($res === false)
1068         {
1069             $this->_debug("S: ".ldap_error($this->conn));
1070             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1071             return false;
1072         }
1073         return array('id' => $new_gid, 'name' => $group_name);
1074     }
1075
1076     /**
1077      * Delete the given group and all linked group members
1078      *
1079      * @param string Group identifier
1080      * @return boolean True on success, false if no data was changed
1081      */
1082     function delete_group($group_id)
1083     {
1084         if (!$this->group_cache)
1085             $this->list_groups();
1086
d1e08f 1087         $base_dn = $this->groups_base_dn;
6039aa 1088         $group_name = $this->group_cache[$group_id]['name'];
T 1089
1090         $del_dn = "cn=$group_name,$base_dn";
1091         $res = ldap_delete($this->conn, $del_dn);
1092         if ($res === false)
1093         {
1094             $this->_debug("S: ".ldap_error($this->conn));
1095             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1096             return false;
1097         }
1098         return true;
1099     }
1100
1101     /**
1102      * Rename a specific contact group
1103      *
1104      * @param string Group identifier
1105      * @param string New name to set for this group
360bd3 1106      * @param string New group identifier (if changed, otherwise don't set)
6039aa 1107      * @return boolean New name on success, false if no data was changed
T 1108      */
15e944 1109     function rename_group($group_id, $new_name, &$new_gid)
6039aa 1110     {
T 1111         if (!$this->group_cache)
1112             $this->list_groups();
1113
d1e08f 1114         $base_dn = $this->groups_base_dn;
6039aa 1115         $group_name = $this->group_cache[$group_id]['name'];
T 1116         $old_dn = "cn=$group_name,$base_dn";
1117         $new_rdn = "cn=$new_name";
15e944 1118         $new_gid = base64_encode($new_name);
6039aa 1119
T 1120         $res = ldap_rename($this->conn, $old_dn, $new_rdn, NULL, TRUE);
1121         if ($res === false)
1122         {
1123             $this->_debug("S: ".ldap_error($this->conn));
1124             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1125             return false;
1126         }
1127         return $new_name;
1128     }
1129
1130     /**
1131      * Add the given contact records the a certain group
1132      *
1133      * @param string  Group identifier
1134      * @param array   List of contact identifiers to be added
1135      * @return int    Number of contacts added
1136      */
1137     function add_to_group($group_id, $contact_ids)
1138     {
1139         if (!$this->group_cache)
1140             $this->list_groups();
1141
d1e08f 1142         $base_dn = $this->groups_base_dn;
6039aa 1143         $group_name = $this->group_cache[$group_id]['name'];
T 1144         $group_dn = "cn=$group_name,$base_dn";
1145
1146         $new_attrs = array();
1147         foreach (explode(",", $contact_ids) as $id)
1148             $new_attrs['member'][] = base64_decode($id);
1149
1150         $res = ldap_mod_add($this->conn, $group_dn, $new_attrs);
1151         if ($res === false)
1152         {
1153             $this->_debug("S: ".ldap_error($this->conn));
1154             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1155             return 0;
1156         }
1157         return count($new_attrs['member']);
1158     }
1159
1160     /**
1161      * Remove the given contact records from a certain group
1162      *
1163      * @param string  Group identifier
1164      * @param array   List of contact identifiers to be removed
1165      * @return int    Number of deleted group members
1166      */
1167     function remove_from_group($group_id, $contact_ids)
1168     {
1169         if (!$this->group_cache)
1170             $this->list_groups();
1171
d1e08f 1172         $base_dn = $this->groups_base_dn;
6039aa 1173         $group_name = $this->group_cache[$group_id]['name'];
T 1174         $group_dn = "cn=$group_name,$base_dn";
1175
1176         $del_attrs = array();
1177         foreach (explode(",", $contact_ids) as $id)
1178             $del_attrs['member'][] = base64_decode($id);
1179
1180         $res = ldap_mod_del($this->conn, $group_dn, $del_attrs);
1181         if ($res === false)
1182         {
1183             $this->_debug("S: ".ldap_error($this->conn));
1184             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1185             return 0;
1186         }
1187         return count($del_attrs['member']);
1188     }
1189
1190     /**
1191      * Get group assignments of a specific contact record
1192      *
1193      * @param mixed Record identifier
1194      *
1195      * @return array List of assigned groups as ID=>Name pairs
1196      * @since 0.5-beta
1197      */
1198     function get_record_groups($contact_id)
1199     {
a97937 1200         if (!$this->groups)
6039aa 1201             return array();
T 1202
d1e08f 1203         $base_dn = $this->groups_base_dn;
6039aa 1204         $contact_dn = base64_decode($contact_id);
T 1205         $filter = "(member=$contact_dn)";
1206
1207         $res = ldap_search($this->conn, $base_dn, $filter, array('cn'));
1208         if ($res === false)
1209         {
1210             $this->_debug("S: ".ldap_error($this->conn));
1211             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1212             return array();
1213         }
1214         $ldap_data = ldap_get_entries($this->conn, $res);
1215
1216         $groups = array();
1217         for ($i=0; $i<$ldap_data["count"]; $i++)
1218         {
1219             $group_name = $ldap_data[$i]['cn'][0];
1220             $group_id = base64_encode($group_name);
1221             $groups[$group_id] = $group_id;
1222         }
1223         return $groups;
1224     }
f11541 1225 }