PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/program/lib/Roundcube/rcube_ldap.php

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