comparison program/lib/Roundcube/rcube_ldap.php @ 0:4681f974d28b

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