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