Aleksander Machniak
2015-07-02 6a8c4fc73b5b2f5100d24a7a8b8273ffc6baca9c
commit | author | age
d1d2c4 1 <?php
041c93 2
a95874 3 /**
d1d2c4 4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube Webmail client                     |
203323 6  | Copyright (C) 2006-2013, The Roundcube Dev Team                       |
TB 7  | Copyright (C) 2011-2013, 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 {
3e7b9b 30     // public properties
a97937 31     public $primary_key = 'ID';
4feb8e 32     public $groups      = false;
AM 33     public $readonly    = true;
34     public $ready       = false;
35     public $group_id    = 0;
36     public $coltypes    = array();
79367a 37     public $export_groups = false;
1148c6 38
3e7b9b 39     // private properties
203323 40     protected $ldap;
4feb8e 41     protected $prop     = array();
a97937 42     protected $fieldmap = array();
4feb8e 43     protected $filter   = '';
13db9e 44     protected $sub_filter;
4feb8e 45     protected $result;
AM 46     protected $ldap_result;
a97937 47     protected $mail_domain = '';
T 48     protected $debug = false;
3e7b9b 49
AM 50     /**
51      * Group objectclass (lowercase) to member attribute mapping
52      *
53      * @var array
54      */
3ce7c5 55     private $group_types = array(
3e7b9b 56         'group'                   => 'member',
AM 57         'groupofnames'            => 'member',
58         'kolabgroupofnames'       => 'member',
59         'groupofuniquenames'      => 'uniqueMember',
60         'kolabgroupofuniquenames' => 'uniqueMember',
61         'univentiongroup'         => 'uniqueMember',
62         'groupofurls'             => null,
63     );
6039aa 64
4feb8e 65     private $base_dn        = '';
d1e08f 66     private $groups_base_dn = '';
834fb6 67     private $group_data;
TB 68     private $group_search_cache;
8fb04b 69     private $cache;
1148c6 70
A 71
a97937 72     /**
T 73     * Object constructor
74     *
c64bee 75     * @param array   $p            LDAP connection properties
0c2596 76     * @param boolean $debug        Enables debug mode
A 77     * @param string  $mail_domain  Current user mail domain name
a97937 78     */
0c2596 79     function __construct($p, $debug = false, $mail_domain = null)
f11541 80     {
a97937 81         $this->prop = $p;
b1f084 82
49cb69 83         $fetch_attributes = array('objectClass');
010274 84
a97937 85         // check if groups are configured
f763fb 86         if (is_array($p['groups']) && count($p['groups'])) {
a97937 87             $this->groups = true;
f763fb 88             // set member field
A 89             if (!empty($p['groups']['member_attr']))
015dec 90                 $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
f763fb 91             else if (empty($p['member_attr']))
A 92                 $this->prop['member_attr'] = 'member';
448f81 93             // set default name attribute to cn
T 94             if (empty($this->prop['groups']['name_attr']))
95                 $this->prop['groups']['name_attr'] = 'cn';
fb6cc8 96             if (empty($this->prop['groups']['scope']))
T 97                 $this->prop['groups']['scope'] = 'sub';
3ce7c5 98             // extend group objectclass => member attribute mapping
a2cf7c 99             if (!empty($this->prop['groups']['class_member_attr']))
TB 100                 $this->group_types = array_merge($this->group_types, $this->prop['groups']['class_member_attr']);
ec2185 101
49cb69 102             // add group name attrib to the list of attributes to be fetched
TB 103             $fetch_attributes[] = $this->prop['groups']['name_attr'];
ec2185 104         }
834fb6 105         if (is_array($p['group_filters'])) {
TB 106             $this->groups = $this->groups || count($p['group_filters']);
8862f6 107
9eaf68 108             foreach ($p['group_filters'] as $k => $group_filter) {
TB 109                 // set default name attribute to cn
110                 if (empty($group_filter['name_attr']) && empty($this->prop['groups']['name_attr']))
111                     $this->prop['group_filters'][$k]['name_attr'] = $group_filter['name_attr'] = 'cn';
112
8862f6 113                 if ($group_filter['name_attr'])
TB 114                     $fetch_attributes[] = $group_filter['name_attr'];
115             }
f763fb 116         }
cd6749 117
a97937 118         // fieldmap property is given
T 119         if (is_array($p['fieldmap'])) {
bf99c5 120             $p['fieldmap'] = array_filter($p['fieldmap']);
a97937 121             foreach ($p['fieldmap'] as $rf => $lf)
T 122                 $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
123         }
38dc51 124         else if (!empty($p)) {
a97937 125             // read deprecated *_field properties to remain backwards compatible
T 126             foreach ($p as $prop => $value)
bf99c5 127                 if (!empty($value) && preg_match('/^(.+)_field$/', $prop, $matches))
a97937 128                     $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
b9f9f1 129         }
4f9c83 130
a97937 131         // use fieldmap to advertise supported coltypes to the application
a605b2 132         foreach ($this->fieldmap as $colv => $lfv) {
T 133             list($col, $type) = explode(':', $colv);
134             list($lf, $limit, $delim) = explode(':', $lfv);
135
136             if ($limit == '*') $limit = null;
137             else               $limit = max(1, intval($limit));
138
a97937 139             if (!is_array($this->coltypes[$col])) {
T 140                 $subtypes = $type ? array($type) : null;
1078a6 141                 $this->coltypes[$col] = array('limit' => $limit, 'subtypes' => $subtypes, 'attributes' => array($lf));
1148c6 142             }
a97937 143             elseif ($type) {
T 144                 $this->coltypes[$col]['subtypes'][] = $type;
1078a6 145                 $this->coltypes[$col]['attributes'][] = $lf;
a605b2 146                 $this->coltypes[$col]['limit'] += $limit;
a97937 147             }
a605b2 148
T 149             if ($delim)
150                $this->coltypes[$col]['serialized'][$type] = $delim;
151
1078a6 152            $this->fieldmap[$colv] = $lf;
1148c6 153         }
f76765 154
1937f4 155         // support for composite address
1078a6 156         if ($this->coltypes['street'] && $this->coltypes['locality']) {
a605b2 157             $this->coltypes['address'] = array(
T 158                'limit'    => max(1, $this->coltypes['locality']['limit'] + $this->coltypes['address']['limit']),
5b0b03 159                'subtypes' => array_merge((array)$this->coltypes['address']['subtypes'], (array)$this->coltypes['locality']['subtypes']),
a605b2 160                'childs' => array(),
T 161                ) + (array)$this->coltypes['address'];
162
3ac5cd 163             foreach (array('street','locality','zipcode','region','country') as $childcol) {
1078a6 164                 if ($this->coltypes[$childcol]) {
3ac5cd 165                     $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
T 166                     unset($this->coltypes[$childcol]);  // remove address child col from global coltypes list
167                 }
168             }
fb001f 169
AM 170             // at least one address type must be specified
171             if (empty($this->coltypes['address']['subtypes'])) {
172                 $this->coltypes['address']['subtypes'] = array('home');
173             }
1937f4 174         }
19fccd 175         else if ($this->coltypes['address']) {
24f1bf 176             $this->coltypes['address'] += array('type' => 'textarea', 'childs' => null, 'size' => 40);
T 177
178             // 'serialized' means the UI has to present a composite address field
179             if ($this->coltypes['address']['serialized']) {
180                 $childprop = array('type' => 'text');
181                 $this->coltypes['address']['type'] = 'composite';
182                 $this->coltypes['address']['childs'] = array('street' => $childprop, 'locality' => $childprop, 'zipcode' => $childprop, 'country' => $childprop);
183             }
19fccd 184         }
4f9c83 185
a97937 186         // make sure 'required_fields' is an array
19fccd 187         if (!is_array($this->prop['required_fields'])) {
a97937 188             $this->prop['required_fields'] = (array) $this->prop['required_fields'];
19fccd 189         }
4f9c83 190
19fccd 191         // make sure LDAP_rdn field is required
540e13 192         if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])
AM 193             && !in_array($this->prop['LDAP_rdn'], array_keys((array)$this->prop['autovalues']))) {
19fccd 194             $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
A 195         }
196
197         foreach ($this->prop['required_fields'] as $key => $val) {
a97937 198             $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
19fccd 199         }
13db9e 200
A 201         // Build sub_fields filter
202         if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
203             $this->sub_filter = '';
3725cf 204             foreach ($this->prop['sub_fields'] as $class) {
13db9e 205                 if (!empty($class)) {
A 206                     $class = is_array($class) ? array_pop($class) : $class;
207                     $this->sub_filter .= '(objectClass=' . $class . ')';
208                 }
209             }
210             if (count($this->prop['sub_fields']) > 1) {
211                 $this->sub_filter = '(|' . $this->sub_filter . ')';
212             }
213         }
f11541 214
f763fb 215         $this->sort_col    = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
A 216         $this->debug       = $debug;
a97937 217         $this->mail_domain = $mail_domain;
8fb04b 218
T 219         // initialize cache
b20025 220         $rcube = rcube::get_instance();
AM 221         if ($cache_type = $rcube->config->get('ldap_cache', 'db')) {
222             $cache_ttl  = $rcube->config->get('ldap_cache_ttl', '10m');
223             $cache_name = 'LDAP.' . asciiwords($this->prop['name']);
b07426 224
b20025 225             $this->cache = $rcube->get_cache($cache_name, $cache_type, $cache_ttl);
AM 226         }
f11541 227
807c3d 228         // determine which attributes to fetch
8862f6 229         $this->prop['list_attributes'] = array_unique($fetch_attributes);
f924f5 230         $this->prop['attributes'] = array_merge(array_values($this->fieldmap), $fetch_attributes);
807c3d 231         foreach ($rcube->config->get('contactlist_fields') as $col) {
TB 232             $this->prop['list_attributes'] = array_merge($this->prop['list_attributes'], $this->_map_field($col));
233         }
234
235         // initialize ldap wrapper object
fae90d 236         $this->ldap = new rcube_ldap_generic($this->prop);
6ac939 237         $this->ldap->config_set(array('cache' => $this->cache, 'debug' => $this->debug));
203323 238
a97937 239         $this->_connect();
736307 240     }
010274 241
a97937 242     /**
a95874 243      * Establish a connection to the LDAP server
AM 244      */
a97937 245     private function _connect()
6b603d 246     {
be98df 247         $rcube = rcube::get_instance();
f11541 248
203323 249         if ($this->ready)
a97937 250             return true;
f11541 251
a97937 252         if (!is_array($this->prop['hosts']))
T 253             $this->prop['hosts'] = array($this->prop['hosts']);
f11541 254
e114a6 255         // try to connect + bind for every host configured
TB 256         // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable
257         // see http://www.php.net/manual/en/function.ldap-connect.php
258         foreach ($this->prop['hosts'] as $host) {
203323 259             // skip host if connection failed
TB 260             if (!$this->ldap->connect($host)) {
e114a6 261                 continue;
TB 262             }
263
264             // See if the directory is writeable.
265             if ($this->prop['writable']) {
266                 $this->readonly = false;
267             }
268
269             $bind_pass = $this->prop['bind_pass'];
270             $bind_user = $this->prop['bind_user'];
271             $bind_dn   = $this->prop['bind_dn'];
272
273             $this->base_dn        = $this->prop['base_dn'];
274             $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
203323 275                 $this->prop['groups']['base_dn'] : $this->base_dn;
e114a6 276
TB 277             // User specific access, generate the proper values to use.
278             if ($this->prop['user_specific']) {
279                 // No password set, use the session password
280                 if (empty($bind_pass)) {
281                     $bind_pass = $rcube->get_user_password();
282                 }
283
284                 // Get the pieces needed for variable replacement.
0f6341 285                 if ($fu = $rcube->get_user_email()) {
e114a6 286                     list($u, $d) = explode('@', $fu);
0f6341 287                 }
TB 288                 else {
e114a6 289                     $d = $this->mail_domain;
0f6341 290                 }
e114a6 291
TB 292                 $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
293
0f6341 294                 // resolve $dc through LDAP
TB 295                 if (!empty($this->prop['domain_filter']) && !empty($this->prop['search_bind_dn']) &&
296                         method_exists($this->ldap, 'domain_root_dn')) {
297                     $this->ldap->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
298                     $dc = $this->ldap->domain_root_dn($d);
299                 }
300
e114a6 301                 $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
TB 302
5a6c3a 303                 // Search for the dn to use to authenticate
e426ae 304                 if ($this->prop['search_base_dn'] && $this->prop['search_filter']
AM 305                     && (strstr($bind_dn, '%dn') || strstr($this->base_dn, '%dn') || strstr($this->groups_base_dn, '%dn'))
306                 ) {
3ce7c5 307                     $search_attribs = array('uid');
TB 308                      if ($search_bind_attrib = (array)$this->prop['search_bind_attrib']) {
309                          foreach ($search_bind_attrib as $r => $attr) {
310                              $search_attribs[] = $attr;
311                              $replaces[$r] = '';
312                          }
313                      }
314
5a6c3a 315                     $search_bind_dn = strtr($this->prop['search_bind_dn'], $replaces);
AM 316                     $search_base_dn = strtr($this->prop['search_base_dn'], $replaces);
317                     $search_filter  = strtr($this->prop['search_filter'], $replaces);
e114a6 318
5a6c3a 319                     $cache_key = 'DN.' . md5("$host:$search_bind_dn:$search_base_dn:$search_filter:"
AM 320                         .$this->prop['search_bind_pw']);
e114a6 321
b20025 322                     if ($this->cache && ($dn = $this->cache->get($cache_key))) {
5a6c3a 323                         $replaces['%dn'] = $dn;
e114a6 324                     }
TB 325                     else {
5a6c3a 326                         $ldap = $this->ldap;
AM 327                         if (!empty($search_bind_dn) && !empty($this->prop['search_bind_pw'])) {
328                             // To protect from "Critical extension is unavailable" error
329                             // we need to use a separate LDAP connection
330                             if (!empty($this->prop['vlv'])) {
331                                 $ldap = new rcube_ldap_generic($this->prop);
6ac939 332                                 $ldap->config_set(array('cache' => $this->cache, 'debug' => $this->debug));
5a6c3a 333                                 if (!$ldap->connect($host)) {
AM 334                                     continue;
335                                 }
336                             }
337
338                             if (!$ldap->bind($search_bind_dn, $this->prop['search_bind_pw'])) {
339                                 continue;  // bind failed, try next host
340                             }
341                         }
342
3ce7c5 343                         $res = $ldap->search($search_base_dn, $search_filter, 'sub', $search_attribs);
5a6c3a 344                         if ($res) {
AM 345                             $res->rewind();
8ee8be 346                             $replaces['%dn'] = key($res->entries(TRUE));
3ce7c5 347
TB 348                             // add more replacements from 'search_bind_attrib' config
349                             if ($search_bind_attrib) {
350                                 $res = $res->current();
351                                 foreach ($search_bind_attrib as $r => $attr) {
352                                     $replaces[$r] = $res[$attr][0];
353                                 }
354                             }
5a6c3a 355                         }
AM 356
357                         if ($ldap != $this->ldap) {
358                             $ldap->close();
359                         }
e114a6 360                     }
TB 361
362                     // DN not found
363                     if (empty($replaces['%dn'])) {
364                         if (!empty($this->prop['search_dn_default']))
365                             $replaces['%dn'] = $this->prop['search_dn_default'];
366                         else {
367                             rcube::raise_error(array(
368                                 'code' => 100, 'type' => 'ldap',
369                                 'file' => __FILE__, 'line' => __LINE__,
370                                 'message' => "DN not found using LDAP search."), true);
5a6c3a 371                             continue;
e114a6 372                         }
TB 373                     }
5a6c3a 374
b20025 375                     if ($this->cache && !empty($replaces['%dn'])) {
5a6c3a 376                         $this->cache->set($cache_key, $replaces['%dn']);
AM 377                     }
e114a6 378                 }
TB 379
380                 // Replace the bind_dn and base_dn variables.
381                 $bind_dn              = strtr($bind_dn, $replaces);
382                 $this->base_dn        = strtr($this->base_dn, $replaces);
383                 $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
3ce7c5 384
TB 385                 // replace placeholders in filter settings
386                 if (!empty($this->prop['filter']))
387                     $this->prop['filter'] = strtr($this->prop['filter'], $replaces);
1e9a59 388
TB 389                 foreach (array('base_dn','filter','member_filter') as $k) {
390                     if (!empty($this->prop['groups'][$k]))
391                         $this->prop['groups'][$k] = strtr($this->prop['groups'][$k], $replaces);
392                 }
3ce7c5 393
834fb6 394                 if (is_array($this->prop['group_filters'])) {
3ce7c5 395                     foreach ($this->prop['group_filters'] as $i => $gf) {
TB 396                         if (!empty($gf['base_dn']))
397                             $this->prop['group_filters'][$i]['base_dn'] = strtr($gf['base_dn'], $replaces);
398                         if (!empty($gf['filter']))
399                             $this->prop['group_filters'][$i]['filter'] = strtr($gf['filter'], $replaces);
400                     }
401                 }
e114a6 402
TB 403                 if (empty($bind_user)) {
404                     $bind_user = $u;
405                 }
406             }
407
408             if (empty($bind_pass)) {
409                 $this->ready = true;
410             }
411             else {
412                 if (!empty($bind_dn)) {
203323 413                     $this->ready = $this->ldap->bind($bind_dn, $bind_pass);
e114a6 414                 }
TB 415                 else if (!empty($this->prop['auth_cid'])) {
203323 416                     $this->ready = $this->ldap->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
e114a6 417                 }
TB 418                 else {
203323 419                     $this->ready = $this->ldap->sasl_bind($bind_user, $bind_pass);
e114a6 420                 }
TB 421             }
422
423             // connection established, we're done here
424             if ($this->ready) {
a97937 425                 break;
T 426             }
427
e114a6 428         }  // end foreach hosts
c041d5 429
203323 430         if (!is_resource($this->ldap->conn)) {
0c2596 431             rcube::raise_error(array('code' => 100, 'type' => 'ldap',
c041d5 432                 'file' => __FILE__, 'line' => __LINE__,
203323 433                 'message' => "Could not connect to any LDAP server, last tried $host"), true);
c041d5 434
A 435             return false;
436         }
437
438         return $this->ready;
a97937 439     }
T 440
441     /**
cc90ed 442      * Close connection to LDAP server
A 443      */
a97937 444     function close()
T 445     {
203323 446         if ($this->ldap) {
TB 447             $this->ldap->close();
a97937 448         }
T 449     }
450
451     /**
cc90ed 452      * Returns address book name
A 453      *
454      * @return string Address book name
455      */
456     function get_name()
457     {
458         return $this->prop['name'];
203323 459     }
TB 460
461     /**
462      * Set internal list page
463      *
464      * @param  number  Page number to list
465      */
466     function set_page($page)
467     {
468         $this->list_page = (int)$page;
469         $this->ldap->set_vlv_page($this->list_page, $this->page_size);
470     }
471
472     /**
473      * Set internal page size
474      *
475      * @param  number  Number of records to display on one page
476      */
477     function set_pagesize($size)
478     {
479         $this->page_size = (int)$size;
480         $this->ldap->set_vlv_page($this->list_page, $this->page_size);
cc90ed 481     }
A 482
483     /**
438753 484      * Set internal sort settings
cc90ed 485      *
438753 486      * @param string $sort_col Sort column
T 487      * @param string $sort_order Sort order
cc90ed 488      */
438753 489     function set_sort_order($sort_col, $sort_order = null)
a97937 490     {
1078a6 491         if ($this->coltypes[$sort_col]['attributes'])
TB 492             $this->sort_col = $this->coltypes[$sort_col]['attributes'][0];
a97937 493     }
T 494
495     /**
cc90ed 496      * Save a search string for future listings
A 497      *
498      * @param string $filter Filter string
499      */
a97937 500     function set_search_set($filter)
T 501     {
502         $this->filter = $filter;
503     }
504
505     /**
cc90ed 506      * Getter for saved search properties
A 507      *
508      * @return mixed Search properties used by this class
509      */
a97937 510     function get_search_set()
T 511     {
512         return $this->filter;
513     }
514
515     /**
cc90ed 516      * Reset all saved results and search parameters
A 517      */
a97937 518     function reset()
T 519     {
520         $this->result = null;
521         $this->ldap_result = null;
522         $this->filter = '';
523     }
524
525     /**
cc90ed 526      * List the current set of contact records
A 527      *
a95874 528      * @param array List of cols to show
AM 529      * @param int   Only return this number of records
cc90ed 530      *
a95874 531      * @return array Indexed list of contact records, each a hash array
cc90ed 532      */
a97937 533     function list_records($cols=null, $subset=0)
T 534     {
203323 535         if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id) {
2d3e2b 536             $this->result = new rcube_result_set(0);
T 537             $this->result->searchonly = true;
538             return $this->result;
539         }
b1f084 540
a31482 541         // fetch group members recursively
203323 542         if ($this->group_id && $this->group_data['dn']) {
a31482 543             $entries = $this->list_group_members($this->group_data['dn']);
T 544
545             // make list of entries unique and sort it
546             $seen = array();
547             foreach ($entries as $i => $rec) {
548                 if ($seen[$rec['dn']]++)
549                     unset($entries[$i]);
550             }
551             usort($entries, array($this, '_entry_sort_cmp'));
552
553             $entries['count'] = count($entries);
554             $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
555         }
203323 556         else {
4287c9 557             $prop    = $this->group_id ? $this->group_data : $this->prop;
8fc49e 558             $base_dn = $this->group_id ? $prop['base_dn'] : $this->base_dn;
ec2185 559
203323 560             // use global search filter
TB 561             if (!empty($this->filter))
562                 $prop['filter'] = $this->filter;
a31482 563
T 564             // exec LDAP search if no result resource is stored
203323 565             if ($this->ready && !$this->ldap_result)
4287c9 566                 $this->ldap_result = $this->ldap->search($base_dn, $prop['filter'], $prop['scope'], $this->prop['attributes'], $prop);
a31482 567
T 568             // count contacts for this user
569             $this->result = $this->count();
570
571             // we have a search result resource
203323 572             if ($this->ldap_result && $this->result->count > 0) {
a31482 573                 // sorting still on the ldap server
203323 574                 if ($this->sort_col && $prop['scope'] !== 'base' && !$this->ldap->vlv_active)
TB 575                     $this->ldap_result->sort($this->sort_col);
a31482 576
T 577                 // get all entries from the ldap server
203323 578                 $entries = $this->ldap_result->entries();
a31482 579             }
T 580
581         }  // end else
582
583         // start and end of the page
203323 584         $start_row = $this->ldap->vlv_active ? 0 : $this->result->first;
a31482 585         $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
T 586         $last_row = $this->result->first + $this->page_size;
587         $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
588
589         // filter entries for this page
590         for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
591             $this->result->add($this->_ldap2result($entries[$i]));
592
593         return $this->result;
594     }
595
596     /**
9b3311 597      * Get all members of the given group
A 598      *
3ce7c5 599      * @param string  Group DN
TB 600      * @param boolean Count only
601      * @param array   Group entries (if called recursively)
602      * @return array  Accumulated group members
a31482 603      */
b35a0f 604     function list_group_members($dn, $count = false, $entries = null)
a31482 605     {
T 606         $group_members = array();
607
608         // fetch group object
609         if (empty($entries)) {
3ce7c5 610             $attribs = array_merge(array('dn','objectClass','memberURL'), array_values($this->group_types));
1b52cf 611             $entries = $this->ldap->read_entries($dn, '(objectClass=*)', $attribs);
203323 612             if ($entries === false) {
a31482 613                 return $group_members;
T 614             }
615         }
616
203323 617         for ($i=0; $i < $entries['count']; $i++) {
a31482 618             $entry = $entries[$i];
1b52cf 619             $attrs = array();
a31482 620
203323 621             foreach ((array)$entry['objectclass'] as $objectclass) {
3ce7c5 622                 if (($member_attr = $this->get_group_member_attr(array($objectclass), ''))
1b52cf 623                     && ($member_attr = strtolower($member_attr)) && !in_array($member_attr, $attrs)
AM 624                 ) {
625                     $members       = $this->_list_group_members($dn, $entry, $member_attr, $count);
626                     $group_members = array_merge($group_members, $members);
627                     $attrs[]       = $member_attr;
3ce7c5 628                 }
TB 629                 else if (!empty($entry['memberurl'])) {
630                     $members       = $this->_list_group_memberurl($dn, $entry, $count);
631                     $group_members = array_merge($group_members, $members);
1b52cf 632                 }
AM 633
634                 if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit']) {
635                     break 2;
a31482 636                 }
T 637             }
638         }
639
640         return array_filter($group_members);
641     }
642
643     /**
644      * Fetch members of the given group entry from server
645      *
646      * @param string Group DN
647      * @param array  Group entry
648      * @param string Member attribute to use
3ce7c5 649      * @param boolean Count only
a31482 650      * @return array Accumulated group members
T 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();
1b52cf 657         if (empty($entry[$attr])) {
a31482 658             return $group_members;
1b52cf 659         }
a31482 660
b35a0f 661         // read these attributes for all members
807c3d 662         $attrib = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
3ce7c5 663         $attrib = array_merge($attrib, array_values($this->group_types));
b35a0f 664         $attrib[] = 'memberURL';
T 665
c5a5f9 666         $filter = $this->prop['groups']['member_filter'] ? $this->prop['groups']['member_filter'] : '(objectclass=*)';
TB 667
203323 668         for ($i=0; $i < $entry[$attr]['count']; $i++) {
3ed9e8 669             if (empty($entry[$attr][$i]))
T 670                 continue;
671
203323 672             $members = $this->ldap->read_entries($entry[$attr][$i], $filter, $attrib);
TB 673             if ($members == false) {
a31482 674                 $members = array();
T 675             }
676
677             // for nested groups, call recursively
b35a0f 678             $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
a31482 679
T 680             unset($members['count']);
681             $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
682         }
683
684         return $group_members;
685     }
686
687     /**
688      * List members of group class groupOfUrls
689      *
690      * @param string Group DN
691      * @param array  Group entry
b35a0f 692      * @param boolean True if only used for counting
a31482 693      * @return array Accumulated group members
T 694      */
b35a0f 695     private function _list_group_memberurl($dn, $entry, $count)
a31482 696     {
T 697         $group_members = array();
698
807c3d 699         for ($i=0; $i < $entry['memberurl']['count']; $i++) {
8fb04b 700             // extract components from url
5aa1d2 701             if (!preg_match('!ldap://[^/]*/([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m)) {
a31482 702                 continue;
5aa1d2 703             }
a31482 704
T 705             // add search filter if any
706             $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
807c3d 707             $attrs = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
203323 708             if ($result = $this->ldap->search($m[1], $filter, $m[2], $attrs, $this->group_data)) {
TB 709                 $entries = $result->entries();
ec2185 710                 for ($j = 0; $j < $entries['count']; $j++) {
4c02ef 711                     if ($this->is_group_entry($entries[$j]) && ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count)))
ec2185 712                         $group_members = array_merge($group_members, $nested_group_members);
TB 713                     else
714                         $group_members[] = $entries[$j];
715                 }
8fb04b 716             }
a97937 717         }
39cafa 718
a31482 719         return $group_members;
T 720     }
a97937 721
a31482 722     /**
T 723      * Callback for sorting entries
724      */
725     function _entry_sort_cmp($a, $b)
726     {
727         return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
a97937 728     }
T 729
730     /**
cc90ed 731      * Search contacts
A 732      *
733      * @param mixed   $fields   The field name of array of field names to search in
734      * @param mixed   $value    Search value (or array of values when $fields is array)
f21a04 735      * @param int     $mode     Matching mode:
A 736      *                          0 - partial (*abc*),
737      *                          1 - strict (=),
738      *                          2 - prefix (abc*)
cc90ed 739      * @param boolean $select   True if results are requested, False if count only
A 740      * @param boolean $nocount  (Not used)
741      * @param array   $required List of fields that cannot be empty
742      *
743      * @return array  Indexed list of contact records and 'count' value
744      */
f21a04 745     function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
a97937 746     {
f21a04 747         $mode = intval($mode);
A 748
a97937 749         // special treatment for ID-based search
203323 750         if ($fields == 'ID' || $fields == $this->primary_key) {
648674 751             $ids = !is_array($value) ? explode(',', $value) : $value;
a97937 752             $result = new rcube_result_set();
203323 753             foreach ($ids as $id) {
TB 754                 if ($rec = $this->get_record($id, true)) {
a97937 755                     $result->add($rec);
T 756                     $result->count++;
757                 }
758             }
759             return $result;
760         }
761
fc91c1 762         // use VLV pseudo-search for autocompletion
e1cfb0 763         $rcube = rcube::get_instance();
699cb1 764         $list_fields = $rcube->config->get('contactlist_fields');
baecd8 765
203323 766         if ($this->prop['vlv_search'] && $this->ready && join(',', (array)$fields) == join(',', $list_fields)) {
9b3311 767             $this->result = new rcube_result_set(0);
A 768
aafcce 769             $this->ldap->config_set('fuzzy_search', intval($this->prop['fuzzy_search'] && $mode != 1));
772b73 770             $ldap_data = $this->ldap->search($this->base_dn, $this->prop['filter'], $this->prop['scope'], $this->prop['attributes'],
aafcce 771                 array('search' => $value /*, 'sort' => $this->prop['sort'] */));
772b73 772             if ($ldap_data === false) {
6bddd9 773                 return $this->result;
A 774             }
9b3311 775
fc91c1 776             // get all entries of this page and post-filter those that really match the query
772b73 777             $search = mb_strtolower($value);
9e4246 778             foreach ($ldap_data as $entry) {
772b73 779                 $rec = $this->_ldap2result($entry);
699cb1 780                 foreach ($fields as $f) {
AM 781                     foreach ((array)$rec[$f] as $val) {
83f707 782                         if ($this->compare_search_value($f, $val, $search, $mode)) {
699cb1 783                             $this->result->add($rec);
AM 784                             $this->result->count++;
785                             break 2;
786                         }
f21a04 787                     }
fc91c1 788                 }
T 789             }
790
791             return $this->result;
792         }
793
36ee2c 794         // advanced per-attribute search
TB 795         if (is_array($value)) {
796             // use AND operator for advanced searches
797             $filter = '(&';
e9a9f2 798
36ee2c 799             // set wildcards
TB 800             $wp = $ws = '';
801             if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
802                 $ws = '*';
803                 if (!$mode) {
804                     $wp = '*';
e9a9f2 805                 }
3cacf9 806             }
36ee2c 807
e9a9f2 808             foreach ((array)$fields as $idx => $field) {
36ee2c 809                 $val = $value[$idx];
TB 810                 if (!strlen($val))
811                     continue;
1078a6 812                 if ($attrs = $this->_map_field($field)) {
TB 813                     if (count($attrs) > 1)
814                         $filter .= '(|';
815                     foreach ($attrs as $f)
4500b2 816                         $filter .= "($f=$wp" . rcube_ldap_generic::quote_string($val) . "$ws)";
1078a6 817                     if (count($attrs) > 1)
TB 818                         $filter .= ')';
e9a9f2 819                 }
A 820             }
36ee2c 821
TB 822             $filter .= ')';
a97937 823         }
36ee2c 824         else {
TB 825             if ($fields == '*') {
826                 // search_fields are required for fulltext search
827                 if (empty($this->prop['search_fields'])) {
828                     $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
829                     $this->result = new rcube_result_set();
830                     return $this->result;
831                 }
832                 $attributes = (array)$this->prop['search_fields'];
833             }
834             else {
835                 // map address book fields into ldap attributes
6cdffb 836                 $me         = $this;
36ee2c 837                 $attributes = array();
6a8c4f 838                 array_walk((array) $fields, function($field) use ($me, &$attributes) {
6cdffb 839                     if ($me->coltypes[$field] && ($attrs = (array)$me->coltypes[$field]['attributes'])) {
36ee2c 840                         $attributes = array_merge($attributes, $attrs);
TB 841                     }
842                 });
843             }
844
845             // compose a full-text-like search filter
846             $filter = rcube_ldap_generic::fulltext_search_filter($value, $attributes, $mode);
847         }
a97937 848
T 849         // add required (non empty) fields filter
850         $req_filter = '';
1078a6 851         foreach ((array)$required as $field) {
4500b2 852             if (in_array($field, (array)$fields))  // required field is already in search filter
TB 853                 continue;
1078a6 854             if ($attrs = $this->_map_field($field)) {
TB 855                 if (count($attrs) > 1)
856                     $req_filter .= '(|';
857                 foreach ($attrs as $f)
858                     $req_filter .= "($f=*)";
859                 if (count($attrs) > 1)
860                     $req_filter .= ')';
861             }
862         }
a97937 863
T 864         if (!empty($req_filter))
865             $filter = '(&' . $req_filter . $filter . ')';
866
867         // avoid double-wildcard if $value is empty
868         $filter = preg_replace('/\*+/', '*', $filter);
869
870         // add general filter to query
871         if (!empty($this->prop['filter']))
872             $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
873
874         // set filter string and execute search
875         $this->set_search_set($filter);
876
877         if ($select)
878             $this->list_records();
879         else
880             $this->result = $this->count();
881
882         return $this->result;
883     }
884
885     /**
cc90ed 886      * Count number of available contacts in database
A 887      *
888      * @return object rcube_result_set Resultset with values for 'count' and 'first'
889      */
a97937 890     function count()
T 891     {
892         $count = 0;
203323 893         if ($this->ldap_result) {
TB 894             $count = $this->ldap_result->count();
a31482 895         }
T 896         else if ($this->group_id && $this->group_data['dn']) {
b35a0f 897             $count = count($this->list_group_members($this->group_data['dn'], true));
a31482 898         }
203323 899         // We have a connection but no result set, attempt to get one.
TB 900         else if ($this->ready) {
4287c9 901             $prop    = $this->group_id ? $this->group_data : $this->prop;
AM 902             $base_dn = $this->group_id ? $this->group_base_dn : $this->base_dn;
ec2185 903
203323 904             if (!empty($this->filter)) {  // Use global search filter
TB 905                 $prop['filter'] = $this->filter;
a31482 906             }
4287c9 907             $count = $this->ldap->search($base_dn, $prop['filter'], $prop['scope'], array('dn'), $prop, true);
a31482 908         }
a97937 909
T 910         return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
911     }
912
913     /**
cc90ed 914      * Return the last result set
A 915      *
916      * @return object rcube_result_set Current resultset or NULL if nothing selected yet
917      */
a97937 918     function get_result()
T 919     {
920         return $this->result;
921     }
922
923     /**
cc90ed 924      * Get a specific contact record
A 925      *
926      * @param mixed   Record identifier
927      * @param boolean Return as associative array
928      *
929      * @return mixed  Hash array or rcube_result_set with all record fields
930      */
a97937 931     function get_record($dn, $assoc=false)
T 932     {
13db9e 933         $res = $this->result = null;
A 934
203323 935         if ($this->ready && $dn) {
c3ba0e 936             $dn = self::dn_decode($dn);
a97937 937
203323 938             if ($rec = $this->ldap->get_entry($dn)) {
TB 939                 $rec = array_change_key_case($rec, CASE_LOWER);
13db9e 940             }
a97937 941
13db9e 942             // Use ldap_list to get subentries like country (c) attribute (#1488123)
A 943             if (!empty($rec) && $this->sub_filter) {
203323 944                 if ($entries = $this->ldap->list_entries($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
13db9e 945                     foreach ($entries as $entry) {
A 946                         $lrec = array_change_key_case($entry, CASE_LOWER);
947                         $rec  = array_merge($lrec, $rec);
948                     }
949                 }
950             }
a97937 951
13db9e 952             if (!empty($rec)) {
a97937 953                 // Add in the dn for the entry.
T 954                 $rec['dn'] = $dn;
955                 $res = $this->_ldap2result($rec);
203323 956                 $this->result = new rcube_result_set(1);
a97937 957                 $this->result->add($res);
6039aa 958             }
T 959         }
a97937 960
T 961         return $assoc ? $res : $this->result;
028734 962     }
TB 963
964     /**
965      * Returns the last error occurred (e.g. when updating/inserting failed)
966      *
967      * @return array Hash array with the following fields: type, message
968      */
969     function get_error()
970     {
971         $err = $this->error;
972
973         // check ldap connection for errors
974         if (!$err && $this->ldap->get_error()) {
975             $err = array(self::ERROR_SEARCH, $this->ldap->get_error());
976         }
977
978         return $err;
f11541 979     }
T 980
a97937 981     /**
e84818 982      * Check the given data before saving.
T 983      * If input not valid, the message to display can be fetched using get_error()
984      *
985      * @param array Assoziative array with data to save
39cafa 986      * @param boolean Try to fix/complete record automatically
e84818 987      * @return boolean True if input is valid, False if not.
T 988      */
39cafa 989     public function validate(&$save_data, $autofix = false)
e84818 990     {
19fccd 991         // validate e-mail addresses
A 992         if (!parent::validate($save_data, $autofix)) {
993             return false;
994         }
995
e84818 996         // check for name input
T 997         if (empty($save_data['name'])) {
39cafa 998             $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
T 999             return false;
1000         }
1001
1002         // Verify that the required fields are set.
1003         $missing = null;
1004         $ldap_data = $this->_map_data($save_data);
1005         foreach ($this->prop['required_fields'] as $fld) {
19fccd 1006             if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
39cafa 1007                 $missing[$fld] = 1;
T 1008             }
1009         }
1010
1011         if ($missing) {
1012             // try to complete record automatically
1013             if ($autofix) {
19fccd 1014                 $sn_field    = $this->fieldmap['surname'];
A 1015                 $fn_field    = $this->fieldmap['firstname'];
9336ba 1016                 $mail_field  = $this->fieldmap['email'];
A 1017
1018                 // try to extract surname and firstname from displayname
1019                 $name_parts  = preg_split('/[\s,.]+/', $save_data['name']);
19fccd 1020
A 1021                 if ($sn_field && $missing[$sn_field]) {
1022                     $save_data['surname'] = array_pop($name_parts);
1023                     unset($missing[$sn_field]);
39cafa 1024                 }
T 1025
19fccd 1026                 if ($fn_field && $missing[$fn_field]) {
A 1027                     $save_data['firstname'] = array_shift($name_parts);
1028                     unset($missing[$fn_field]);
1029                 }
9336ba 1030
A 1031                 // try to fix missing e-mail, very often on import
1032                 // from vCard we have email:other only defined
1033                 if ($mail_field && $missing[$mail_field]) {
1034                     $emails = $this->get_col_values('email', $save_data, true);
1035                     if (!empty($emails) && ($email = array_shift($emails))) {
1036                         $save_data['email'] = $email;
1037                         unset($missing[$mail_field]);
1038                     }
1039                 }
39cafa 1040             }
T 1041
1042             // TODO: generate message saying which fields are missing
19fccd 1043             if (!empty($missing)) {
A 1044                 $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
1045                 return false;
1046             }
e84818 1047         }
cc90ed 1048
19fccd 1049         return true;
e84818 1050     }
T 1051
1052     /**
cc90ed 1053      * Create a new contact record
A 1054      *
1055      * @param array    Hash array with save data
1056      *
1057      * @return encoded record ID on success, False on error
1058      */
a97937 1059     function insert($save_cols)
f11541 1060     {
a97937 1061         // Map out the column names to their LDAP ones to build the new entry.
39cafa 1062         $newentry = $this->_map_data($save_cols);
a97937 1063         $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
T 1064
3f250a 1065         // add automatically generated attributes
TB 1066         $this->add_autovalues($newentry);
1067
a97937 1068         // Verify that the required fields are set.
6f45fa 1069         $missing = null;
a97937 1070         foreach ($this->prop['required_fields'] as $fld) {
T 1071             if (!isset($newentry[$fld])) {
1072                 $missing[] = $fld;
1073             }
1074         }
1075
1076         // abort process if requiered fields are missing
1077         // TODO: generate message saying which fields are missing
1078         if ($missing) {
39cafa 1079             $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
a97937 1080             return false;
T 1081         }
1082
1083         // Build the new entries DN.
4500b2 1084         $dn = $this->prop['LDAP_rdn'].'='.rcube_ldap_generic::quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
a97937 1085
13db9e 1086         // Remove attributes that need to be added separately (child objects)
A 1087         $xfields = array();
1088         if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
3725cf 1089             foreach (array_keys($this->prop['sub_fields']) as $xf) {
13db9e 1090                 if (!empty($newentry[$xf])) {
A 1091                     $xfields[$xf] = $newentry[$xf];
1092                     unset($newentry[$xf]);
1093                 }
1094             }
1095         }
a97937 1096
6ac939 1097         if (!$this->ldap->add_entry($dn, $newentry)) {
a97937 1098             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1099             return false;
13db9e 1100         }
4f9c83 1101
13db9e 1102         foreach ($xfields as $xidx => $xf) {
4500b2 1103             $xdn = $xidx.'='.rcube_ldap_generic::quote_string($xf).','.$dn;
13db9e 1104             $xf = array(
A 1105                 $xidx => $xf,
1106                 'objectClass' => (array) $this->prop['sub_fields'][$xidx],
1107             );
1108
6ac939 1109             $this->ldap->add_entry($xdn, $xf);
13db9e 1110         }
4f9c83 1111
c3ba0e 1112         $dn = self::dn_encode($dn);
A 1113
a97937 1114         // add new contact to the selected group
5d692b 1115         if ($this->group_id)
c3ba0e 1116             $this->add_to_group($this->group_id, $dn);
4f9c83 1117
c3ba0e 1118         return $dn;
e83f03 1119     }
4f9c83 1120
a97937 1121     /**
cc90ed 1122      * Update a specific contact record
A 1123      *
1124      * @param mixed Record identifier
1125      * @param array Hash array with save data
1126      *
1127      * @return boolean True on success, False on error
1128      */
a97937 1129     function update($id, $save_cols)
f11541 1130     {
a97937 1131         $record = $this->get_record($id, true);
4aaecb 1132
13db9e 1133         $newdata     = array();
a97937 1134         $replacedata = array();
13db9e 1135         $deletedata  = array();
A 1136         $subdata     = array();
1137         $subdeldata  = array();
1138         $subnewdata  = array();
c3ba0e 1139
d6aafd 1140         $ldap_data = $this->_map_data($save_cols);
13db9e 1141         $old_data  = $record['_raw_attrib'];
1803f8 1142
21a0d9 1143         // special handling of photo col
A 1144         if ($photo_fld = $this->fieldmap['photo']) {
1145             // undefined means keep old photo
1146             if (!array_key_exists('photo', $save_cols)) {
1147                 $ldap_data[$photo_fld] = $record['photo'];
1148             }
1149         }
1150
3725cf 1151         foreach ($this->fieldmap as $fld) {
a97937 1152             if ($fld) {
13db9e 1153                 $val = $ldap_data[$fld];
A 1154                 $old = $old_data[$fld];
a97937 1155                 // remove empty array values
T 1156                 if (is_array($val))
1157                     $val = array_filter($val);
13db9e 1158                 // $this->_map_data() result and _raw_attrib use different format
A 1159                 // make sure comparing array with one element with a string works as expected
1160                 if (is_array($old) && count($old) == 1 && !is_array($val)) {
1161                     $old = array_pop($old);
21a0d9 1162                 }
A 1163                 if (is_array($val) && count($val) == 1 && !is_array($old)) {
1164                     $val = array_pop($val);
13db9e 1165                 }
A 1166                 // Subentries must be handled separately
1167                 if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
1168                     if ($old != $val) {
1169                         if ($old !== null) {
1170                             $subdeldata[$fld] = $old;
1171                         }
1172                         if ($val) {
1173                             $subnewdata[$fld] = $val;
1174                         }
1175                     }
1176                     else if ($old !== null) {
1177                         $subdata[$fld] = $old;
1178                     }
1179                     continue;
1180                 }
21a0d9 1181
a97937 1182                 // The field does exist compare it to the ldap record.
13db9e 1183                 if ($old != $val) {
a97937 1184                     // Changed, but find out how.
13db9e 1185                     if ($old === null) {
a97937 1186                         // Field was not set prior, need to add it.
T 1187                         $newdata[$fld] = $val;
1803f8 1188                     }
T 1189                     else if ($val == '') {
a97937 1190                         // Field supplied is empty, verify that it is not required.
T 1191                         if (!in_array($fld, $this->prop['required_fields'])) {
afaccf 1192                             // ...It is not, safe to clear.
AM 1193                             // #1488420: Workaround "ldap_mod_del(): Modify: Inappropriate matching in..."
1194                             // jpegPhoto attribute require an array() here. It looks to me that it works for other attribs too
1195                             $deletedata[$fld] = array();
1196                             //$deletedata[$fld] = $old_data[$fld];
1803f8 1197                         }
13db9e 1198                     }
a97937 1199                     else {
T 1200                         // The data was modified, save it out.
1201                         $replacedata[$fld] = $val;
1803f8 1202                     }
a97937 1203                 } // end if
T 1204             } // end if
1205         } // end foreach
a605b2 1206
T 1207         // console($old_data, $ldap_data, '----', $newdata, $replacedata, $deletedata, '----', $subdata, $subnewdata, $subdeldata);
1208
c3ba0e 1209         $dn = self::dn_decode($id);
a97937 1210
T 1211         // Update the entry as required.
1212         if (!empty($deletedata)) {
1213             // Delete the fields.
203323 1214             if (!$this->ldap->mod_del($dn, $deletedata)) {
a97937 1215                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1216                 return false;
1217             }
1218         } // end if
1219
1220         if (!empty($replacedata)) {
1221             // Handle RDN change
1222             if ($replacedata[$this->prop['LDAP_rdn']]) {
1223                 $newdn = $this->prop['LDAP_rdn'].'='
4500b2 1224                     .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true)
d1e08f 1225                     .','.$this->base_dn;
a97937 1226                 if ($dn != $newdn) {
T 1227                     $newrdn = $this->prop['LDAP_rdn'].'='
4500b2 1228                     .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true);
a97937 1229                     unset($replacedata[$this->prop['LDAP_rdn']]);
T 1230                 }
1231             }
1232             // Replace the fields.
1233             if (!empty($replacedata)) {
203323 1234                 if (!$this->ldap->mod_replace($dn, $replacedata)) {
13db9e 1235                     $this->set_error(self::ERROR_SAVING, 'errorsaving');
a97937 1236                     return false;
T 1237                 }
13db9e 1238             }
a97937 1239         } // end if
13db9e 1240
A 1241         // RDN change, we need to remove all sub-entries
1242         if (!empty($newrdn)) {
1243             $subdeldata = array_merge($subdeldata, $subdata);
1244             $subnewdata = array_merge($subnewdata, $subdata);
1245         }
1246
1247         // remove sub-entries
1248         if (!empty($subdeldata)) {
1249             foreach ($subdeldata as $fld => $val) {
4500b2 1250                 $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
6ac939 1251                 if (!$this->ldap->delete_entry($subdn)) {
13db9e 1252                     return false;
A 1253                 }
1254             }
1255         }
a97937 1256
T 1257         if (!empty($newdata)) {
1258             // Add the fields.
203323 1259             if (!$this->ldap->mod_add($dn, $newdata)) {
a97937 1260                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1261                 return false;
1262             }
1263         } // end if
1264
1265         // Handle RDN change
1266         if (!empty($newrdn)) {
203323 1267             if (!$this->ldap->rename($dn, $newrdn, null, true)) {
13db9e 1268                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
a97937 1269                 return false;
T 1270             }
1271
c3ba0e 1272             $dn    = self::dn_encode($dn);
A 1273             $newdn = self::dn_encode($newdn);
1274
a97937 1275             // change the group membership of the contact
13db9e 1276             if ($this->groups) {
c3ba0e 1277                 $group_ids = $this->get_record_groups($dn);
42b9ce 1278                 foreach (array_keys($group_ids) as $group_id) {
c3ba0e 1279                     $this->remove_from_group($group_id, $dn);
A 1280                     $this->add_to_group($group_id, $newdn);
a97937 1281                 }
T 1282             }
c3ba0e 1283
13db9e 1284             $dn = self::dn_decode($newdn);
a97937 1285         }
T 1286
13db9e 1287         // add sub-entries
A 1288         if (!empty($subnewdata)) {
1289             foreach ($subnewdata as $fld => $val) {
4500b2 1290                 $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
13db9e 1291                 $xf = array(
A 1292                     $fld => $val,
1293                     'objectClass' => (array) $this->prop['sub_fields'][$fld],
1294                 );
6ac939 1295                 $this->ldap->add_entry($subdn, $xf);
13db9e 1296             }
A 1297         }
1298
1299         return $newdn ? $newdn : true;
f11541 1300     }
a97937 1301
T 1302     /**
cc90ed 1303      * Mark one or more contact records as deleted
A 1304      *
63fda8 1305      * @param array   Record identifiers
A 1306      * @param boolean Remove record(s) irreversible (unsupported)
cc90ed 1307      *
A 1308      * @return boolean True on success, False on error
1309      */
63fda8 1310     function delete($ids, $force=true)
f11541 1311     {
a97937 1312         if (!is_array($ids)) {
T 1313             // Not an array, break apart the encoded DNs.
0f1fae 1314             $ids = explode(',', $ids);
a97937 1315         } // end if
T 1316
0f1fae 1317         foreach ($ids as $id) {
c3ba0e 1318             $dn = self::dn_decode($id);
13db9e 1319
A 1320             // Need to delete all sub-entries first
1321             if ($this->sub_filter) {
203323 1322                 if ($entries = $this->ldap->list_entries($dn, $this->sub_filter)) {
13db9e 1323                     foreach ($entries as $entry) {
6ac939 1324                         if (!$this->ldap->delete_entry($entry['dn'])) {
13db9e 1325                             $this->set_error(self::ERROR_SAVING, 'errorsaving');
A 1326                             return false;
1327                         }
1328                     }
1329                 }
1330             }
1331
a97937 1332             // Delete the record.
6ac939 1333             if (!$this->ldap->delete_entry($dn)) {
a97937 1334                 $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1335                 return false;
13db9e 1336             }
a97937 1337
6ac939 1338             // remove contact from all groups where he was a member
c3ba0e 1339             if ($this->groups) {
A 1340                 $dn = self::dn_encode($dn);
1341                 $group_ids = $this->get_record_groups($dn);
42b9ce 1342                 foreach (array_keys($group_ids) as $group_id) {
c3ba0e 1343                     $this->remove_from_group($group_id, $dn);
a97937 1344                 }
T 1345             }
1346         } // end foreach
1347
0f1fae 1348         return count($ids);
d6eb7c 1349     }
A 1350
1351     /**
1352      * Remove all contact records
18b40c 1353      *
AM 1354      * @param bool $with_groups Delete also groups if enabled
d6eb7c 1355      */
18b40c 1356     function delete_all($with_groups = false)
d6eb7c 1357     {
203323 1358         // searching for contact entries
TB 1359         $dn_list = $this->ldap->list_entries($this->base_dn, $this->prop['filter'] ? $this->prop['filter'] : '(objectclass=*)');
d6eb7c 1360
A 1361         if (!empty($dn_list)) {
1362             foreach ($dn_list as $idx => $entry) {
1363                 $dn_list[$idx] = self::dn_encode($entry['dn']);
1364             }
1365             $this->delete($dn_list);
1366         }
18b40c 1367
AM 1368         if ($with_groups && $this->groups && ($groups = $this->_fetch_groups()) && count($groups)) {
1369             foreach ($groups as $group) {
6ac939 1370                 $this->ldap->delete_entry($group['dn']);
18b40c 1371             }
AM 1372
1373             if ($this->cache) {
1374                 $this->cache->remove('groups');
1375             }
1376         }
f11541 1377     }
4368a0 1378
3f250a 1379     /**
TB 1380      * Generate missing attributes as configured
1381      *
1382      * @param array LDAP record attributes
1383      */
1384     protected function add_autovalues(&$attrs)
1385     {
4741d1 1386         if (empty($this->prop['autovalues'])) {
AM 1387             return;
1388         }
1389
3f250a 1390         $attrvals = array();
TB 1391         foreach ($attrs as $k => $v) {
1392             $attrvals['{'.$k.'}'] = is_array($v) ? $v[0] : $v;
1393         }
1394
1395         foreach ((array)$this->prop['autovalues'] as $lf => $templ) {
1396             if (empty($attrs[$lf])) {
c2e1ab 1397                 if (strpos($templ, '(') !== false) {
TB 1398                     // replace {attr} placeholders with (escaped!) attribute values to be safely eval'd
1399                     $code = preg_replace('/\{\w+\}/', '', strtr($templ, array_map('addslashes', $attrvals)));
4741d1 1400                     $fn   = create_function('', "return ($code);");
AM 1401                     if (!$fn) {
1402                         rcube::raise_error(array(
1403                             'code' => 505, 'type' => 'php',
1404                             'file' => __FILE__, 'line' => __LINE__,
1405                             'message' => "Expression parse error on: ($code)"), true, false);
1406                         continue;
1407                     }
1408
1409                     $attrs[$lf] = $fn();
c2e1ab 1410                 }
TB 1411                 else {
1412                     // replace {attr} placeholders with concrete attribute values
1413                     $attrs[$lf] = preg_replace('/\{\w+\}/', '', strtr($templ, $attrvals));
1414                 }
3f250a 1415             }
TB 1416         }
1417     }
4368a0 1418
a97937 1419     /**
cc90ed 1420      * Converts LDAP entry into an array
A 1421      */
a97937 1422     private function _ldap2result($rec)
T 1423     {
c5a5f9 1424         $out = array('_type' => 'person');
ec2185 1425         $fieldmap = $this->fieldmap;
a97937 1426
T 1427         if ($rec['dn'])
c3ba0e 1428             $out[$this->primary_key] = self::dn_encode($rec['dn']);
a97937 1429
c5a5f9 1430         // determine record type
4c02ef 1431         if ($this->is_group_entry($rec)) {
c5a5f9 1432             $out['_type'] = 'group';
TB 1433             $out['readonly'] = true;
8862f6 1434             $fieldmap['name'] = $this->group_data['name_attr'] ? $this->group_data['name_attr'] : $this->prop['groups']['name_attr'];
c5a5f9 1435         }
a97937 1436
532c10 1437         // assign object type from object class mapping
TB 1438         if (!empty($this->prop['class_type_map'])) {
1439             foreach (array_map('strtolower', (array)$rec['objectclass']) as $objcls) {
1440                 if (!empty($this->prop['class_type_map'][$objcls])) {
1441                     $out['_type'] = $this->prop['class_type_map'][$objcls];
1442                     break;
1443                 }
1444             }
1445         }
1446
ec2185 1447         foreach ($fieldmap as $rf => $lf)
a97937 1448         {
T 1449             for ($i=0; $i < $rec[$lf]['count']; $i++) {
1450                 if (!($value = $rec[$lf][$i]))
1451                     continue;
1803f8 1452
ad8c9d 1453                 list($col, $subtype) = explode(':', $rf);
1803f8 1454                 $out['_raw_attrib'][$lf][$i] = $value;
T 1455
1078a6 1456                 if ($col == 'email' && $this->mail_domain && !strpos($value, '@'))
a97937 1457                     $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
ad8c9d 1458                 else if (in_array($col, array('street','zipcode','locality','country','region')))
T 1459                     $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
a605b2 1460                 else if ($col == 'address' && strpos($value, '$') !== false)  // address data is represented as string separated with $
T 1461                     list($out[$rf][$i]['street'], $out[$rf][$i]['locality'], $out[$rf][$i]['zipcode'], $out[$rf][$i]['country']) = explode('$', $value);
a97937 1462                 else if ($rec[$lf]['count'] > 1)
T 1463                     $out[$rf][] = $value;
1464                 else
1465                     $out[$rf] = $value;
1466             }
b1f084 1467
A 1468             // Make sure name fields aren't arrays (#1488108)
1469             if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
1803f8 1470                 $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
b1f084 1471             }
a97937 1472         }
T 1473
1474         return $out;
1475     }
1476
1477     /**
1078a6 1478      * Return LDAP attribute(s) for the given field
cc90ed 1479      */
a97937 1480     private function _map_field($field)
T 1481     {
1078a6 1482         return (array)$this->coltypes[$field]['attributes'];
a97937 1483     }
T 1484
1485     /**
39cafa 1486      * Convert a record data set into LDAP field attributes
T 1487      */
1488     private function _map_data($save_cols)
1489     {
d6aafd 1490         // flatten composite fields first
T 1491         foreach ($this->coltypes as $col => $colprop) {
1492             if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
1493                 foreach ($values as $subtype => $childs) {
1494                     $subtype = $subtype ? ':'.$subtype : '';
1495                     foreach ($childs as $i => $child_values) {
1496                         foreach ((array)$child_values as $childcol => $value) {
1497                             $save_cols[$childcol.$subtype][$i] = $value;
1498                         }
1499                     }
1500                 }
1501             }
a605b2 1502
T 1503             // if addresses are to be saved as serialized string, do so
1504             if (is_array($colprop['serialized'])) {
1505                foreach ($colprop['serialized'] as $subtype => $delim) {
1506                   $key = $col.':'.$subtype;
49cb69 1507                   foreach ((array)$save_cols[$key] as $i => $val) {
TB 1508                      $values = array($val['street'], $val['locality'], $val['zipcode'], $val['country']);
1509                      $save_cols[$key][$i] = count(array_filter($values)) ? join($delim, $values) : null;
1510                  }
a605b2 1511                }
T 1512             }
d6aafd 1513         }
T 1514
39cafa 1515         $ldap_data = array();
1078a6 1516         foreach ($this->fieldmap as $rf => $fld) {
TB 1517             $val = $save_cols[$rf];
1518
1519             // check for value in base field (eg.g email instead of email:foo)
1520             list($col, $subtype) = explode(':', $rf);
1521             if (!$val && !empty($save_cols[$col])) {
1522                 $val = $save_cols[$col];
1523                 unset($save_cols[$col]);  // only use this value once
1524             }
1525             else if (!$val && !$subtype) { // extract values from subtype cols
1526                 $val = $this->get_col_values($col, $save_cols, true);
1527             }
1528
39cafa 1529             if (is_array($val))
T 1530                 $val = array_filter($val);  // remove empty entries
1531             if ($fld && $val) {
1532                 // The field does exist, add it to the entry.
1533                 $ldap_data[$fld] = $val;
1534             }
1535         }
13db9e 1536
39cafa 1537         return $ldap_data;
T 1538     }
1539
1540     /**
cc90ed 1541      * Returns unified attribute name (resolving aliases)
A 1542      */
a605b2 1543     private static function _attr_name($namev)
a97937 1544     {
T 1545         // list of known attribute aliases
a605b2 1546         static $aliases = array(
3e7b9b 1547             'gn'            => 'givenname',
a97937 1548             'rfc822mailbox' => 'email',
3e7b9b 1549             'userid'        => 'uid',
AM 1550             'emailaddress'  => 'email',
1551             'pkcs9email'    => 'email',
a97937 1552         );
a605b2 1553
T 1554         list($name, $limit) = explode(':', $namev, 2);
1555         $suffix = $limit ? ':'.$limit : '';
1556
1557         return (isset($aliases[$name]) ? $aliases[$name] : $name) . $suffix;
a97937 1558     }
T 1559
f924f5 1560     /**
TB 1561      * Determines whether the given LDAP entry is a group record
1562      */
4c02ef 1563     private function is_group_entry($entry)
f924f5 1564     {
3e7b9b 1565         $classes = array_map('strtolower', (array)$entry['objectclass']);
AM 1566
3ce7c5 1567         return count(array_intersect(array_keys($this->group_types), $classes)) > 0;
f924f5 1568     }
a97937 1569
T 1570     /**
06744d 1571      * Activate/deactivate debug mode
T 1572      *
1573      * @param boolean $dbg True if LDAP commands should be logged
1574      */
1575     function set_debug($dbg = true)
1576     {
1577         $this->debug = $dbg;
fae90d 1578
AM 1579         if ($this->ldap) {
6ac939 1580             $this->ldap->config_set('debug', $dbg);
fae90d 1581         }
06744d 1582     }
T 1583
1584     /**
6039aa 1585      * Setter for the current group
T 1586      */
1587     function set_group($group_id)
1588     {
ec2185 1589         if ($group_id) {
6039aa 1590             $this->group_id = $group_id;
ec2185 1591             $this->group_data = $this->get_group_entry($group_id);
6039aa 1592         }
ec2185 1593         else {
a97937 1594             $this->group_id = 0;
a31482 1595             $this->group_data = null;
8fb04b 1596         }
6039aa 1597     }
T 1598
1599     /**
1600      * List all active contact groups of this source
1601      *
1602      * @param string  Optional search string to match group name
ec4331 1603      * @param int     Matching mode:
AM 1604      *                0 - partial (*abc*),
1605      *                1 - strict (=),
1606      *                2 - prefix (abc*)
1607      *
6039aa 1608      * @return array  Indexed list of contact groups, each a hash array
T 1609      */
ec4331 1610     function list_groups($search = null, $mode = 0)
6039aa 1611     {
4feb8e 1612         if (!$this->groups) {
a97937 1613             return array();
b20025 1614         }
a31482 1615
834fb6 1616         $group_cache = $this->_fetch_groups($search, $mode);
4feb8e 1617         $groups      = array();
AM 1618
a31482 1619         if ($search) {
T 1620             foreach ($group_cache as $group) {
028734 1621                 if ($this->compare_search_value('name', $group['name'], mb_strtolower($search), $mode)) {
a31482 1622                     $groups[] = $group;
ec4331 1623                 }
a31482 1624             }
T 1625         }
4feb8e 1626         else {
a31482 1627             $groups = $group_cache;
4feb8e 1628         }
a31482 1629
T 1630         return array_values($groups);
1631     }
1632
1633     /**
1634      * Fetch groups from server
1635      */
834fb6 1636     private function _fetch_groups($search = null, $mode = 0, $vlv_page = null)
a31482 1637     {
834fb6 1638         // reset group search cache
TB 1639         if ($search !== null && $vlv_page === null) {
1640             $this->group_search_cache = null;
1641         }
1642         // return in-memory cache from previous search results
1643         else if (is_array($this->group_search_cache) && $vlv_page === null) {
1644             return $this->group_search_cache;
1645         }
1646
ec2185 1647         // special case: list groups from 'group_filters' config
834fb6 1648         if ($vlv_page === null && $search === null && is_array($this->prop['group_filters'])) {
ec2185 1649             $groups = array();
6b2b2e 1650             $rcube  = rcube::get_instance();
ec2185 1651
TB 1652             // list regular groups configuration as special filter
1653             if (!empty($this->prop['groups']['filter'])) {
1654                 $id = '__groups__';
6b2b2e 1655                 $groups[$id] = array('ID' => $id, 'name' => $rcube->gettext('groups'), 'virtual' => true) + $this->prop['groups'];
ec2185 1656             }
TB 1657
1658             foreach ($this->prop['group_filters'] as $id => $prop) {
203323 1659                 $groups[$id] = $prop + array('ID' => $id, 'name' => ucfirst($id), 'virtual' => true, 'base_dn' => $this->base_dn);
ec2185 1660             }
TB 1661
1662             return $groups;
1663         }
1664
834fb6 1665         if ($this->cache && $search === null && $vlv_page === null && ($groups = $this->cache->get('groups')) !== null) {
4feb8e 1666             return $groups;
AM 1667         }
1668
1669         $base_dn    = $this->groups_base_dn;
1670         $filter     = $this->prop['groups']['filter'];
4287c9 1671         $scope      = $this->prop['groups']['scope'];
4feb8e 1672         $name_attr  = $this->prop['groups']['name_attr'];
a31482 1673         $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
fb6cc8 1674         $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
4feb8e 1675         $sort_attr  = $sort_attrs[0];
6039aa 1676
203323 1677         $ldap = $this->ldap;
755189 1678
fb6cc8 1679         // use vlv to list groups
T 1680         if ($this->prop['groups']['vlv']) {
1681             $page_size = 200;
4feb8e 1682             if (!$this->prop['groups']['sort']) {
fb6cc8 1683                 $this->prop['groups']['sort'] = $sort_attrs;
4feb8e 1684             }
203323 1685
TB 1686             $ldap = clone $this->ldap;
6ac939 1687             $ldap->config_set($this->prop['groups']);
203323 1688             $ldap->set_vlv_page($vlv_page+1, $page_size);
fb6cc8 1689         }
T 1690
834fb6 1691         $props = array('sort' => $this->prop['groups']['sort']);
TB 1692         $attrs = array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr));
1693
1694         // add search filter
1695         if ($search !== null) {
1696             // set wildcards
1697             $wp = $ws = '';
1698             if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
1699                 $ws = '*';
1700                 $wp = !$mode ? '*' : '';
1701             }
1702             $filter = "(&$filter($name_attr=$wp" . rcube_ldap_generic::quote_string($search) . "$ws))";
1703             $props['search'] = $wp . $search . $ws;
1704         }
1705
1706         $ldap_data = $ldap->search($base_dn, $filter, $scope, $attrs, $props);
4feb8e 1707
203323 1708         if ($ldap_data === false) {
6039aa 1709             return array();
T 1710         }
755189 1711
4feb8e 1712         $groups          = array();
6039aa 1713         $group_sortnames = array();
4feb8e 1714         $group_count     = $ldap_data->count();
AM 1715
203323 1716         foreach ($ldap_data as $entry) {
TB 1717             if (!$entry['dn'])  // DN is mandatory
1718                 $entry['dn'] = $ldap_data->get_dn();
1719
1720             $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
1721             $group_id = self::dn_encode($entry['dn']);
a31482 1722             $groups[$group_id]['ID'] = $group_id;
203323 1723             $groups[$group_id]['dn'] = $entry['dn'];
a31482 1724             $groups[$group_id]['name'] = $group_name;
203323 1725             $groups[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
a31482 1726
T 1727             // list email attributes of a group
203323 1728             for ($j=0; $entry[$email_attr] && $j < $entry[$email_attr]['count']; $j++) {
TB 1729                 if (strpos($entry[$email_attr][$j], '@') > 0)
1730                     $groups[$group_id]['email'][] = $entry[$email_attr][$j];
a31482 1731             }
T 1732
203323 1733             $group_sortnames[] = mb_strtolower($entry[$sort_attr][0]);
6039aa 1734         }
fb6cc8 1735
T 1736         // recursive call can exit here
4feb8e 1737         if ($vlv_page > 0) {
fb6cc8 1738             return $groups;
4feb8e 1739         }
fb6cc8 1740
T 1741         // call recursively until we have fetched all groups
203323 1742         while ($this->prop['groups']['vlv'] && $group_count == $page_size) {
834fb6 1743             $next_page   = $this->_fetch_groups($search, $mode, ++$vlv_page);
4feb8e 1744             $groups      = array_merge($groups, $next_page);
fb6cc8 1745             $group_count = count($next_page);
T 1746         }
1747
1748         // when using VLV the list of groups is already sorted
4feb8e 1749         if (!$this->prop['groups']['vlv']) {
fb6cc8 1750             array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
4feb8e 1751         }
8fb04b 1752
T 1753         // cache this
834fb6 1754         if ($this->cache && $search === null) {
b20025 1755             $this->cache->set('groups', $groups);
AM 1756         }
834fb6 1757         else if ($search !== null) {
TB 1758             $this->group_search_cache = $groups;
1759         }
a97937 1760
6039aa 1761         return $groups;
a31482 1762     }
T 1763
1764     /**
ec2185 1765      * Fetch a group entry from LDAP and save in local cache
TB 1766      */
1767     private function get_group_entry($group_id)
1768     {
4feb8e 1769         $group_cache = $this->_fetch_groups();
ec2185 1770
TB 1771         // add group record to cache if it isn't yet there
1772         if (!isset($group_cache[$group_id])) {
1773             $name_attr = $this->prop['groups']['name_attr'];
1774             $dn = self::dn_decode($group_id);
1775
203323 1776             if ($list = $this->ldap->read_entries($dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL',$name_attr,$this->fieldmap['email']))) {
ec2185 1777                 $entry = $list[0];
TB 1778                 $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
1779                 $group_cache[$group_id]['ID'] = $group_id;
1780                 $group_cache[$group_id]['dn'] = $dn;
1781                 $group_cache[$group_id]['name'] = $group_name;
1782                 $group_cache[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
1783             }
1784             else {
1785                 $group_cache[$group_id] = false;
1786             }
1787
b20025 1788             if ($this->cache) {
AM 1789                 $this->cache->set('groups', $group_cache);
1790             }
ec2185 1791         }
TB 1792
1793         return $group_cache[$group_id];
a31482 1794     }
T 1795
1796     /**
1797      * Get group properties such as name and email address(es)
1798      *
1799      * @param string Group identifier
1800      * @return array Group properties as hash array
1801      */
1802     function get_group($group_id)
1803     {
86552f 1804         $group_data = $this->get_group_entry($group_id);
a31482 1805         unset($group_data['dn'], $group_data['member_attr']);
T 1806
1807         return $group_data;
6039aa 1808     }
T 1809
1810     /**
1811      * Create a contact group with the given name
1812      *
1813      * @param string The group name
1814      * @return mixed False on error, array with record props in success
1815      */
1816     function create_group($group_name)
1817     {
4feb8e 1818         $new_dn      = 'cn=' . rcube_ldap_generic::quote_string($group_name, true) . ',' . $this->groups_base_dn;
AM 1819         $new_gid     = self::dn_encode($new_dn);
097dbc 1820         $member_attr = $this->get_group_member_attr();
4feb8e 1821         $name_attr   = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
AM 1822         $new_entry   = array(
d1e08f 1823             'objectClass' => $this->prop['groups']['object_classes'],
448f81 1824             $name_attr => $group_name,
b4b377 1825             $member_attr => '',
6039aa 1826         );
T 1827
6ac939 1828         if (!$this->ldap->add_entry($new_dn, $new_entry)) {
6039aa 1829             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1830             return false;
1831         }
755189 1832
b20025 1833         if ($this->cache) {
AM 1834             $this->cache->remove('groups');
1835         }
755189 1836
6039aa 1837         return array('id' => $new_gid, 'name' => $group_name);
T 1838     }
1839
1840     /**
1841      * Delete the given group and all linked group members
1842      *
1843      * @param string Group identifier
1844      * @return boolean True on success, false if no data was changed
1845      */
1846     function delete_group($group_id)
1847     {
4feb8e 1848         $group_cache = $this->_fetch_groups();
AM 1849         $del_dn      = $group_cache[$group_id]['dn'];
755189 1850
6ac939 1851         if (!$this->ldap->delete_entry($del_dn)) {
6039aa 1852             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1853             return false;
1854         }
755189 1855
b20025 1856         if ($this->cache) {
AM 1857             unset($group_cache[$group_id]);
1858             $this->cache->set('groups', $group_cache);
1859         }
755189 1860
6039aa 1861         return true;
T 1862     }
1863
1864     /**
1865      * Rename a specific contact group
1866      *
1867      * @param string Group identifier
1868      * @param string New name to set for this group
360bd3 1869      * @param string New group identifier (if changed, otherwise don't set)
6039aa 1870      * @return boolean New name on success, false if no data was changed
T 1871      */
15e944 1872     function rename_group($group_id, $new_name, &$new_gid)
6039aa 1873     {
4feb8e 1874         $group_cache = $this->_fetch_groups();
AM 1875         $old_dn      = $group_cache[$group_id]['dn'];
1876         $new_rdn     = "cn=" . rcube_ldap_generic::quote_string($new_name, true);
1877         $new_gid     = self::dn_encode($new_rdn . ',' . $this->groups_base_dn);
6039aa 1878
203323 1879         if (!$this->ldap->rename($old_dn, $new_rdn, null, true)) {
6039aa 1880             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1881             return false;
1882         }
755189 1883
b20025 1884         if ($this->cache) {
AM 1885             $this->cache->remove('groups');
1886         }
755189 1887
6039aa 1888         return $new_name;
T 1889     }
1890
1891     /**
1892      * Add the given contact records the a certain group
1893      *
40d419 1894      * @param string       Group identifier
AM 1895      * @param array|string List of contact identifiers to be added
1896      *
1897      * @return int Number of contacts added
6039aa 1898      */
T 1899     function add_to_group($group_id, $contact_ids)
1900     {
4feb8e 1901         $group_cache = $this->_fetch_groups();
8fb04b 1902         $member_attr = $group_cache[$group_id]['member_attr'];
c8a714 1903         $group_dn    = $group_cache[$group_id]['dn'];
40d419 1904         $new_attrs   = array();
6039aa 1905
4feb8e 1906         if (!is_array($contact_ids)) {
AM 1907             $contact_ids = explode(',', $contact_ids);
1908         }
1909
1910         foreach ($contact_ids as $id) {
f763fb 1911             $new_attrs[$member_attr][] = self::dn_decode($id);
4feb8e 1912         }
6039aa 1913
203323 1914         if (!$this->ldap->mod_add($group_dn, $new_attrs)) {
6039aa 1915             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1916             return 0;
1917         }
755189 1918
b20025 1919         if ($this->cache) {
AM 1920             $this->cache->remove('groups');
1921         }
755189 1922
40d419 1923         return count($new_attrs[$member_attr]);
6039aa 1924     }
T 1925
1926     /**
1927      * Remove the given contact records from a certain group
1928      *
40d419 1929      * @param string       Group identifier
AM 1930      * @param array|string List of contact identifiers to be removed
1931      *
1932      * @return int Number of deleted group members
6039aa 1933      */
T 1934     function remove_from_group($group_id, $contact_ids)
1935     {
4feb8e 1936         $group_cache = $this->_fetch_groups();
8fb04b 1937         $member_attr = $group_cache[$group_id]['member_attr'];
c8a714 1938         $group_dn    = $group_cache[$group_id]['dn'];
4feb8e 1939         $del_attrs   = array();
6039aa 1940
4feb8e 1941         if (!is_array($contact_ids)) {
AM 1942             $contact_ids = explode(',', $contact_ids);
1943         }
1944
1945         foreach ($contact_ids as $id) {
f763fb 1946             $del_attrs[$member_attr][] = self::dn_decode($id);
4feb8e 1947         }
6039aa 1948
203323 1949         if (!$this->ldap->mod_del($group_dn, $del_attrs)) {
6039aa 1950             $this->set_error(self::ERROR_SAVING, 'errorsaving');
T 1951             return 0;
1952         }
755189 1953
b20025 1954         if ($this->cache) {
AM 1955             $this->cache->remove('groups');
1956         }
755189 1957
40d419 1958         return count($del_attrs[$member_attr]);
6039aa 1959     }
T 1960
1961     /**
1962      * Get group assignments of a specific contact record
1963      *
1964      * @param mixed Record identifier
1965      *
1966      * @return array List of assigned groups as ID=>Name pairs
1967      * @since 0.5-beta
1968      */
1969     function get_record_groups($contact_id)
1970     {
4feb8e 1971         if (!$this->groups) {
6039aa 1972             return array();
4feb8e 1973         }
6039aa 1974
f763fb 1975         $base_dn     = $this->groups_base_dn;
A 1976         $contact_dn  = self::dn_decode($contact_id);
097dbc 1977         $name_attr   = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
A 1978         $member_attr = $this->get_group_member_attr();
8fb04b 1979         $add_filter  = '';
3e7b9b 1980
8fb04b 1981         if ($member_attr != 'member' && $member_attr != 'uniqueMember')
T 1982             $add_filter = "($member_attr=$contact_dn)";
1983         $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
6039aa 1984
203323 1985         $ldap_data = $this->ldap->search($base_dn, $filter, 'sub', array('dn', $name_attr));
9e4246 1986         if ($ldap_data === false) {
6039aa 1987             return array();
T 1988         }
1989
1990         $groups = array();
203323 1991         foreach ($ldap_data as $entry) {
TB 1992             if (!$entry['dn'])
1993                 $entry['dn'] = $ldap_data->get_dn();
1994             $group_name = $entry[$name_attr][0];
1995             $group_id = self::dn_encode($entry['dn']);
42b9ce 1996             $groups[$group_id] = $group_name;
6039aa 1997         }
42b9ce 1998
6039aa 1999         return $groups;
T 2000     }
69ea3a 2001
097dbc 2002     /**
A 2003      * Detects group member attribute name
2004      */
1b52cf 2005     private function get_group_member_attr($object_classes = array(), $default = 'member')
097dbc 2006     {
A 2007         if (empty($object_classes)) {
2008             $object_classes = $this->prop['groups']['object_classes'];
2009         }
1b52cf 2010
097dbc 2011         if (!empty($object_classes)) {
A 2012             foreach ((array)$object_classes as $oc) {
3ce7c5 2013                 if ($attr = $this->group_types[strtolower($oc)]) {
3e7b9b 2014                     return $attr;
097dbc 2015                 }
A 2016             }
2017         }
2018
2019         if (!empty($this->prop['groups']['member_attr'])) {
2020             return $this->prop['groups']['member_attr'];
2021         }
2022
1b52cf 2023         return $default;
097dbc 2024     }
A 2025
69ea3a 2026     /**
c3ba0e 2027      * HTML-safe DN string encoding
A 2028      *
2029      * @param string $str DN string
2030      *
2031      * @return string Encoded HTML identifier string
2032      */
2033     static function dn_encode($str)
2034     {
2035         // @TODO: to make output string shorter we could probably
2036         //        remove dc=* items from it
2037         return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
2038     }
2039
2040     /**
2041      * Decodes DN string encoded with _dn_encode()
2042      *
2043      * @param string $str Encoded HTML identifier string
2044      *
2045      * @return string DN string
2046      */
2047     static function dn_decode($str)
2048     {
2049         $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
2050         return base64_decode($str);
13db9e 2051     }
f11541 2052 }