3 +-----------------------------------------------------------------------+
4 | program/include/rcube_ldap.php |
6 | This file is part of the RoundCube Webmail client |
7 | Copyright (C) 2006-2008, 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 1482 2008-06-06 09:42:31Z alec $
23 * Model class to access an LDAP address directory
25 * @package Addressbook
31 var $fieldmap = array();
35 var $ldap_result = null;
38 /** public properties */
39 var $primary_key = 'ID';
49 * @param array LDAP connection properties
50 * @param integer User-ID
52 function __construct($p)
56 foreach ($p as $prop => $value)
57 if (preg_match('/^(.+)_field$/', $prop, $matches))
58 $this->fieldmap[$matches[1]] = $value;
60 $this->sort_col = $p["sort"];
66 * PHP 4 object constructor
68 * @see rcube_ldap::__construct()
70 function rcube_ldap($p)
72 $this->__construct($p);
77 * Establish a connection to the LDAP server
81 if (!function_exists('ldap_connect'))
82 raise_error(array('type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
84 if (is_resource($this->conn))
87 if (!is_array($this->prop['hosts']))
88 $this->prop['hosts'] = array($this->prop['hosts']);
90 if (empty($this->prop['ldap_version']))
91 $this->prop['ldap_version'] = 3;
93 foreach ($this->prop['hosts'] as $host)
95 if ($lc = @ldap_connect($host, $this->prop['port']))
97 if ($this->prop['use_tls']===true)
98 if (!ldap_start_tls($lc))
101 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
102 $this->prop['host'] = $host;
108 if (is_resource($this->conn))
112 if ($this->prop["user_specific"]) {
113 // User specific access, generate the proper values to use.
114 global $CONFIG, $RCMAIL;
115 if (empty($this->prop['bind_pass'])) {
116 // No password set, use the users.
117 $this->prop['bind_pass'] = $RCMAIL->decrypt_passwd($_SESSION["password"]);
120 // Get the pieces needed for variable replacement.
121 // See if the logged in username has an "@" in it.
122 if (is_bool(strstr($_SESSION["username"], "@"))) {
123 // It does not, use the global default.
124 $fu = $_SESSION["username"]."@".$CONFIG["username_domain"];
125 $u = $_SESSION["username"];
126 $d = $CONFIG["username_domain"];
130 $fu = $_SESSION["username"];
131 // Get the pieces needed for username and domain.
132 list($u, $d) = explode("@", $_SESSION["username"]);
135 // Replace the bind_dn variables.
136 $bind_dn = str_replace(array("%fu", "%u", "%d"),
138 $this->prop['bind_dn']);
139 $this->prop['bind_dn'] = $bind_dn;
140 // Replace the base_dn variables.
141 $base_dn = str_replace(array("%fu", "%u", "%d"),
143 $this->prop['base_dn']);
144 $this->prop['base_dn'] = $base_dn;
146 $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
148 elseif (!empty($this->prop['bind_dn']) && !empty($this->prop['bind_pass']))
149 $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
152 raise_error(array('type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
154 // See if the directory is writeable.
155 if ($this->prop['writable']) {
156 $this->readonly = false;
163 * Bind connection with DN and password
165 * @param string Bind DN
166 * @param string Bind password
167 * @return boolean True on success, False on error
169 function bind($dn, $pass)
175 if (ldap_bind($this->conn, $dn, $pass)) {
180 'code' => ldap_errno($this->conn),
182 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
190 * Close connection to LDAP server
196 @ldap_unbind($this->conn);
203 * Set internal list page
205 * @param number Page number to list
208 function set_page($page)
210 $this->list_page = (int)$page;
215 * Set internal page size
217 * @param number Number of messages to display on one page
220 function set_pagesize($size)
222 $this->page_size = (int)$size;
227 * Save a search string for future listings
229 * @param string Filter string
231 function set_search_set($filter)
233 $this->filter = $filter;
238 * Getter for saved search properties
240 * @return mixed Search properties used by this class
242 function get_search_set()
244 return $this->filter;
249 * Reset all saved results and search parameters
253 $this->result = null;
254 $this->ldap_result = null;
260 * List the current set of contact records
262 * @param array List of cols to show
263 * @param int Only return this number of records
264 * @return array Indexed list of contact records, each a hash array
266 function list_records($cols=null, $subset=0)
268 // add general filter to query
269 if (!empty($this->prop['filter']))
271 $filter = $this->prop['filter'];
272 $this->set_search_set($filter);
275 // exec LDAP search if no result resource is stored
276 if ($this->conn && !$this->ldap_result)
277 $this->_exec_search();
279 // count contacts for this user
280 $this->result = $this->count();
282 // we have a search result resource
283 if ($this->ldap_result && $this->result->count > 0)
285 if ($this->sort_col && $this->prop['scope'] !== "base")
286 @ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
288 $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
289 $last_row = $this->result->first + $this->page_size;
290 $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
292 $entries = ldap_get_entries($this->conn, $this->ldap_result);
293 for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
294 $this->result->add($this->_ldap2result($entries[$i]));
297 return $this->result;
304 * @param array List of fields to search in
305 * @param string Search value
306 * @param boolean True if results are requested, False if count only
307 * @return array Indexed list of contact records and 'count' value
309 function search($fields, $value, $strict=false, $select=true)
311 // special treatment for ID-based search
312 if ($fields == 'ID' || $fields == $this->primary_key)
314 $ids = explode(',', $value);
315 $result = new rcube_result_set();
316 foreach ($ids as $id)
317 if ($rec = $this->get_record($id, true))
327 $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
328 if (is_array($this->prop['search_fields']))
330 foreach ($this->prop['search_fields'] as $k => $field)
331 $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
335 foreach ((array)$fields as $field)
336 if ($f = $this->_map_field($field))
337 $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
341 // avoid double-wildcard if $value is empty
342 $filter = preg_replace('/\*+/', '*', $filter);
344 // add general filter to query
345 if (!empty($this->prop['filter']))
346 $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
348 // set filter string and execute search
349 $this->set_search_set($filter);
350 $this->_exec_search();
353 $this->list_records();
355 $this->result = $this->count();
357 return $this->result;
362 * Count number of available contacts in database
364 * @return object rcube_result_set Resultset with values for 'count' and 'first'
369 if ($this->conn && $this->ldap_result) {
370 $count = ldap_count_entries($this->conn, $this->ldap_result);
372 elseif ($this->conn) {
373 // We have a connection but no result set, attempt to get one.
374 if (empty($this->filter)) {
375 // The filter is not set, set it.
376 $this->filter = $this->prop['filter'];
378 $this->_exec_search();
379 if ($this->ldap_result) {
380 $count = ldap_count_entries($this->conn, $this->ldap_result);
384 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
389 * Return the last result set
391 * @return object rcube_result_set Current resultset or NULL if nothing selected yet
393 function get_result()
395 return $this->result;
400 * Get a specific contact record
402 * @param mixed Record identifier
403 * @param boolean Return as associative array
404 * @return mixed Hash array or rcube_result_set with all record fields
406 function get_record($dn, $assoc=false)
409 if ($this->conn && $dn)
411 $this->ldap_result = @ldap_read($this->conn, base64_decode($dn), "(objectclass=*)", array_values($this->fieldmap));
412 $entry = @ldap_first_entry($this->conn, $this->ldap_result);
414 if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
416 // Add in the dn for the entry.
417 $rec["dn"] = base64_decode($dn);
418 $res = $this->_ldap2result($rec);
419 $this->result = new rcube_result_set(1);
420 $this->result->add($res);
424 return $assoc ? $res : $this->result;
429 * Create a new contact record
431 * @param array Hash array with save data
432 * @return encoded record ID on success, False on error
434 function insert($save_cols)
436 // Map out the column names to their LDAP ones to build the new entry.
438 $newentry["objectClass"] = $this->prop["LDAP_Object_Classes"];
439 foreach ($save_cols as $col => $val) {
441 $fld = $this->_map_field($col);
443 // The field does exist, add it to the entry.
444 $newentry[$fld] = $val;
448 // Verify that the required fields are set.
449 // We know that the email address is required as a default of rcube, so
450 // we will default its value into any unfilled required fields.
451 foreach ($this->prop["required_fields"] as $fld) {
452 if (!isset($newentry[$fld])) {
453 $newentry[$fld] = $newentry[$this->_map_field("email")];
457 // Build the new entries DN.
458 $dn = $this->prop["LDAP_rdn"]."=".$newentry[$this->prop["LDAP_rdn"]].",".$this->prop['base_dn'];
459 $res = @ldap_add($this->conn, $dn, $newentry);
460 if ($res === FALSE) {
464 return base64_encode($dn);
469 * Update a specific contact record
471 * @param mixed Record identifier
472 * @param array Hash array with save data
473 * @return boolean True on success, False on error
475 function update($id, $save_cols)
477 $record = $this->get_record($id, true);
478 $result = $this->get_result();
479 $record = $result->first();
482 $replacedata = array();
483 $deletedata = array();
484 foreach ($save_cols as $col => $val) {
486 $fld = $this->_map_field($col);
488 // The field does exist compare it to the ldap record.
489 if ($record[$col] != $val) {
490 // Changed, but find out how.
491 if (!isset($record[$col])) {
492 // Field was not set prior, need to add it.
493 $newdata[$fld] = $val;
495 elseif ($val == "") {
496 // Field supplied is empty, verify that it is not required.
497 if (!in_array($fld, $this->prop["required_fields"])) {
498 // It is not, safe to clear.
499 $deletedata[$fld] = $record[$col];
503 // The data was modified, save it out.
504 $replacedata[$fld] = $val;
510 // Update the entry as required.
511 $dn = base64_decode($id);
512 if (!empty($deletedata)) {
513 // Delete the fields.
514 $res = @ldap_mod_del($this->conn, $dn, $deletedata);
515 if ($res === FALSE) {
520 if (!empty($replacedata)) {
521 // Replace the fields.
522 $res = @ldap_mod_replace($this->conn, $dn, $replacedata);
523 if ($res === FALSE) {
528 if (!empty($newdata)) {
530 $res = @ldap_mod_add($this->conn, $dn, $newdata);
531 if ($res === FALSE) {
541 * Mark one or more contact records as deleted
543 * @param array Record identifiers
544 * @return boolean True on success, False on error
546 function delete($ids)
548 if (!is_array($ids)) {
549 // Not an array, break apart the encoded DNs.
550 $dns = explode(",", $ids);
553 foreach ($dns as $id) {
554 $dn = base64_decode($id);
555 // Delete the record.
556 $res = @ldap_delete($this->conn, $dn);
557 if ($res === FALSE) {
567 * Execute the LDAP search based on the stored credentials
571 function _exec_search()
573 if ($this->conn && $this->filter)
575 $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
576 $this->ldap_result = $function($this->conn, $this->prop['base_dn'], $this->filter, array_values($this->fieldmap), 0, 0);
587 function _ldap2result($rec)
592 $out[$this->primary_key] = base64_encode($rec['dn']);
594 foreach ($this->fieldmap as $rf => $lf)
596 if ($rec[$lf]['count'])
597 $out[$rf] = $rec[$lf][0];
607 function _map_field($field)
609 return $this->fieldmap[$field];
616 function quote_string($str)
618 return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));