PageRenderTime 79ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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. $templ = preg_replace('/\{\w+\}/', '', strtr($templ, $attrvals));
  1196. if (strpos($templ, '(') !== false)
  1197. $attrs[$lf] = eval("return ($templ);");
  1198. else
  1199. $attrs[$lf] = $templ;
  1200. }
  1201. }
  1202. }
  1203. /**
  1204. * Execute the LDAP search based on the stored credentials
  1205. */
  1206. private function _exec_search($count = false)
  1207. {
  1208. if ($this->ready)
  1209. {
  1210. $filter = $this->filter ? $this->filter : '(objectclass=*)';
  1211. $function = $this->_scope2func($this->prop['scope'], $ns_function);
  1212. $this->_debug("C: Search [$filter][dn: $this->base_dn]");
  1213. // when using VLV, we get the total count by...
  1214. if (!$count && $function != 'ldap_read' && $this->prop['vlv'] && !$this->group_id) {
  1215. // ...either reading numSubOrdinates attribute
  1216. if ($this->prop['numsub_filter'] && ($result_count = @$ns_function($this->conn, $this->base_dn, $this->prop['numsub_filter'], array('numSubOrdinates'), 0, 0, 0))) {
  1217. $counts = ldap_get_entries($this->conn, $result_count);
  1218. for ($this->vlv_count = $j = 0; $j < $counts['count']; $j++)
  1219. $this->vlv_count += $counts[$j]['numsubordinates'][0];
  1220. $this->_debug("D: total numsubordinates = " . $this->vlv_count);
  1221. }
  1222. else if (!function_exists('ldap_parse_virtuallist_control')) // ...or by fetching all records dn and count them
  1223. $this->vlv_count = $this->_exec_search(true);
  1224. $this->vlv_active = $this->_vlv_set_controls($this->prop, $this->list_page, $this->page_size);
  1225. }
  1226. // only fetch dn for count (should keep the payload low)
  1227. $attrs = $count ? array('dn') : array_values($this->fieldmap);
  1228. if ($this->ldap_result = @$function($this->conn, $this->base_dn, $filter,
  1229. $attrs, 0, (int)$this->prop['sizelimit'], (int)$this->prop['timelimit'])
  1230. ) {
  1231. // when running on a patched PHP we can use the extended functions to retrieve the total count from the LDAP search result
  1232. if ($this->vlv_active && function_exists('ldap_parse_virtuallist_control')) {
  1233. if (ldap_parse_result($this->conn, $this->ldap_result,
  1234. $errcode, $matcheddn, $errmsg, $referrals, $serverctrls)
  1235. ) {
  1236. ldap_parse_virtuallist_control($this->conn, $serverctrls,
  1237. $last_offset, $this->vlv_count, $vresult);
  1238. $this->_debug("S: VLV result: last_offset=$last_offset; content_count=$this->vlv_count");
  1239. }
  1240. else {
  1241. $this->_debug("S: ".($errmsg ? $errmsg : ldap_error($this->conn)));
  1242. }
  1243. }
  1244. $entries_count = ldap_count_entries($this->conn, $this->ldap_result);
  1245. $this->_debug("S: $entries_count record(s)");
  1246. return $count ? $entries_count : true;
  1247. }
  1248. else {
  1249. $this->_debug("S: ".ldap_error($this->conn));
  1250. }
  1251. }
  1252. return false;
  1253. }
  1254. /**
  1255. * Choose the right PHP function according to scope property
  1256. */
  1257. private function _scope2func($scope, &$ns_function = null)
  1258. {
  1259. switch ($scope) {
  1260. case 'sub':
  1261. $function = $ns_function = 'ldap_search';
  1262. break;
  1263. case 'base':
  1264. $function = $ns_function = 'ldap_read';
  1265. break;
  1266. default:
  1267. $function = 'ldap_list';
  1268. $ns_function = 'ldap_read';
  1269. break;
  1270. }
  1271. return $function;
  1272. }
  1273. /**
  1274. * Set server controls for Virtual List View (paginated listing)
  1275. */
  1276. private function _vlv_set_controls($prop, $list_page, $page_size, $search = null)
  1277. {
  1278. $sort_ctrl = array('oid' => "1.2.840.113556.1.4.473", 'value' => $this->_sort_ber_encode((array)$prop['sort']));
  1279. $vlv_ctrl = array('oid' => "2.16.840.1.113730.3.4.9", 'value' => $this->_vlv_ber_encode(($offset = ($list_page-1) * $page_size + 1), $page_size, $search), 'iscritical' => true);
  1280. $sort = (array)$prop['sort'];
  1281. $this->_debug("C: set controls sort=" . join(' ', unpack('H'.(strlen($sort_ctrl['value'])*2), $sort_ctrl['value'])) . " ($sort[0]);"
  1282. . " vlv=" . join(' ', (unpack('H'.(strlen($vlv_ctrl['value'])*2), $vlv_ctrl['value']))) . " ($offset/$page_size)");
  1283. if (!ldap_set_option($this->conn, LDAP_OPT_SERVER_CONTROLS, array($sort_ctrl, $vlv_ctrl))) {
  1284. $this->_debug("S: ".ldap_error($this->conn));
  1285. $this->set_error(self::ERROR_SEARCH, 'vlvnotsupported');
  1286. return false;
  1287. }
  1288. return true;
  1289. }
  1290. /**
  1291. * Converts LDAP entry into an array
  1292. */
  1293. private function _ldap2result($rec)
  1294. {
  1295. $out = array();
  1296. if ($rec['dn'])
  1297. $out[$this->primary_key] = self::dn_encode($rec['dn']);
  1298. foreach ($this->fieldmap as $rf => $lf)
  1299. {
  1300. for ($i=0; $i < $rec[$lf]['count']; $i++) {
  1301. if (!($value = $rec[$lf][$i]))
  1302. continue;
  1303. list($col, $subtype) = explode(':', $rf);
  1304. $out['_raw_attrib'][$lf][$i] = $value;
  1305. if ($col == 'email' && $this->mail_domain && !strpos($value, '@'))
  1306. $out[$rf][] = sprintf('%s@%s', $value, $this->mail_domain);
  1307. else if (in_array($col, array('street','zipcode','locality','country','region')))
  1308. $out['address'.($subtype?':':'').$subtype][$i][$col] = $value;
  1309. else if ($col == 'address' && strpos($value, '$') !== false) // address data is represented as string separated with $
  1310. list($out[$rf][$i]['street'], $out[$rf][$i]['locality'], $out[$rf][$i]['zipcode'], $out[$rf][$i]['country']) = explode('$', $value);
  1311. else if ($rec[$lf]['count'] > 1)
  1312. $out[$rf][] = $value;
  1313. else
  1314. $out[$rf] = $value;
  1315. }
  1316. // Make sure name fields aren't arrays (#1488108)
  1317. if (is_array($out[$rf]) && in_array($rf, array('name', 'surname', 'firstname', 'middlename', 'nickname'))) {
  1318. $out[$rf] = $out['_raw_attrib'][$lf] = $out[$rf][0];
  1319. }
  1320. }
  1321. return $out;
  1322. }
  1323. /**
  1324. * Return LDAP attribute(s) for the given field
  1325. */
  1326. private function _map_field($field)
  1327. {
  1328. return (array)$this->coltypes[$field]['attributes'];
  1329. }
  1330. /**
  1331. * Convert a record data set into LDAP field attributes
  1332. */
  1333. private function _map_data($save_cols)
  1334. {
  1335. // flatten composite fields first
  1336. foreach ($this->coltypes as $col => $colprop) {
  1337. if (is_array($colprop['childs']) && ($values = $this->get_col_values($col, $save_cols, false))) {
  1338. foreach ($values as $subtype => $childs) {
  1339. $subtype = $subtype ? ':'.$subtype : '';
  1340. foreach ($childs as $i => $child_values) {
  1341. foreach ((array)$child_values as $childcol => $value) {
  1342. $save_cols[$childcol.$subtype][$i] = $value;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. // if addresses are to be saved as serialized string, do so
  1348. if (is_array($colprop['serialized'])) {
  1349. foreach ($colprop['serialized'] as $subtype => $delim) {
  1350. $key = $col.':'.$subtype;
  1351. foreach ((array)$save_cols[$key] as $i => $val)
  1352. $save_cols[$key][$i] = join($delim, array($val['street'], $val['locality'], $val['zipcode'], $val['country']));
  1353. }
  1354. }
  1355. }
  1356. $ldap_data = array();
  1357. foreach ($this->fieldmap as $rf => $fld) {
  1358. $val = $save_cols[$rf];
  1359. // check for value in base field (eg.g email instead of email:foo)
  1360. list($col, $subtype) = explode(':', $rf);
  1361. if (!$val && !empty($save_cols[$col])) {
  1362. $val = $save_cols[$col];
  1363. unset($save_cols[$col]); // only use this value once
  1364. }
  1365. else if (!$val && !$subtype) { // extract values from subtype cols
  1366. $val = $this->get_col_values($col, $save_cols, true);
  1367. }
  1368. if (is_array($val))
  1369. $val = array_filter($val); // remove empty entries
  1370. if ($fld && $val) {
  1371. // The field does exist, add it to the entry.
  1372. $ldap_data[$fld] = $val;
  1373. }
  1374. }
  1375. return $ldap_data;
  1376. }
  1377. /**
  1378. * Returns unified attribute name (resolving aliases)
  1379. */
  1380. private static function _attr_name($namev)
  1381. {
  1382. // list of known attribute aliases
  1383. static $aliases = array(
  1384. 'gn' => 'givenname',
  1385. 'rfc822mailbox' => 'email',
  1386. 'userid' => 'uid',
  1387. 'emailaddress' => 'email',
  1388. 'pkcs9email' => 'email',
  1389. );
  1390. list($name, $limit) = explode(':', $namev, 2);
  1391. $suffix = $limit ? ':'.$limit : '';
  1392. return (isset($aliases[$name]) ? $aliases[$name] : $name) . $suffix;
  1393. }
  1394. /**
  1395. * Prints debug info to the log
  1396. */
  1397. private function _debug($str)
  1398. {
  1399. if ($this->debug) {
  1400. rcube::write_log('ldap', $str);
  1401. }
  1402. }
  1403. /**
  1404. * Activate/deactivate debug mode
  1405. *
  1406. * @param boolean $dbg True if LDAP commands should be logged
  1407. * @access public
  1408. */
  1409. function set_debug($dbg = true)
  1410. {
  1411. $this->debug = $dbg;
  1412. }
  1413. /**
  1414. * Quotes attribute value string
  1415. *
  1416. * @param string $str Attribute value
  1417. * @param bool $dn True if the attribute is a DN
  1418. *
  1419. * @return string Quoted string
  1420. */
  1421. private static function _quote_string($str, $dn=false)
  1422. {
  1423. // take firt entry if array given
  1424. if (is_array($str))
  1425. $str = reset($str);
  1426. if ($dn)
  1427. $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
  1428. '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
  1429. else
  1430. $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
  1431. '/'=>'\2f');
  1432. return strtr($str, $replace);
  1433. }
  1434. /**
  1435. * Setter for the current group
  1436. * (empty, has to be re-implemented by extending class)
  1437. */
  1438. function set_group($group_id)
  1439. {
  1440. if ($group_id)
  1441. {
  1442. if (($group_cache = $this->cache->get('groups')) === null)
  1443. $group_cache = $this->_fetch_groups();
  1444. $this->group_id = $group_id;
  1445. $this->group_data = $group_cache[$group_id];
  1446. }
  1447. else
  1448. {
  1449. $this->group_id = 0;
  1450. $this->group_data = null;
  1451. }
  1452. }
  1453. /**
  1454. * List all active contact groups of this source
  1455. *
  1456. * @param string Optional search string to match group name
  1457. * @return array Indexed list of contact groups, each a hash array
  1458. */
  1459. function list_groups($search = null)
  1460. {
  1461. if (!$this->groups)
  1462. return array();
  1463. // use cached list for searching
  1464. $this->cache->expunge();
  1465. if (!$search || ($group_cache = $this->cache->get('groups')) === null)
  1466. $group_cache = $this->_fetch_groups();
  1467. $groups = array();
  1468. if ($search) {
  1469. $search = mb_strtolower($search);
  1470. foreach ($group_cache as $group) {
  1471. if (strpos(mb_strtolower($group['name']), $search) !== false)
  1472. $groups[] = $group;
  1473. }
  1474. }
  1475. else
  1476. $groups = $group_cache;
  1477. return array_values($groups);
  1478. }
  1479. /**
  1480. * Fetch groups from server
  1481. */
  1482. private function _fetch_groups($vlv_page = 0)
  1483. {
  1484. $base_dn = $this->groups_base_dn;
  1485. $filter = $this->prop['groups']['filter'];
  1486. $name_attr = $this->prop['groups']['name_attr'];
  1487. $email_attr = $this->prop['groups']['email_attr'] ? $this->prop['groups']['email_attr'] : 'mail';
  1488. $sort_attrs = $this->prop['groups']['sort'] ? (array)$this->prop['groups']['sort'] : array($name_attr);
  1489. $sort_attr = $sort_attrs[0];
  1490. $this->_debug("C: Search [$filter][dn: $base_dn]");
  1491. // use vlv to list groups
  1492. if ($this->prop['groups']['vlv']) {
  1493. $page_size = 200;
  1494. if (!$this->prop['groups']['sort'])
  1495. $this->prop['groups']['sort'] = $sort_attrs;
  1496. $vlv_active = $this->_vlv_set_controls($this->prop['groups'], $vlv_page+1, $page_size);
  1497. }
  1498. $function = $this->_scope2func($this->prop['groups']['scope'], $ns_function);
  1499. $res = @$function($this->conn, $base_dn, $filter, array_unique(array('dn', 'objectClass', $name_attr, $email_attr, $sort_attr)));
  1500. if ($res === false)
  1501. {
  1502. $this->_debug("S: ".ldap_error($this->conn));
  1503. return array();
  1504. }
  1505. $ldap_data = ldap_get_entries($this->conn, $res);
  1506. $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
  1507. $groups = array();
  1508. $group_sortnames = array();
  1509. $group_count = $ldap_data["count"];
  1510. for ($i=0; $i < $group_count; $i++)
  1511. {
  1512. $group_name = is_array($ldap_data[$i][$name_attr]) ? $ldap_data[$i][$name_attr][0] : $ldap_data[$i][$name_attr];
  1513. $group_id = self::dn_encode($group_name);
  1514. $groups[$group_id]['ID'] = $group_id;
  1515. $groups[$group_id]['dn'] = $ldap_data[$i]['dn'];
  1516. $groups[$group_id]['name'] = $group_name;
  1517. $groups[$group_id]['member_attr'] = $this->get_group_member_attr($ldap_data[$i]['objectclass']);
  1518. // list email attributes of a group
  1519. for ($j=0; $ldap_data[$i][$email_attr] && $j < $ldap_data[$i][$email_attr]['count']; $j++) {
  1520. if (strpos($ldap_data[$i][$email_attr][$j], '@') > 0)
  1521. $groups[$group_id]['email'][] = $ldap_data[$i][$email_attr][$j];
  1522. }
  1523. $group_sortnames[] = mb_strtolower($ldap_data[$i][$sort_attr][0]);
  1524. }
  1525. // recursive call can exit here
  1526. if ($vlv_page > 0)
  1527. return $groups;
  1528. // call recursively until we have fetched all groups
  1529. while ($vlv_active && $group_count == $page_size)
  1530. {
  1531. $next_page = $this->_fetch_groups(++$vlv_page);
  1532. $groups = array_merge($groups, $next_page);
  1533. $group_count = count($next_page);
  1534. }
  1535. // when using VLV the list of groups is already sorted
  1536. if (!$this->prop['groups']['vlv'])
  1537. array_multisort($group_sortnames, SORT_ASC, SORT_STRING, $groups);
  1538. // cache this
  1539. $this->cache->set('groups', $groups);
  1540. return $groups;
  1541. }
  1542. /**
  1543. * Get group properties such as name and email address(es)
  1544. *
  1545. * @param string Group identifier
  1546. * @return array Group properties as hash array
  1547. */
  1548. function get_group($group_id)
  1549. {
  1550. if (($group_cache = $this->cache->get('groups')) === null)
  1551. $group_cache = $this->_fetch_groups();
  1552. $group_data = $group_cache[$group_id];
  1553. unset($group_data['dn'], $group_data['member_attr']);
  1554. return $group_data;
  1555. }
  1556. /**
  1557. * Create a contact group with the given name
  1558. *
  1559. * @param string The group name
  1560. * @return mixed False on error, array with record props in success
  1561. */
  1562. function create_group($group_name)
  1563. {
  1564. $base_dn = $this->groups_base_dn;
  1565. $new_dn = "cn=$group_name,$base_dn";
  1566. $new_gid = self::dn_encode($group_name);
  1567. $member_attr = $this->get_group_member_attr();
  1568. $name_attr = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
  1569. $new_entry = array(
  1570. 'objectClass' => $this->prop['groups']['object_classes'],
  1571. $name_attr => $group_name,
  1572. $member_attr => '',
  1573. );
  1574. if (!$this->ldap_add($new_dn, $new_entry)) {
  1575. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1576. return false;
  1577. }
  1578. $this->cache->remove('groups');
  1579. return array('id' => $new_gid, 'name' => $group_name);
  1580. }
  1581. /**
  1582. * Delete the given group and all linked group members
  1583. *
  1584. * @param string Group identifier
  1585. * @return boolean True on success, false if no data was changed
  1586. */
  1587. function delete_group($group_id)
  1588. {
  1589. if (($group_cache = $this->cache->get('groups')) === null)
  1590. $group_cache = $this->_fetch_groups();
  1591. $base_dn = $this->groups_base_dn;
  1592. $group_name = $group_cache[$group_id]['name'];
  1593. $del_dn = "cn=$group_name,$base_dn";
  1594. if (!$this->ldap_delete($del_dn)) {
  1595. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1596. return false;
  1597. }
  1598. $this->cache->remove('groups');
  1599. return true;
  1600. }
  1601. /**
  1602. * Rename a specific contact group
  1603. *
  1604. * @param string Group identifier
  1605. * @param string New name to set for this group
  1606. * @param string New group identifier (if changed, otherwise don't set)
  1607. * @return boolean New name on success, false if no data was changed
  1608. */
  1609. function rename_group($group_id, $new_name, &$new_gid)
  1610. {
  1611. if (($group_cache = $this->cache->get('groups')) === null)
  1612. $group_cache = $this->_fetch_groups();
  1613. $base_dn = $this->groups_base_dn;
  1614. $group_name = $group_cache[$group_id]['name'];
  1615. $old_dn = "cn=$group_name,$base_dn";
  1616. $new_rdn = "cn=$new_name";
  1617. $new_gid = self::dn_encode($new_name);
  1618. if (!$this->ldap_rename($old_dn, $new_rdn, null, true)) {
  1619. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1620. return false;
  1621. }
  1622. $this->cache->remove('groups');
  1623. return $new_name;
  1624. }
  1625. /**
  1626. * Add the given contact records the a certain group
  1627. *
  1628. * @param string Group identifier
  1629. * @param array List of contact identifiers to be added
  1630. * @return int Number of contacts added
  1631. */
  1632. function add_to_group($group_id, $contact_ids)
  1633. {
  1634. if (($group_cache = $this->cache->get('groups')) === null)
  1635. $group_cache = $this->_fetch_groups();
  1636. if (!is_array($contact_ids))
  1637. $contact_ids = explode(',', $contact_ids);
  1638. $base_dn = $this->groups_base_dn;
  1639. $group_name = $group_cache[$group_id]['name'];
  1640. $member_attr = $group_cache[$group_id]['member_attr'];
  1641. $group_dn = "cn=$group_name,$base_dn";
  1642. $new_attrs = array();
  1643. foreach ($contact_ids as $id)
  1644. $new_attrs[$member_attr][] = self::dn_decode($id);
  1645. if (!$this->ldap_mod_add($group_dn, $new_attrs)) {
  1646. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1647. return 0;
  1648. }
  1649. $this->cache->remove('groups');
  1650. return count($new_attrs['member']);
  1651. }
  1652. /**
  1653. * Remove the given contact records from a certain group
  1654. *
  1655. * @param string Group identifier
  1656. * @param array List of contact identifiers to be removed
  1657. * @return int Number of deleted group members
  1658. */
  1659. function remove_from_group($group_id, $contact_ids)
  1660. {
  1661. if (($group_cache = $this->cache->get('groups')) === null)
  1662. $group_cache = $this->_fetch_groups();
  1663. $base_dn = $this->groups_base_dn;
  1664. $group_name = $group_cache[$group_id]['name'];
  1665. $member_attr = $group_cache[$group_id]['member_attr'];
  1666. $group_dn = "cn=$group_name,$base_dn";
  1667. $del_attrs = array();
  1668. foreach (explode(",", $contact_ids) as $id)
  1669. $del_attrs[$member_attr][] = self::dn_decode($id);
  1670. if (!$this->ldap_mod_del($group_dn, $del_attrs)) {
  1671. $this->set_error(self::ERROR_SAVING, 'errorsaving');
  1672. return 0;
  1673. }
  1674. $this->cache->remove('groups');
  1675. return count($del_attrs['member']);
  1676. }
  1677. /**
  1678. * Get group assignments of a specific contact record
  1679. *
  1680. * @param mixed Record identifier
  1681. *
  1682. * @return array List of assigned groups as ID=>Name pairs
  1683. * @since 0.5-beta
  1684. */
  1685. function get_record_groups($contact_id)
  1686. {
  1687. if (!$this->groups)
  1688. return array();
  1689. $base_dn = $this->groups_base_dn;
  1690. $contact_dn = self::dn_decode($contact_id);
  1691. $name_attr = $this->prop['groups']['name_attr'] ? $this->prop['groups']['name_attr'] : 'cn';
  1692. $member_attr = $this->get_group_member_attr();
  1693. $add_filter = '';
  1694. if ($member_attr != 'member' && $member_attr != 'uniqueMember')
  1695. $add_filter = "($member_attr=$contact_dn)";
  1696. $filter = strtr("(|(member=$contact_dn)(uniqueMember=$contact_dn)$add_filter)", array('\\' => '\\\\'));
  1697. $this->_debug("C: Search [$filter][dn: $base_dn]");
  1698. $res = @ldap_search($this->conn, $base_dn, $filter, array($name_attr));
  1699. if ($res === false)
  1700. {
  1701. $this->_debug("S: ".ldap_error($this->conn));
  1702. return array();
  1703. }
  1704. $ldap_data = ldap_get_entries($this->conn, $res);
  1705. $this->_debug("S: ".ldap_count_entries($this->conn, $res)." record(s)");
  1706. $groups = array();
  1707. for ($i=0; $i<$ldap_data["count"]; $i++)
  1708. {
  1709. $group_name = $ldap_data[$i][$name_attr][0];
  1710. $group_id = self::dn_encode($group_name);
  1711. $groups[$group_id] = $group_id;
  1712. }
  1713. return $groups;
  1714. }
  1715. /**
  1716. * Detects group member attribute name
  1717. */
  1718. private function get_group_member_attr($object_classes = array())
  1719. {
  1720. if (empty($object_classes)) {
  1721. $object_classes = $this->prop['groups']['object_classes'];
  1722. }
  1723. if (!empty($object_classes)) {
  1724. foreach ((array)$object_classes as $oc) {
  1725. switch (strtolower($oc)) {
  1726. case 'group':
  1727. case 'groupofnames':
  1728. case 'kolabgroupofnames':
  1729. $member_attr = 'member';
  1730. break;
  1731. case 'groupofuniquenames':
  1732. case 'kolabgroupofuniquenames':
  1733. $member_attr = 'uniqueMember';
  1734. break;
  1735. }
  1736. }
  1737. }
  1738. if (!empty($member_attr)) {
  1739. return $member_attr;
  1740. }
  1741. if (!empty($this->prop['groups']['member_attr'])) {
  1742. return $this->prop['groups']['member_attr'];
  1743. }
  1744. return 'member';
  1745. }
  1746. /**
  1747. * Generate BER encoded string for Virtual List View option
  1748. *
  1749. * @param integer List offset (first record)
  1750. * @param integer Records per page
  1751. * @return string BER encoded option value
  1752. */
  1753. private function _vlv_ber_encode($offset, $rpp, $search = '')
  1754. {
  1755. # this string is ber-encoded, php will prefix this value with:
  1756. # 04 (octet string) and 10 (length of 16 bytes)
  1757. # the code behind this string is broken down as follows:
  1758. # 30 = ber sequence with a length of 0e (14) bytes following
  1759. # 02 = type integer (in two's complement form) with 2 bytes following (beforeCount): 01 00 (ie 0)
  1760. # 02 = type integer (in two's complement form) with 2 bytes following (afterCount): 01 18 (ie 25-1=24)
  1761. # a0 = type context-specific/constructed with a length of 06 (6) bytes following
  1762. # 02 = type integer with 2 bytes following (offset): 01 01 (ie 1)
  1763. # 02 = type integer with 2 bytes following (contentCount): 01 00
  1764. # whith a search string present:
  1765. # 81 = type context-specific/constructed with a length of 04 (4) bytes following (the length will change here)
  1766. # 81 indicates a user string is present where as a a0 indicates just a offset search
  1767. # 81 = type context-specific/constructed with a length of 06 (6) bytes following
  1768. # the following info was taken from the ISO/IEC 8825-1:2003 x.690 standard re: the
  1769. # encoding of integer values (note: these values are in
  1770. # two-complement form so since offset will never be negative bit 8 of the
  1771. # leftmost octet should never by set to 1):
  1772. # 8.3.2: If the contents octets of an integer value encoding consist
  1773. # of more than one octet, then the bits of the first octet (rightmost) and bit 8
  1774. # of the second (to the left of first octet) octet:
  1775. # a) shall not all be ones; and
  1776. # b) shall not all be zero
  1777. if ($search)
  1778. {
  1779. $search = preg_replace('/[^-[:alpha:] ,.()0-9]+/', '', $search);
  1780. $ber_val = self::_string2hex($search);
  1781. $str = self::_ber_addseq($ber_val, '81');
  1782. }
  1783. else
  1784. {
  1785. # construct the string from right to left
  1786. $str = "020100"; # contentCount
  1787. $ber_val = self::_ber_encode_int($offset); // returns encoded integer value in hex format
  1788. // calculate octet length of $ber_val
  1789. $str = self::_ber_addseq($ber_val, '02') . $str;
  1790. // now compute length over $str
  1791. $str = self::_ber_addseq($str, 'a0');
  1792. }
  1793. // now tack on records per page
  1794. $str = "020100" . self::_ber_addseq(self::_ber_encode_int($rpp-1), '02') . $str;
  1795. // now tack on sequence identifier and length
  1796. $str = self::_ber_addseq($str, '30');
  1797. return pack('H'.strlen($str), $str);
  1798. }
  1799. /**
  1800. * create ber encoding for sort control
  1801. *
  1802. * @param array List of cols to sort by
  1803. * @return string BER encoded option value
  1804. */
  1805. private function _sort_ber_encode($sortcols)
  1806. {
  1807. $str = '';
  1808. foreach (array_reverse((array)$sortcols) as $col) {
  1809. $ber_val = self::_string2hex($col);
  1810. # 30 = ber sequence with a length of octet value
  1811. # 04 = octet string with a length of the ascii value
  1812. $oct = self::_ber_addseq($ber_val, '04');
  1813. $str = self::_ber_addseq($oct, '30') . $str;
  1814. }
  1815. // now tack on sequence identifier and length
  1816. $str = self::_ber_addseq($str, '30');
  1817. return pack('H'.strlen($str), $str);
  1818. }
  1819. /**
  1820. * Add BER sequence with correct length and the given identifier
  1821. */
  1822. private static function _ber_addseq($str, $identifier)
  1823. {
  1824. $len = dechex(strlen($str)/2);
  1825. if (strlen($len) % 2 != 0)
  1826. $len = '0'.$len;
  1827. return $identifier . $len . $str;
  1828. }
  1829. /**
  1830. * Returns BER encoded integer value in hex format
  1831. */
  1832. private static function _ber_encode_int($offset)
  1833. {
  1834. $val = dechex($offset);
  1835. $prefix = '';
  1836. // check if bit 8 of high byte is 1
  1837. if (preg_match('/^[89abcdef]/', $val))
  1838. $prefix = '00';
  1839. if (strlen($val)%2 != 0)
  1840. $prefix .= '0';
  1841. return $prefix . $val;
  1842. }
  1843. /**
  1844. * Returns ascii string encoded in hex
  1845. */
  1846. private static function _string2hex($str)
  1847. {
  1848. $hex = '';
  1849. for ($i=0; $i < strlen($str); $i++)
  1850. $hex .= dechex(ord($str[$i]));
  1851. return $hex;
  1852. }
  1853. /**
  1854. * HTML-safe DN string encoding
  1855. *
  1856. * @param string $str DN string
  1857. *
  1858. * @return string Encoded HTML identifier string
  1859. */
  1860. static function dn_encode($str)
  1861. {
  1862. // @TODO: to make output string shorter we could probably
  1863. // remove dc=* items from it
  1864. return rtrim(strtr(base64_encode($str), '+/', '-_'), '=');
  1865. }
  1866. /**
  1867. * Decodes DN string encoded with _dn_encode()
  1868. *
  1869. * @param string $str Encoded HTML identifier string
  1870. *
  1871. * @return string DN string
  1872. */
  1873. static function dn_decode($str)
  1874. {
  1875. $str = str_pad(strtr($str, '-_', '+/'), strlen($str) % 4, '=', STR_PAD_RIGHT);
  1876. return base64_decode($str);
  1877. }
  1878. /**
  1879. * Wrapper for ldap_add()
  1880. */
  1881. protected function ldap_add($dn, $entry)
  1882. {
  1883. $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
  1884. $res = ldap_add($this->conn, $dn, $entry);
  1885. if ($res === false) {
  1886. $this->_debug("S: ".ldap_error($this->conn));
  1887. return false;
  1888. }
  1889. $this->_debug("S: OK");
  1890. return true;
  1891. }
  1892. /**
  1893. * Wrapper for ldap_delete()
  1894. */
  1895. protected function ldap_delete($dn)
  1896. {
  1897. $this->_debug("C: Delete [dn: $dn]");
  1898. $res = ldap_delete($this->conn, $dn);
  1899. if ($res === false) {
  1900. $this->_debug("S: ".ldap_error($this->conn));
  1901. return false;
  1902. }
  1903. $this->_debug("S: OK");
  1904. return true;
  1905. }
  1906. /**
  1907. * Wrapper for ldap_mod_replace()
  1908. */
  1909. protected function ldap_mod_replace($dn, $entry)
  1910. {
  1911. $this->_debug("C: Replace [dn: $dn]: ".print_r($entry, true));
  1912. if (!ldap_mod_replace($this->conn, $dn, $entry)) {
  1913. $this->_debug("S: ".ldap_error($this->conn));
  1914. return false;
  1915. }
  1916. $this->_debug("S: OK");
  1917. return true;
  1918. }
  1919. /**
  1920. * Wrapper for ldap_mod_add()
  1921. */
  1922. protected function ldap_mod_add($dn, $entry)
  1923. {
  1924. $this->_debug("C: Add [dn: $dn]: ".print_r($entry, true));
  1925. if (!ldap_mod_add($this->conn, $dn, $entry)) {
  1926. $this->_debug("S: ".ldap_error($this->conn));
  1927. return false;
  1928. }
  1929. $this->_debug("S: OK");
  1930. return true;
  1931. }
  1932. /**
  1933. * Wrapper for ldap_mod_del()
  1934. */
  1935. protected function ldap_mod_del($dn, $entry)
  1936. {
  1937. $this->_debug("C: Delete [dn: $dn]: ".print_r($entry, true));
  1938. if (!ldap_mod_del($this->conn, $dn, $entry)) {
  1939. $this->_debug("S: ".ldap_error($this->conn));
  1940. return false;
  1941. }
  1942. $this->_debug("S: OK");
  1943. return true;
  1944. }
  1945. /**
  1946. * Wrapper for ldap_rename()
  1947. */
  1948. protected function ldap_rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
  1949. {
  1950. $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
  1951. if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
  1952. $this->_debug("S: ".ldap_error($this->conn));
  1953. return false;
  1954. }
  1955. $this->_debug("S: OK");
  1956. return true;
  1957. }
  1958. /**
  1959. * Wrapper for ldap_list()
  1960. */
  1961. protected function ldap_list($dn, $filter, $attrs = array(''))
  1962. {
  1963. $list = array();
  1964. $this->_debug("C: List [dn: $dn] [{$filter}]");
  1965. if ($result = ldap_list($this->conn, $dn, $filter, $attrs)) {
  1966. $list = ldap_get_entries($this->conn, $result);
  1967. if ($list === false) {
  1968. $this->_debug("S: ".ldap_error($this->conn));
  1969. return array();
  1970. }
  1971. $count = $list['count'];
  1972. unset($list['count']);
  1973. $this->_debug("S: $count record(s)");
  1974. }
  1975. else {
  1976. $this->_debug("S: ".ldap_error($this->conn));
  1977. }
  1978. return $list;
  1979. }
  1980. }