PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/program/include/rcube_ldap.php

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

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