PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/program/lib/Roundcube/rcube_ldap.php

https://github.com/sanderbaas/roundcubemail
PHP | 2348 lines | 1555 code | 338 blank | 455 comment | 329 complexity | 4ee52c3ae1b06874c229f47109a4e804 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-2012, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2012, 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 $conn;
  37. protected $prop = array();
  38. protected $fieldmap = array();
  39. protected $sub_filter;
  40. protected $filter = '';
  41. protected $result = null;
  42. protected $ldap_result = null;
  43. protected $mail_domain = '';
  44. protected $debug = false;
  45. private $base_dn = '';
  46. private $groups_base_dn = '';
  47. private $group_url = null;
  48. private $cache;
  49. private $vlv_active = false;
  50. private $vlv_count = 0;
  51. /**
  52. * Object constructor
  53. *
  54. * @param array $p LDAP connection properties
  55. * @param boolean $debug Enables debug mode
  56. * @param string $mail_domain Current user mail domain name
  57. */
  58. function __construct($p, $debug = false, $mail_domain = null)
  59. {
  60. $this->prop = $p;
  61. if (isset($p['searchonly']))
  62. $this->searchonly = $p['searchonly'];
  63. // check if groups are configured
  64. if (is_array($p['groups']) && count($p['groups'])) {
  65. $this->groups = true;
  66. // set member field
  67. if (!empty($p['groups']['member_attr']))
  68. $this->prop['member_attr'] = strtolower($p['groups']['member_attr']);
  69. else if (empty($p['member_attr']))
  70. $this->prop['member_attr'] = 'member';
  71. // set default name attribute to cn
  72. if (empty($this->prop['groups']['name_attr']))
  73. $this->prop['groups']['name_attr'] = 'cn';
  74. if (empty($this->prop['groups']['scope']))
  75. $this->prop['groups']['scope'] = 'sub';
  76. }
  77. // fieldmap property is given
  78. if (is_array($p['fieldmap'])) {
  79. foreach ($p['fieldmap'] as $rf => $lf)
  80. $this->fieldmap[$rf] = $this->_attr_name(strtolower($lf));
  81. }
  82. else if (!empty($p)) {
  83. // read deprecated *_field properties to remain backwards compatible
  84. foreach ($p as $prop => $value)
  85. if (preg_match('/^(.+)_field$/', $prop, $matches))
  86. $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
  87. }
  88. // use fieldmap to advertise supported coltypes to the application
  89. foreach ($this->fieldmap as $colv => $lfv) {
  90. list($col, $type) = explode(':', $colv);
  91. list($lf, $limit, $delim) = explode(':', $lfv);
  92. if ($limit == '*') $limit = null;
  93. else $limit = max(1, intval($limit));
  94. if (!is_array($this->coltypes[$col])) {
  95. $subtypes = $type ? array($type) : null;
  96. $this->coltypes[$col] = array('limit' => $limit, 'subtypes' => $subtypes, 'attributes' => array($lf));
  97. }
  98. elseif ($type) {
  99. $this->coltypes[$col]['subtypes'][] = $type;
  100. $this->coltypes[$col]['attributes'][] = $lf;
  101. $this->coltypes[$col]['limit'] += $limit;
  102. }
  103. if ($delim)
  104. $this->coltypes[$col]['serialized'][$type] = $delim;
  105. $this->fieldmap[$colv] = $lf;
  106. }
  107. // support for composite address
  108. if ($this->coltypes['street'] && $this->coltypes['locality']) {
  109. $this->coltypes['address'] = array(
  110. 'limit' => max(1, $this->coltypes['locality']['limit'] + $this->coltypes['address']['limit']),
  111. 'subtypes' => array_merge((array)$this->coltypes['address']['subtypes'], (array)$this->coltypes['locality']['subtypes']),
  112. 'childs' => array(),
  113. ) + (array)$this->coltypes['address'];
  114. foreach (array('street','locality','zipcode','region','country') as $childcol) {
  115. if ($this->coltypes[$childcol]) {
  116. $this->coltypes['address']['childs'][$childcol] = array('type' => 'text');
  117. unset($this->coltypes[$childcol]); // remove address child col from global coltypes list
  118. }
  119. }
  120. // at least one address type must be specified
  121. if (empty($this->coltypes['address']['subtypes'])) {
  122. $this->coltypes['address']['subtypes'] = array('home');
  123. }
  124. }
  125. else if ($this->coltypes['address']) {
  126. $this->coltypes['address'] += array('type' => 'textarea', 'childs' => null, 'size' => 40);
  127. // 'serialized' means the UI has to present a composite address field
  128. if ($this->coltypes['address']['serialized']) {
  129. $childprop = array('type' => 'text');
  130. $this->coltypes['address']['type'] = 'composite';
  131. $this->coltypes['address']['childs'] = array('street' => $childprop, 'locality' => $childprop, 'zipcode' => $childprop, 'country' => $childprop);
  132. }
  133. }
  134. // make sure 'required_fields' is an array
  135. if (!is_array($this->prop['required_fields'])) {
  136. $this->prop['required_fields'] = (array) $this->prop['required_fields'];
  137. }
  138. // make sure LDAP_rdn field is required
  139. if (!empty($this->prop['LDAP_rdn']) && !in_array($this->prop['LDAP_rdn'], $this->prop['required_fields'])
  140. && !in_array($this->prop['LDAP_rdn'], array_keys((array)$this->prop['autovalues']))) {
  141. $this->prop['required_fields'][] = $this->prop['LDAP_rdn'];
  142. }
  143. foreach ($this->prop['required_fields'] as $key => $val) {
  144. $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
  145. }
  146. // Build sub_fields filter
  147. if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
  148. $this->sub_filter = '';
  149. foreach ($this->prop['sub_fields'] as $attr => $class) {
  150. if (!empty($class)) {
  151. $class = is_array($class) ? array_pop($class) : $class;
  152. $this->sub_filter .= '(objectClass=' . $class . ')';
  153. }
  154. }
  155. if (count($this->prop['sub_fields']) > 1) {
  156. $this->sub_filter = '(|' . $this->sub_filter . ')';
  157. }
  158. }
  159. $this->sort_col = is_array($p['sort']) ? $p['sort'][0] : $p['sort'];
  160. $this->debug = $debug;
  161. $this->mail_domain = $mail_domain;
  162. // initialize cache
  163. $rcube = rcube::get_instance();
  164. $this->cache = $rcube->get_cache('LDAP.' . asciiwords($this->prop['name']), 'db', 600);
  165. $this->_connect();
  166. }
  167. /**
  168. * Establish a connection to the LDAP server
  169. */
  170. private function _connect()
  171. {
  172. $rcube = rcube::get_instance();
  173. if (!function_exists('ldap_connect'))
  174. rcube::raise_error(array('code' => 100, 'type' => 'ldap',
  175. 'file' => __FILE__, 'line' => __LINE__,
  176. 'message' => "No ldap support in this installation of PHP"),
  177. true, true);
  178. if (is_resource($this->conn))
  179. return true;
  180. if (!is_array($this->prop['hosts']))
  181. $this->prop['hosts'] = array($this->prop['hosts']);
  182. if (empty($this->prop['ldap_version']))
  183. $this->prop['ldap_version'] = 3;
  184. // try to connect + bind for every host configured
  185. // with OpenLDAP 2.x ldap_connect() always succeeds but ldap_bind will fail if host isn't reachable
  186. // see http://www.php.net/manual/en/function.ldap-connect.php
  187. foreach ($this->prop['hosts'] as $host) {
  188. $host = rcube_utils::idn_to_ascii(rcube_utils::parse_host($host));
  189. $hostname = $host.($this->prop['port'] ? ':'.$this->prop['port'] : '');
  190. $this->_debug("C: Connect [$hostname] [{$this->prop['name']}]");
  191. if ($lc = @ldap_connect($host, $this->prop['port'])) {
  192. if ($this->prop['use_tls'] === true)
  193. if (!ldap_start_tls($lc))
  194. continue;
  195. $this->_debug("S: OK");
  196. ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
  197. $this->prop['host'] = $host;
  198. $this->conn = $lc;
  199. if (!empty($this->prop['network_timeout']))
  200. ldap_set_option($lc, LDAP_OPT_NETWORK_TIMEOUT, $this->prop['network_timeout']);
  201. if (isset($this->prop['referrals']))
  202. ldap_set_option($lc, LDAP_OPT_REFERRALS, $this->prop['referrals']);
  203. }
  204. else {
  205. $this->_debug("S: NOT OK");
  206. continue;
  207. }
  208. // See if the directory is writeable.
  209. if ($this->prop['writable']) {
  210. $this->readonly = false;
  211. }
  212. $bind_pass = $this->prop['bind_pass'];
  213. $bind_user = $this->prop['bind_user'];
  214. $bind_dn = $this->prop['bind_dn'];
  215. $this->base_dn = $this->prop['base_dn'];
  216. $this->groups_base_dn = ($this->prop['groups']['base_dn']) ?
  217. $this->prop['groups']['base_dn'] : $this->base_dn;
  218. // User specific access, generate the proper values to use.
  219. if ($this->prop['user_specific']) {
  220. // No password set, use the session password
  221. if (empty($bind_pass)) {
  222. $bind_pass = $rcube->get_user_password();
  223. }
  224. // Get the pieces needed for variable replacement.
  225. if ($fu = $rcube->get_user_email())
  226. list($u, $d) = explode('@', $fu);
  227. else
  228. $d = $this->mail_domain;
  229. $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
  230. $replaces = array('%dn' => '', '%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
  231. if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
  232. if (!empty($this->prop['search_bind_dn']) && !empty($this->prop['search_bind_pw'])) {
  233. $this->bind($this->prop['search_bind_dn'], $this->prop['search_bind_pw']);
  234. }
  235. // Search for the dn to use to authenticate
  236. $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
  237. $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
  238. $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
  239. $res = @ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
  240. if ($res) {
  241. if (($entry = ldap_first_entry($this->conn, $res))
  242. && ($bind_dn = ldap_get_dn($this->conn, $entry))
  243. ) {
  244. $this->_debug("S: search returned dn: $bind_dn");
  245. $dn = ldap_explode_dn($bind_dn, 1);
  246. $replaces['%dn'] = $dn[0];
  247. }
  248. }
  249. else {
  250. $this->_debug("S: ".ldap_error($this->conn));
  251. }
  252. // DN not found
  253. if (empty($replaces['%dn'])) {
  254. if (!empty($this->prop['search_dn_default']))
  255. $replaces['%dn'] = $this->prop['search_dn_default'];
  256. else {
  257. rcube::raise_error(array(
  258. 'code' => 100, 'type' => 'ldap',
  259. 'file' => __FILE__, 'line' => __LINE__,
  260. 'message' => "DN not found using LDAP search."), true);
  261. return false;
  262. }
  263. }
  264. }
  265. // Replace the bind_dn and base_dn variables.
  266. $bind_dn = strtr($bind_dn, $replaces);
  267. $this->base_dn = strtr($this->base_dn, $replaces);
  268. $this->groups_base_dn = strtr($this->groups_base_dn, $replaces);
  269. if (empty($bind_user)) {
  270. $bind_user = $u;
  271. }
  272. }
  273. if (empty($bind_pass)) {
  274. $this->ready = true;
  275. }
  276. else {
  277. if (!empty($bind_dn)) {
  278. $this->ready = $this->bind($bind_dn, $bind_pass);
  279. }
  280. else if (!empty($this->prop['auth_cid'])) {
  281. $this->ready = $this->sasl_bind($this->prop['auth_cid'], $bind_pass, $bind_user);
  282. }
  283. else {
  284. $this->ready = $this->sasl_bind($bind_user, $bind_pass);
  285. }
  286. }
  287. // connection established, we're done here
  288. if ($this->ready) {
  289. break;
  290. }
  291. } // end foreach hosts
  292. if (!is_resource($this->conn)) {
  293. rcube::raise_error(array('code' => 100, 'type' => 'ldap',
  294. 'file' => __FILE__, 'line' => __LINE__,
  295. 'message' => "Could not connect to any LDAP server, last tried $hostname"), true);
  296. return false;
  297. }
  298. return $this->ready;
  299. }
  300. /**
  301. * Bind connection with (SASL-) user and password
  302. *
  303. * @param string $authc Authentication user
  304. * @param string $pass Bind password
  305. * @param string $authz Autorization user
  306. *
  307. * @return boolean True on success, False on error
  308. */
  309. public function sasl_bind($authc, $pass, $authz=null)
  310. {
  311. if (!$this->conn) {
  312. return false;
  313. }
  314. if (!function_exists('ldap_sasl_bind')) {
  315. rcube::raise_error(array('code' => 100, 'type' => 'ldap',
  316. 'file' => __FILE__, 'line' => __LINE__,
  317. 'message' => "Unable to bind: ldap_sasl_bind() not exists"),
  318. true, true);
  319. }
  320. if (!empty($authz)) {
  321. $authz = 'u:' . $authz;
  322. }
  323. if (!empty($this->prop['auth_method'])) {
  324. $method = $this->prop['auth_method'];
  325. }
  326. else {
  327. $method = 'DIGEST-MD5';
  328. }
  329. $this->_debug("C: Bind [mech: $method, authc: $authc, authz: $authz] [pass: $pass]");
  330. if (ldap_sasl_bind($this->conn, NULL, $pass, $method, NULL, $authc, $authz)) {
  331. $this->_debug("S: OK");
  332. return true;
  333. }
  334. $this->_debug("S: ".ldap_error($this->conn));
  335. rcube::raise_error(array(
  336. 'code' => ldap_errno($this->conn), 'type' => 'ldap',
  337. 'file' => __FILE__, 'line' => __LINE__,
  338. 'message' => "Bind failed for authcid=$authc ".ldap_error($this->conn)),
  339. true);
  340. return false;
  341. }
  342. /**
  343. * Bind connection with DN and password
  344. *
  345. * @param string Bind DN
  346. * @param string Bind password
  347. *
  348. * @return boolean True on success, False on error
  349. */
  350. public function bind($dn, $pass)
  351. {
  352. if (!$this->conn) {
  353. return false;
  354. }
  355. $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
  356. if (@ldap_bind($this->conn, $dn, $pass)) {
  357. $this->_debug("S: OK");
  358. return true;
  359. }
  360. $this->_debug("S: ".ldap_error($this->conn));
  361. rcube::raise_error(array(
  362. 'code' => ldap_errno($this->conn), 'type' => 'ldap',
  363. 'file' => __FILE__, 'line' => __LINE__,
  364. 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
  365. true);
  366. return false;
  367. }
  368. /**
  369. * Close connection to LDAP server
  370. */
  371. function close()
  372. {
  373. if ($this->conn)
  374. {
  375. $this->_debug("C: Close");
  376. ldap_unbind($this->conn);
  377. $this->conn = null;
  378. }
  379. }
  380. /**
  381. * Returns address book name
  382. *
  383. * @return string Address book name
  384. */
  385. function get_name()
  386. {
  387. return $this->prop['name'];
  388. }
  389. /**
  390. * Set internal sort settings
  391. *
  392. * @param string $sort_col Sort column
  393. * @param string $sort_order Sort order
  394. */
  395. function set_sort_order($sort_col, $sort_order = null)
  396. {
  397. if ($this->coltypes[$sort_col]['attributes'])
  398. $this->sort_col = $this->coltypes[$sort_col]['attributes'][0];
  399. }
  400. /**
  401. * Save a search string for future listings
  402. *
  403. * @param string $filter Filter string
  404. */
  405. function set_search_set($filter)
  406. {
  407. $this->filter = $filter;
  408. }
  409. /**
  410. * Getter for saved search properties
  411. *
  412. * @return mixed Search properties used by this class
  413. */
  414. function get_search_set()
  415. {
  416. return $this->filter;
  417. }
  418. /**
  419. * Reset all saved results and search parameters
  420. */
  421. function reset()
  422. {
  423. $this->result = null;
  424. $this->ldap_result = null;
  425. $this->filter = '';
  426. }
  427. /**
  428. * List the current set of contact records
  429. *
  430. * @param array List of cols to show
  431. * @param int Only return this number of records
  432. *
  433. * @return array Indexed list of contact records, each a hash array
  434. */
  435. function list_records($cols=null, $subset=0)
  436. {
  437. if ($this->prop['searchonly'] && empty($this->filter) && !$this->group_id)
  438. {
  439. $this->result = new rcube_result_set(0);
  440. $this->result->searchonly = true;
  441. return $this->result;
  442. }
  443. // fetch group members recursively
  444. if ($this->group_id && $this->group_data['dn'])
  445. {
  446. $entries = $this->list_group_members($this->group_data['dn']);
  447. // make list of entries unique and sort it
  448. $seen = array();
  449. foreach ($entries as $i => $rec) {
  450. if ($seen[$rec['dn']]++)
  451. unset($entries[$i]);
  452. }
  453. usort($entries, array($this, '_entry_sort_cmp'));
  454. $entries['count'] = count($entries);
  455. $this->result = new rcube_result_set($entries['count'], ($this->list_page-1) * $this->page_size);
  456. }
  457. else
  458. {
  459. // add general filter to query
  460. if (!empty($this->prop['filter']) && empty($this->filter))
  461. $this->set_search_set($this->prop['filter']);
  462. // exec LDAP search if no result resource is stored
  463. if ($this->conn && !$this->ldap_result)
  464. $this->_exec_search();
  465. // count contacts for this user
  466. $this->result = $this->count();
  467. // we have a search result resource
  468. if ($this->ldap_result && $this->result->count > 0)
  469. {
  470. // sorting still on the ldap server
  471. if ($this->sort_col && $this->prop['scope'] !== 'base' && !$this->vlv_active)
  472. ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
  473. // get all entries from the ldap server
  474. $entries = ldap_get_entries($this->conn, $this->ldap_result);
  475. }
  476. } // end else
  477. // start and end of the page
  478. $start_row = $this->vlv_active ? 0 : $this->result->first;
  479. $start_row = $subset < 0 ? $start_row + $this->page_size + $subset : $start_row;
  480. $last_row = $this->result->first + $this->page_size;
  481. $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
  482. // filter entries for this page
  483. for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
  484. $this->result->add($this->_ldap2result($entries[$i]));
  485. return $this->result;
  486. }
  487. /**
  488. * Get all members of the given group
  489. *
  490. * @param string Group DN
  491. * @param array Group entries (if called recursively)
  492. * @return array Accumulated group members
  493. */
  494. function list_group_members($dn, $count = false, $entries = null)
  495. {
  496. $group_members = array();
  497. // fetch group object
  498. if (empty($entries)) {
  499. $result = @ldap_read($this->conn, $dn, '(objectClass=*)', array('dn','objectClass','member','uniqueMember','memberURL'));
  500. if ($result === false)
  501. {
  502. $this->_debug("S: ".ldap_error($this->conn));
  503. return $group_members;
  504. }
  505. $entries = @ldap_get_entries($this->conn, $result);
  506. }
  507. for ($i=0; $i < $entries['count']; $i++)
  508. {
  509. $entry = $entries[$i];
  510. if (empty($entry['objectclass']))
  511. continue;
  512. foreach ((array)$entry['objectclass'] as $objectclass)
  513. {
  514. switch (strtolower($objectclass)) {
  515. case "group":
  516. case "groupofnames":
  517. case "kolabgroupofnames":
  518. $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'member', $count));
  519. break;
  520. case "groupofuniquenames":
  521. case "kolabgroupofuniquenames":
  522. $group_members = array_merge($group_members, $this->_list_group_members($dn, $entry, 'uniquemember', $count));
  523. break;
  524. case "groupofurls":
  525. $group_members = array_merge($group_members, $this->_list_group_memberurl($dn, $entry, $count));
  526. break;
  527. }
  528. }
  529. if ($this->prop['sizelimit'] && count($group_members) > $this->prop['sizelimit'])
  530. break;
  531. }
  532. return array_filter($group_members);
  533. }
  534. /**
  535. * Fetch members of the given group entry from server
  536. *
  537. * @param string Group DN
  538. * @param array Group entry
  539. * @param string Member attribute to use
  540. * @return array Accumulated group members
  541. */
  542. private function _list_group_members($dn, $entry, $attr, $count)
  543. {
  544. // Use the member attributes to return an array of member ldap objects
  545. // NOTE that the member attribute is supposed to contain a DN
  546. $group_members = array();
  547. if (empty($entry[$attr]))
  548. return $group_members;
  549. // read these attributes for all members
  550. $attrib = $count ? array('dn') : array_values($this->fieldmap);
  551. $attrib[] = 'objectClass';
  552. $attrib[] = 'member';
  553. $attrib[] = 'uniqueMember';
  554. $attrib[] = 'memberURL';
  555. for ($i=0; $i < $entry[$attr]['count']; $i++)
  556. {
  557. if (empty($entry[$attr][$i]))
  558. continue;
  559. $result = @ldap_read($this->conn, $entry[$attr][$i], '(objectclass=*)',
  560. $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit']);
  561. $members = @ldap_get_entries($this->conn, $result);
  562. if ($members == false)
  563. {
  564. $this->_debug("S: ".ldap_error($this->conn));
  565. $members = array();
  566. }
  567. // for nested groups, call recursively
  568. $nested_group_members = $this->list_group_members($entry[$attr][$i], $count, $members);
  569. unset($members['count']);
  570. $group_members = array_merge($group_members, array_filter($members), $nested_group_members);
  571. }
  572. return $group_members;
  573. }
  574. /**
  575. * List members of group class groupOfUrls
  576. *
  577. * @param string Group DN
  578. * @param array Group entry
  579. * @param boolean True if only used for counting
  580. * @return array Accumulated group members
  581. */
  582. private function _list_group_memberurl($dn, $entry, $count)
  583. {
  584. $group_members = array();
  585. for ($i=0; $i < $entry['memberurl']['count']; $i++)
  586. {
  587. // extract components from url
  588. if (!preg_match('!ldap:///([^\?]+)\?\?(\w+)\?(.*)$!', $entry['memberurl'][$i], $m))
  589. continue;
  590. // add search filter if any
  591. $filter = $this->filter ? '(&(' . $m[3] . ')(' . $this->filter . '))' : $m[3];
  592. $func = $m[2] == 'sub' ? 'ldap_search' : ($m[2] == 'base' ? 'ldap_read' : 'ldap_list');
  593. $attrib = $count ? array('dn') : array_values($this->fieldmap);
  594. if ($result = @$func($this->conn, $m[1], $filter,
  595. $attrib, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
  596. ) {
  597. $this->_debug("S: ".ldap_count_entries($this->conn, $result)." record(s) for ".$m[1]);
  598. }
  599. else {
  600. $this->_debug("S: ".ldap_error($this->conn));
  601. return $group_members;
  602. }
  603. $entries = @ldap_get_entries($this->conn, $result);
  604. for ($j = 0; $j < $entries['count']; $j++)
  605. {
  606. if ($nested_group_members = $this->list_group_members($entries[$j]['dn'], $count))
  607. $group_members = array_merge($group_members, $nested_group_members);
  608. else
  609. $group_members[] = $entries[$j];
  610. }
  611. }
  612. return $group_members;
  613. }
  614. /**
  615. * Callback for sorting entries
  616. */
  617. function _entry_sort_cmp($a, $b)
  618. {
  619. return strcmp($a[$this->sort_col][0], $b[$this->sort_col][0]);
  620. }
  621. /**
  622. * Search contacts
  623. *
  624. * @param mixed $fields The field name of array of field names to search in
  625. * @param mixed $value Search value (or array of values when $fields is array)
  626. * @param int $mode Matching mode:
  627. * 0 - partial (*abc*),
  628. * 1 - strict (=),
  629. * 2 - prefix (abc*)
  630. * @param boolean $select True if results are requested, False if count only
  631. * @param boolean $nocount (Not used)
  632. * @param array $required List of fields that cannot be empty
  633. *
  634. * @return array Indexed list of contact records and 'count' value
  635. */
  636. function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array())
  637. {
  638. $mode = intval($mode);
  639. // special treatment for ID-based search
  640. if ($fields == 'ID' || $fields == $this->primary_key)
  641. {
  642. $ids = !is_array($value) ? explode(',', $value) : $value;
  643. $result = new rcube_result_set();
  644. foreach ($ids as $id)
  645. {
  646. if ($rec = $this->get_record($id, true))
  647. {
  648. $result->add($rec);
  649. $result->count++;
  650. }
  651. }
  652. return $result;
  653. }
  654. // use VLV pseudo-search for autocompletion
  655. $rcube = rcube::get_instance();
  656. $list_fields = $rcube->config->get('contactlist_fields');
  657. if ($this->prop['vlv_search'] && $this->conn && join(',', (array)$fields) == join(',', $list_fields))
  658. {
  659. // add general filter to query
  660. if (!empty($this->prop['filter']) && empty($this->filter))
  661. $this->set_search_set($this->prop['filter']);
  662. // set VLV controls with encoded search string
  663. $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size, $value);
  664. $function = $this->_scope2func($this->prop['scope']);
  665. $this->ldap_result = @$function($this->conn, $this->base_dn, $this->filter ? $this->filter : '(objectclass=*)',
  666. array_values($this->fieldmap), 0, $this->page_size, (int)$this->prop['timelimit']);
  667. $this->result = new rcube_result_set(0);
  668. if (!$this->ldap_result) {
  669. $this->_debug("S: ".ldap_error($this->conn));
  670. return $this->result;
  671. }
  672. $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
  673. // get all entries of this page and post-filter those that really match the query
  674. $search = mb_strtolower($value);
  675. $entries = ldap_get_entries($this->conn, $this->ldap_result);
  676. for ($i = 0; $i < $entries['count']; $i++) {
  677. $rec = $this->_ldap2result($entries[$i]);
  678. foreach ($fields as $f) {
  679. foreach ((array)$rec[$f] as $val) {
  680. if ($this->compare_search_value($f, $val, $search, $mode)) {
  681. $this->result->add($rec);
  682. $this->result->count++;
  683. break 2;
  684. }
  685. }
  686. }
  687. }
  688. return $this->result;
  689. }
  690. // use AND operator for advanced searches
  691. $filter = is_array($value) ? '(&' : '(|';
  692. // set wildcards
  693. $wp = $ws = '';
  694. if (!empty($this->prop['fuzzy_search']) && $mode != 1) {
  695. $ws = '*';
  696. if (!$mode) {
  697. $wp = '*';
  698. }
  699. }
  700. if ($fields == '*')
  701. {
  702. // search_fields are required for fulltext search
  703. if (empty($this->prop['search_fields']))
  704. {
  705. $this->set_error(self::ERROR_SEARCH, 'nofulltextsearch');
  706. $this->result = new rcube_result_set();
  707. return $this->result;
  708. }
  709. if (is_array($this->prop['search_fields']))
  710. {
  711. foreach ($this->prop['search_fields'] as $field) {
  712. $filter .= "($field=$wp" . $this->_quote_string($value) . "$ws)";
  713. }
  714. }
  715. }
  716. else
  717. {
  718. foreach ((array)$fields as $idx => $field) {
  719. $val = is_array($value) ? $value[$idx] : $value;
  720. if ($attrs = $this->_map_field($field)) {
  721. if (count($attrs) > 1)
  722. $filter .= '(|';
  723. foreach ($attrs as $f)
  724. $filter .= "($f=$wp" . $this->_quote_string($val) . "$ws)";
  725. if (count($attrs) > 1)
  726. $filter .= ')';
  727. }
  728. }
  729. }
  730. $filter .= ')';
  731. // add required (non empty) fields filter
  732. $req_filter = '';
  733. foreach ((array)$required as $field) {
  734. if ($attrs = $this->_map_field($field)) {
  735. if (count($attrs) > 1)
  736. $req_filter .= '(|';
  737. foreach ($attrs as $f)
  738. $req_filter .= "($f=*)";
  739. if (count($attrs) > 1)
  740. $req_filter .= ')';
  741. }
  742. }
  743. if (!empty($req_filter))
  744. $filter = '(&' . $req_filter . $filter . ')';
  745. // avoid double-wildcard if $value is empty
  746. $filter = preg_replace('/\*+/', '*', $filter);
  747. // add general filter to query
  748. if (!empty($this->prop['filter']))
  749. $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
  750. // set filter string and execute search
  751. $this->set_search_set($filter);
  752. $this->_exec_search();
  753. if ($select)
  754. $this->list_records();
  755. else
  756. $this->result = $this->count();
  757. return $this->result;
  758. }
  759. /**
  760. * Count number of available contacts in database
  761. *
  762. * @return object rcube_result_set Resultset with values for 'count' and 'first'
  763. */
  764. function count()
  765. {
  766. $count = 0;
  767. if ($this->conn && $this->ldap_result) {
  768. $count = $this->vlv_active ? $this->vlv_count : ldap_count_entries($this->conn, $this->ldap_result);
  769. }
  770. else if ($this->group_id && $this->group_data['dn']) {
  771. $count = count($this->list_group_members($this->group_data['dn'], true));
  772. }
  773. else if ($this->conn) {
  774. // We have a connection but no result set, attempt to get one.
  775. if (empty($this->filter)) {
  776. // The filter is not set, set it.
  777. $this->filter = $this->prop['filter'];
  778. }
  779. $count = (int) $this->_exec_search(true);
  780. }
  781. return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
  782. }
  783. /**
  784. * Return the last result set
  785. *
  786. * @return object rcube_result_set Current resultset or NULL if nothing selected yet
  787. */
  788. function get_result()
  789. {
  790. return $this->result;
  791. }
  792. /**
  793. * Get a specific contact record
  794. *
  795. * @param mixed Record identifier
  796. * @param boolean Return as associative array
  797. *
  798. * @return mixed Hash array or rcube_result_set with all record fields
  799. */
  800. function get_record($dn, $assoc=false)
  801. {
  802. $res = $this->result = null;
  803. if ($this->conn && $dn)
  804. {
  805. $dn = self::dn_decode($dn);
  806. $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
  807. if ($ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap))) {
  808. $this->_debug("S: OK");
  809. $entry = ldap_first_entry($this->conn, $ldap_result);
  810. if ($entry && ($rec = ldap_get_attributes($this->conn, $entry))) {
  811. $rec = array_change_key_case($rec, CASE_LOWER);
  812. }
  813. }
  814. else {
  815. $this->_debug("S: ".ldap_error($this->conn));
  816. }
  817. // Use ldap_list to get subentries like country (c) attribute (#1488123)
  818. if (!empty($rec) && $this->sub_filter) {
  819. if ($entries = $this->ldap_list($dn, $this->sub_filter, array_keys($this->prop['sub_fields']))) {
  820. foreach ($entries as $entry) {
  821. $lrec = array_change_key_case($entry, CASE_LOWER);
  822. $rec = array_merge($lrec, $rec);
  823. }
  824. }
  825. }
  826. if (!empty($rec)) {
  827. // Add in the dn for the entry.
  828. $rec['dn'] = $dn;
  829. $res = $this->_ldap2result($rec);
  830. $this->result = new rcube_result_set();
  831. $this->result->add($res);
  832. }
  833. }
  834. return $assoc ? $res : $this->result;
  835. }
  836. /**
  837. * Check the given data before saving.
  838. * If input not valid, the message to display can be fetched using get_error()
  839. *
  840. * @param array Assoziative array with data to save
  841. * @param boolean Try to fix/complete record automatically
  842. * @return boolean True if input is valid, False if not.
  843. */
  844. public function validate(&$save_data, $autofix = false)
  845. {
  846. // validate e-mail addresses
  847. if (!parent::validate($save_data, $autofix)) {
  848. return false;
  849. }
  850. // check for name input
  851. if (empty($save_data['name'])) {
  852. $this->set_error(self::ERROR_VALIDATE, 'nonamewarning');
  853. return false;
  854. }
  855. // Verify that the required fields are set.
  856. $missing = null;
  857. $ldap_data = $this->_map_data($save_data);
  858. foreach ($this->prop['required_fields'] as $fld) {
  859. if (!isset($ldap_data[$fld]) || $ldap_data[$fld] === '') {
  860. $missing[$fld] = 1;
  861. }
  862. }
  863. if ($missing) {
  864. // try to complete record automatically
  865. if ($autofix) {
  866. $sn_field = $this->fieldmap['surname'];
  867. $fn_field = $this->fieldmap['firstname'];
  868. $mail_field = $this->fieldmap['email'];
  869. // try to extract surname and firstname from displayname
  870. $reverse_map = array_flip($this->fieldmap);
  871. $name_parts = preg_split('/[\s,.]+/', $save_data['name']);
  872. if ($sn_field && $missing[$sn_field]) {
  873. $save_data['surname'] = array_pop($name_parts);
  874. unset($missing[$sn_field]);
  875. }
  876. if ($fn_field && $missing[$fn_field]) {
  877. $save_data['firstname'] = array_shift($name_parts);
  878. unset($missing[$fn_field]);
  879. }
  880. // try to fix missing e-mail, very often on import
  881. // from vCard we have email:other only defined
  882. if ($mail_field && $missing[$mail_field]) {
  883. $emails = $this->get_col_values('email', $save_data, true);
  884. if (!empty($emails) && ($email = array_shift($emails))) {
  885. $save_data['email'] = $email;
  886. unset($missing[$mail_field]);
  887. }
  888. }
  889. }
  890. // TODO: generate message saying which fields are missing
  891. if (!empty($missing)) {
  892. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  893. return false;
  894. }
  895. }
  896. return true;
  897. }
  898. /**
  899. * Create a new contact record
  900. *
  901. * @param array Hash array with save data
  902. *
  903. * @return encoded record ID on success, False on error
  904. */
  905. function insert($save_cols)
  906. {
  907. // Map out the column names to their LDAP ones to build the new entry.
  908. $newentry = $this->_map_data($save_cols);
  909. $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
  910. // add automatically generated attributes
  911. $this->add_autovalues($newentry);
  912. // Verify that the required fields are set.
  913. $missing = null;
  914. foreach ($this->prop['required_fields'] as $fld) {
  915. if (!isset($newentry[$fld])) {
  916. $missing[] = $fld;
  917. }
  918. }
  919. // abort process if requiered fields are missing
  920. // TODO: generate message saying which fields are missing
  921. if ($missing) {
  922. $this->set_error(self::ERROR_VALIDATE, 'formincomplete');
  923. return false;
  924. }
  925. // Build the new entries DN.
  926. $dn = $this->prop['LDAP_rdn'].'='.$this->_quote_string($newentry[$this->prop['LDAP_rdn']], true).','.$this->base_dn;
  927. // Remove attributes that need to be added separately (child objects)
  928. $xfields = array();
  929. if (!empty($this->prop['sub_fields']) && is_array($this->prop['sub_fields'])) {
  930. foreach ($this->prop['sub_fields'] as $xf => $xclass) {
  931. if (!empty($newentry[$xf])) {
  932. $xfields[$xf] = $newentry[$xf];
  933. unset($newentry[$xf]);
  934. }
  935. }
  936. }
  937. if (!$this->ldap_add($dn, $newentry)) {
  938. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  939. return false;
  940. }
  941. foreach ($xfields as $xidx => $xf) {
  942. $xdn = $xidx.'='.$this->_quote_string($xf).','.$dn;
  943. $xf = array(
  944. $xidx => $xf,
  945. 'objectClass' => (array) $this->prop['sub_fields'][$xidx],
  946. );
  947. $this->ldap_add($xdn, $xf);
  948. }
  949. $dn = self::dn_encode($dn);
  950. // add new contact to the selected group
  951. if ($this->group_id)
  952. $this->add_to_group($this->group_id, $dn);
  953. return $dn;
  954. }
  955. /**
  956. * Update a specific contact record
  957. *
  958. * @param mixed Record identifier
  959. * @param array Hash array with save data
  960. *
  961. * @return boolean True on success, False on error
  962. */
  963. function update($id, $save_cols)
  964. {
  965. $record = $this->get_record($id, true);
  966. $newdata = array();
  967. $replacedata = array();
  968. $deletedata = array();
  969. $subdata = array();
  970. $subdeldata = array();
  971. $subnewdata = array();
  972. $ldap_data = $this->_map_data($save_cols);
  973. $old_data = $record['_raw_attrib'];
  974. // special handling of photo col
  975. if ($photo_fld = $this->fieldmap['photo']) {
  976. // undefined means keep old photo
  977. if (!array_key_exists('photo', $save_cols)) {
  978. $ldap_data[$photo_fld] = $record['photo'];
  979. }
  980. }
  981. foreach ($this->fieldmap as $col => $fld) {
  982. if ($fld) {
  983. $val = $ldap_data[$fld];
  984. $old = $old_data[$fld];
  985. // remove empty array values
  986. if (is_array($val))
  987. $val = array_filter($val);
  988. // $this->_map_data() result and _raw_attrib use different format
  989. // make sure comparing array with one element with a string works as expected
  990. if (is_array($old) && count($old) == 1 && !is_array($val)) {
  991. $old = array_pop($old);
  992. }
  993. if (is_array($val) && count($val) == 1 && !is_array($old)) {
  994. $val = array_pop($val);
  995. }
  996. // Subentries must be handled separately
  997. if (!empty($this->prop['sub_fields']) && isset($this->prop['sub_fields'][$fld])) {
  998. if ($old != $val) {
  999. if ($old !== null) {
  1000. $subdeldata[$fld] = $old;
  1001. }
  1002. if ($val) {
  1003. $subnewdata[$fld] = $val;
  1004. }
  1005. }
  1006. else if ($old !== null) {
  1007. $subdata[$fld] = $old;
  1008. }
  1009. continue;
  1010. }
  1011. // The field does exist compare it to the ldap record.
  1012. if ($old != $val) {
  1013. // Changed, but find out how.
  1014. if ($old === null) {
  1015. // Field was not set prior, need to add it.
  1016. $newdata[$fld] = $val;
  1017. }
  1018. else if ($val == '') {
  1019. // Field supplied is empty, verify that it is not required.
  1020. if (!in_array($fld, $this->prop['required_fields'])) {
  1021. // ...It is not, safe to clear.
  1022. // #1488420: Workaround "ldap_mod_del(): Modify: Inappropriate matching in..."
  1023. // jpegPhoto attribute require an array() here. It looks to me that it works for other attribs too
  1024. $deletedata[$fld] = array();
  1025. //$deletedata[$fld] = $old_data[$fld];
  1026. }
  1027. }
  1028. else {
  1029. // The data was modified, save it out.
  1030. $replacedata[$fld] = $val;
  1031. }
  1032. } // end if
  1033. } // end if
  1034. } // end foreach
  1035. // console($old_data, $ldap_data, '----', $newdata, $replacedata, $deletedata, '----', $subdata, $subnewdata, $subdeldata);
  1036. $dn = self::dn_decode($id);
  1037. // Update the entry as required.
  1038. if (!empty($deletedata)) {
  1039. // Delete the fields.
  1040. if (!$this->ldap_mod_del($dn, $deletedata)) {
  1041. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1042. return false;
  1043. }
  1044. } // end if
  1045. if (!empty($replacedata)) {
  1046. // Handle RDN change
  1047. if ($replacedata[$this->prop['LDAP_rdn']]) {
  1048. $newdn = $this->prop['LDAP_rdn'].'='
  1049. .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true)
  1050. .','.$this->base_dn;
  1051. if ($dn != $newdn) {
  1052. $newrdn = $this->prop['LDAP_rdn'].'='
  1053. .$this->_quote_string($replacedata[$this->prop['LDAP_rdn']], true);
  1054. unset($replacedata[$this->prop['LDAP_rdn']]);
  1055. }
  1056. }
  1057. // Replace the fields.
  1058. if (!empty($replacedata)) {
  1059. if (!$this->ldap_mod_replace($dn, $replacedata)) {
  1060. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1061. return false;
  1062. }
  1063. }
  1064. } // end if
  1065. // RDN change, we need to remove all sub-entries
  1066. if (!empty($newrdn)) {
  1067. $subdeldata = array_merge($subdeldata, $subdata);
  1068. $subnewdata = array_merge($subnewdata, $subdata);
  1069. }
  1070. // remove sub-entries
  1071. if (!empty($subdeldata)) {
  1072. foreach ($subdeldata as $fld => $val) {
  1073. $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
  1074. if (!$this->ldap_delete($subdn)) {
  1075. return false;
  1076. }
  1077. }
  1078. }
  1079. if (!empty($newdata)) {
  1080. // Add the fields.
  1081. if (!$this->ldap_mod_add($dn, $newdata)) {
  1082. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1083. return false;
  1084. }
  1085. } // end if
  1086. // Handle RDN change
  1087. if (!empty($newrdn)) {
  1088. if (!$this->ldap_rename($dn, $newrdn, null, true)) {
  1089. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1090. return false;
  1091. }
  1092. $dn = self::dn_encode($dn);
  1093. $newdn = self::dn_encode($newdn);
  1094. // change the group membership of the contact
  1095. if ($this->groups) {
  1096. $group_ids = $this->get_record_groups($dn);
  1097. foreach ($group_ids as $group_id)
  1098. {
  1099. $this->remove_from_group($group_id, $dn);
  1100. $this->add_to_group($group_id, $newdn);
  1101. }
  1102. }
  1103. $dn = self::dn_decode($newdn);
  1104. }
  1105. // add sub-entries
  1106. if (!empty($subnewdata)) {
  1107. foreach ($subnewdata as $fld => $val) {
  1108. $subdn = $fld.'='.$this->_quote_string($val).','.$dn;
  1109. $xf = array(
  1110. $fld => $val,
  1111. 'objectClass' => (array) $this->prop['sub_fields'][$fld],
  1112. );
  1113. $this->ldap_add($subdn, $xf);
  1114. }
  1115. }
  1116. return $newdn ? $newdn : true;
  1117. }
  1118. /**
  1119. * Mark one or more contact records as deleted
  1120. *
  1121. * @param array Record identifiers
  1122. * @param boolean Remove record(s) irreversible (unsupported)
  1123. *
  1124. * @return boolean True on success, False on error
  1125. */
  1126. function delete($ids, $force=true)
  1127. {
  1128. if (!is_array($ids)) {
  1129. // Not an array, break apart the encoded DNs.
  1130. $ids = explode(',', $ids);
  1131. } // end if
  1132. foreach ($ids as $id) {
  1133. $dn = self::dn_decode($id);
  1134. // Need to delete all sub-entries first
  1135. if ($this->sub_filter) {
  1136. if ($entries = $this->ldap_list($dn, $this->sub_filter)) {
  1137. foreach ($entries as $entry) {
  1138. if (!$this->ldap_delete($entry['dn'])) {
  1139. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1140. return false;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. // Delete the record.
  1146. if (!$this->ldap_delete($dn)) {
  1147. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1148. return false;
  1149. }
  1150. // remove contact from all groups where he was member
  1151. if ($this->groups) {
  1152. $dn = self::dn_encode($dn);
  1153. $group_ids = $this->get_record_groups($dn);
  1154. foreach ($group_ids as $group_id) {
  1155. $this->remove_from_group($group_id, $dn);
  1156. }
  1157. }
  1158. } // end foreach
  1159. return count($ids);
  1160. }
  1161. /**
  1162. * Remove all contact records
  1163. */
  1164. function delete_all()
  1165. {
  1166. //searching for contact entries
  1167. $dn_list = $this->ldap_list($this->base_dn, $this->prop['filter'] ? $this->prop['filter'] : '(objectclass=*)');
  1168. if (!empty($dn_list)) {
  1169. foreach ($dn_list as $idx => $entry) {
  1170. $dn_list[$idx] = self::dn_encode($entry['dn']);
  1171. }
  1172. $this->delete($dn_list);
  1173. }
  1174. }
  1175. /**
  1176. * Generate missing attributes as configured
  1177. *
  1178. * @param array LDAP record attributes
  1179. */
  1180. protected function add_autovalues(&$attrs)
  1181. {
  1182. $attrvals = array();
  1183. foreach ($attrs as $k => $v) {
  1184. $attrvals['{'.$k.'}'] = is_array($v) ? $v[0] : $v;
  1185. }
  1186. foreach ((array)$this->prop['aut…

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