3 +-----------------------------------------------------------------------+
4 | program/include/rcube_ldap.php |
6 | This file is part of the Roundcube Webmail client |
7 | Copyright (C) 2006-2010, 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 4509 2011-02-09 10:51:50Z thomasb $
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',
88 'file' => __FILE__, 'line' => __LINE__,
89 'message' => "No ldap support in this installation of PHP"), true);
91 if (is_resource($this->conn))
94 if (!is_array($this->prop['hosts']))
95 $this->prop['hosts'] = array($this->prop['hosts']);
97 if (empty($this->prop['ldap_version']))
98 $this->prop['ldap_version'] = 3;
100 foreach ($this->prop['hosts'] as $host)
102 $host = rcube_idn_to_ascii(rcube_parse_host($host));
103 $this->_debug("C: Connect [$host".($this->prop['port'] ? ':'.$this->prop['port'] : '')."]");
105 if ($lc = @ldap_connect($host, $this->prop['port']))
107 if ($this->prop['use_tls']===true)
108 if (!ldap_start_tls($lc))
111 $this->_debug("S: OK");
113 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
114 $this->prop['host'] = $host;
118 $this->_debug("S: NOT OK");
121 if (is_resource($this->conn))
125 // User specific access, generate the proper values to use.
126 if ($this->prop['user_specific']) {
127 // No password set, use the session password
128 if (empty($this->prop['bind_pass'])) {
129 $this->prop['bind_pass'] = $RCMAIL->decrypt($_SESSION['password']);
132 // Get the pieces needed for variable replacement.
133 $fu = $RCMAIL->user->get_username();
134 list($u, $d) = explode('@', $fu);
135 $dc = 'dc='.strtr($d, array('.' => ',dc=')); // hierarchal domain string
137 $replaces = array('%dc' => $dc, '%d' => $d, '%fu' => $fu, '%u' => $u);
139 if ($this->prop['search_base_dn'] && $this->prop['search_filter']) {
140 // Search for the dn to use to authenticate
141 $this->prop['search_base_dn'] = strtr($this->prop['search_base_dn'], $replaces);
142 $this->prop['search_filter'] = strtr($this->prop['search_filter'], $replaces);
144 $this->_debug("S: searching with base {$this->prop['search_base_dn']} for {$this->prop['search_filter']}");
146 $res = ldap_search($this->conn, $this->prop['search_base_dn'], $this->prop['search_filter'], array('uid'));
147 if ($res && ($entry = ldap_first_entry($this->conn, $res))) {
148 $bind_dn = ldap_get_dn($this->conn, $entry);
150 $this->_debug("S: search returned dn: $bind_dn");
153 $this->prop['bind_dn'] = $bind_dn;
154 $dn = ldap_explode_dn($bind_dn, 1);
155 $replaces['%dn'] = $dn[0];
159 // Replace the bind_dn and base_dn variables.
160 $this->prop['bind_dn'] = strtr($this->prop['bind_dn'], $replaces);
161 $this->prop['base_dn'] = strtr($this->prop['base_dn'], $replaces);
164 if (!empty($this->prop['bind_dn']) && !empty($this->prop['bind_pass']))
165 $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
168 raise_error(array('code' => 100, 'type' => 'ldap',
169 'file' => __FILE__, 'line' => __LINE__,
170 'message' => "Could not connect to any LDAP server, last tried $host:{$this->prop[port]}"), true);
172 // See if the directory is writeable.
173 if ($this->prop['writable']) {
174 $this->readonly = false;
181 * Bind connection with DN and password
183 * @param string Bind DN
184 * @param string Bind password
185 * @return boolean True on success, False on error
187 function bind($dn, $pass)
193 $this->_debug("C: Bind [dn: $dn] [pass: $pass]");
195 if (@ldap_bind($this->conn, $dn, $pass)) {
196 $this->_debug("S: OK");
200 $this->_debug("S: ".ldap_error($this->conn));
203 'code' => ldap_errno($this->conn), 'type' => 'ldap',
204 'file' => __FILE__, 'line' => __LINE__,
205 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
213 * Close connection to LDAP server
219 $this->_debug("C: Close");
220 ldap_unbind($this->conn);
227 * Set internal list page
229 * @param number Page number to list
232 function set_page($page)
234 $this->list_page = (int)$page;
239 * Set internal page size
241 * @param number Number of messages to display on one page
244 function set_pagesize($size)
246 $this->page_size = (int)$size;
251 * Save a search string for future listings
253 * @param string Filter string
255 function set_search_set($filter)
257 $this->filter = $filter;
262 * Getter for saved search properties
264 * @return mixed Search properties used by this class
266 function get_search_set()
268 return $this->filter;
273 * Reset all saved results and search parameters
277 $this->result = null;
278 $this->ldap_result = null;
284 * List the current set of contact records
286 * @param array List of cols to show
287 * @param int Only return this number of records
288 * @return array Indexed list of contact records, each a hash array
290 function list_records($cols=null, $subset=0)
292 // add general filter to query
293 if (!empty($this->prop['filter']) && empty($this->filter))
295 $filter = $this->prop['filter'];
296 $this->set_search_set($filter);
299 // exec LDAP search if no result resource is stored
300 if ($this->conn && !$this->ldap_result)
301 $this->_exec_search();
303 // count contacts for this user
304 $this->result = $this->count();
306 // we have a search result resource
307 if ($this->ldap_result && $this->result->count > 0)
309 if ($this->sort_col && $this->prop['scope'] !== 'base')
310 ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
312 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
313 $last_row = $this->result->first + $this->page_size;
314 $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
316 $entries = ldap_get_entries($this->conn, $this->ldap_result);
317 for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
318 $this->result->add($this->_ldap2result($entries[$i]));
321 return $this->result;
328 * @param array List of fields to search in
329 * @param string Search value
330 * @param boolean True for strict, False for partial (fuzzy) matching
331 * @param boolean True if results are requested, False if count only
332 * @param boolean (Not used)
333 * @param array List of fields that cannot be empty
334 * @return array Indexed list of contact records and 'count' value
336 function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array())
338 // special treatment for ID-based search
339 if ($fields == 'ID' || $fields == $this->primary_key)
341 $ids = explode(',', $value);
342 $result = new rcube_result_set();
343 foreach ($ids as $id)
344 if ($rec = $this->get_record($id, true))
354 $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
355 if (is_array($this->prop['search_fields']))
357 foreach ($this->prop['search_fields'] as $k => $field)
358 $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
362 foreach ((array)$fields as $field)
363 if ($f = $this->_map_field($field))
364 $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
368 // add required (non empty) fields filter
370 foreach ((array)$required as $field)
371 if ($f = $this->_map_field($field))
372 $req_filter .= "($f=*)";
374 if (!empty($req_filter))
375 $filter = '(&' . $req_filter . $filter . ')';
377 // avoid double-wildcard if $value is empty
378 $filter = preg_replace('/\*+/', '*', $filter);
380 // add general filter to query
381 if (!empty($this->prop['filter']))
382 $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
384 // set filter string and execute search
385 $this->set_search_set($filter);
386 $this->_exec_search();
389 $this->list_records();
391 $this->result = $this->count();
393 return $this->result;
398 * Count number of available contacts in database
400 * @return object rcube_result_set Resultset with values for 'count' and 'first'
405 if ($this->conn && $this->ldap_result) {
406 $count = ldap_count_entries($this->conn, $this->ldap_result);
408 elseif ($this->conn) {
409 // We have a connection but no result set, attempt to get one.
410 if (empty($this->filter)) {
411 // The filter is not set, set it.
412 $this->filter = $this->prop['filter'];
414 $this->_exec_search();
415 if ($this->ldap_result) {
416 $count = ldap_count_entries($this->conn, $this->ldap_result);
420 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
425 * Return the last result set
427 * @return object rcube_result_set Current resultset or NULL if nothing selected yet
429 function get_result()
431 return $this->result;
436 * Get a specific contact record
438 * @param mixed Record identifier
439 * @param boolean Return as associative array
440 * @return mixed Hash array or rcube_result_set with all record fields
442 function get_record($dn, $assoc=false)
445 if ($this->conn && $dn)
447 $dn = base64_decode($dn);
449 $this->_debug("C: Read [dn: $dn] [(objectclass=*)]");
451 if ($this->ldap_result = @ldap_read($this->conn, $dn, '(objectclass=*)', array_values($this->fieldmap)))
452 $entry = ldap_first_entry($this->conn, $this->ldap_result);
454 $this->_debug("S: ".ldap_error($this->conn));
456 if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
458 $this->_debug("S: OK");
460 $rec = array_change_key_case($rec, CASE_LOWER);
462 // Add in the dn for the entry.
464 $res = $this->_ldap2result($rec);
465 $this->result = new rcube_result_set(1);
466 $this->result->add($res);
470 return $assoc ? $res : $this->result;
475 * Create a new contact record
477 * @param array Hash array with save data
478 * @return encoded record ID on success, False on error
480 function insert($save_cols)
482 // Map out the column names to their LDAP ones to build the new entry.
484 $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
485 foreach ($save_cols as $col => $val) {
486 $fld = $this->_map_field($col);
488 // The field does exist, add it to the entry.
489 $newentry[$fld] = $val;
493 // Verify that the required fields are set.
494 // We know that the email address is required as a default of rcube, so
495 // we will default its value into any unfilled required fields.
496 foreach ($this->prop['required_fields'] as $fld) {
497 if (!isset($newentry[$fld])) {
498 $newentry[$fld] = $newentry[$this->_map_field('email')];
502 // Build the new entries DN.
503 $dn = $this->prop['LDAP_rdn'].'='.rcube_ldap::quote_string($newentry[$this->prop['LDAP_rdn']], true)
504 .','.$this->prop['base_dn'];
506 $this->_debug("C: Add [dn: $dn]: ".print_r($newentry, true));
508 $res = ldap_add($this->conn, $dn, $newentry);
509 if ($res === FALSE) {
510 $this->_debug("S: ".ldap_error($this->conn));
514 $this->_debug("S: OK");
516 return base64_encode($dn);
521 * Update a specific contact record
523 * @param mixed Record identifier
524 * @param array Hash array with save data
525 * @return boolean True on success, False on error
527 function update($id, $save_cols)
529 $record = $this->get_record($id, true);
530 $result = $this->get_result();
531 $record = $result->first();
534 $replacedata = array();
535 $deletedata = array();
536 foreach ($save_cols as $col => $val) {
537 $fld = $this->_map_field($col);
539 // The field does exist compare it to the ldap record.
540 if ($record[$col] != $val) {
541 // Changed, but find out how.
542 if (!isset($record[$col])) {
543 // Field was not set prior, need to add it.
544 $newdata[$fld] = $val;
546 elseif ($val == '') {
547 // Field supplied is empty, verify that it is not required.
548 if (!in_array($fld, $this->prop['required_fields'])) {
549 // It is not, safe to clear.
550 $deletedata[$fld] = $record[$col];
554 // The data was modified, save it out.
555 $replacedata[$fld] = $val;
561 $dn = base64_decode($id);
563 // Update the entry as required.
564 if (!empty($deletedata)) {
565 // Delete the fields.
566 $this->_debug("C: Delete [dn: $dn]: ".print_r($deletedata, true));
567 if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
568 $this->_debug("S: ".ldap_error($this->conn));
571 $this->_debug("S: OK");
574 if (!empty($replacedata)) {
576 if ($replacedata[$this->prop['LDAP_rdn']]) {
577 $newdn = $this->prop['LDAP_rdn'].'='
578 .rcube_ldap::quote_string($replacedata[$this->prop['LDAP_rdn']], true)
579 .','.$this->prop['base_dn'];
581 $newrdn = $this->prop['LDAP_rdn'].'='
582 .rcube_ldap::quote_string($replacedata[$this->prop['LDAP_rdn']], true);
583 unset($replacedata[$this->prop['LDAP_rdn']]);
586 // Replace the fields.
587 if (!empty($replacedata)) {
588 $this->_debug("C: Replace [dn: $dn]: ".print_r($replacedata, true));
589 if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
590 $this->_debug("S: ".ldap_error($this->conn));
593 $this->_debug("S: OK");
597 if (!empty($newdata)) {
599 $this->_debug("C: Add [dn: $dn]: ".print_r($newdata, true));
600 if (!ldap_mod_add($this->conn, $dn, $newdata)) {
601 $this->_debug("S: ".ldap_error($this->conn));
604 $this->_debug("S: OK");
608 if (!empty($newrdn)) {
609 $this->_debug("C: Rename [dn: $dn] [dn: $newrdn]");
610 if (@ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
611 $this->_debug("S: ".ldap_error($this->conn));
612 return base64_encode($newdn);
614 $this->_debug("S: OK");
622 * Mark one or more contact records as deleted
624 * @param array Record identifiers
625 * @return boolean True on success, False on error
627 function delete($ids)
629 if (!is_array($ids)) {
630 // Not an array, break apart the encoded DNs.
631 $dns = explode(',', $ids);
634 foreach ($dns as $id) {
635 $dn = base64_decode($id);
636 $this->_debug("C: Delete [dn: $dn]");
637 // Delete the record.
638 $res = ldap_delete($this->conn, $dn);
639 if ($res === FALSE) {
640 $this->_debug("S: ".ldap_error($this->conn));
643 $this->_debug("S: OK");
651 * Execute the LDAP search based on the stored credentials
655 private function _exec_search()
659 $filter = $this->filter ? $this->filter : '(objectclass=*)';
660 $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
662 $this->_debug("C: Search [".$filter."]");
664 if ($this->ldap_result = @$function($this->conn, $this->prop['base_dn'], $filter,
665 array_values($this->fieldmap), 0, (int) $this->prop['sizelimit'], (int) $this->prop['timelimit'])
667 $this->_debug("S: ".ldap_count_entries($this->conn, $this->ldap_result)." record(s)");
670 $this->_debug("S: ".ldap_error($this->conn));
680 private function _ldap2result($rec)
687 $out[$this->primary_key] = base64_encode($rec['dn']);
689 foreach ($this->fieldmap as $rf => $lf)
691 if ($rec[$lf]['count']) {
692 if ($rf == 'email' && $this->mail_domain && !strpos($rec[$lf][0], '@'))
693 $out[$rf] = sprintf('%s@%s', $rec[$lf][0], $this->mail_domain);
695 $out[$rf] = $rec[$lf][0];
706 private function _map_field($field)
708 return $this->fieldmap[$field];
715 private function _attr_name($name)
717 // list of known attribute aliases
720 'rfc822mailbox' => 'email',
722 'emailaddress' => 'email',
723 'pkcs9email' => 'email',
725 return isset($aliases[$name]) ? $aliases[$name] : $name;
732 private function _debug($str)
735 write_log('ldap', $str);
742 function quote_string($str, $dn=false)
745 $replace = array(','=>'\2c', '='=>'\3d', '+'=>'\2b', '<'=>'\3c',
746 '>'=>'\3e', ';'=>'\3b', '\\'=>'\5c', '"'=>'\22', '#'=>'\23');
748 $replace = array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c',
751 return strtr($str, $replace);