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