PageRenderTime 73ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/etc/apps/webmail/program/lib/Roundcube/rcube_ldap.php

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