Aleksander Machniak
2012-11-17 9ab34604d94270f6c1795c7dd7b615273d05db0c
commit | author | age
d1d2c4 1 <?php
041c93 2
d1d2c4 3 /*
S 4  +-----------------------------------------------------------------------+
47124c 5  | program/include/rcube_ldap.php                                        |
d1d2c4 6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
438753 8  | Copyright (C) 2006-2012, The Roundcube Dev Team                       |
9ab346 9  | Copyright (C) 2011-2012, Kolab Systems AG                             |
7fe381 10  |                                                                       |
T 11  | Licensed under the GNU General Public License version 3 or            |
12  | any later version with exceptions for skins & plugins.                |
13  | See the README file for a full license statement.                     |
d1d2c4 14  |                                                                       |
S 15  | PURPOSE:                                                              |
f11541 16  |   Interface to an LDAP address directory                              |
d1d2c4 17  |                                                                       |
S 18  +-----------------------------------------------------------------------+
f11541 19  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
6039aa 20  |         Andreas Dick <andudi (at) gmx (dot) ch>                       |
c3ba0e 21  |         Aleksander Machniak <machniak@kolabsys.com>                   |
d1d2c4 22  +-----------------------------------------------------------------------+
S 23 */
24
6d969b 25
T 26 /**
27  * Model class to access an LDAP address directory
28  *
9ab346 29  * @package    Framework
AM 30  * @subpackage Addressbook
6d969b 31  */
cc97ea 32 class rcube_ldap extends rcube_addressbook
f11541 33 {
a97937 34     /** public properties */
T 35     public $primary_key = 'ID';
36     public $groups = false;
37     public $readonly = true;
38     public $ready = false;
39     public $group_id = 0;
40     public $coltypes = array();
1148c6 41
a97937 42     /** private properties */
T 43     protected $conn;
44     protected $prop = array();
45     protected $fieldmap = array();
13db9e 46     protected $sub_filter;
a97937 47     protected $filter = '';
T 48     protected $result = null;
49     protected $ldap_result = null;
50     protected $mail_domain = '';
51     protected $debug = false;
6039aa 52
d1e08f 53     private $base_dn = '';
T 54     private $groups_base_dn = '';
8fb04b 55     private $group_url = null;
T 56     private $cache;
1148c6 57
69ea3a 58     private $vlv_active = false;
T 59     private $vlv_count = 0;
60
1148c6 61
a97937 62     /**
T 63     * Object constructor
64     *
0c2596 65     * @param array      $p            LDAP connection properties
A 66     * @param boolean $debug        Enables debug mode
67     * @param string  $mail_domain  Current user mail domain name
a97937 68     */
0c2596 69     function __construct($p, $debug = false, $mail_domain = null)
f11541 70     {
a97937 71         $this->prop = $p;
b1f084 72
2d3e2b 73         if (isset($p['searchonly']))
T 74             $this->searchonly = $p['searchonly'];
010274 75
a97937 76         // check if groups are configured
f763fb 77         if (is_array($p['groups']) && count($p['groups'])) {
a97937 78             $this->groups = true;
f763fb 79             // set member field
A 80             if (!empty($p['groups']['member_attr']))
015dec 81                 $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
f763fb 82             else if (empty($p['member_attr']))
A 83                 $this->prop['member_attr'] = 'member';
448f81 84             // set default name attribute to cn
T 85             if (empty($this->prop['groups']['name_attr']))
86                 $this->prop['groups']['name_attr'] = 'cn';
fb6cc8 87             if (empty($this->prop['groups']['scope']))
T 88                 $this->prop['groups']['scope'] = 'sub';
f763fb 89         }
cd6749 90
a97937 91         // fieldmap property is given
T 92         if (is_array($p['fieldmap'])) {
93             foreach ($p['fieldmap'] as $rf => $lf)
94                 $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
95         }
38dc51 96         else if (!empty($p)) {
a97937 97             // read deprecated *_field properties to remain backwards compatible
T 98             foreach ($p as $prop => $value)
99                 if (preg_match('/^(.+)_field$/', $prop, $matches))
100                     $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
b9f9f1 101         }
4f9c83 102
a97937 103         // use fieldmap to advertise supported coltypes to the application
a605b2 104         foreach ($this->fieldmap as $colv => $lfv) {
T 105             list($col, $type) = explode(':', $colv);
106             list($lf, $limit, $delim) = explode(':', $lfv);
107
108             if ($limit == '*') $limit = null;
109             else               $limit = max(1, intval($limit));
110
a97937 111             if (!is_array($this->coltypes[$col])) {
T 112                 $subtypes = $type ? array($type) : null;
1078a6 113                 $this->coltypes[$col] = array('limit' => $limit, 'subtypes' => $subtypes, 'attributes' => array($lf));
1148c6 114             }
a97937 115             elseif ($type) {
T 116                 $this->coltypes[$col]['subtypes'][] = $type;
1078a6 117                 $this->coltypes[$col]['attributes'][] = $lf;
a605b2 118                 $this->coltypes[$col]['limit'] += $limit;
a97937 119             }
a605b2 120
T 121             if ($delim)
122                $this->coltypes[$col]['serialized'][$type] = $delim;
123
1078a6 124            $this->fieldmap[$colv] = $lf;
1148c6 125         }
f76765 126
1937f4 127         // support for composite address
1078a6 128         if ($this->coltypes['street'] && $this->coltypes['locality']) {
a605b2 129             $this->coltypes['address'] = array(
T 130                'limit'    => max(1, $this->coltypes['locality']['limit'] + $this->coltypes['address']['limit']),
5b0b03 131                'subtypes' => array_merge((array)$this->coltypes['address']['subtypes'], (array)$this->coltypes['locality']['subtypes']),
a605b2 132                'childs' => array(),
T 133                ) + (array)$this->coltypes['address'];
134
3ac5cd 135             foreach (array('street','locality','zipcode','region','country') as $childcol) {
1078a6 136                 if ($this->coltypes[$childcol]) {
3ac5cd 137                     $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
T 138                     unset($this->coltypes[$childcol]);  // remove address child col from global coltypes list
139                 }
140             }
fb001f 141
AM 142             // at least one address type must be specified
143             if (empty($this->coltypes['address']['subtypes'])) {
144                 $this->coltypes['address']['subtypes'] = array('home');
145             }
1937f4 146         }
19fccd 147         else if ($this->coltypes['address']) {
24f1bf 148             $this->coltypes['address'] += array('type' => 'textarea', 'childs' => null, 'size' => 40);
T 149
150             // 'serialized' means the UI has to present a composite address field
151             if ($this->coltypes['address']['serialized']) {
152                 $childprop = array('type' => 'text');
153                 $this->coltypes['address']['type'] = 'composite';
154                 $this->coltypes['address']['childs'] = array('street' => $childprop, 'locality' => $childprop, 'zipcode' => $childprop, 'country' => $childprop);
155             }
19fccd 156         }
4f9c83 157
a97937 158         // make sure 'required_fields' is an array
19fccd 159         if (!is_array($this->prop['required_fields'])) {
a97937 160             $this->prop['required_fields'] = (array) $this->prop['required_fields'];
19fccd 161         }
4f9c83 162
19fccd 163         // make sure LDAP_rdn field is required
540e13 164         if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])
AM 165             && !in_array($this->prop['LDAP_rdn'], array_keys((array)$this->prop['autovalues']))) {
19fccd 166             $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
A 167         }
168
169         foreach ($this->prop['required_fields'] as $key => $val) {
a97937 170             $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
19fccd 171         }
13db9e 172
A 173         // Build sub_fields filter
174         if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
175             $this->sub_filter = '';
176             foreach ($this->prop['sub_fields'] as $attr => $class) {
177                 if (!empty($class)) {
178                     $class = is_array($class) ? array_pop($class) : $class;
179                     $this->sub_filter .= '(objectClass=' . $class . ')';
180                 }
181             }
182             if (count($this->prop['sub_fields']) > 1) {
183                 $this->sub_filter = '(|' . $this->sub_filter . ')';
184             }
185         }
f11541 186
f763fb 187         $this->sort_col    = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
A 188         $this->debug       = $debug;
a97937 189         $this->mail_domain = $mail_domain;
8fb04b 190
T 191         // initialize cache
be98df 192         $rcube = rcube::get_instance();
A 193         $this->cache = $rcube->get_cache('LDAP.' . asciiwords($this->prop['name']), 'db', 600);
f11541 194
a97937 195         $this->_connect();
736307 196     }
010274 197
736307 198
a97937 199     /**
T 200     * Establish a connection to the LDAP server
201     */
202     private function _connect()
6b603d 203     {
be98df 204         $rcube = rcube::get_instance();
f11541 205
a97937 206         if (!function_exists('ldap_connect'))
0c2596 207             rcube::raise_error(array('code' => 100, 'type' => 'ldap',
56651c 208                 'file' => __FILE__, 'line' => __LINE__,
A 209                 'message' => "No ldap support in this installation of PHP"),
210                 true, true);
f11541 211
a97937 212         if (is_resource($this->conn))
T 213             return true;
f11541 214
a97937 215         if (!is_array($this->prop['hosts']))
T 216             $this->prop['hosts'] = array($this->prop['hosts']);
f11541 217
a97937 218         if (empty($this->prop['ldap_version']))
T 219             $this->prop['ldap_version'] = 3;
f11541 220
a97937 221         foreach ($this->prop['hosts'] as $host)
6039aa 222         {
be98df 223             $host     = rcube_utils::idn_to_ascii(rcube_utils::parse_host($host));
c041d5 224             $hostname = $host.($this->prop['port'] ? ':'.$this->prop['port'] : '');
A 225
8764b6 226             $this->_debug("C: Connect [$hostname] [{$this->prop['name']}]");
a97937 227
T 228             if ($lc = @ldap_connect($host, $this->prop['port']))
6039aa 229             {
c041d5 230                 if ($this->prop['use_tls'] === true)
a97937 231                     if (!ldap_start_tls($lc))
T 232                         continue;
233
234                 $this->_debug("S: OK");
235
236                 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
237                 $this->prop['host'] = $host;
238                 $this->conn = $lc;
3b4b03 239
T 240                 if (isset($this->prop['referrals']))
241                     ldap_set_option($lc, LDAP_OPT_REFERRALS, $this->prop['referrals']);
a97937 242                 break;
T 243             }
244             $this->_debug("S: NOT OK");
245         }
246
247         // See if the directory is writeable.
248         if ($this->prop['writable']) {
249             $this->readonly = false;
c041d5 250         }
A 251
252         if (!is_resource($this->conn)) {
0c2596 253             rcube::raise_error(array('code' => 100, 'type' => 'ldap',
c041d5 254                 'file' => __FILE__, 'line' => __LINE__,
A 255                 'message' => "Could not connect to any LDAP server, last tried $hostname"), true);
256
257             return false;
258         }
259
260         $bind_pass = $this->prop['bind_pass'];
261         $bind_user = $this->prop['bind_user'];
262         $bind_dn   = $this->prop['bind_dn'];
263
264         $this->base_dn        = $this->prop['base_dn'];
265         $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
266         $this->prop['groups']['base_dn'] : $this->base_dn;
267
268         // User specific access, generate the proper values to use.
269         if ($this->prop['user_specific']) {
270             // No password set, use the session password
271             if (empty($bind_pass)) {
be98df 272                 $bind_pass = $rcube->decrypt($_SESSION['password']);
c041d5 273             }
A 274
275             // Get the pieces needed for variable replacement.
be98df 276             if ($fu = $rcube->get_user_name())
c041d5 277                 list($u, $d) = explode('@', $fu);
A 278             else
279                 $d = $this->mail_domain;
280
281             $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
282
283             $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
284
285             if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
03e520 286                 if (!empty($this->prop['search_bind_dn']) && !empty($this->prop['search_bind_pw'])) {
2d08ec 287                     $this->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
A 288                 }
289
c041d5 290                 // Search for the dn to use to authenticate
A 291                 $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
292                 $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
293
294                 $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
295
296                 $res = @ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
297                 if ($res) {
298                     if (($entry = ldap_first_entry($this->conn, $res))
299                         && ($bind_dn = ldap_get_dn($this->conn, $entry))
300                     ) {
301                         $this->_debug("S: search returned dn: $bind_dn");
302                         $dn = ldap_explode_dn($bind_dn, 1);
303                         $replaces['%dn'] = $dn[0];
304                     }
305                 }
306                 else {
307                     $this->_debug("S: ".ldap_error($this->conn));
308                 }
309
310                 // DN not found
311                 if (empty($replaces['%dn'])) {
312                     if (!empty($this->prop['search_dn_default']))
313                         $replaces['%dn'] = $this->prop['search_dn_default'];
314                     else {
0c2596 315                         rcube::raise_error(array(
c041d5 316                             'code' => 100, 'type' => 'ldap',
A 317                             'file' => __FILE__, 'line' => __LINE__,
318                             'message' => "DN not found using LDAP search."), true);
319                         return false;
320                     }
321                 }
322             }
323
324             // Replace the bind_dn and base_dn variables.
325             $bind_dn              = strtr($bind_dn, $replaces);
326             $this->base_dn        = strtr($this->base_dn, $replaces);
327             $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
328
329             if (empty($bind_user)) {
330                 $bind_user = $u;
331             }
332         }
333
334         if (empty($bind_pass)) {
335             $this->ready = true;
336         }
337         else {
338             if (!empty($bind_dn)) {
339                 $this->ready = $this->bind($bind_dn, $bind_pass);
340             }
341             else if (!empty($this->prop['auth_cid'])) {
342                 $this->ready = $this->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
343             }
344             else {
345                 $this->ready = $this->sasl_bind($bind_user, $bind_pass);
346             }
347         }
348
349         return $this->ready;
a97937 350     }
T 351
352
353     /**
4d982d 354      * Bind connection with (SASL-) user and password
A 355      *
356      * @param string $authc Authentication user
357      * @param string $pass  Bind password
358      * @param string $authz Autorization user
359      *
360      * @return boolean True on success, False on error
361      */
9eeb14 362     public function sasl_bind($authc, $pass, $authz=null)
4d982d 363     {
A 364         if (!$this->conn) {
365             return false;
366         }
367
368         if (!function_exists('ldap_sasl_bind')) {
0c2596 369             rcube::raise_error(array('code' => 100, 'type' => 'ldap',
4d982d 370                 'file' => __FILE__, 'line' => __LINE__,
A 371                 'message' => "Unable to bind: ldap_sasl_bind() not exists"),
56651c 372                 true, true);
4d982d 373         }
A 374
375         if (!empty($authz)) {
376             $authz = 'u:' . $authz;
377         }
378
379         if (!empty($this->prop['auth_method'])) {
380             $method = $this->prop['auth_method'];
381         }
382         else {
383             $method = 'DIGEST-MD5';
384         }
385
386         $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz] [pass: $pass]");
387
388         if (ldap_sasl_bind($this->conn, NULL, $pass, $method, NULL, $authc, $authz)) {
389             $this->_debug("S: OK");
390             return true;
391         }
392
393         $this->_debug("S: ".ldap_error($this->conn));
394
0c2596 395         rcube::raise_error(array(
4d982d 396             'code' => ldap_errno($this->conn), 'type' => 'ldap',
A 397             'file' => __FILE__, 'line' => __LINE__,
398             'message' => "Bind failed for authcid=$authc ".ldap_error($this->conn)),
399             true);
400
401         return false;
402     }
403
404
405     /**
cc90ed 406      * Bind connection with DN and password
A 407      *
408      * @param string Bind DN
409      * @param string Bind password
410      *
411      * @return boolean True on success, False on error
412      */
9eeb14 413     public function bind($dn, $pass)
a97937 414     {
T 415         if (!$this->conn) {
416             return false;
417         }
418
419         $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
420
421         if (@ldap_bind($this->conn, $dn, $pass)) {
422             $this->_debug("S: OK");
423             return true;
424         }
425
426         $this->_debug("S: ".ldap_error($this->conn));
427
0c2596 428         rcube::raise_error(array(
56651c 429             'code' => ldap_errno($this->conn), 'type' => 'ldap',
A 430             'file' => __FILE__, 'line' => __LINE__,
431             'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
432             true);
a97937 433
T 434         return false;
435     }
436
437
438     /**
cc90ed 439      * Close connection to LDAP server
A 440      */
a97937 441     function close()
T 442     {
443         if ($this->conn)
444         {
445             $this->_debug("C: Close");
446             ldap_unbind($this->conn);
447             $this->conn = null;
448         }
449     }
450
451
452     /**
cc90ed 453      * Returns address book name
A 454      *
455      * @return string Address book name
456      */
457     function get_name()
458     {
459         return $this->prop['name'];
460     }
461
462
463     /**
438753 464      * Set internal sort settings
cc90ed 465      *
438753 466      * @param string $sort_col Sort column
T 467      * @param string $sort_order Sort order
cc90ed 468      */
438753 469     function set_sort_order($sort_col, $sort_order = null)
a97937 470     {
1078a6 471         if ($this->coltypes[$sort_col]['attributes'])
TB 472             $this->sort_col = $this->coltypes[$sort_col]['attributes'][0];
a97937 473     }
T 474
475
476     /**
cc90ed 477      * Save a search string for future listings
A 478      *
479      * @param string $filter Filter string
480      */
a97937 481     function set_search_set($filter)
T 482     {
483         $this->filter = $filter;
484     }
485
486
487     /**
cc90ed 488      * Getter for saved search properties
A 489      *
490      * @return mixed Search properties used by this class
491      */
a97937 492     function get_search_set()
T 493     {
494         return $this->filter;
495     }
496
497
498     /**
cc90ed 499      * Reset all saved results and search parameters
A 500      */
a97937 501     function reset()
T 502     {
503         $this->result = null;
504         $this->ldap_result = null;
505         $this->filter = '';
506     }
507
508
509     /**
cc90ed 510      * List the current set of contact records
A 511      *
512      * @param  array  List of cols to show
513      * @param  int    Only return this number of records
514      *
515      * @return array  Indexed list of contact records, each a hash array
516      */
a97937 517     function list_records($cols=null, $subset=0)
T 518     {
8fb04b 519         if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id)
T 520         {
2d3e2b 521             $this->result = new rcube_result_set(0);
T 522             $this->result->searchonly = true;
523             return $this->result;
524         }
b1f084 525
a31482 526         // fetch group members recursively
T 527         if ($this->group_id && $this->group_data['dn'])
528         {
529             $entries = $this->list_group_members($this->group_data['dn']);
530
531             // make list of entries unique and sort it
532             $seen = array();
533             foreach ($entries as $i => $rec) {
534                 if ($seen[$rec['dn']]++)
535                     unset($entries[$i]);
536             }
537             usort($entries, array($this, '_entry_sort_cmp'));
538
539             $entries['count'] = count($entries);
540             $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
541         }
542         else
543         {
544             // add general filter to query
545             if (!empty($this->prop['filter']) && empty($this->filter))
546                 $this->set_search_set($this->prop['filter']);
547
548             // exec LDAP search if no result resource is stored
549             if ($this->conn && !$this->ldap_result)
550                 $this->_exec_search();
551
552             // count contacts for this user
553             $this->result = $this->count();
554
555             // we have a search result resource
556             if ($this->ldap_result && $this->result->count > 0)
557             {
558                 // sorting still on the ldap server
559                 if ($this->sort_col && $this->prop['scope'] !== 'base' && !$this->vlv_active)
560                     ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
561
562                 // get all entries from the ldap server
563                 $entries = ldap_get_entries($this->conn, $this->ldap_result);
564             }
565
566         }  // end else
567
568         // start and end of the page
569         $start_row = $this->vlv_active ? 0 : $this->result->first;
570         $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
571         $last_row = $this->result->first + $this->page_size;
572         $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
573
574         // filter entries for this page
575         for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
576             $this->result->add($this->_ldap2result($entries[$i]));
577
578         return $this->result;
579     }
580
581     /**
9b3311 582      * Get all members of the given group
A 583      *
584      * @param string Group DN
585      * @param array  Group entries (if called recursively)
586      * @return array Accumulated group members
a31482 587      */
b35a0f 588     function list_group_members($dn, $count = false, $entries = null)
a31482 589     {
T 590         $group_members = array();
591
592         // fetch group object
593         if (empty($entries)) {
594             $result = @ldap_read($this->conn, $dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL'));
595             if ($result === false)
596             {
597                 $this->_debug("S: ".ldap_error($this->conn));
598                 return $group_members;
599             }
600
601             $entries = @ldap_get_entries($this->conn, $result);
602         }
603
337dc5 604         for ($i=0; $i < $entries['count']; $i++)
a31482 605         {
T 606             $entry = $entries[$i];
607
608             if (empty($entry['objectclass']))
609                 continue;
610
b35a0f 611             foreach ((array)$entry['objectclass'] as $objectclass)
a31482 612             {
T 613                 switch (strtolower($objectclass)) {
337dc5 614                     case "group":
a31482 615                     case "groupofnames":
T 616                     case "kolabgroupofnames":
b35a0f 617                         $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'member', $count));
a31482 618                         break;
T 619                     case "groupofuniquenames":
620                     case "kolabgroupofuniquenames":
b35a0f 621                         $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'uniquemember', $count));
a31482 622                         break;
T 623                     case "groupofurls":
b35a0f 624                         $group_members = array_merge($group_members, $this->_list_group_memberurl($dn, $entry, $count));
a31482 625                         break;
T 626                 }
627             }
337dc5 628
fb6cc8 629             if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit'])
T 630               break;
a31482 631         }
T 632
633         return array_filter($group_members);
634     }
635
636     /**
637      * Fetch members of the given group entry from server
638      *
639      * @param string Group DN
640      * @param array  Group entry
641      * @param string Member attribute to use
642      * @return array Accumulated group members
643      */
b35a0f 644     private function _list_group_members($dn, $entry, $attr, $count)
a31482 645     {
T 646         // Use the member attributes to return an array of member ldap objects
647         // NOTE that the member attribute is supposed to contain a DN
648         $group_members = array();
649         if (empty($entry[$attr]))
650             return $group_members;
651
b35a0f 652         // read these attributes for all members
T 653         $attrib = $count ? array('dn') : array_values($this->fieldmap);
654         $attrib[] = 'objectClass';
655         $attrib[] = 'member';
656         $attrib[] = 'uniqueMember';
657         $attrib[] = 'memberURL';
658
a31482 659         for ($i=0; $i < $entry[$attr]['count']; $i++)
T 660         {
3ed9e8 661             if (empty($entry[$attr][$i]))
T 662                 continue;
663
a31482 664             $result = @ldap_read($this->conn, $entry[$attr][$i], '(objectclass=*)',
b35a0f 665                 $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']);
a31482 666
T 667             $members = @ldap_get_entries($this->conn, $result);
668             if ($members == false)
669             {
670                 $this->_debug("S: ".ldap_error($this->conn));
671                 $members = array();
672             }
673
674             // for nested groups, call recursively
b35a0f 675             $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
a31482 676
T 677             unset($members['count']);
678             $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
679         }
680
681         return $group_members;
682     }
683
684     /**
685      * List members of group class groupOfUrls
686      *
687      * @param string Group DN
688      * @param array  Group entry
b35a0f 689      * @param boolean True if only used for counting
a31482 690      * @return array Accumulated group members
T 691      */
b35a0f 692     private function _list_group_memberurl($dn, $entry, $count)
a31482 693     {
T 694         $group_members = array();
695
696         for ($i=0; $i < $entry['memberurl']['count']; $i++)
8fb04b 697         {
T 698             // extract components from url
a31482 699             if (!preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m))
T 700                 continue;
701
702             // add search filter if any
703             $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
704             $func = $m[2] == 'sub' ? 'ldap_search' : ($m[2] == 'base' ? 'ldap_read' : 'ldap_list');
705
b35a0f 706             $attrib = $count ? array('dn') : array_values($this->fieldmap);
a31482 707             if ($result = @$func($this->conn, $m[1], $filter,
a505dd 708                 $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
A 709             ) {
a31482 710                 $this->_debug("S: ".ldap_count_entries($this->conn, $result)." record(s) for ".$m[1]);
T 711             }
a505dd 712             else {
a31482 713                 $this->_debug("S: ".ldap_error($this->conn));
T 714                 return $group_members;
715             }
716
717             $entries = @ldap_get_entries($this->conn, $result);
718             for ($j = 0; $j < $entries['count']; $j++)
719             {
b35a0f 720                 if ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count))
a31482 721                     $group_members = array_merge($group_members, $nested_group_members);
T 722                 else
723                     $group_members[] = $entries[$j];
8fb04b 724             }
a97937 725         }
39cafa 726
a31482 727         return $group_members;
T 728     }
a97937 729
a31482 730     /**
T 731      * Callback for sorting entries
732      */
733     function _entry_sort_cmp($a, $b)
734     {
735         return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
a97937 736     }
T 737
738
739     /**
cc90ed 740      * Search contacts
A 741      *
742      * @param mixed   $fields   The field name of array of field names to search in
743      * @param mixed   $value    Search value (or array of values when $fields is array)
f21a04 744      * @param int     $mode     Matching mode:
A 745      *                          0 - partial (*abc*),
746      *                          1 - strict (=),
747      *                          2 - prefix (abc*)
cc90ed 748      * @param boolean $select   True if results are requested, False if count only
A 749      * @param boolean $nocount  (Not used)
750      * @param array   $required List of fields that cannot be empty
751      *
752      * @return array  Indexed list of contact records and 'count' value
753      */
f21a04 754     function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
a97937 755     {
f21a04 756         $mode = intval($mode);
A 757
a97937 758         // special treatment for ID-based search
T 759         if ($fields == 'ID' || $fields == $this->primary_key)
760         {
648674 761             $ids = !is_array($value) ? explode(',', $value) : $value;
a97937 762             $result = new rcube_result_set();
T 763             foreach ($ids as $id)
764             {
765                 if ($rec = $this->get_record($id, true))
766                 {
767                     $result->add($rec);
768                     $result->count++;
769                 }
770             }
771             return $result;
772         }
773
fc91c1 774         // use VLV pseudo-search for autocompletion
e1cfb0 775         $rcube = rcube::get_instance();
699cb1 776         $list_fields = $rcube->config->get('contactlist_fields');
baecd8 777
699cb1 778         if ($this->prop['vlv_search'] && $this->conn && join(',', (array)$fields) == join(',', $list_fields))
fc91c1 779         {
T 780             // add general filter to query
781             if (!empty($this->prop['filter']) && empty($this->filter))
782                 $this->set_search_set($this->prop['filter']);
783
784             // set VLV controls with encoded search string
785             $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size, $value);
786
787             $function = $this->_scope2func($this->prop['scope']);
788             $this->ldap_result = @$function($this->conn, $this->base_dn, $this->filter ? $this->filter : '(objectclass=*)',
7f79e2 789                 array_values($this->fieldmap), 0, $this->page_size, (int)$this->prop['timelimit']);
fc91c1 790
9b3311 791             $this->result = new rcube_result_set(0);
A 792
6bddd9 793             if (!$this->ldap_result) {
9b3311 794                 $this->_debug("S: ".ldap_error($this->conn));
6bddd9 795                 return $this->result;
A 796             }
9b3311 797
6bddd9 798             $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
9b3311 799
fc91c1 800             // get all entries of this page and post-filter those that really match the query
f21a04 801             $search = mb_strtolower($value);
fc91c1 802             $entries = ldap_get_entries($this->conn, $this->ldap_result);
f21a04 803
fc91c1 804             for ($i = 0; $i < $entries['count']; $i++) {
T 805                 $rec = $this->_ldap2result($entries[$i]);
699cb1 806                 foreach ($fields as $f) {
AM 807                     foreach ((array)$rec[$f] as $val) {
808                         $val = mb_strtolower($val);
809                         switch ($mode) {
810                         case 1:
811                             $got = ($val == $search);
812                             break;
813                         case 2:
814                             $got = ($search == substr($val, 0, strlen($search)));
815                             break;
816                         default:
817                             $got = (strpos($val, $search) !== false);
818                             break;
819                         }
f21a04 820
699cb1 821                         if ($got) {
AM 822                             $this->result->add($rec);
823                             $this->result->count++;
824                             break 2;
825                         }
f21a04 826                     }
fc91c1 827                 }
T 828             }
829
830             return $this->result;
831         }
832
e9a9f2 833         // use AND operator for advanced searches
A 834         $filter = is_array($value) ? '(&' : '(|';
f21a04 835         // set wildcards
A 836         $wp = $ws = '';
837         if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
838             $ws = '*';
839             if (!$mode) {
840                 $wp = '*';
841             }
842         }
e9a9f2 843
3cacf9 844         if ($fields == '*')
3e2637 845         {
T 846             // search_fields are required for fulltext search
3cacf9 847             if (empty($this->prop['search_fields']))
3e2637 848             {
T 849                 $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
850                 $this->result = new rcube_result_set();
851                 return $this->result;
852             }
3cacf9 853             if (is_array($this->prop['search_fields']))
A 854             {
e9a9f2 855                 foreach ($this->prop['search_fields'] as $field) {
f21a04 856                     $filter .= "($field=$wp" . $this->_quote_string($value) . "$ws)";
e9a9f2 857                 }
3cacf9 858             }
a97937 859         }
T 860         else
861         {
e9a9f2 862             foreach ((array)$fields as $idx => $field) {
A 863                 $val = is_array($value) ? $value[$idx] : $value;
1078a6 864                 if ($attrs = $this->_map_field($field)) {
TB 865                     if (count($attrs) > 1)
866                         $filter .= '(|';
867                     foreach ($attrs as $f)
868                         $filter .= "($f=$wp" . $this->_quote_string($val) . "$ws)";
869                     if (count($attrs) > 1)
870                         $filter .= ')';
e9a9f2 871                 }
A 872             }
a97937 873         }
T 874         $filter .= ')';
875
876         // add required (non empty) fields filter
877         $req_filter = '';
1078a6 878         foreach ((array)$required as $field) {
TB 879             if ($attrs = $this->_map_field($field)) {
880                 if (count($attrs) > 1)
881                     $req_filter .= '(|';
882                 foreach ($attrs as $f)
883                     $req_filter .= "($f=*)";
884                 if (count($attrs) > 1)
885                     $req_filter .= ')';
886             }
887         }
a97937 888
T 889         if (!empty($req_filter))
890             $filter = '(&' . $req_filter . $filter . ')';
891
892         // avoid double-wildcard if $value is empty
893         $filter = preg_replace('/\*+/', '*', $filter);
894
895         // add general filter to query
896         if (!empty($this->prop['filter']))
897             $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
898
899         // set filter string and execute search
900         $this->set_search_set($filter);
901         $this->_exec_search();
902
903         if ($select)
904             $this->list_records();
905         else
906             $this->result = $this->count();
907
908         return $this->result;
909     }
910
911
912     /**
cc90ed 913      * Count number of available contacts in database
A 914      *
915      * @return object rcube_result_set Resultset with values for 'count' and 'first'
916      */
a97937 917     function count()
T 918     {
919         $count = 0;
920         if ($this->conn && $this->ldap_result) {
69ea3a 921             $count = $this->vlv_active ? $this->vlv_count : ldap_count_entries($this->conn, $this->ldap_result);
a31482 922         }
T 923         else if ($this->group_id && $this->group_data['dn']) {
b35a0f 924             $count = count($this->list_group_members($this->group_data['dn'], true));
a31482 925         }
T 926         else if ($this->conn) {
a97937 927             // We have a connection but no result set, attempt to get one.
T 928             if (empty($this->filter)) {
929                 // The filter is not set, set it.
930                 $this->filter = $this->prop['filter'];
a31482 931             }
122446 932
A 933             $count = (int) $this->_exec_search(true);
a31482 934         }
a97937 935
T 936         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
937     }
938
939
940     /**
cc90ed 941      * Return the last result set
A 942      *
943      * @return object rcube_result_set Current resultset or NULL if nothing selected yet
944      */
a97937 945     function get_result()
T 946     {
947         return $this->result;
948     }
949
950
951     /**
cc90ed 952      * Get a specific contact record
A 953      *
954      * @param mixed   Record identifier
955      * @param boolean Return as associative array
956      *
957      * @return mixed  Hash array or rcube_result_set with all record fields
958      */
a97937 959     function get_record($dn, $assoc=false)
T 960     {
13db9e 961         $res = $this->result = null;
A 962
a97937 963         if ($this->conn && $dn)
T 964         {
c3ba0e 965             $dn = self::dn_decode($dn);
a97937 966
T 967             $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
968
13db9e 969             if ($ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap))) {
A 970                 $this->_debug("S: OK");
971
972                 $entry = ldap_first_entry($this->conn, $ldap_result);
973
974                 if ($entry && ($rec = ldap_get_attributes($this->conn, $entry))) {
975                     $rec = array_change_key_case($rec, CASE_LOWER);
976                 }
977             }
978             else {
a97937 979                 $this->_debug("S: ".ldap_error($this->conn));
13db9e 980             }
a97937 981
13db9e 982             // Use ldap_list to get subentries like country (c) attribute (#1488123)
A 983             if (!empty($rec) && $this->sub_filter) {
984                 if ($entries = $this->ldap_list($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
985                     foreach ($entries as $entry) {
986                         $lrec = array_change_key_case($entry, CASE_LOWER);
987                         $rec  = array_merge($lrec, $rec);
988                     }
989                 }
990             }
a97937 991
13db9e 992             if (!empty($rec)) {
a97937 993                 // Add in the dn for the entry.
T 994                 $rec['dn'] = $dn;
995                 $res = $this->_ldap2result($rec);
13db9e 996                 $this->result = new rcube_result_set();
a97937 997                 $this->result->add($res);
6039aa 998             }
T 999         }
a97937 1000
T 1001         return $assoc ? $res : $this->result;
f11541 1002     }
T 1003
1004
a97937 1005     /**
e84818 1006      * Check the given data before saving.
T 1007      * If input not valid, the message to display can be fetched using get_error()
1008      *
1009      * @param array Assoziative array with data to save
39cafa 1010      * @param boolean Try to fix/complete record automatically
e84818 1011      * @return boolean True if input is valid, False if not.
T 1012      */
39cafa 1013     public function validate(&$save_data, $autofix = false)
e84818 1014     {
19fccd 1015         // validate e-mail addresses
A 1016         if (!parent::validate($save_data, $autofix)) {
1017             return false;
1018         }
1019
e84818 1020         // check for name input
T 1021         if (empty($save_data['name'])) {
39cafa 1022             $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
T 1023             return false;
1024         }
1025
1026         // Verify that the required fields are set.
1027         $missing = null;
1028         $ldap_data = $this->_map_data($save_data);
1029         foreach ($this->prop['required_fields'] as $fld) {
19fccd 1030             if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
39cafa 1031                 $missing[$fld] = 1;
T 1032             }
1033         }
1034
1035         if ($missing) {
1036             // try to complete record automatically
1037             if ($autofix) {
19fccd 1038                 $sn_field    = $this->fieldmap['surname'];
A 1039                 $fn_field    = $this->fieldmap['firstname'];
9336ba 1040                 $mail_field  = $this->fieldmap['email'];
A 1041
1042                 // try to extract surname and firstname from displayname
1043                 $reverse_map = array_flip($this->fieldmap);
1044                 $name_parts  = preg_split('/[\s,.]+/', $save_data['name']);
19fccd 1045
A 1046                 if ($sn_field && $missing[$sn_field]) {
1047                     $save_data['surname'] = array_pop($name_parts);
1048                     unset($missing[$sn_field]);
39cafa 1049                 }
T 1050
19fccd 1051                 if ($fn_field && $missing[$fn_field]) {
A 1052                     $save_data['firstname'] = array_shift($name_parts);
1053                     unset($missing[$fn_field]);
1054                 }
9336ba 1055
A 1056                 // try to fix missing e-mail, very often on import
1057                 // from vCard we have email:other only defined
1058                 if ($mail_field && $missing[$mail_field]) {
1059                     $emails = $this->get_col_values('email', $save_data, true);
1060                     if (!empty($emails) && ($email = array_shift($emails))) {
1061                         $save_data['email'] = $email;
1062                         unset($missing[$mail_field]);
1063                     }
1064                 }
39cafa 1065             }
T 1066
1067             // TODO: generate message saying which fields are missing
19fccd 1068             if (!empty($missing)) {
A 1069                 $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
1070                 return false;
1071             }
e84818 1072         }
cc90ed 1073
19fccd 1074         return true;
e84818 1075     }
T 1076
1077
1078     /**
cc90ed 1079      * Create a new contact record
A 1080      *
1081      * @param array    Hash array with save data
1082      *
1083      * @return encoded record ID on success, False on error
1084      */
a97937 1085     function insert($save_cols)
f11541 1086     {
a97937 1087         // Map out the column names to their LDAP ones to build the new entry.
39cafa 1088         $newentry = $this->_map_data($save_cols);
a97937 1089         $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
T 1090
3f250a 1091         // add automatically generated attributes
TB 1092         $this->add_autovalues($newentry);
1093
a97937 1094         // Verify that the required fields are set.
6f45fa 1095         $missing = null;
a97937 1096         foreach ($this->prop['required_fields'] as $fld) {
T 1097             if (!isset($newentry[$fld])) {
1098                 $missing[] = $fld;
1099             }
1100         }
1101
1102         // abort process if requiered fields are missing
1103         // TODO: generate message saying which fields are missing
1104         if ($missing) {
39cafa 1105             $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
a97937 1106             return false;
T 1107         }
1108
1109         // Build the new entries DN.
d1e08f 1110         $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
a97937 1111
13db9e 1112         // Remove attributes that need to be added separately (child objects)
A 1113         $xfields = array();
1114         if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
1115             foreach ($this->prop['sub_fields'] as $xf => $xclass) {
1116                 if (!empty($newentry[$xf])) {
1117                     $xfields[$xf] = $newentry[$xf];
1118                     unset($newentry[$xf]);
1119                 }
1120             }
1121         }
a97937 1122
13db9e 1123         if (!$this->ldap_add($dn, $newentry)) {
a97937 1124             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1125             return false;
13db9e 1126         }
4f9c83 1127
13db9e 1128         foreach ($xfields as $xidx => $xf) {
A 1129             $xdn = $xidx.'='.$this->_quote_string($xf).','.$dn;
1130             $xf = array(
1131                 $xidx => $xf,
1132                 'objectClass' => (array) $this->prop['sub_fields'][$xidx],
1133             );
1134
1135             $this->ldap_add($xdn, $xf);
1136         }
4f9c83 1137
c3ba0e 1138         $dn = self::dn_encode($dn);
A 1139
a97937 1140         // add new contact to the selected group
5d692b 1141         if ($this->group_id)
c3ba0e 1142             $this->add_to_group($this->group_id, $dn);
4f9c83 1143
c3ba0e 1144         return $dn;
e83f03 1145     }
A 1146
4f9c83 1147
a97937 1148     /**
cc90ed 1149      * Update a specific contact record
A 1150      *
1151      * @param mixed Record identifier
1152      * @param array Hash array with save data
1153      *
1154      * @return boolean True on success, False on error
1155      */
a97937 1156     function update($id, $save_cols)
f11541 1157     {
a97937 1158         $record = $this->get_record($id, true);
4aaecb 1159
13db9e 1160         $newdata     = array();
a97937 1161         $replacedata = array();
13db9e 1162         $deletedata  = array();
A 1163         $subdata     = array();
1164         $subdeldata  = array();
1165         $subnewdata  = array();
c3ba0e 1166
d6aafd 1167         $ldap_data = $this->_map_data($save_cols);
13db9e 1168         $old_data  = $record['_raw_attrib'];
1803f8 1169
21a0d9 1170         // special handling of photo col
A 1171         if ($photo_fld = $this->fieldmap['photo']) {
1172             // undefined means keep old photo
1173             if (!array_key_exists('photo', $save_cols)) {
1174                 $ldap_data[$photo_fld] = $record['photo'];
1175             }
1176         }
1177
a97937 1178         foreach ($this->fieldmap as $col => $fld) {
T 1179             if ($fld) {
13db9e 1180                 $val = $ldap_data[$fld];
A 1181                 $old = $old_data[$fld];
a97937 1182                 // remove empty array values
T 1183                 if (is_array($val))
1184                     $val = array_filter($val);
13db9e 1185                 // $this->_map_data() result and _raw_attrib use different format
A 1186                 // make sure comparing array with one element with a string works as expected
1187                 if (is_array($old) && count($old) == 1 && !is_array($val)) {
1188                     $old = array_pop($old);
21a0d9 1189                 }
A 1190                 if (is_array($val) && count($val) == 1 && !is_array($old)) {
1191                     $val = array_pop($val);
13db9e 1192                 }
A 1193                 // Subentries must be handled separately
1194                 if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
1195                     if ($old != $val) {
1196                         if ($old !== null) {
1197                             $subdeldata[$fld] = $old;
1198                         }
1199                         if ($val) {
1200                             $subnewdata[$fld] = $val;
1201                         }
1202                     }
1203                     else if ($old !== null) {
1204                         $subdata[$fld] = $old;
1205                     }
1206                     continue;
1207                 }
21a0d9 1208
a97937 1209                 // The field does exist compare it to the ldap record.
13db9e 1210                 if ($old != $val) {
a97937 1211                     // Changed, but find out how.
13db9e 1212                     if ($old === null) {
a97937 1213                         // Field was not set prior, need to add it.
T 1214                         $newdata[$fld] = $val;
1803f8 1215                     }
T 1216                     else if ($val == '') {
a97937 1217                         // Field supplied is empty, verify that it is not required.
T 1218                         if (!in_array($fld, $this->prop['required_fields'])) {
afaccf 1219                             // ...It is not, safe to clear.
AM 1220                             // #1488420: Workaround "ldap_mod_del(): Modify: Inappropriate matching in..."
1221                             // jpegPhoto attribute require an array() here. It looks to me that it works for other attribs too
1222                             $deletedata[$fld] = array();
1223                             //$deletedata[$fld] = $old_data[$fld];
1803f8 1224                         }
13db9e 1225                     }
a97937 1226                     else {
T 1227                         // The data was modified, save it out.
1228                         $replacedata[$fld] = $val;
1803f8 1229                     }
a97937 1230                 } // end if
T 1231             } // end if
1232         } // end foreach
a605b2 1233
T 1234         // console($old_data, $ldap_data, '----', $newdata, $replacedata, $deletedata, '----', $subdata, $subnewdata, $subdeldata);
1235
c3ba0e 1236         $dn = self::dn_decode($id);
a97937 1237
T 1238         // Update the entry as required.
1239         if (!empty($deletedata)) {
1240             // Delete the fields.
13db9e 1241             if (!$this->ldap_mod_del($dn, $deletedata)) {
a97937 1242                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1243                 return false;
1244             }
1245         } // end if
1246
1247         if (!empty($replacedata)) {
1248             // Handle RDN change
1249             if ($replacedata[$this->prop['LDAP_rdn']]) {
1250                 $newdn = $this->prop['LDAP_rdn'].'='
1251                     .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
d1e08f 1252                     .','.$this->base_dn;
a97937 1253                 if ($dn != $newdn) {
T 1254                     $newrdn = $this->prop['LDAP_rdn'].'='
1255                     .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
1256                     unset($replacedata[$this->prop['LDAP_rdn']]);
1257                 }
1258             }
1259             // Replace the fields.
1260             if (!empty($replacedata)) {
13db9e 1261                 if (!$this->ldap_mod_replace($dn, $replacedata)) {
A 1262                     $this->set_error(self::ERROR_SAVING, 'errorsaving');
a97937 1263                     return false;
T 1264                 }
13db9e 1265             }
a97937 1266         } // end if
13db9e 1267
A 1268         // RDN change, we need to remove all sub-entries
1269         if (!empty($newrdn)) {
1270             $subdeldata = array_merge($subdeldata, $subdata);
1271             $subnewdata = array_merge($subnewdata, $subdata);
1272         }
1273
1274         // remove sub-entries
1275         if (!empty($subdeldata)) {
1276             foreach ($subdeldata as $fld => $val) {
1277                 $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
1278                 if (!$this->ldap_delete($subdn)) {
1279                     return false;
1280                 }
1281             }
1282         }
a97937 1283
T 1284         if (!empty($newdata)) {
1285             // Add the fields.
13db9e 1286             if (!$this->ldap_mod_add($dn, $newdata)) {
a97937 1287                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1288                 return false;
1289             }
1290         } // end if
1291
1292         // Handle RDN change
1293         if (!empty($newrdn)) {
13db9e 1294             if (!$this->ldap_rename($dn, $newrdn, null, true)) {
A 1295                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
a97937 1296                 return false;
T 1297             }
1298
c3ba0e 1299             $dn    = self::dn_encode($dn);
A 1300             $newdn = self::dn_encode($newdn);
1301
a97937 1302             // change the group membership of the contact
13db9e 1303             if ($this->groups) {
c3ba0e 1304                 $group_ids = $this->get_record_groups($dn);
a97937 1305                 foreach ($group_ids as $group_id)
T 1306                 {
c3ba0e 1307                     $this->remove_from_group($group_id, $dn);
A 1308                     $this->add_to_group($group_id, $newdn);
a97937 1309                 }
T 1310             }
c3ba0e 1311
13db9e 1312             $dn = self::dn_decode($newdn);
a97937 1313         }
T 1314
13db9e 1315         // add sub-entries
A 1316         if (!empty($subnewdata)) {
1317             foreach ($subnewdata as $fld => $val) {
1318                 $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
1319                 $xf = array(
1320                     $fld => $val,
1321                     'objectClass' => (array) $this->prop['sub_fields'][$fld],
1322                 );
1323                 $this->ldap_add($subdn, $xf);
1324             }
1325         }
1326
1327         return $newdn ? $newdn : true;
f11541 1328     }
a97937 1329
T 1330
1331     /**
cc90ed 1332      * Mark one or more contact records as deleted
A 1333      *
63fda8 1334      * @param array   Record identifiers
A 1335      * @param boolean Remove record(s) irreversible (unsupported)
cc90ed 1336      *
A 1337      * @return boolean True on success, False on error
1338      */
63fda8 1339     function delete($ids, $force=true)
f11541 1340     {
a97937 1341         if (!is_array($ids)) {
T 1342             // Not an array, break apart the encoded DNs.
0f1fae 1343             $ids = explode(',', $ids);
a97937 1344         } // end if
T 1345
0f1fae 1346         foreach ($ids as $id) {
c3ba0e 1347             $dn = self::dn_decode($id);
13db9e 1348
A 1349             // Need to delete all sub-entries first
1350             if ($this->sub_filter) {
d6eb7c 1351                 if ($entries = $this->ldap_list($dn, $this->sub_filter)) {
13db9e 1352                     foreach ($entries as $entry) {
A 1353                         if (!$this->ldap_delete($entry['dn'])) {
1354                             $this->set_error(self::ERROR_SAVING, 'errorsaving');
1355                             return false;
1356                         }
1357                     }
1358                 }
1359             }
1360
a97937 1361             // Delete the record.
13db9e 1362             if (!$this->ldap_delete($dn)) {
a97937 1363                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1364                 return false;
13db9e 1365             }
a97937 1366
T 1367             // remove contact from all groups where he was member
c3ba0e 1368             if ($this->groups) {
A 1369                 $dn = self::dn_encode($dn);
1370                 $group_ids = $this->get_record_groups($dn);
1371                 foreach ($group_ids as $group_id) {
1372                     $this->remove_from_group($group_id, $dn);
a97937 1373                 }
T 1374             }
1375         } // end foreach
1376
0f1fae 1377         return count($ids);
d6eb7c 1378     }
A 1379
1380
1381     /**
1382      * Remove all contact records
1383      */
1384     function delete_all()
1385     {
1386         //searching for contact entries
1387         $dn_list = $this->ldap_list($this->base_dn, $this->prop['filter'] ? $this->prop['filter'] : '(objectclass=*)');
1388
1389         if (!empty($dn_list)) {
1390             foreach ($dn_list as $idx => $entry) {
1391                 $dn_list[$idx] = self::dn_encode($entry['dn']);
1392             }
1393             $this->delete($dn_list);
1394         }
f11541 1395     }
4368a0 1396
3f250a 1397     /**
TB 1398      * Generate missing attributes as configured
1399      *
1400      * @param array LDAP record attributes
1401      */
1402     protected function add_autovalues(&$attrs)
1403     {
1404         $attrvals = array();
1405         foreach ($attrs as $k => $v) {
1406             $attrvals['{'.$k.'}'] = is_array($v) ? $v[0] : $v;
1407         }
1408
1409         foreach ((array)$this->prop['autovalues'] as $lf => $templ) {
1410             if (empty($attrs[$lf])) {
1411                 // replace {attr} placeholders with concrete attribute values
1412                 $templ = preg_replace('/\{\w+\}/', '', strtr($templ, $attrvals));
1413
1414                 if (strpos($templ, '(') !== false)
1415                     $attrs[$lf] = eval("return ($templ);");
1416                 else
1417                     $attrs[$lf] = $templ;
1418             }
1419         }
1420     }
4368a0 1421
a97937 1422     /**
cc90ed 1423      * Execute the LDAP search based on the stored credentials
A 1424      */
c1db48 1425     private function _exec_search($count = false)
a97937 1426     {
T 1427         if ($this->ready)
1428         {
1429             $filter = $this->filter ? $this->filter : '(objectclass=*)';
fb6cc8 1430             $function = $this->_scope2func($this->prop['scope'], $ns_function);
a31482 1431
fb6cc8 1432             $this->_debug("C: Search [$filter][dn: $this->base_dn]");
69ea3a 1433
6af7e0 1434             // when using VLV, we get the total count by...
e2a8b4 1435             if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
6af7e0 1436                 // ...either reading numSubOrdinates attribute
a31482 1437                 if ($this->prop['numsub_filter'] && ($result_count = @$ns_function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
6af7e0 1438                     $counts = ldap_get_entries($this->conn, $result_count);
T 1439                     for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
1440                         $this->vlv_count += $counts[$j]['numsubordinates'][0];
1441                     $this->_debug("D: total numsubordinates = " . $this->vlv_count);
1442                 }
f09c18 1443                 else if (!function_exists('ldap_parse_virtuallist_control'))  // ...or by fetching all records dn and count them
6af7e0 1444                     $this->vlv_count = $this->_exec_search(true);
755189 1445
fb6cc8 1446                 $this->vlv_active = $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size);
69ea3a 1447             }
100440 1448
c1db48 1449             // only fetch dn for count (should keep the payload low)
T 1450             $attrs = $count ? array('dn') : array_values($this->fieldmap);
d1e08f 1451             if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
a505dd 1452                 $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
A 1453             ) {
f09c18 1454                 // when running on a patched PHP we can use the extended functions to retrieve the total count from the LDAP search result
a505dd 1455                 if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control')) {
A 1456                     if (ldap_parse_result($this->conn, $this->ldap_result,
1457                         $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)
1458                     ) {
1459                         ldap_parse_virtuallist_control($this->conn, $serverctrls,
1460                             $last_offset, $this->vlv_count, $vresult);
1461                         $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$this->vlv_count");
1462                     }
1463                     else {
1464                         $this->_debug("S: ".($errmsg ? $errmsg : ldap_error($this->conn)));
1465                     }
f09c18 1466                 }
T 1467
a505dd 1468                 $entries_count = ldap_count_entries($this->conn, $this->ldap_result);
A 1469                 $this->_debug("S: $entries_count record(s)");
f09c18 1470
a505dd 1471                 return $count ? $entries_count : true;
a97937 1472             }
a505dd 1473             else {
a97937 1474                 $this->_debug("S: ".ldap_error($this->conn));
T 1475             }
1476         }
1477
1478         return false;
69ea3a 1479     }
cc90ed 1480
69ea3a 1481     /**
fb6cc8 1482      * Choose the right PHP function according to scope property
T 1483      */
1484     private function _scope2func($scope, &$ns_function = null)
1485     {
1486         switch ($scope) {
1487           case 'sub':
1488             $function = $ns_function  = 'ldap_search';
1489             break;
1490           case 'base':
1491             $function = $ns_function = 'ldap_read';
1492             break;
1493           default:
1494             $function = 'ldap_list';
1495             $ns_function = 'ldap_read';
1496             break;
1497         }
13db9e 1498
fb6cc8 1499         return $function;
T 1500     }
1501
1502     /**
69ea3a 1503      * Set server controls for Virtual List View (paginated listing)
T 1504      */
fc91c1 1505     private function _vlv_set_controls($prop, $list_page, $page_size, $search = null)
69ea3a 1506     {
fb6cc8 1507         $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473",  'value' => $this->_sort_ber_encode((array)$prop['sort']));
fc91c1 1508         $vlv_ctrl  = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($list_page-1) * $page_size + 1), $page_size, $search), 'iscritical' => true);
69ea3a 1509
fb6cc8 1510         $sort = (array)$prop['sort'];
T 1511         $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ($sort[0]);"
1512             . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset/$page_size)");
69ea3a 1513
T 1514         if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
1515             $this->_debug("S: ".ldap_error($this->conn));
1516             $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');
1517             return false;
1518         }
1519
1520         return true;
a97937 1521     }
T 1522
1523
1524     /**
cc90ed 1525      * Converts LDAP entry into an array
A 1526      */
a97937 1527     private function _ldap2result($rec)
T 1528     {
1529         $out = array();
1530
1531         if ($rec['dn'])
c3ba0e 1532             $out[$this->primary_key] = self::dn_encode($rec['dn']);
a97937 1533
T 1534         foreach ($this->fieldmap as $rf => $lf)
1535         {
1536             for ($i=0; $i < $rec[$lf]['count']; $i++) {
1537                 if (!($value = $rec[$lf][$i]))
1538                     continue;
1803f8 1539
ad8c9d 1540                 list($col, $subtype) = explode(':', $rf);
1803f8 1541                 $out['_raw_attrib'][$lf][$i] = $value;
T 1542
1078a6 1543                 if ($col == 'email' && $this->mail_domain && !strpos($value, '@'))
a97937 1544                     $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
ad8c9d 1545                 else if (in_array($col, array('street','zipcode','locality','country','region')))
T 1546                     $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
a605b2 1547                 else if ($col == 'address' && strpos($value, '$') !== false)  // address data is represented as string separated with $
T 1548                     list($out[$rf][$i]['street'], $out[$rf][$i]['locality'], $out[$rf][$i]['zipcode'], $out[$rf][$i]['country']) = explode('$', $value);
a97937 1549                 else if ($rec[$lf]['count'] > 1)
T 1550                     $out[$rf][] = $value;
1551                 else
1552                     $out[$rf] = $value;
1553             }
b1f084 1554
A 1555             // Make sure name fields aren't arrays (#1488108)
1556             if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
1803f8 1557                 $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
b1f084 1558             }
a97937 1559         }
T 1560
1561         return $out;
1562     }
1563
1564
1565     /**
1078a6 1566      * Return LDAP attribute(s) for the given field
cc90ed 1567      */
a97937 1568     private function _map_field($field)
T 1569     {
1078a6 1570         return (array)$this->coltypes[$field]['attributes'];
a97937 1571     }
T 1572
1573
1574     /**
39cafa 1575      * Convert a record data set into LDAP field attributes
T 1576      */
1577     private function _map_data($save_cols)
1578     {
d6aafd 1579         // flatten composite fields first
T 1580         foreach ($this->coltypes as $col => $colprop) {
1581             if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
1582                 foreach ($values as $subtype => $childs) {
1583                     $subtype = $subtype ? ':'.$subtype : '';
1584                     foreach ($childs as $i => $child_values) {
1585                         foreach ((array)$child_values as $childcol => $value) {
1586                             $save_cols[$childcol.$subtype][$i] = $value;
1587                         }
1588                     }
1589                 }
1590             }
a605b2 1591
T 1592             // if addresses are to be saved as serialized string, do so
1593             if (is_array($colprop['serialized'])) {
1594                foreach ($colprop['serialized'] as $subtype => $delim) {
1595                   $key = $col.':'.$subtype;
1596                   foreach ((array)$save_cols[$key] as $i => $val)
1597                      $save_cols[$key][$i] = join($delim, array($val['street'], $val['locality'], $val['zipcode'], $val['country']));
1598                }
1599             }
d6aafd 1600         }
T 1601
39cafa 1602         $ldap_data = array();
1078a6 1603         foreach ($this->fieldmap as $rf => $fld) {
TB 1604             $val = $save_cols[$rf];
1605
1606             // check for value in base field (eg.g email instead of email:foo)
1607             list($col, $subtype) = explode(':', $rf);
1608             if (!$val && !empty($save_cols[$col])) {
1609                 $val = $save_cols[$col];
1610                 unset($save_cols[$col]);  // only use this value once
1611             }
1612             else if (!$val && !$subtype) { // extract values from subtype cols
1613                 $val = $this->get_col_values($col, $save_cols, true);
1614             }
1615
39cafa 1616             if (is_array($val))
T 1617                 $val = array_filter($val);  // remove empty entries
1618             if ($fld && $val) {
1619                 // The field does exist, add it to the entry.
1620                 $ldap_data[$fld] = $val;
1621             }
1622         }
13db9e 1623
39cafa 1624         return $ldap_data;
T 1625     }
1626
1627
1628     /**
cc90ed 1629      * Returns unified attribute name (resolving aliases)
A 1630      */
a605b2 1631     private static function _attr_name($namev)
a97937 1632     {
T 1633         // list of known attribute aliases
a605b2 1634         static $aliases = array(
a97937 1635             'gn' => 'givenname',
T 1636             'rfc822mailbox' => 'email',
1637             'userid' => 'uid',
1638             'emailaddress' => 'email',
1639             'pkcs9email' => 'email',
1640         );
a605b2 1641
T 1642         list($name, $limit) = explode(':', $namev, 2);
1643         $suffix = $limit ? ':'.$limit : '';
1644
1645         return (isset($aliases[$name]) ? $aliases[$name] : $name) . $suffix;
a97937 1646     }
T 1647
1648
1649     /**
cc90ed 1650      * Prints debug info to the log
A 1651      */
a97937 1652     private function _debug($str)
T 1653     {
0c2596 1654         if ($this->debug) {
be98df 1655             rcube::write_log('ldap', $str);
0c2596 1656         }
a97937 1657     }
T 1658
1659
1660     /**
06744d 1661      * Activate/deactivate debug mode
T 1662      *
1663      * @param boolean $dbg True if LDAP commands should be logged
1664      * @access public
1665      */
1666     function set_debug($dbg = true)
1667     {
1668         $this->debug = $dbg;
1669     }
1670
1671
1672     /**
cc90ed 1673      * Quotes attribute value string
A 1674      *
1675      * @param string $str Attribute value
1676      * @param bool   $dn  True if the attribute is a DN
1677      *
1678      * @return string Quoted string
1679      */
1680     private static function _quote_string($str, $dn=false)
a97937 1681     {
T 1682         // take firt entry if array given
1683         if (is_array($str))
1684             $str = reset($str);
1685
1686         if ($dn)
1687             $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
1688                 '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
1689         else
1690             $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
1691                 '/'=>'\2f');
1692
1693         return strtr($str, $replace);
1694     }
f11541 1695
6039aa 1696
T 1697     /**
1698      * Setter for the current group
1699      * (empty, has to be re-implemented by extending class)
1700      */
1701     function set_group($group_id)
1702     {
1703         if ($group_id)
1704         {
a31482 1705             if (($group_cache = $this->cache->get('groups')) === null)
T 1706                 $group_cache = $this->_fetch_groups();
a97937 1707
6039aa 1708             $this->group_id = $group_id;
a31482 1709             $this->group_data = $group_cache[$group_id];
6039aa 1710         }
a97937 1711         else
8fb04b 1712         {
a97937 1713             $this->group_id = 0;
a31482 1714             $this->group_data = null;
8fb04b 1715         }
6039aa 1716     }
T 1717
1718     /**
1719      * List all active contact groups of this source
1720      *
1721      * @param string  Optional search string to match group name
1722      * @return array  Indexed list of contact groups, each a hash array
1723      */
1724     function list_groups($search = null)
1725     {
a97937 1726         if (!$this->groups)
T 1727             return array();
6039aa 1728
a31482 1729         // use cached list for searching
T 1730         $this->cache->expunge();
1731         if (!$search || ($group_cache = $this->cache->get('groups')) === null)
1732             $group_cache = $this->_fetch_groups();
1733
1734         $groups = array();
1735         if ($search) {
f21a04 1736             $search = mb_strtolower($search);
a31482 1737             foreach ($group_cache as $group) {
f21a04 1738                 if (strpos(mb_strtolower($group['name']), $search) !== false)
a31482 1739                     $groups[] = $group;
T 1740             }
1741         }
1742         else
1743             $groups = $group_cache;
1744
1745         return array_values($groups);
1746     }
1747
1748     /**
1749      * Fetch groups from server
1750      */
fb6cc8 1751     private function _fetch_groups($vlv_page = 0)
a31482 1752     {
d1e08f 1753         $base_dn = $this->groups_base_dn;
T 1754         $filter = $this->prop['groups']['filter'];
448f81 1755         $name_attr = $this->prop['groups']['name_attr'];
a31482 1756         $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
fb6cc8 1757         $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
T 1758         $sort_attr = $sort_attrs[0];
6039aa 1759
755189 1760         $this->_debug("C: Search [$filter][dn: $base_dn]");
A 1761
fb6cc8 1762         // use vlv to list groups
T 1763         if ($this->prop['groups']['vlv']) {
1764             $page_size = 200;
1765             if (!$this->prop['groups']['sort'])
1766                 $this->prop['groups']['sort'] = $sort_attrs;
1767             $vlv_active = $this->_vlv_set_controls($this->prop['groups'], $vlv_page+1, $page_size);
1768         }
1769
1770         $function = $this->_scope2func($this->prop['groups']['scope'], $ns_function);
1771         $res = @$function($this->conn, $base_dn, $filter, array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr)));
6039aa 1772         if ($res === false)
T 1773         {
1774             $this->_debug("S: ".ldap_error($this->conn));
1775             return array();
1776         }
755189 1777
6039aa 1778         $ldap_data = ldap_get_entries($this->conn, $res);
755189 1779         $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
6039aa 1780
T 1781         $groups = array();
1782         $group_sortnames = array();
fb6cc8 1783         $group_count = $ldap_data["count"];
T 1784         for ($i=0; $i < $group_count; $i++)
6039aa 1785         {
fb6cc8 1786             $group_name = is_array($ldap_data[$i][$name_attr]) ? $ldap_data[$i][$name_attr][0] : $ldap_data[$i][$name_attr];
a31482 1787             $group_id = self::dn_encode($group_name);
T 1788             $groups[$group_id]['ID'] = $group_id;
1789             $groups[$group_id]['dn'] = $ldap_data[$i]['dn'];
1790             $groups[$group_id]['name'] = $group_name;
097dbc 1791             $groups[$group_id]['member_attr'] = $this->get_group_member_attr($ldap_data[$i]['objectclass']);
a31482 1792
T 1793             // list email attributes of a group
1794             for ($j=0; $ldap_data[$i][$email_attr] && $j < $ldap_data[$i][$email_attr]['count']; $j++) {
1795                 if (strpos($ldap_data[$i][$email_attr][$j], '@') > 0)
1796                     $groups[$group_id]['email'][] = $ldap_data[$i][$email_attr][$j];
1797             }
1798
f21a04 1799             $group_sortnames[] = mb_strtolower($ldap_data[$i][$sort_attr][0]);
6039aa 1800         }
fb6cc8 1801
T 1802         // recursive call can exit here
1803         if ($vlv_page > 0)
1804             return $groups;
1805
1806         // call recursively until we have fetched all groups
1807         while ($vlv_active && $group_count == $page_size)
1808         {
1809             $next_page = $this->_fetch_groups(++$vlv_page);
1810             $groups = array_merge($groups, $next_page);
1811             $group_count = count($next_page);
1812         }
1813
1814         // when using VLV the list of groups is already sorted
1815         if (!$this->prop['groups']['vlv'])
1816             array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
8fb04b 1817
T 1818         // cache this
1819         $this->cache->set('groups', $groups);
a97937 1820
6039aa 1821         return $groups;
a31482 1822     }
T 1823
1824     /**
1825      * Get group properties such as name and email address(es)
1826      *
1827      * @param string Group identifier
1828      * @return array Group properties as hash array
1829      */
1830     function get_group($group_id)
1831     {
1832         if (($group_cache = $this->cache->get('groups')) === null)
1833             $group_cache = $this->_fetch_groups();
1834
1835         $group_data = $group_cache[$group_id];
1836         unset($group_data['dn'], $group_data['member_attr']);
1837
1838         return $group_data;
6039aa 1839     }
T 1840
1841     /**
1842      * Create a contact group with the given name
1843      *
1844      * @param string The group name
1845      * @return mixed False on error, array with record props in success
1846      */
1847     function create_group($group_name)
1848     {
d1e08f 1849         $base_dn = $this->groups_base_dn;
6039aa 1850         $new_dn = "cn=$group_name,$base_dn";
c3ba0e 1851         $new_gid = self::dn_encode($group_name);
097dbc 1852         $member_attr = $this->get_group_member_attr();
A 1853         $name_attr = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
6039aa 1854
T 1855         $new_entry = array(
d1e08f 1856             'objectClass' => $this->prop['groups']['object_classes'],
448f81 1857             $name_attr => $group_name,
b4b377 1858             $member_attr => '',
6039aa 1859         );
T 1860
13db9e 1861         if (!$this->ldap_add($new_dn, $new_entry)) {
6039aa 1862             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1863             return false;
1864         }
755189 1865
8fb04b 1866         $this->cache->remove('groups');
755189 1867
6039aa 1868         return array('id' => $new_gid, 'name' => $group_name);
T 1869     }
1870
1871     /**
1872      * Delete the given group and all linked group members
1873      *
1874      * @param string Group identifier
1875      * @return boolean True on success, false if no data was changed
1876      */
1877     function delete_group($group_id)
1878     {
a31482 1879         if (($group_cache = $this->cache->get('groups')) === null)
T 1880             $group_cache = $this->_fetch_groups();
6039aa 1881
d1e08f 1882         $base_dn = $this->groups_base_dn;
8fb04b 1883         $group_name = $group_cache[$group_id]['name'];
6039aa 1884         $del_dn = "cn=$group_name,$base_dn";
755189 1885
13db9e 1886         if (!$this->ldap_delete($del_dn)) {
6039aa 1887             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1888             return false;
1889         }
755189 1890
8fb04b 1891         $this->cache->remove('groups');
755189 1892
6039aa 1893         return true;
T 1894     }
1895
1896     /**
1897      * Rename a specific contact group
1898      *
1899      * @param string Group identifier
1900      * @param string New name to set for this group
360bd3 1901      * @param string New group identifier (if changed, otherwise don't set)
6039aa 1902      * @return boolean New name on success, false if no data was changed
T 1903      */
15e944 1904     function rename_group($group_id, $new_name, &$new_gid)
6039aa 1905     {
a31482 1906         if (($group_cache = $this->cache->get('groups')) === null)
T 1907             $group_cache = $this->_fetch_groups();
6039aa 1908
d1e08f 1909         $base_dn = $this->groups_base_dn;
8fb04b 1910         $group_name = $group_cache[$group_id]['name'];
6039aa 1911         $old_dn = "cn=$group_name,$base_dn";
T 1912         $new_rdn = "cn=$new_name";
c3ba0e 1913         $new_gid = self::dn_encode($new_name);
6039aa 1914
13db9e 1915         if (!$this->ldap_rename($old_dn, $new_rdn, null, true)) {
6039aa 1916             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1917             return false;
1918         }
755189 1919
8fb04b 1920         $this->cache->remove('groups');
755189 1921
6039aa 1922         return $new_name;
T 1923     }
1924
1925     /**
1926      * Add the given contact records the a certain group
1927      *
1928      * @param string  Group identifier
1929      * @param array   List of contact identifiers to be added
1930      * @return int    Number of contacts added
1931      */
1932     function add_to_group($group_id, $contact_ids)
1933     {
a31482 1934         if (($group_cache = $this->cache->get('groups')) === null)
T 1935             $group_cache = $this->_fetch_groups();
6039aa 1936
5d692b 1937         if (!is_array($contact_ids))
T 1938             $contact_ids = explode(',', $contact_ids);
1939
f763fb 1940         $base_dn     = $this->groups_base_dn;
8fb04b 1941         $group_name  = $group_cache[$group_id]['name'];
T 1942         $member_attr = $group_cache[$group_id]['member_attr'];
f763fb 1943         $group_dn    = "cn=$group_name,$base_dn";
6039aa 1944
T 1945         $new_attrs = array();
5d692b 1946         foreach ($contact_ids as $id)
f763fb 1947             $new_attrs[$member_attr][] = self::dn_decode($id);
6039aa 1948
13db9e 1949         if (!$this->ldap_mod_add($group_dn, $new_attrs)) {
6039aa 1950             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1951             return 0;
1952         }
755189 1953
8fb04b 1954         $this->cache->remove('groups');
755189 1955
6039aa 1956         return count($new_attrs['member']);
T 1957     }
1958
1959     /**
1960      * Remove the given contact records from a certain group
1961      *
1962      * @param string  Group identifier
1963      * @param array   List of contact identifiers to be removed
1964      * @return int    Number of deleted group members
1965      */
1966     function remove_from_group($group_id, $contact_ids)
1967     {
a31482 1968         if (($group_cache = $this->cache->get('groups')) === null)
T 1969             $group_cache = $this->_fetch_groups();
6039aa 1970
f763fb 1971         $base_dn     = $this->groups_base_dn;
8fb04b 1972         $group_name  = $group_cache[$group_id]['name'];
T 1973         $member_attr = $group_cache[$group_id]['member_attr'];
f763fb 1974         $group_dn    = "cn=$group_name,$base_dn";
6039aa 1975
T 1976         $del_attrs = array();
1977         foreach (explode(",", $contact_ids) as $id)
f763fb 1978             $del_attrs[$member_attr][] = self::dn_decode($id);
6039aa 1979
13db9e 1980         if (!$this->ldap_mod_del($group_dn, $del_attrs)) {
6039aa 1981             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1982             return 0;
1983         }
755189 1984
8fb04b 1985         $this->cache->remove('groups');
755189 1986
6039aa 1987         return count($del_attrs['member']);
T 1988     }
1989
1990     /**
1991      * Get group assignments of a specific contact record
1992      *
1993      * @param mixed Record identifier
1994      *
1995      * @return array List of assigned groups as ID=>Name pairs
1996      * @since 0.5-beta
1997      */
1998     function get_record_groups($contact_id)
1999     {
a97937 2000         if (!$this->groups)
6039aa 2001             return array();
T 2002
f763fb 2003         $base_dn     = $this->groups_base_dn;
A 2004         $contact_dn  = self::dn_decode($contact_id);
097dbc 2005         $name_attr   = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
A 2006         $member_attr = $this->get_group_member_attr();
8fb04b 2007         $add_filter  = '';
T 2008         if ($member_attr != 'member' && $member_attr != 'uniqueMember')
2009             $add_filter = "($member_attr=$contact_dn)";
2010         $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
6039aa 2011
755189 2012         $this->_debug("C: Search [$filter][dn: $base_dn]");
A 2013
448f81 2014         $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
6039aa 2015         if ($res === false)
T 2016         {
2017             $this->_debug("S: ".ldap_error($this->conn));
2018             return array();
2019         }
2020         $ldap_data = ldap_get_entries($this->conn, $res);
755189 2021         $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
6039aa 2022
T 2023         $groups = array();
2024         for ($i=0; $i<$ldap_data["count"]; $i++)
2025         {
448f81 2026             $group_name = $ldap_data[$i][$name_attr][0];
c3ba0e 2027             $group_id = self::dn_encode($group_name);
6039aa 2028             $groups[$group_id] = $group_id;
T 2029         }
2030         return $groups;
2031     }
69ea3a 2032
097dbc 2033     /**
A 2034      * Detects group member attribute name
2035      */
2036     private function get_group_member_attr($object_classes = array())
2037     {
2038         if (empty($object_classes)) {
2039             $object_classes = $this->prop['groups']['object_classes'];
2040         }
2041         if (!empty($object_classes)) {
2042             foreach ((array)$object_classes as $oc) {
2043                 switch (strtolower($oc)) {
2044                     case 'group':
2045                     case 'groupofnames':
2046                     case 'kolabgroupofnames':
2047                         $member_attr = 'member';
2048                         break;
2049
2050                     case 'groupofuniquenames':
2051                     case 'kolabgroupofuniquenames':
2052                         $member_attr = 'uniqueMember';
2053                         break;
2054                 }
2055             }
2056         }
2057
2058         if (!empty($member_attr)) {
2059             return $member_attr;
2060         }
2061
2062         if (!empty($this->prop['groups']['member_attr'])) {
2063             return $this->prop['groups']['member_attr'];
2064         }
2065
2066         return 'member';
2067     }
2068
69ea3a 2069
T 2070     /**
2071      * Generate BER encoded string for Virtual List View option
2072      *
2073      * @param integer List offset (first record)
2074      * @param integer Records per page
2075      * @return string BER encoded option value
2076      */
fc91c1 2077     private function _vlv_ber_encode($offset, $rpp, $search = '')
69ea3a 2078     {
T 2079         # this string is ber-encoded, php will prefix this value with:
2080         # 04 (octet string) and 10 (length of 16 bytes)
2081         # the code behind this string is broken down as follows:
2082         # 30 = ber sequence with a length of 0e (14) bytes following
ce53b6 2083         # 02 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
T 2084         # 02 = type integer (in two's complement form) with 2 bytes following (afterCount):  01 18 (ie 25-1=24)
69ea3a 2085         # a0 = type context-specific/constructed with a length of 06 (6) bytes following
ce53b6 2086         # 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
T 2087         # 02 = type integer with 2 bytes following (contentCount):  01 00
413df0 2088
fc91c1 2089         # whith a search string present:
T 2090         # 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
2091         # 81 indicates a user string is present where as a a0 indicates just a offset search
2092         # 81 = type context-specific/constructed with a length of 06 (6) bytes following
413df0 2093
69ea3a 2094         # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
T 2095         # encoding of integer values (note: these values are in
2096         # two-complement form so since offset will never be negative bit 8 of the
2097         # leftmost octet should never by set to 1):
2098         # 8.3.2: If the contents octets of an integer value encoding consist
2099         # of more than one octet, then the bits of the first octet (rightmost) and bit 8
2100         # of the second (to the left of first octet) octet:
2101         # a) shall not all be ones; and
2102         # b) shall not all be zero
413df0 2103
fc91c1 2104         if ($search)
T 2105         {
2106             $search = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
2107             $ber_val = self::_string2hex($search);
2108             $str = self::_ber_addseq($ber_val, '81');
2109         }
2110         else
2111         {
2112             # construct the string from right to left
2113             $str = "020100"; # contentCount
69ea3a 2114
fc91c1 2115             $ber_val = self::_ber_encode_int($offset);  // returns encoded integer value in hex format
cc90ed 2116
fc91c1 2117             // calculate octet length of $ber_val
T 2118             $str = self::_ber_addseq($ber_val, '02') . $str;
69ea3a 2119
fc91c1 2120             // now compute length over $str
T 2121             $str = self::_ber_addseq($str, 'a0');
2122         }
413df0 2123
69ea3a 2124         // now tack on records per page
ce53b6 2125         $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;
69ea3a 2126
T 2127         // now tack on sequence identifier and length
2128         $str = self::_ber_addseq($str, '30');
2129
2130         return pack('H'.strlen($str), $str);
2131     }
2132
2133
2134     /**
2135      * create ber encoding for sort control
2136      *
c3ba0e 2137      * @param array List of cols to sort by
69ea3a 2138      * @return string BER encoded option value
T 2139      */
2140     private function _sort_ber_encode($sortcols)
2141     {
2142         $str = '';
2143         foreach (array_reverse((array)$sortcols) as $col) {
2144             $ber_val = self::_string2hex($col);
2145
2146             # 30 = ber sequence with a length of octet value
2147             # 04 = octet string with a length of the ascii value
2148             $oct = self::_ber_addseq($ber_val, '04');
2149             $str = self::_ber_addseq($oct, '30') . $str;
2150         }
2151
2152         // now tack on sequence identifier and length
2153         $str = self::_ber_addseq($str, '30');
2154
2155         return pack('H'.strlen($str), $str);
2156     }
2157
2158     /**
2159      * Add BER sequence with correct length and the given identifier
2160      */
2161     private static function _ber_addseq($str, $identifier)
2162     {
6f3fa9 2163         $len = dechex(strlen($str)/2);
69ea3a 2164         if (strlen($len) % 2 != 0)
T 2165             $len = '0'.$len;
2166
2167         return $identifier . $len . $str;
2168     }
2169
2170     /**
2171      * Returns BER encoded integer value in hex format
2172      */
2173     private static function _ber_encode_int($offset)
2174     {
6f3fa9 2175         $val = dechex($offset);
69ea3a 2176         $prefix = '';
cc90ed 2177
69ea3a 2178         // check if bit 8 of high byte is 1
T 2179         if (preg_match('/^[89abcdef]/', $val))
2180             $prefix = '00';
2181
2182         if (strlen($val)%2 != 0)
2183             $prefix .= '0';
2184
2185         return $prefix . $val;
2186     }
2187
2188     /**
2189      * Returns ascii string encoded in hex
2190      */
c3ba0e 2191     private static function _string2hex($str)
A 2192     {
69ea3a 2193         $hex = '';
T 2194         for ($i=0; $i < strlen($str); $i++)
2195             $hex .= dechex(ord($str[$i]));
2196         return $hex;
2197     }
2198
c3ba0e 2199     /**
A 2200      * HTML-safe DN string encoding
2201      *
2202      * @param string $str DN string
2203      *
2204      * @return string Encoded HTML identifier string
2205      */
2206     static function dn_encode($str)
2207     {
2208         // @TODO: to make output string shorter we could probably
2209         //        remove dc=* items from it
2210         return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
2211     }
2212
2213     /**
2214      * Decodes DN string encoded with _dn_encode()
2215      *
2216      * @param string $str Encoded HTML identifier string
2217      *
2218      * @return string DN string
2219      */
2220     static function dn_decode($str)
2221     {
2222         $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
2223         return base64_decode($str);
2224     }
13db9e 2225
A 2226     /**
2227      * Wrapper for ldap_add()
2228      */
2229     protected function ldap_add($dn, $entry)
2230     {
2231         $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2232
2233         $res = ldap_add($this->conn, $dn, $entry);
2234         if ($res === false) {
2235             $this->_debug("S: ".ldap_error($this->conn));
2236             return false;
2237         }
2238
2239         $this->_debug("S: OK");
2240         return true;
2241     }
2242
2243     /**
2244      * Wrapper for ldap_delete()
2245      */
2246     protected function ldap_delete($dn)
2247     {
2248         $this->_debug("C: Delete [dn: $dn]");
2249
2250         $res = ldap_delete($this->conn, $dn);
2251         if ($res === false) {
2252             $this->_debug("S: ".ldap_error($this->conn));
2253             return false;
2254         }
2255
2256         $this->_debug("S: OK");
2257         return true;
2258     }
2259
2260     /**
2261      * Wrapper for ldap_mod_replace()
2262      */
2263     protected function ldap_mod_replace($dn, $entry)
2264     {
2265         $this->_debug("C: Replace [dn: $dn]: ".print_r($entry, true));
2266
2267         if (!ldap_mod_replace($this->conn, $dn, $entry)) {
2268             $this->_debug("S: ".ldap_error($this->conn));
2269             return false;
2270         }
2271
2272         $this->_debug("S: OK");
2273         return true;
2274     }
2275
2276     /**
2277      * Wrapper for ldap_mod_add()
2278      */
2279     protected function ldap_mod_add($dn, $entry)
2280     {
2281         $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
2282
2283         if (!ldap_mod_add($this->conn, $dn, $entry)) {
2284             $this->_debug("S: ".ldap_error($this->conn));
2285             return false;
2286         }
2287
2288         $this->_debug("S: OK");
2289         return true;
2290     }
2291
2292     /**
2293      * Wrapper for ldap_mod_del()
2294      */
2295     protected function ldap_mod_del($dn, $entry)
2296     {
2297         $this->_debug("C: Delete [dn: $dn]: ".print_r($entry, true));
2298
2299         if (!ldap_mod_del($this->conn, $dn, $entry)) {
2300             $this->_debug("S: ".ldap_error($this->conn));
2301             return false;
2302         }
2303
2304         $this->_debug("S: OK");
2305         return true;
2306     }
2307
2308     /**
2309      * Wrapper for ldap_rename()
2310      */
2311     protected function ldap_rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
2312     {
2313         $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
2314
2315         if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
2316             $this->_debug("S: ".ldap_error($this->conn));
2317             return false;
2318         }
2319
2320         $this->_debug("S: OK");
2321         return true;
2322     }
2323
2324     /**
2325      * Wrapper for ldap_list()
2326      */
d6eb7c 2327     protected function ldap_list($dn, $filter, $attrs = array(''))
13db9e 2328     {
A 2329         $list = array();
2330         $this->_debug("C: List [dn: $dn] [{$filter}]");
2331
2332         if ($result = ldap_list($this->conn, $dn, $filter, $attrs)) {
2333             $list = ldap_get_entries($this->conn, $result);
2334
2335             if ($list === false) {
2336                 $this->_debug("S: ".ldap_error($this->conn));
2337                 return array();
2338             }
2339
2340             $count = $list['count'];
2341             unset($list['count']);
2342
2343             $this->_debug("S: $count record(s)");
2344         }
2345         else {
2346             $this->_debug("S: ".ldap_error($this->conn));
2347         }
2348
2349         return $list;
2350     }
2351
f11541 2352 }