PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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);

Large files files are truncated, but you can click here to view the full file