PageRenderTime 71ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/program/lib/Roundcube/rcube_ldap.php

https://github.com/fretelweb/roundcubemail
PHP | 1952 lines | 1234 code | 296 blank | 422 comment | 320 complexity | 28b794a2e9aaebf5c7ba3210d12fd0b7 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  1. <?php
  2. /*
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2006-2013, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2013, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Interface to an LDAP address directory |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Andreas Dick <andudi (at) gmx (dot) ch> |
  17. | Aleksander Machniak <machniak@kolabsys.com> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. /**
  21. * Model class to access an LDAP address directory
  22. *
  23. * @package Framework
  24. * @subpackage Addressbook
  25. */
  26. class rcube_ldap extends rcube_addressbook
  27. {
  28. // public properties
  29. public $primary_key = 'ID';
  30. public $groups = false;
  31. public $readonly = true;
  32. public $ready = false;
  33. public $group_id = 0;
  34. public $coltypes = array();
  35. // private properties
  36. protected $ldap;
  37. protected $prop = array();
  38. protected $fieldmap = array();
  39. protected $filter = '';
  40. protected $sub_filter;
  41. protected $result;
  42. protected $ldap_result;
  43. protected $mail_domain = '';
  44. protected $debug = false;
  45. /**
  46. * Group objectclass (lowercase) to member attribute mapping
  47. *
  48. * @var array
  49. */
  50. private static $group_types = array(
  51. 'group' => 'member',
  52. 'groupofnames' => 'member',
  53. 'kolabgroupofnames' => 'member',
  54. 'groupofuniquenames' => 'uniqueMember',
  55. 'kolabgroupofuniquenames' => 'uniqueMember',
  56. 'univentiongroup' => 'uniqueMember',
  57. 'groupofurls' => null,
  58. );
  59. private $base_dn = '';
  60. private $groups_base_dn = '';
  61. private $group_url;
  62. private $cache;
  63. /**
  64. * Object constructor
  65. *
  66. * @param array $p LDAP connection properties
  67. * @param boolean $debug Enables debug mode
  68. * @param string $mail_domain Current user mail domain name
  69. */
  70. function __construct($p, $debug = false, $mail_domain = null)
  71. {
  72. $this->prop = $p;
  73. $fetch_attributes = array('objectClass');
  74. // check if groups are configured
  75. if (is_array($p['groups']) && count($p['groups'])) {
  76. $this->groups = true;
  77. // set member field
  78. if (!empty($p['groups']['member_attr']))
  79. $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
  80. else if (empty($p['member_attr']))
  81. $this->prop['member_attr'] = 'member';
  82. // set default name attribute to cn
  83. if (empty($this->prop['groups']['name_attr']))
  84. $this->prop['groups']['name_attr'] = 'cn';
  85. if (empty($this->prop['groups']['scope']))
  86. $this->prop['groups']['scope'] = 'sub';
  87. // add group name attrib to the list of attributes to be fetched
  88. $fetch_attributes[] = $this->prop['groups']['name_attr'];
  89. }
  90. if (is_array($p['group_filters']) && count($p['group_filters'])) {
  91. $this->groups = true;
  92. foreach ($p['group_filters'] as $k => $group_filter) {
  93. // set default name attribute to cn
  94. if (empty($group_filter['name_attr']) && empty($this->prop['groups']['name_attr']))
  95. $this->prop['group_filters'][$k]['name_attr'] = $group_filter['name_attr'] = 'cn';
  96. if ($group_filter['name_attr'])
  97. $fetch_attributes[] = $group_filter['name_attr'];
  98. }
  99. }
  100. // fieldmap property is given
  101. if (is_array($p['fieldmap'])) {
  102. foreach ($p['fieldmap'] as $rf => $lf)
  103. $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
  104. }
  105. else if (!empty($p)) {
  106. // read deprecated *_field properties to remain backwards compatible
  107. foreach ($p as $prop => $value)
  108. if (preg_match('/^(.+)_field$/', $prop, $matches))
  109. $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
  110. }
  111. // use fieldmap to advertise supported coltypes to the application
  112. foreach ($this->fieldmap as $colv => $lfv) {
  113. list($col, $type) = explode(':', $colv);
  114. list($lf, $limit, $delim) = explode(':', $lfv);
  115. if ($limit == '*') $limit = null;
  116. else $limit = max(1, intval($limit));
  117. if (!is_array($this->coltypes[$col])) {
  118. $subtypes = $type ? array($type) : null;
  119. $this->coltypes[$col] = array('limit' => $limit, 'subtypes' => $subtypes, 'attributes' => array($lf));
  120. }
  121. elseif ($type) {
  122. $this->coltypes[$col]['subtypes'][] = $type;
  123. $this->coltypes[$col]['attributes'][] = $lf;
  124. $this->coltypes[$col]['limit'] += $limit;
  125. }
  126. if ($delim)
  127. $this->coltypes[$col]['serialized'][$type] = $delim;
  128. $this->fieldmap[$colv] = $lf;
  129. }
  130. // support for composite address
  131. if ($this->coltypes['street'] && $this->coltypes['locality']) {
  132. $this->coltypes['address'] = array(
  133. 'limit' => max(1, $this->coltypes['locality']['limit'] + $this->coltypes['address']['limit']),
  134. 'subtypes' => array_merge((array)$this->coltypes['address']['subtypes'], (array)$this->coltypes['locality']['subtypes']),
  135. 'childs' => array(),
  136. ) + (array)$this->coltypes['address'];
  137. foreach (array('street','locality','zipcode','region','country') as $childcol) {
  138. if ($this->coltypes[$childcol]) {
  139. $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
  140. unset($this->coltypes[$childcol]); // remove address child col from global coltypes list
  141. }
  142. }
  143. // at least one address type must be specified
  144. if (empty($this->coltypes['address']['subtypes'])) {
  145. $this->coltypes['address']['subtypes'] = array('home');
  146. }
  147. }
  148. else if ($this->coltypes['address']) {
  149. $this->coltypes['address'] += array('type' => 'textarea', 'childs' => null, 'size' => 40);
  150. // 'serialized' means the UI has to present a composite address field
  151. if ($this->coltypes['address']['serialized']) {
  152. $childprop = array('type' => 'text');
  153. $this->coltypes['address']['type'] = 'composite';
  154. $this->coltypes['address']['childs'] = array('street' => $childprop, 'locality' => $childprop, 'zipcode' => $childprop, 'country' => $childprop);
  155. }
  156. }
  157. // make sure 'required_fields' is an array
  158. if (!is_array($this->prop['required_fields'])) {
  159. $this->prop['required_fields'] = (array) $this->prop['required_fields'];
  160. }
  161. // make sure LDAP_rdn field is required
  162. if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])
  163. && !in_array($this->prop['LDAP_rdn'], array_keys((array)$this->prop['autovalues']))) {
  164. $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
  165. }
  166. foreach ($this->prop['required_fields'] as $key => $val) {
  167. $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
  168. }
  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 $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. }
  182. $this->sort_col = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
  183. $this->debug = $debug;
  184. $this->mail_domain = $mail_domain;
  185. // initialize cache
  186. $rcube = rcube::get_instance();
  187. if ($cache_type = $rcube->config->get('ldap_cache', 'db')) {
  188. $cache_ttl = $rcube->config->get('ldap_cache_ttl', '10m');
  189. $cache_name = 'LDAP.' . asciiwords($this->prop['name']);
  190. $this->cache = $rcube->get_cache($cache_name, $cache_type, $cache_ttl);
  191. }
  192. // determine which attributes to fetch
  193. $this->prop['list_attributes'] = array_unique($fetch_attributes);
  194. $this->prop['attributes'] = array_merge(array_values($this->fieldmap), $fetch_attributes);
  195. foreach ($rcube->config->get('contactlist_fields') as $col) {
  196. $this->prop['list_attributes'] = array_merge($this->prop['list_attributes'], $this->_map_field($col));
  197. }
  198. // initialize ldap wrapper object
  199. $this->ldap = new rcube_ldap_generic($this->prop);
  200. $this->ldap->set_cache($this->cache);
  201. $this->ldap->set_debug($this->debug);
  202. $this->_connect();
  203. }
  204. /**
  205. * Establish a connection to the LDAP server
  206. */
  207. private function _connect()
  208. {
  209. $rcube = rcube::get_instance();
  210. if ($this->ready)
  211. return true;
  212. if (!is_array($this->prop['hosts']))
  213. $this->prop['hosts'] = array($this->prop['hosts']);
  214. // try to connect + bind for every host configured
  215. // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable
  216. // see http://www.php.net/manual/en/function.ldap-connect.php
  217. foreach ($this->prop['hosts'] as $host) {
  218. // skip host if connection failed
  219. if (!$this->ldap->connect($host)) {
  220. continue;
  221. }
  222. // See if the directory is writeable.
  223. if ($this->prop['writable']) {
  224. $this->readonly = false;
  225. }
  226. $bind_pass = $this->prop['bind_pass'];
  227. $bind_user = $this->prop['bind_user'];
  228. $bind_dn = $this->prop['bind_dn'];
  229. $this->base_dn = $this->prop['base_dn'];
  230. $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
  231. $this->prop['groups']['base_dn'] : $this->base_dn;
  232. // User specific access, generate the proper values to use.
  233. if ($this->prop['user_specific']) {
  234. // No password set, use the session password
  235. if (empty($bind_pass)) {
  236. $bind_pass = $rcube->get_user_password();
  237. }
  238. // Get the pieces needed for variable replacement.
  239. if ($fu = $rcube->get_user_email())
  240. list($u, $d) = explode('@', $fu);
  241. else
  242. $d = $this->mail_domain;
  243. $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
  244. $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
  245. // Search for the dn to use to authenticate
  246. if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
  247. $search_bind_dn = strtr($this->prop['search_bind_dn'], $replaces);
  248. $search_base_dn = strtr($this->prop['search_base_dn'], $replaces);
  249. $search_filter = strtr($this->prop['search_filter'], $replaces);
  250. $cache_key = 'DN.' . md5("$host:$search_bind_dn:$search_base_dn:$search_filter:"
  251. .$this->prop['search_bind_pw']);
  252. if ($this->cache && ($dn = $this->cache->get($cache_key))) {
  253. $replaces['%dn'] = $dn;
  254. }
  255. else {
  256. $ldap = $this->ldap;
  257. if (!empty($search_bind_dn) && !empty($this->prop['search_bind_pw'])) {
  258. // To protect from "Critical extension is unavailable" error
  259. // we need to use a separate LDAP connection
  260. if (!empty($this->prop['vlv'])) {
  261. $ldap = new rcube_ldap_generic($this->prop);
  262. $ldap->set_debug($this->debug);
  263. $ldap->set_cache($this->cache);
  264. if (!$ldap->connect($host)) {
  265. continue;
  266. }
  267. }
  268. if (!$ldap->bind($search_bind_dn, $this->prop['search_bind_pw'])) {
  269. continue; // bind failed, try next host
  270. }
  271. }
  272. $res = $ldap->search($search_base_dn, $search_filter, 'sub', array('uid'));
  273. if ($res) {
  274. $res->rewind();
  275. $replaces['%dn'] = $res->get_dn();
  276. }
  277. if ($ldap != $this->ldap) {
  278. $ldap->close();
  279. }
  280. }
  281. // DN not found
  282. if (empty($replaces['%dn'])) {
  283. if (!empty($this->prop['search_dn_default']))
  284. $replaces['%dn'] = $this->prop['search_dn_default'];
  285. else {
  286. rcube::raise_error(array(
  287. 'code' => 100, 'type' => 'ldap',
  288. 'file' => __FILE__, 'line' => __LINE__,
  289. 'message' => "DN not found using LDAP search."), true);
  290. continue;
  291. }
  292. }
  293. if ($this->cache && !empty($replaces['%dn'])) {
  294. $this->cache->set($cache_key, $replaces['%dn']);
  295. }
  296. }
  297. // Replace the bind_dn and base_dn variables.
  298. $bind_dn = strtr($bind_dn, $replaces);
  299. $this->base_dn = strtr($this->base_dn, $replaces);
  300. $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
  301. if (empty($bind_user)) {
  302. $bind_user = $u;
  303. }
  304. }
  305. if (empty($bind_pass)) {
  306. $this->ready = true;
  307. }
  308. else {
  309. if (!empty($bind_dn)) {
  310. $this->ready = $this->ldap->bind($bind_dn, $bind_pass);
  311. }
  312. else if (!empty($this->prop['auth_cid'])) {
  313. $this->ready = $this->ldap->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
  314. }
  315. else {
  316. $this->ready = $this->ldap->sasl_bind($bind_user, $bind_pass);
  317. }
  318. }
  319. // connection established, we're done here
  320. if ($this->ready) {
  321. break;
  322. }
  323. } // end foreach hosts
  324. if (!is_resource($this->ldap->conn)) {
  325. rcube::raise_error(array('code' => 100, 'type' => 'ldap',
  326. 'file' => __FILE__, 'line' => __LINE__,
  327. 'message' => "Could not connect to any LDAP server, last tried $host"), true);
  328. return false;
  329. }
  330. return $this->ready;
  331. }
  332. /**
  333. * Close connection to LDAP server
  334. */
  335. function close()
  336. {
  337. if ($this->ldap) {
  338. $this->ldap->close();
  339. }
  340. }
  341. /**
  342. * Returns address book name
  343. *
  344. * @return string Address book name
  345. */
  346. function get_name()
  347. {
  348. return $this->prop['name'];
  349. }
  350. /**
  351. * Set internal list page
  352. *
  353. * @param number Page number to list
  354. */
  355. function set_page($page)
  356. {
  357. $this->list_page = (int)$page;
  358. $this->ldap->set_vlv_page($this->list_page, $this->page_size);
  359. }
  360. /**
  361. * Set internal page size
  362. *
  363. * @param number Number of records to display on one page
  364. */
  365. function set_pagesize($size)
  366. {
  367. $this->page_size = (int)$size;
  368. $this->ldap->set_vlv_page($this->list_page, $this->page_size);
  369. }
  370. /**
  371. * Set internal sort settings
  372. *
  373. * @param string $sort_col Sort column
  374. * @param string $sort_order Sort order
  375. */
  376. function set_sort_order($sort_col, $sort_order = null)
  377. {
  378. if ($this->coltypes[$sort_col]['attributes'])
  379. $this->sort_col = $this->coltypes[$sort_col]['attributes'][0];
  380. }
  381. /**
  382. * Save a search string for future listings
  383. *
  384. * @param string $filter Filter string
  385. */
  386. function set_search_set($filter)
  387. {
  388. $this->filter = $filter;
  389. }
  390. /**
  391. * Getter for saved search properties
  392. *
  393. * @return mixed Search properties used by this class
  394. */
  395. function get_search_set()
  396. {
  397. return $this->filter;
  398. }
  399. /**
  400. * Reset all saved results and search parameters
  401. */
  402. function reset()
  403. {
  404. $this->result = null;
  405. $this->ldap_result = null;
  406. $this->filter = '';
  407. }
  408. /**
  409. * List the current set of contact records
  410. *
  411. * @param array List of cols to show
  412. * @param int Only return this number of records
  413. *
  414. * @return array Indexed list of contact records, each a hash array
  415. */
  416. function list_records($cols=null, $subset=0)
  417. {
  418. if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id) {
  419. $this->result = new rcube_result_set(0);
  420. $this->result->searchonly = true;
  421. return $this->result;
  422. }
  423. // fetch group members recursively
  424. if ($this->group_id && $this->group_data['dn']) {
  425. $entries = $this->list_group_members($this->group_data['dn']);
  426. // make list of entries unique and sort it
  427. $seen = array();
  428. foreach ($entries as $i => $rec) {
  429. if ($seen[$rec['dn']]++)
  430. unset($entries[$i]);
  431. }
  432. usort($entries, array($this, '_entry_sort_cmp'));
  433. $entries['count'] = count($entries);
  434. $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
  435. }
  436. else {
  437. $prop = $this->group_id ? $this->group_data : $this->prop;
  438. // use global search filter
  439. if (!empty($this->filter))
  440. $prop['filter'] = $this->filter;
  441. // exec LDAP search if no result resource is stored
  442. if ($this->ready && !$this->ldap_result)
  443. $this->ldap_result = $this->ldap->search($prop['base_dn'], $prop['filter'], $prop['scope'], $this->prop['attributes'], $prop);
  444. // count contacts for this user
  445. $this->result = $this->count();
  446. // we have a search result resource
  447. if ($this->ldap_result && $this->result->count > 0) {
  448. // sorting still on the ldap server
  449. if ($this->sort_col && $prop['scope'] !== 'base' && !$this->ldap->vlv_active)
  450. $this->ldap_result->sort($this->sort_col);
  451. // get all entries from the ldap server
  452. $entries = $this->ldap_result->entries();
  453. }
  454. } // end else
  455. // start and end of the page
  456. $start_row = $this->ldap->vlv_active ? 0 : $this->result->first;
  457. $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
  458. $last_row = $this->result->first + $this->page_size;
  459. $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
  460. // filter entries for this page
  461. for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
  462. $this->result->add($this->_ldap2result($entries[$i]));
  463. return $this->result;
  464. }
  465. /**
  466. * Get all members of the given group
  467. *
  468. * @param string Group DN
  469. * @param array Group entries (if called recursively)
  470. * @return array Accumulated group members
  471. */
  472. function list_group_members($dn, $count = false, $entries = null)
  473. {
  474. $group_members = array();
  475. // fetch group object
  476. if (empty($entries)) {
  477. $attribs = array('dn','objectClass','member','uniqueMember','memberURL');
  478. $entries = $this->ldap->read_entries($dn, '(objectClass=*)', $attribs);
  479. if ($entries === false) {
  480. return $group_members;
  481. }
  482. }
  483. for ($i=0; $i < $entries['count']; $i++) {
  484. $entry = $entries[$i];
  485. $attrs = array();
  486. foreach ((array)$entry['objectclass'] as $objectclass) {
  487. if (strtolower($objectclass) == 'groupofurls') {
  488. $members = $this->_list_group_memberurl($dn, $entry, $count);
  489. $group_members = array_merge($group_members, $members);
  490. }
  491. else if (($member_attr = $this->get_group_member_attr(array($objectclass), ''))
  492. && ($member_attr = strtolower($member_attr)) && !in_array($member_attr, $attrs)
  493. ) {
  494. $members = $this->_list_group_members($dn, $entry, $member_attr, $count);
  495. $group_members = array_merge($group_members, $members);
  496. $attrs[] = $member_attr;
  497. }
  498. if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit']) {
  499. break 2;
  500. }
  501. }
  502. }
  503. return array_filter($group_members);
  504. }
  505. /**
  506. * Fetch members of the given group entry from server
  507. *
  508. * @param string Group DN
  509. * @param array Group entry
  510. * @param string Member attribute to use
  511. * @return array Accumulated group members
  512. */
  513. private function _list_group_members($dn, $entry, $attr, $count)
  514. {
  515. // Use the member attributes to return an array of member ldap objects
  516. // NOTE that the member attribute is supposed to contain a DN
  517. $group_members = array();
  518. if (empty($entry[$attr])) {
  519. return $group_members;
  520. }
  521. // read these attributes for all members
  522. $attrib = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
  523. $attrib[] = 'member';
  524. $attrib[] = 'uniqueMember';
  525. $attrib[] = 'memberURL';
  526. $filter = $this->prop['groups']['member_filter'] ? $this->prop['groups']['member_filter'] : '(objectclass=*)';
  527. for ($i=0; $i < $entry[$attr]['count']; $i++) {
  528. if (empty($entry[$attr][$i]))
  529. continue;
  530. $members = $this->ldap->read_entries($entry[$attr][$i], $filter, $attrib);
  531. if ($members == false) {
  532. $members = array();
  533. }
  534. // for nested groups, call recursively
  535. $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
  536. unset($members['count']);
  537. $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
  538. }
  539. return $group_members;
  540. }
  541. /**
  542. * List members of group class groupOfUrls
  543. *
  544. * @param string Group DN
  545. * @param array Group entry
  546. * @param boolean True if only used for counting
  547. * @return array Accumulated group members
  548. */
  549. private function _list_group_memberurl($dn, $entry, $count)
  550. {
  551. $group_members = array();
  552. for ($i=0; $i < $entry['memberurl']['count']; $i++) {
  553. // extract components from url
  554. if (!preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m))
  555. continue;
  556. // add search filter if any
  557. $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
  558. $attrs = $count ? array('dn','objectClass') : $this->prop['list_attributes'];
  559. if ($result = $this->ldap->search($m[1], $filter, $m[2], $attrs, $this->group_data)) {
  560. $entries = $result->entries();
  561. for ($j = 0; $j < $entries['count']; $j++) {
  562. if (self::is_group_entry($entries[$j]) && ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count)))
  563. $group_members = array_merge($group_members, $nested_group_members);
  564. else
  565. $group_members[] = $entries[$j];
  566. }
  567. }
  568. }
  569. return $group_members;
  570. }
  571. /**
  572. * Callback for sorting entries
  573. */
  574. function _entry_sort_cmp($a, $b)
  575. {
  576. return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
  577. }
  578. /**
  579. * Search contacts
  580. *
  581. * @param mixed $fields The field name of array of field names to search in
  582. * @param mixed $value Search value (or array of values when $fields is array)
  583. * @param int $mode Matching mode:
  584. * 0 - partial (*abc*),
  585. * 1 - strict (=),
  586. * 2 - prefix (abc*)
  587. * @param boolean $select True if results are requested, False if count only
  588. * @param boolean $nocount (Not used)
  589. * @param array $required List of fields that cannot be empty
  590. *
  591. * @return array Indexed list of contact records and 'count' value
  592. */
  593. function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
  594. {
  595. $mode = intval($mode);
  596. // special treatment for ID-based search
  597. if ($fields == 'ID' || $fields == $this->primary_key) {
  598. $ids = !is_array($value) ? explode(',', $value) : $value;
  599. $result = new rcube_result_set();
  600. foreach ($ids as $id) {
  601. if ($rec = $this->get_record($id, true)) {
  602. $result->add($rec);
  603. $result->count++;
  604. }
  605. }
  606. return $result;
  607. }
  608. // use VLV pseudo-search for autocompletion
  609. $rcube = rcube::get_instance();
  610. $list_fields = $rcube->config->get('contactlist_fields');
  611. if ($this->prop['vlv_search'] && $this->ready && join(',', (array)$fields) == join(',', $list_fields)) {
  612. $this->result = new rcube_result_set(0);
  613. $search_suffix = $this->prop['fuzzy_search'] && $mode != 1 ? '*' : '';
  614. $ldap_data = $this->ldap->search($this->base_dn, $this->prop['filter'], $this->prop['scope'], $this->prop['attributes'],
  615. array('search' => $value . $search_suffix /*, 'sort' => $this->prop['sort'] */));
  616. if ($ldap_data === false) {
  617. return $this->result;
  618. }
  619. // get all entries of this page and post-filter those that really match the query
  620. $search = mb_strtolower($value);
  621. foreach ($ldap_data as $i => $entry) {
  622. $rec = $this->_ldap2result($entry);
  623. foreach ($fields as $f) {
  624. foreach ((array)$rec[$f] as $val) {
  625. if ($this->compare_search_value($f, $val, $search, $mode)) {
  626. $this->result->add($rec);
  627. $this->result->count++;
  628. break 2;
  629. }
  630. }
  631. }
  632. }
  633. return $this->result;
  634. }
  635. // use AND operator for advanced searches
  636. $filter = is_array($value) ? '(&' : '(|';
  637. // set wildcards
  638. $wp = $ws = '';
  639. if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
  640. $ws = '*';
  641. if (!$mode) {
  642. $wp = '*';
  643. }
  644. }
  645. if ($fields == '*') {
  646. // search_fields are required for fulltext search
  647. if (empty($this->prop['search_fields'])) {
  648. $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
  649. $this->result = new rcube_result_set();
  650. return $this->result;
  651. }
  652. if (is_array($this->prop['search_fields'])) {
  653. foreach ($this->prop['search_fields'] as $field) {
  654. $filter .= "($field=$wp" . rcube_ldap_generic::quote_string($value) . "$ws)";
  655. }
  656. }
  657. }
  658. else {
  659. foreach ((array)$fields as $idx => $field) {
  660. $val = is_array($value) ? $value[$idx] : $value;
  661. if ($attrs = $this->_map_field($field)) {
  662. if (count($attrs) > 1)
  663. $filter .= '(|';
  664. foreach ($attrs as $f)
  665. $filter .= "($f=$wp" . rcube_ldap_generic::quote_string($val) . "$ws)";
  666. if (count($attrs) > 1)
  667. $filter .= ')';
  668. }
  669. }
  670. }
  671. $filter .= ')';
  672. // add required (non empty) fields filter
  673. $req_filter = '';
  674. foreach ((array)$required as $field) {
  675. if (in_array($field, (array)$fields)) // required field is already in search filter
  676. continue;
  677. if ($attrs = $this->_map_field($field)) {
  678. if (count($attrs) > 1)
  679. $req_filter .= '(|';
  680. foreach ($attrs as $f)
  681. $req_filter .= "($f=*)";
  682. if (count($attrs) > 1)
  683. $req_filter .= ')';
  684. }
  685. }
  686. if (!empty($req_filter))
  687. $filter = '(&' . $req_filter . $filter . ')';
  688. // avoid double-wildcard if $value is empty
  689. $filter = preg_replace('/\*+/', '*', $filter);
  690. // add general filter to query
  691. if (!empty($this->prop['filter']))
  692. $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
  693. // set filter string and execute search
  694. $this->set_search_set($filter);
  695. if ($select)
  696. $this->list_records();
  697. else
  698. $this->result = $this->count();
  699. return $this->result;
  700. }
  701. /**
  702. * Count number of available contacts in database
  703. *
  704. * @return object rcube_result_set Resultset with values for 'count' and 'first'
  705. */
  706. function count()
  707. {
  708. $count = 0;
  709. if ($this->ldap_result) {
  710. $count = $this->ldap_result->count();
  711. }
  712. else if ($this->group_id && $this->group_data['dn']) {
  713. $count = count($this->list_group_members($this->group_data['dn'], true));
  714. }
  715. // We have a connection but no result set, attempt to get one.
  716. else if ($this->ready) {
  717. $prop = $this->group_id ? $this->group_data : $this->prop;
  718. if (!empty($this->filter)) { // Use global search filter
  719. $prop['filter'] = $this->filter;
  720. }
  721. $count = $this->ldap->search($prop['base_dn'], $prop['filter'], $prop['scope'], array('dn'), $prop, true);
  722. }
  723. return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
  724. }
  725. /**
  726. * Return the last result set
  727. *
  728. * @return object rcube_result_set Current resultset or NULL if nothing selected yet
  729. */
  730. function get_result()
  731. {
  732. return $this->result;
  733. }
  734. /**
  735. * Get a specific contact record
  736. *
  737. * @param mixed Record identifier
  738. * @param boolean Return as associative array
  739. *
  740. * @return mixed Hash array or rcube_result_set with all record fields
  741. */
  742. function get_record($dn, $assoc=false)
  743. {
  744. $res = $this->result = null;
  745. if ($this->ready && $dn) {
  746. $dn = self::dn_decode($dn);
  747. if ($rec = $this->ldap->get_entry($dn)) {
  748. $rec = array_change_key_case($rec, CASE_LOWER);
  749. }
  750. // Use ldap_list to get subentries like country (c) attribute (#1488123)
  751. if (!empty($rec) && $this->sub_filter) {
  752. if ($entries = $this->ldap->list_entries($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
  753. foreach ($entries as $entry) {
  754. $lrec = array_change_key_case($entry, CASE_LOWER);
  755. $rec = array_merge($lrec, $rec);
  756. }
  757. }
  758. }
  759. if (!empty($rec)) {
  760. // Add in the dn for the entry.
  761. $rec['dn'] = $dn;
  762. $res = $this->_ldap2result($rec);
  763. $this->result = new rcube_result_set(1);
  764. $this->result->add($res);
  765. }
  766. }
  767. return $assoc ? $res : $this->result;
  768. }
  769. /**
  770. * Check the given data before saving.
  771. * If input not valid, the message to display can be fetched using get_error()
  772. *
  773. * @param array Assoziative array with data to save
  774. * @param boolean Try to fix/complete record automatically
  775. * @return boolean True if input is valid, False if not.
  776. */
  777. public function validate(&$save_data, $autofix = false)
  778. {
  779. // validate e-mail addresses
  780. if (!parent::validate($save_data, $autofix)) {
  781. return false;
  782. }
  783. // check for name input
  784. if (empty($save_data['name'])) {
  785. $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
  786. return false;
  787. }
  788. // Verify that the required fields are set.
  789. $missing = null;
  790. $ldap_data = $this->_map_data($save_data);
  791. foreach ($this->prop['required_fields'] as $fld) {
  792. if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
  793. $missing[$fld] = 1;
  794. }
  795. }
  796. if ($missing) {
  797. // try to complete record automatically
  798. if ($autofix) {
  799. $sn_field = $this->fieldmap['surname'];
  800. $fn_field = $this->fieldmap['firstname'];
  801. $mail_field = $this->fieldmap['email'];
  802. // try to extract surname and firstname from displayname
  803. $name_parts = preg_split('/[\s,.]+/', $save_data['name']);
  804. if ($sn_field && $missing[$sn_field]) {
  805. $save_data['surname'] = array_pop($name_parts);
  806. unset($missing[$sn_field]);
  807. }
  808. if ($fn_field && $missing[$fn_field]) {
  809. $save_data['firstname'] = array_shift($name_parts);
  810. unset($missing[$fn_field]);
  811. }
  812. // try to fix missing e-mail, very often on import
  813. // from vCard we have email:other only defined
  814. if ($mail_field && $missing[$mail_field]) {
  815. $emails = $this->get_col_values('email', $save_data, true);
  816. if (!empty($emails) && ($email = array_shift($emails))) {
  817. $save_data['email'] = $email;
  818. unset($missing[$mail_field]);
  819. }
  820. }
  821. }
  822. // TODO: generate message saying which fields are missing
  823. if (!empty($missing)) {
  824. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  825. return false;
  826. }
  827. }
  828. return true;
  829. }
  830. /**
  831. * Create a new contact record
  832. *
  833. * @param array Hash array with save data
  834. *
  835. * @return encoded record ID on success, False on error
  836. */
  837. function insert($save_cols)
  838. {
  839. // Map out the column names to their LDAP ones to build the new entry.
  840. $newentry = $this->_map_data($save_cols);
  841. $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
  842. // add automatically generated attributes
  843. $this->add_autovalues($newentry);
  844. // Verify that the required fields are set.
  845. $missing = null;
  846. foreach ($this->prop['required_fields'] as $fld) {
  847. if (!isset($newentry[$fld])) {
  848. $missing[] = $fld;
  849. }
  850. }
  851. // abort process if requiered fields are missing
  852. // TODO: generate message saying which fields are missing
  853. if ($missing) {
  854. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  855. return false;
  856. }
  857. // Build the new entries DN.
  858. $dn = $this->prop['LDAP_rdn'].'='.rcube_ldap_generic::quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
  859. // Remove attributes that need to be added separately (child objects)
  860. $xfields = array();
  861. if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
  862. foreach (array_keys($this->prop['sub_fields']) as $xf) {
  863. if (!empty($newentry[$xf])) {
  864. $xfields[$xf] = $newentry[$xf];
  865. unset($newentry[$xf]);
  866. }
  867. }
  868. }
  869. if (!$this->ldap->add($dn, $newentry)) {
  870. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  871. return false;
  872. }
  873. foreach ($xfields as $xidx => $xf) {
  874. $xdn = $xidx.'='.rcube_ldap_generic::quote_string($xf).','.$dn;
  875. $xf = array(
  876. $xidx => $xf,
  877. 'objectClass' => (array) $this->prop['sub_fields'][$xidx],
  878. );
  879. $this->ldap->add($xdn, $xf);
  880. }
  881. $dn = self::dn_encode($dn);
  882. // add new contact to the selected group
  883. if ($this->group_id)
  884. $this->add_to_group($this->group_id, $dn);
  885. return $dn;
  886. }
  887. /**
  888. * Update a specific contact record
  889. *
  890. * @param mixed Record identifier
  891. * @param array Hash array with save data
  892. *
  893. * @return boolean True on success, False on error
  894. */
  895. function update($id, $save_cols)
  896. {
  897. $record = $this->get_record($id, true);
  898. $newdata = array();
  899. $replacedata = array();
  900. $deletedata = array();
  901. $subdata = array();
  902. $subdeldata = array();
  903. $subnewdata = array();
  904. $ldap_data = $this->_map_data($save_cols);
  905. $old_data = $record['_raw_attrib'];
  906. // special handling of photo col
  907. if ($photo_fld = $this->fieldmap['photo']) {
  908. // undefined means keep old photo
  909. if (!array_key_exists('photo', $save_cols)) {
  910. $ldap_data[$photo_fld] = $record['photo'];
  911. }
  912. }
  913. foreach ($this->fieldmap as $fld) {
  914. if ($fld) {
  915. $val = $ldap_data[$fld];
  916. $old = $old_data[$fld];
  917. // remove empty array values
  918. if (is_array($val))
  919. $val = array_filter($val);
  920. // $this->_map_data() result and _raw_attrib use different format
  921. // make sure comparing array with one element with a string works as expected
  922. if (is_array($old) && count($old) == 1 && !is_array($val)) {
  923. $old = array_pop($old);
  924. }
  925. if (is_array($val) && count($val) == 1 && !is_array($old)) {
  926. $val = array_pop($val);
  927. }
  928. // Subentries must be handled separately
  929. if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
  930. if ($old != $val) {
  931. if ($old !== null) {
  932. $subdeldata[$fld] = $old;
  933. }
  934. if ($val) {
  935. $subnewdata[$fld] = $val;
  936. }
  937. }
  938. else if ($old !== null) {
  939. $subdata[$fld] = $old;
  940. }
  941. continue;
  942. }
  943. // The field does exist compare it to the ldap record.
  944. if ($old != $val) {
  945. // Changed, but find out how.
  946. if ($old === null) {
  947. // Field was not set prior, need to add it.
  948. $newdata[$fld] = $val;
  949. }
  950. else if ($val == '') {
  951. // Field supplied is empty, verify that it is not required.
  952. if (!in_array($fld, $this->prop['required_fields'])) {
  953. // ...It is not, safe to clear.
  954. // #1488420: Workaround "ldap_mod_del(): Modify: Inappropriate matching in..."
  955. // jpegPhoto attribute require an array() here. It looks to me that it works for other attribs too
  956. $deletedata[$fld] = array();
  957. //$deletedata[$fld] = $old_data[$fld];
  958. }
  959. }
  960. else {
  961. // The data was modified, save it out.
  962. $replacedata[$fld] = $val;
  963. }
  964. } // end if
  965. } // end if
  966. } // end foreach
  967. // console($old_data, $ldap_data, '----', $newdata, $replacedata, $deletedata, '----', $subdata, $subnewdata, $subdeldata);
  968. $dn = self::dn_decode($id);
  969. // Update the entry as required.
  970. if (!empty($deletedata)) {
  971. // Delete the fields.
  972. if (!$this->ldap->mod_del($dn, $deletedata)) {
  973. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  974. return false;
  975. }
  976. } // end if
  977. if (!empty($replacedata)) {
  978. // Handle RDN change
  979. if ($replacedata[$this->prop['LDAP_rdn']]) {
  980. $newdn = $this->prop['LDAP_rdn'].'='
  981. .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true)
  982. .','.$this->base_dn;
  983. if ($dn != $newdn) {
  984. $newrdn = $this->prop['LDAP_rdn'].'='
  985. .rcube_ldap_generic::quote_string($replacedata[$this->prop['LDAP_rdn']], true);
  986. unset($replacedata[$this->prop['LDAP_rdn']]);
  987. }
  988. }
  989. // Replace the fields.
  990. if (!empty($replacedata)) {
  991. if (!$this->ldap->mod_replace($dn, $replacedata)) {
  992. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  993. return false;
  994. }
  995. }
  996. } // end if
  997. // RDN change, we need to remove all sub-entries
  998. if (!empty($newrdn)) {
  999. $subdeldata = array_merge($subdeldata, $subdata);
  1000. $subnewdata = array_merge($subnewdata, $subdata);
  1001. }
  1002. // remove sub-entries
  1003. if (!empty($subdeldata)) {
  1004. foreach ($subdeldata as $fld => $val) {
  1005. $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
  1006. if (!$this->ldap->delete($subdn)) {
  1007. return false;
  1008. }
  1009. }
  1010. }
  1011. if (!empty($newdata)) {
  1012. // Add the fields.
  1013. if (!$this->ldap->mod_add($dn, $newdata)) {
  1014. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1015. return false;
  1016. }
  1017. } // end if
  1018. // Handle RDN change
  1019. if (!empty($newrdn)) {
  1020. if (!$this->ldap->rename($dn, $newrdn, null, true)) {
  1021. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1022. return false;
  1023. }
  1024. $dn = self::dn_encode($dn);
  1025. $newdn = self::dn_encode($newdn);
  1026. // change the group membership of the contact
  1027. if ($this->groups) {
  1028. $group_ids = $this->get_record_groups($dn);
  1029. foreach (array_keys($group_ids) as $group_id) {
  1030. $this->remove_from_group($group_id, $dn);
  1031. $this->add_to_group($group_id, $newdn);
  1032. }
  1033. }
  1034. $dn = self::dn_decode($newdn);
  1035. }
  1036. // add sub-entries
  1037. if (!empty($subnewdata)) {
  1038. foreach ($subnewdata as $fld => $val) {
  1039. $subdn = $fld.'='.rcube_ldap_generic::quote_string($val).','.$dn;
  1040. $xf = array(
  1041. $fld => $val,
  1042. 'objectClass' => (array) $this->prop['sub_fields'][$fld],
  1043. );
  1044. $this->ldap->add($subdn, $xf);
  1045. }
  1046. }
  1047. return $newdn ? $newdn : true;
  1048. }
  1049. /**
  1050. * Mark one or more contact records as deleted
  1051. *
  1052. * @param array Record identifiers
  1053. * @param boolean Remove record(s) irreversible (unsupported)
  1054. *
  1055. * @return boolean True on success, False on error
  1056. */
  1057. function delete($ids, $force=true)
  1058. {
  1059. if (!is_array($ids)) {
  1060. // Not an array, break apart the encoded DNs.
  1061. $ids = explode(',', $ids);
  1062. } // end if
  1063. foreach ($ids as $id) {
  1064. $dn = self::dn_decode($id);
  1065. // Need to delete all sub-entries first
  1066. if ($this->sub_filter) {
  1067. if ($entries = $this->ldap->list_entries($dn, $this->sub_filter)) {
  1068. foreach ($entries as $entry) {
  1069. if (!$this->ldap->delete($entry['dn'])) {
  1070. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1071. return false;
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // Delete the record.
  1077. if (!$this->ldap->delete($dn)) {
  1078. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1079. return false;
  1080. }
  1081. // remove contact from all groups where he was member
  1082. if ($this->groups) {
  1083. $dn = self::dn_encode($dn);
  1084. $group_ids = $this->get_record_groups($dn);
  1085. foreach (array_keys($group_ids) as $group_id) {
  1086. $this->remove_from_group($group_id, $dn);
  1087. }
  1088. }
  1089. } // end foreach
  1090. return count($ids);
  1091. }
  1092. /**
  1093. * Remove all contact records
  1094. */
  1095. function delete_all()
  1096. {
  1097. // searching for contact entries
  1098. $dn_list = $this->ldap->list_entries($this->base_dn, $this->prop['filter'] ? $this->prop['filter'] : '(objectclass=*)');
  1099. if (!empty($dn_list)) {
  1100. foreach ($dn_list as $idx => $entry) {
  1101. $dn_list[$idx] = self::dn_encode($entry['dn']);
  1102. }
  1103. $this->delete($dn_list);
  1104. }
  1105. }
  1106. /**
  1107. * Generate missing attributes as configured
  1108. *
  1109. * @param array LDAP record attributes
  1110. */
  1111. protected function add_autovalues(&$attrs)
  1112. {
  1113. if (empty($this->prop['autovalues'])) {
  1114. return;
  1115. }
  1116. $attrvals = array();
  1117. foreach ($attrs as $k => $v) {
  1118. $attrvals['{'.$k.'}'] = is_array($v) ? $v[0] : $v;
  1119. }
  1120. foreach ((array)$this->prop['autovalues'] as $lf => $templ) {
  1121. if (empty($attrs[$lf])) {
  1122. if (strpos($templ, '(') !== false) {
  1123. // replace {attr} placeholders with (escaped!) attribute values to be safely eval'd
  1124. $code = preg_replace('/\{\w+\}/', '', strtr($templ, array_map('addslashes', $attrvals)));
  1125. $fn = create_function('', "return ($code);");
  1126. if (!$fn) {
  1127. rcube::raise_error(array(
  1128. 'code' => 505, 'type' => 'php',
  1129. 'file' => __FILE__, 'line' => __LINE__,
  1130. 'message' => "Expression parse error on: ($code)"), true, false);
  1131. continue;
  1132. }
  1133. $attrs[$lf] = $fn();
  1134. }
  1135. else {
  1136. // replace {attr} placeholders with concrete attribute values
  1137. $attrs[$lf] = preg_replace('/\{\w+\}/', '', strtr($templ, $attrvals));
  1138. }
  1139. }
  1140. }
  1141. }
  1142. /**
  1143. * Converts LDAP entry into an array
  1144. */
  1145. private function _ldap2result($rec)
  1146. {
  1147. $out = array('_type' => 'person');
  1148. $fieldmap = $this->fieldmap;
  1149. if ($rec['dn'])
  1150. $out[$this->primary_key] = self::dn_encode($rec['dn']);
  1151. // determine record type
  1152. if (self::is_group_entry($rec)) {
  1153. $out['_type'] = 'group';
  1154. $out['readonly'] = true;
  1155. $fieldmap['name'] = $this->group_data['name_attr'] ? $this->group_data['name_attr'] : $this->prop['groups']['name_attr'];
  1156. }
  1157. foreach ($fieldmap as $rf => $lf)
  1158. {
  1159. for ($i=0; $i < $rec[$lf]['count']; $i++) {
  1160. if (!($value = $rec[$lf][$i]))
  1161. continue;
  1162. list($col, $subtype) = explode(':', $rf);
  1163. $out['_raw_attrib'][$lf][$i] = $value;
  1164. if ($col == 'email' && $this->mail_domain && !strpos($value, '@'))
  1165. $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
  1166. else if (in_array($col, array('street','zipcode','locality','country','region')))
  1167. $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
  1168. else if ($col == 'address' && strpos($value, '$') !== false) // address data is represented as string separated with $
  1169. list($out[$rf][$i]['street'], $out[$rf][$i]['locality'], $out[$rf][$i]['zipcode'], $out[$rf][$i]['country']) = explode('$', $value);
  1170. else if ($rec[$lf]['count'] > 1)
  1171. $out[$rf][] = $value;
  1172. else
  1173. $out[$rf] = $value;
  1174. }
  1175. // Make sure name fields aren't arrays (#1488108)
  1176. if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
  1177. $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
  1178. }
  1179. }
  1180. return $out;
  1181. }
  1182. /**
  1183. * Return LDAP attribute(s) for the given field
  1184. */
  1185. private function _map_field($field)
  1186. {
  1187. return (array)$this->coltypes[$field]['attributes'];
  1188. }
  1189. /**
  1190. * Convert a record data set into LDAP field attributes
  1191. */
  1192. private function _map_data($save_cols)
  1193. {
  1194. // flatten composite fields first
  1195. foreach ($this->coltypes as $col => $colprop) {
  1196. if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
  1197. foreach ($values as $subtype => $childs) {
  1198. $subtype = $subtype ? ':'.$subtype : '';
  1199. foreach ($childs as $i => $child_values) {
  1200. foreach ((array)$child_values as $childcol => $value) {
  1201. $save_cols[$childcol.$subtype][$i] = $value;
  1202. }
  1203. }
  1204. }
  1205. }
  1206. // if addresses are to be saved as serialized string, do so
  1207. if (is_array($colprop['serialized'])) {
  1208. foreach ($colprop['serialized'] as $subtype => $delim) {
  1209. $key = $col.':'.$subtype;
  1210. foreach ((array)$save_cols[$key] as $i => $val) {
  1211. $values = array($val['street'], $val['locality'], $val['zipcode'], $val['country']);
  1212. $save_cols[$key][$i] = count(array_filter($values)) ? join($delim, $values) : null;
  1213. }
  1214. }
  1215. }
  1216. }
  1217. $ldap_data = array();
  1218. foreach ($this->fieldmap as $rf => $fld) {
  1219. $val = $save_cols[$rf];
  1220. // check for value in base field (eg.g email instead of email:foo)
  1221. list($col, $subtype) = explode(':', $rf);
  1222. if (!$val && !empty($save_cols[$col])) {
  1223. $val = $save_cols[$col];
  1224. unset($save_cols[$col]); // only use this value once
  1225. }
  1226. else if (!$val && !$subtype) { // extract values from subtype cols
  1227. $val = $this->get_col_values($col, $save_cols, true);
  1228. }
  1229. if (is_array($val))
  1230. $val = array_filter($val); // remove empty entries
  1231. if ($fld && $val) {
  1232. // The field does exist, add it to the entry.
  1233. $ldap_data[$fld] = $val;
  1234. }
  1235. }
  1236. return $ldap_data;
  1237. }
  1238. /**
  1239. * Returns unified attribute name (resolving aliases)
  1240. */
  1241. private static function _attr_name($namev)
  1242. {
  1243. // list of known attribute aliases
  1244. static $aliases = array(
  1245. 'gn' => 'givenname',
  1246. 'rfc822mailbox' => 'email',
  1247. 'userid' => 'uid',
  1248. 'emailaddress' => 'email',
  1249. 'pkcs9email' => 'email',
  1250. );
  1251. list($name, $limit) = explode(':', $namev, 2);
  1252. $suffix = $limit ? ':'.$limit : '';
  1253. return (isset($aliases[$name]) ? $aliases[$name] : $name) . $suffix;
  1254. }
  1255. /**
  1256. * Determines whether the given LDAP entry is a group record
  1257. */
  1258. private static function is_group_entry($entry)
  1259. {
  1260. $classes = array_map('strtolower', (array)$entry['objectclass']);
  1261. return count(array_intersect(array_keys(self::$group_types), $classes)) > 0;
  1262. }
  1263. /**
  1264. * Prints debug info to the log
  1265. */
  1266. private function _debug($str)
  1267. {
  1268. if ($this->debug) {
  1269. rcube::write_log('ldap', $str);
  1270. }
  1271. }
  1272. /**
  1273. * Activate/deactivate debug mode
  1274. *
  1275. * @param boolean $dbg True if LDAP commands should be logged
  1276. */
  1277. function set_debug($dbg = true)
  1278. {
  1279. $this->debug = $dbg;
  1280. if ($this->ldap) {
  1281. $this->ldap->set_debug($dbg);
  1282. }
  1283. }
  1284. /**
  1285. * Setter for the current group
  1286. */
  1287. function set_group($group_id)
  1288. {
  1289. if ($group_id) {
  1290. $this->group_id = $group_id;
  1291. $this->group_data = $this->get_group_entry($group_id);
  1292. }
  1293. else {
  1294. $this->group_id = 0;
  1295. $this->group_data = null;
  1296. }
  1297. }
  1298. /**
  1299. * List all active contact groups of this source
  1300. *
  1301. * @param string Optional search string to match group name
  1302. * @param int Matching mode:
  1303. * 0 - partial (*abc*),
  1304. * 1 - strict (=),
  1305. * 2 - prefix (abc*)
  1306. *
  1307. * @return array Indexed list of contact groups, each a hash array
  1308. */
  1309. function list_groups($search = null, $mode = 0)
  1310. {
  1311. if (!$this->groups) {
  1312. return array();
  1313. }
  1314. $group_cache = $this->_fetch_groups();
  1315. $groups = array();
  1316. if ($search) {
  1317. foreach ($group_cache as $group) {
  1318. if ($this->compare_search_value('name', $group['name'], $search, $mode)) {
  1319. $groups[] = $group;
  1320. }
  1321. }
  1322. }
  1323. else {
  1324. $groups = $group_cache;
  1325. }
  1326. return array_values($groups);
  1327. }
  1328. /**
  1329. * Fetch groups from server
  1330. */
  1331. private function _fetch_groups($vlv_page = null)
  1332. {
  1333. // special case: list groups from 'group_filters' config
  1334. if ($vlv_page === null && !empty($this->prop['group_filters'])) {
  1335. $groups = array();
  1336. // list regular groups configuration as special filter
  1337. if (!empty($this->prop['groups']['filter'])) {
  1338. $id = '__groups__';
  1339. $groups[$id] = array('ID' => $id, 'name' => rcube_label('groups'), 'virtual' => true) + $this->prop['groups'];
  1340. }
  1341. foreach ($this->prop['group_filters'] as $id => $prop) {
  1342. $groups[$id] = $prop + array('ID' => $id, 'name' => ucfirst($id), 'virtual' => true, 'base_dn' => $this->base_dn);
  1343. }
  1344. return $groups;
  1345. }
  1346. if ($this->cache && $vlv_page === null && ($groups = $this->cache->get('groups')) !== null) {
  1347. return $groups;
  1348. }
  1349. $base_dn = $this->groups_base_dn;
  1350. $filter = $this->prop['groups']['filter'];
  1351. $name_attr = $this->prop['groups']['name_attr'];
  1352. $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
  1353. $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
  1354. $sort_attr = $sort_attrs[0];
  1355. $ldap = $this->ldap;
  1356. // use vlv to list groups
  1357. if ($this->prop['groups']['vlv']) {
  1358. $page_size = 200;
  1359. if (!$this->prop['groups']['sort']) {
  1360. $this->prop['groups']['sort'] = $sort_attrs;
  1361. }
  1362. $ldap = clone $this->ldap;
  1363. $ldap->set_config($this->prop['groups']);
  1364. $ldap->set_vlv_page($vlv_page+1, $page_size);
  1365. }
  1366. $attrs = array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr));
  1367. $ldap_data = $ldap->search($base_dn, $filter, $this->prop['groups']['scope'], $attrs, $this->prop['groups']);
  1368. if ($ldap_data === false) {
  1369. return array();
  1370. }
  1371. $groups = array();
  1372. $group_sortnames = array();
  1373. $group_count = $ldap_data->count();
  1374. foreach ($ldap_data as $entry) {
  1375. if (!$entry['dn']) // DN is mandatory
  1376. $entry['dn'] = $ldap_data->get_dn();
  1377. $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
  1378. $group_id = self::dn_encode($entry['dn']);
  1379. $groups[$group_id]['ID'] = $group_id;
  1380. $groups[$group_id]['dn'] = $entry['dn'];
  1381. $groups[$group_id]['name'] = $group_name;
  1382. $groups[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
  1383. // list email attributes of a group
  1384. for ($j=0; $entry[$email_attr] && $j < $entry[$email_attr]['count']; $j++) {
  1385. if (strpos($entry[$email_attr][$j], '@') > 0)
  1386. $groups[$group_id]['email'][] = $entry[$email_attr][$j];
  1387. }
  1388. $group_sortnames[] = mb_strtolower($entry[$sort_attr][0]);
  1389. }
  1390. // recursive call can exit here
  1391. if ($vlv_page > 0) {
  1392. return $groups;
  1393. }
  1394. // call recursively until we have fetched all groups
  1395. while ($this->prop['groups']['vlv'] && $group_count == $page_size) {
  1396. $next_page = $this->_fetch_groups(++$vlv_page);
  1397. $groups = array_merge($groups, $next_page);
  1398. $group_count = count($next_page);
  1399. }
  1400. // when using VLV the list of groups is already sorted
  1401. if (!$this->prop['groups']['vlv']) {
  1402. array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
  1403. }
  1404. // cache this
  1405. if ($this->cache) {
  1406. $this->cache->set('groups', $groups);
  1407. }
  1408. return $groups;
  1409. }
  1410. /**
  1411. * Fetch a group entry from LDAP and save in local cache
  1412. */
  1413. private function get_group_entry($group_id)
  1414. {
  1415. $group_cache = $this->_fetch_groups();
  1416. // add group record to cache if it isn't yet there
  1417. if (!isset($group_cache[$group_id])) {
  1418. $name_attr = $this->prop['groups']['name_attr'];
  1419. $dn = self::dn_decode($group_id);
  1420. if ($list = $this->ldap->read_entries($dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL',$name_attr,$this->fieldmap['email']))) {
  1421. $entry = $list[0];
  1422. $group_name = is_array($entry[$name_attr]) ? $entry[$name_attr][0] : $entry[$name_attr];
  1423. $group_cache[$group_id]['ID'] = $group_id;
  1424. $group_cache[$group_id]['dn'] = $dn;
  1425. $group_cache[$group_id]['name'] = $group_name;
  1426. $group_cache[$group_id]['member_attr'] = $this->get_group_member_attr($entry['objectclass']);
  1427. }
  1428. else {
  1429. $group_cache[$group_id] = false;
  1430. }
  1431. if ($this->cache) {
  1432. $this->cache->set('groups', $group_cache);
  1433. }
  1434. }
  1435. return $group_cache[$group_id];
  1436. }
  1437. /**
  1438. * Get group properties such as name and email address(es)
  1439. *
  1440. * @param string Group identifier
  1441. * @return array Group properties as hash array
  1442. */
  1443. function get_group($group_id)
  1444. {
  1445. $group_data = $this->get_group_entry($group_id);
  1446. unset($group_data['dn'], $group_data['member_attr']);
  1447. return $group_data;
  1448. }
  1449. /**
  1450. * Create a contact group with the given name
  1451. *
  1452. * @param string The group name
  1453. * @return mixed False on error, array with record props in success
  1454. */
  1455. function create_group($group_name)
  1456. {
  1457. $new_dn = 'cn=' . rcube_ldap_generic::quote_string($group_name, true) . ',' . $this->groups_base_dn;
  1458. $new_gid = self::dn_encode($new_dn);
  1459. $member_attr = $this->get_group_member_attr();
  1460. $name_attr = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
  1461. $new_entry = array(
  1462. 'objectClass' => $this->prop['groups']['object_classes'],
  1463. $name_attr => $group_name,
  1464. $member_attr => '',
  1465. );
  1466. if (!$this->ldap->add($new_dn, $new_entry)) {
  1467. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1468. return false;
  1469. }
  1470. if ($this->cache) {
  1471. $this->cache->remove('groups');
  1472. }
  1473. return array('id' => $new_gid, 'name' => $group_name);
  1474. }
  1475. /**
  1476. * Delete the given group and all linked group members
  1477. *
  1478. * @param string Group identifier
  1479. * @return boolean True on success, false if no data was changed
  1480. */
  1481. function delete_group($group_id)
  1482. {
  1483. $group_cache = $this->_fetch_groups();
  1484. $del_dn = $group_cache[$group_id]['dn'];
  1485. if (!$this->ldap->delete($del_dn)) {
  1486. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1487. return false;
  1488. }
  1489. if ($this->cache) {
  1490. unset($group_cache[$group_id]);
  1491. $this->cache->set('groups', $group_cache);
  1492. }
  1493. return true;
  1494. }
  1495. /**
  1496. * Rename a specific contact group
  1497. *
  1498. * @param string Group identifier
  1499. * @param string New name to set for this group
  1500. * @param string New group identifier (if changed, otherwise don't set)
  1501. * @return boolean New name on success, false if no data was changed
  1502. */
  1503. function rename_group($group_id, $new_name, &$new_gid)
  1504. {
  1505. $group_cache = $this->_fetch_groups();
  1506. $old_dn = $group_cache[$group_id]['dn'];
  1507. $new_rdn = "cn=" . rcube_ldap_generic::quote_string($new_name, true);
  1508. $new_gid = self::dn_encode($new_rdn . ',' . $this->groups_base_dn);
  1509. if (!$this->ldap->rename($old_dn, $new_rdn, null, true)) {
  1510. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1511. return false;
  1512. }
  1513. if ($this->cache) {
  1514. $this->cache->remove('groups');
  1515. }
  1516. return $new_name;
  1517. }
  1518. /**
  1519. * Add the given contact records the a certain group
  1520. *
  1521. * @param string Group identifier
  1522. * @param array|string List of contact identifiers to be added
  1523. *
  1524. * @return int Number of contacts added
  1525. */
  1526. function add_to_group($group_id, $contact_ids)
  1527. {
  1528. $group_cache = $this->_fetch_groups();
  1529. $member_attr = $group_cache[$group_id]['member_attr'];
  1530. $group_dn = $group_cache[$group_id]['dn'];
  1531. $new_attrs = array();
  1532. if (!is_array($contact_ids)) {
  1533. $contact_ids = explode(',', $contact_ids);
  1534. }
  1535. foreach ($contact_ids as $id) {
  1536. $new_attrs[$member_attr][] = self::dn_decode($id);
  1537. }
  1538. if (!$this->ldap->mod_add($group_dn, $new_attrs)) {
  1539. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1540. return 0;
  1541. }
  1542. if ($this->cache) {
  1543. $this->cache->remove('groups');
  1544. }
  1545. return count($new_attrs[$member_attr]);
  1546. }
  1547. /**
  1548. * Remove the given contact records from a certain group
  1549. *
  1550. * @param string Group identifier
  1551. * @param array|string List of contact identifiers to be removed
  1552. *
  1553. * @return int Number of deleted group members
  1554. */
  1555. function remove_from_group($group_id, $contact_ids)
  1556. {
  1557. $group_cache = $this->_fetch_groups();
  1558. $member_attr = $group_cache[$group_id]['member_attr'];
  1559. $group_dn = $group_cache[$group_id]['dn'];
  1560. $del_attrs = array();
  1561. if (!is_array($contact_ids)) {
  1562. $contact_ids = explode(',', $contact_ids);
  1563. }
  1564. foreach ($contact_ids as $id) {
  1565. $del_attrs[$member_attr][] = self::dn_decode($id);
  1566. }
  1567. if (!$this->ldap->mod_del($group_dn, $del_attrs)) {
  1568. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1569. return 0;
  1570. }
  1571. if ($this->cache) {
  1572. $this->cache->remove('groups');
  1573. }
  1574. return count($del_attrs[$member_attr]);
  1575. }
  1576. /**
  1577. * Get group assignments of a specific contact record
  1578. *
  1579. * @param mixed Record identifier
  1580. *
  1581. * @return array List of assigned groups as ID=>Name pairs
  1582. * @since 0.5-beta
  1583. */
  1584. function get_record_groups($contact_id)
  1585. {
  1586. if (!$this->groups) {
  1587. return array();
  1588. }
  1589. $base_dn = $this->groups_base_dn;
  1590. $contact_dn = self::dn_decode($contact_id);
  1591. $name_attr = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
  1592. $member_attr = $this->get_group_member_attr();
  1593. $add_filter = '';
  1594. if ($member_attr != 'member' && $member_attr != 'uniqueMember')
  1595. $add_filter = "($member_attr=$contact_dn)";
  1596. $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
  1597. $ldap_data = $this->ldap->search($base_dn, $filter, 'sub', array('dn', $name_attr));
  1598. if ($res === false) {
  1599. return array();
  1600. }
  1601. $groups = array();
  1602. foreach ($ldap_data as $entry) {
  1603. if (!$entry['dn'])
  1604. $entry['dn'] = $ldap_data->get_dn();
  1605. $group_name = $entry[$name_attr][0];
  1606. $group_id = self::dn_encode($entry['dn']);
  1607. $groups[$group_id] = $group_name;
  1608. }
  1609. return $groups;
  1610. }
  1611. /**
  1612. * Detects group member attribute name
  1613. */
  1614. private function get_group_member_attr($object_classes = array(), $default = 'member')
  1615. {
  1616. if (empty($object_classes)) {
  1617. $object_classes = $this->prop['groups']['object_classes'];
  1618. }
  1619. if (!empty($object_classes)) {
  1620. foreach ((array)$object_classes as $oc) {
  1621. if ($attr = self::$group_types[strtolower($oc)]) {
  1622. return $attr;
  1623. }
  1624. }
  1625. }
  1626. if (!empty($this->prop['groups']['member_attr'])) {
  1627. return $this->prop['groups']['member_attr'];
  1628. }
  1629. return $default;
  1630. }
  1631. /**
  1632. * HTML-safe DN string encoding
  1633. *
  1634. * @param string $str DN string
  1635. *
  1636. * @return string Encoded HTML identifier string
  1637. */
  1638. static function dn_encode($str)
  1639. {
  1640. // @TODO: to make output string shorter we could probably
  1641. // remove dc=* items from it
  1642. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  1643. }
  1644. /**
  1645. * Decodes DN string encoded with _dn_encode()
  1646. *
  1647. * @param string $str Encoded HTML identifier string
  1648. *
  1649. * @return string DN string
  1650. */
  1651. static function dn_decode($str)
  1652. {
  1653. $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
  1654. return base64_decode($str);
  1655. }
  1656. }