3 +-----------------------------------------------------------------------+
4 | program/include/rcube_ldap.php |
6 | This file is part of the RoundCube Webmail client |
7 | Copyright (C) 2006-2009, RoundCube Dev. - Switzerland |
8 | Licensed under the GNU GPL |
11 | Interface to an LDAP address directory |
13 +-----------------------------------------------------------------------+
14 | Author: Thomas Bruederli <roundcube@gmail.com> |
15 +-----------------------------------------------------------------------+
17 $Id: rcube_ldap.php 2976 2009-09-21 11:50:53Z alec $
23 * Model class to access an LDAP address directory
25 * @package Addressbook
27 class rcube_ldap extends rcube_addressbook
31 var $fieldmap = array();
35 var $ldap_result = null;
37 var $mail_domain = '';
40 /** public properties */
41 var $primary_key = 'ID';
51 * @param array LDAP connection properties
52 * @param boolean Enables debug mode
53 * @param string Current user mail domain name
54 * @param integer User-ID
56 function __construct($p, $debug=false, $mail_domain=NULL)
60 foreach ($p as $prop => $value)
61 if (preg_match('/^(.+)_field$/', $prop, $matches))
62 $this->fieldmap[$matches[1]] = $this->_attr_name(strtolower($value));
64 // make sure 'required_fields' is an array
65 if (!is_array($this->prop['required_fields']))
66 $this->prop['required_fields'] = (array) $this->prop['required_fields'];
68 foreach ($this->prop['required_fields'] as $key => $val)
69 $this->prop['required_fields'][$key] = $this->_attr_name(strtolower($val));
71 $this->sort_col = $p['sort'];
72 $this->debug = $debug;
73 $this->mail_domain = $mail_domain;
80 * Establish a connection to the LDAP server
86 if (!function_exists('ldap_connect'))
87 raise_error(array('code' => 100, 'type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
89 if (is_resource($this->conn))
92 if (!is_array($this->prop['hosts']))
93 $this->prop['hosts'] = array($this->prop['hosts']);
95 if (empty($this->prop['ldap_version']))
96 $this->prop['ldap_version'] = 3;
98 foreach ($this->prop['hosts'] as $host)
100 $this->_debug("C: Connect [$host".($this->prop['port'] ? ':'.$this->prop['port'] : '')."]");
102 if ($lc = @ldap_connect($host, $this->prop['port']))
104 if ($this->prop['use_tls']===true)
105 if (!ldap_start_tls($lc))
108 $this->_debug("S: OK");
110 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
111 $this->prop['host'] = $host;
115 $this->_debug("S: NOT OK");
118 if (is_resource($this->conn))
122 // User specific access, generate the proper values to use.
123 if ($this->prop['user_specific']) {
124 // No password set, use the session password
125 if (empty($this->prop['bind_pass'])) {
126 $this->prop['bind_pass'] = $RCMAIL->decrypt($_SESSION['password']);
129 // Get the pieces needed for variable replacement.
130 $fu = $RCMAIL->user->get_username();
131 list($u, $d) = explode('@', $fu);
133 // Replace the bind_dn and base_dn variables.
134 $replaces = array('%fu' => $fu, '%u' => $u, '%d' => $d);
135 $this->prop['bind_dn'] = strtr($this->prop['bind_dn'], $replaces);
136 $this->prop['base_dn'] = strtr($this->prop['base_dn'], $replaces);
139 if (!empty($this->prop['bind_dn']) && !empty($this->prop['bind_pass']))
140 $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
143 raise_error(array('code' => 100, 'type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
145 // See if the directory is writeable.
146 if ($this->prop['writable']) {
147 $this->readonly = false;
154 * Bind connection with DN and password
156 * @param string Bind DN
157 * @param string Bind password
158 * @return boolean True on success, False on error
160 function bind($dn, $pass)
166 $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
168 if (@ldap_bind($this->conn, $dn, $pass)) {
169 $this->_debug("S: OK");
173 $this->_debug("S: ".ldap_error($this->conn));
176 'code' => ldap_errno($this->conn),
178 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
186 * Close connection to LDAP server
192 $this->_debug("C: Close");
193 ldap_unbind($this->conn);
200 * Set internal list page
202 * @param number Page number to list
205 function set_page($page)
207 $this->list_page = (int)$page;
212 * Set internal page size
214 * @param number Number of messages to display on one page
217 function set_pagesize($size)
219 $this->page_size = (int)$size;
224 * Save a search string for future listings
226 * @param string Filter string
228 function set_search_set($filter)
230 $this->filter = $filter;
235 * Getter for saved search properties
237 * @return mixed Search properties used by this class
239 function get_search_set()
241 return $this->filter;
246 * Reset all saved results and search parameters
250 $this->result = null;
251 $this->ldap_result = null;
257 * List the current set of contact records
259 * @param array List of cols to show
260 * @param int Only return this number of records
261 * @return array Indexed list of contact records, each a hash array
263 function list_records($cols=null, $subset=0)
265 // add general filter to query
266 if (!empty($this->prop['filter']) && empty($this->filter))
268 $filter = $this->prop['filter'];
269 $this->set_search_set($filter);
272 // exec LDAP search if no result resource is stored
273 if ($this->conn && !$this->ldap_result)
274 $this->_exec_search();
276 // count contacts for this user
277 $this->result = $this->count();
279 // we have a search result resource
280 if ($this->ldap_result && $this->result->count > 0)
282 if ($this->sort_col && $this->prop['scope'] !== 'base')
283 ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
285 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
286 $last_row = $this->result->first + $this->page_size;
287 $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
289 $entries = ldap_get_entries($this->conn, $this->ldap_result);
290 for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
291 $this->result->add($this->_ldap2result($entries[$i]));
294 return $this->result;
301 * @param array List of fields to search in
302 * @param string Search value
303 * @param boolean True if results are requested, False if count only
304 * @return array Indexed list of contact records and 'count' value
306 function search($fields, $value, $strict=false, $select=true)
308 // special treatment for ID-based search
309 if ($fields == 'ID' || $fields == $this->primary_key)
311 $ids = explode(',', $value);
312 $result = new rcube_result_set();
313 foreach ($ids as $id)
314 if ($rec = $this->get_record($id, true))
324 $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
325 if (is_array($this->prop['search_fields']))
327 foreach ($this->prop['search_fields'] as $k => $field)
328 $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
332 foreach ((array)$fields as $field)
333 if ($f = $this->_map_field($field))
334 $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
338 // avoid double-wildcard if $value is empty
339 $filter = preg_replace('/\*+/', '*', $filter);
341 // add general filter to query
342 if (!empty($this->prop['filter']))
343 $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
345 // set filter string and execute search
346 $this->set_search_set($filter);
347 $this->_exec_search();
350 $this->list_records();
352 $this->result = $this->count();
354 return $this->result;
359 * Count number of available contacts in database
361 * @return object rcube_result_set Resultset with values for 'count' and 'first'
366 if ($this->conn && $this->ldap_result) {
367 $count = ldap_count_entries($this->conn, $this->ldap_result);
369 elseif ($this->conn) {
370 // We have a connection but no result set, attempt to get one.
371 if (empty($this->filter)) {
372 // The filter is not set, set it.
373 $this->filter = $this->prop['filter'];
375 $this->_exec_search();
376 if ($this->ldap_result) {
377 $count = ldap_count_entries($this->conn, $this->ldap_result);
381 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
386 * Return the last result set
388 * @return object rcube_result_set Current resultset or NULL if nothing selected yet
390 function get_result()
392 return $this->result;
397 * Get a specific contact record
399 * @param mixed Record identifier
400 * @param boolean Return as associative array
401 * @return mixed Hash array or rcube_result_set with all record fields
403 function get_record($dn, $assoc=false)
406 if ($this->conn && $dn)
408 $this->_debug("C: Read [dn: ".base64_decode($dn)."] [(objectclass=*)]");
410 if ($this->ldap_result = @ldap_read($this->conn, base64_decode($dn), '(objectclass=*)', array_values($this->fieldmap)))
411 $entry = ldap_first_entry($this->conn, $this->ldap_result);
413 $this->_debug("S: ".ldap_error($this->conn));
415 if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
417 $this->_debug("S: OK");
419 $rec = array_change_key_case($rec, CASE_LOWER);
421 // Add in the dn for the entry.
422 $rec['dn'] = base64_decode($dn);
423 $res = $this->_ldap2result($rec);
424 $this->result = new rcube_result_set(1);
425 $this->result->add($res);
429 return $assoc ? $res : $this->result;
434 * Create a new contact record
436 * @param array Hash array with save data
437 * @return encoded record ID on success, False on error
439 function insert($save_cols)
441 // Map out the column names to their LDAP ones to build the new entry.
443 $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
444 foreach ($save_cols as $col => $val) {
445 $fld = $this->_map_field($col);
447 // The field does exist, add it to the entry.
448 $newentry[$fld] = $val;
452 // Verify that the required fields are set.
453 // We know that the email address is required as a default of rcube, so
454 // we will default its value into any unfilled required fields.
455 foreach ($this->prop['required_fields'] as $fld) {
456 if (!isset($newentry[$fld])) {
457 $newentry[$fld] = $newentry[$this->_map_field('email')];
461 // Build the new entries DN.
462 $dn = $this->prop['LDAP_rdn'].'='.$newentry[$this->prop['LDAP_rdn']].','.$this->prop['base_dn'];
464 $this->_debug("C: Add [dn: $dn]: ".print_r($newentry, true));
466 $res = ldap_add($this->conn, $dn, $newentry);
467 if ($res === FALSE) {
468 $this->_debug("S: ".ldap_error($this->conn));
472 $this->_debug("S: OK");
474 return base64_encode($dn);
479 * Update a specific contact record
481 * @param mixed Record identifier
482 * @param array Hash array with save data
483 * @return boolean True on success, False on error
485 function update($id, $save_cols)
487 $record = $this->get_record($id, true);
488 $result = $this->get_result();
489 $record = $result->first();
492 $replacedata = array();
493 $deletedata = array();
494 foreach ($save_cols as $col => $val) {
495 $fld = $this->_map_field($col);
497 // The field does exist compare it to the ldap record.
498 if ($record[$col] != $val) {
499 // Changed, but find out how.
500 if (!isset($record[$col])) {
501 // Field was not set prior, need to add it.
502 $newdata[$fld] = $val;
504 elseif ($val == '') {
505 // Field supplied is empty, verify that it is not required.
506 if (!in_array($fld, $this->prop['required_fields'])) {
507 // It is not, safe to clear.
508 $deletedata[$fld] = $record[$col];
512 // The data was modified, save it out.
513 $replacedata[$fld] = $val;
519 $dn = base64_decode($id);
521 // Update the entry as required.
522 if (!empty($deletedata)) {
523 // Delete the fields.
524 $this->_debug("C: Delete [dn: $dn]: ".print_r($deletedata, true));
525 if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
526 $this->_debug("S: ".ldap_error($this->conn));
529 $this->_debug("S: OK");
532 if (!empty($replacedata)) {
534 if ($replacedata[$this->prop['LDAP_rdn']]) {
535 $newdn = $this->prop['LDAP_rdn'].'='.$replacedata[$this->prop['LDAP_rdn']].','.$this->prop['base_dn'];
537 $newrdn = $this->prop['LDAP_rdn'].'='.$replacedata[$this->prop['LDAP_rdn']];
538 unset($replacedata[$this->prop['LDAP_rdn']]);
541 // Replace the fields.
542 if (!empty($replacedata)) {
543 $this->_debug("C: Replace [dn: $dn]: ".print_r($replacedata, true));
544 if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
545 $this->_debug("S: ".ldap_error($this->conn));
548 $this->_debug("S: OK");
552 if (!empty($newdata)) {
554 $this->_debug("C: Add [dn: $dn]: ".print_r($newdata, true));
555 if (!ldap_mod_add($this->conn, $dn, $newdata)) {
556 $this->_debug("S: ".ldap_error($this->conn));
559 $this->_debug("S: OK");
563 if (!empty($newrdn)) {
564 $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
565 if (@ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
566 $this->_debug("S: ".ldap_error($this->conn));
567 return base64_encode($newdn);
569 $this->_debug("S: OK");
577 * Mark one or more contact records as deleted
579 * @param array Record identifiers
580 * @return boolean True on success, False on error
582 function delete($ids)
584 if (!is_array($ids)) {
585 // Not an array, break apart the encoded DNs.
586 $dns = explode(',', $ids);
589 foreach ($dns as $id) {
590 $dn = base64_decode($id);
591 $this->_debug("C: Delete [dn: $dn]");
592 // Delete the record.
593 $res = ldap_delete($this->conn, $dn);
594 if ($res === FALSE) {
595 $this->_debug("S: ".ldap_error($this->conn));
598 $this->_debug("S: OK");
606 * Execute the LDAP search based on the stored credentials
610 private function _exec_search()
614 $filter = $this->filter ? $this->filter : '(objectclass=*)';
615 $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
617 $this->_debug("C: Search [".$filter."]");
619 if ($this->ldap_result = @$function($this->conn, $this->prop['base_dn'], $filter, array_values($this->fieldmap), 0, 0)) {
620 $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
623 $this->_debug("S: ".ldap_error($this->conn));
633 private function _ldap2result($rec)
640 $out[$this->primary_key] = base64_encode($rec['dn']);
642 foreach ($this->fieldmap as $rf => $lf)
644 if ($rec[$lf]['count']) {
645 if ($rf == 'email' && $mail_domain && !strpos($rec[$lf][0], '@'))
646 $out[$rf] = sprintf('%s@%s', $rec[$lf][0], $this->mail_domain);
648 $out[$rf] = $rec[$lf][0];
659 private function _map_field($field)
661 return $this->fieldmap[$field];
668 private function _attr_name($name)
670 // list of known attribute aliases
673 'rfc822mailbox' => 'mail',
675 'emailaddress' => 'email',
676 'pkcs9email' => 'email',
678 return isset($aliases[$name]) ? $aliases[$name] : $name;
685 private function _debug($str)
688 write_log('ldap', $str);
695 function quote_string($str)
697 return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));