4 +-----------------------------------------------------------------------+
5 | program/include/rcube_ldap.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2006-2007, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Interface to an LDAP address directory |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: rcube_ldap.inc 787 2007-09-09 17:58:13Z thomasb $
24 * Model class to access an LDAP address directory
26 * @package Addressbook
32 var $fieldmap = array();
36 var $ldap_result = null;
39 /** public properties */
40 var $primary_key = 'ID';
50 * @param array LDAP connection properties
51 * @param integer User-ID
53 function __construct($p)
57 foreach ($p as $prop => $value)
58 if (preg_match('/^(.+)_field$/', $prop, $matches))
59 $this->fieldmap[$matches[1]] = $value;
65 * PHP 4 object constructor
67 * @see rcube_ldap::__construct()
69 function rcube_ldap($p)
71 $this->__construct($p);
76 * Establish a connection to the LDAP server
80 if (!function_exists('ldap_connect'))
81 raise_error(array('type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
83 if (is_resource($this->conn))
86 if (!is_array($this->prop['hosts']))
87 $this->prop['hosts'] = array($this->prop['hosts']);
89 if (empty($this->prop['ldap_version']))
90 $this->prop['ldap_version'] = 3;
92 foreach ($this->prop['hosts'] as $host)
94 if ($lc = @ldap_connect($host, $this->prop['port']))
96 ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
97 $this->prop['host'] = $host;
103 if (is_resource($this->conn))
106 if (!empty($this->prop['bind_dn']) && !empty($this->prop['bind_pass']))
107 $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
110 raise_error(array('type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
115 * Bind connection with DN and password
117 * @param string Bind DN
118 * @param string Bind password
119 * @return boolean True on success, False on error
121 function bind($dn, $pass)
126 if (@ldap_bind($this->conn, $dn, $pass))
131 'code' => ldap_errno($this->conn),
133 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
142 * Close connection to LDAP server
148 @ldap_unbind($this->conn);
155 * Set internal list page
157 * @param number Page number to list
160 function set_page($page)
162 $this->list_page = (int)$page;
167 * Set internal page size
169 * @param number Number of messages to display on one page
172 function set_pagesize($size)
174 $this->page_size = (int)$size;
179 * Save a search string for future listings
181 * @param string Filter string
183 function set_search_set($filter)
185 $this->filter = $filter;
190 * Getter for saved search properties
192 * @return mixed Search properties used by this class
194 function get_search_set()
196 return $this->filter;
201 * Reset all saved results and search parameters
205 $this->result = null;
206 $this->ldap_result = null;
212 * List the current set of contact records
214 * @param array List of cols to show
215 * @param int Only return this number of records (not implemented)
216 * @return array Indexed list of contact records, each a hash array
218 function list_records($cols=null, $subset=0)
220 // add general filter to query
221 if (!empty($this->prop['filter']))
223 $filter = $this->prop['filter'];
224 $this->set_search_set($filter);
227 // exec LDAP search if no result resource is stored
228 if ($this->conn && !$this->ldap_result)
229 $this->_exec_search();
231 // count contacts for this user
232 $this->result = $this->count();
234 // we have a search result resource
235 if ($this->ldap_result && $this->result->count > 0)
237 if ($this->sort_col && $this->prop['scope'] !== "base")
238 @ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
240 $entries = ldap_get_entries($this->conn, $this->ldap_result);
241 for ($i = $this->result->first; $i < min($entries['count'], $this->result->first + $this->page_size); $i++)
242 $this->result->add($this->_ldap2result($entries[$i]));
245 return $this->result;
252 * @param array List of fields to search in
253 * @param string Search value
254 * @param boolean True if results are requested, False if count only
255 * @return array Indexed list of contact records and 'count' value
257 function search($fields, $value, $strict=false, $select=true)
259 // special treatment for ID-based search
260 if ($fields == 'ID' || $fields == $this->primary_key)
262 $ids = explode(',', $value);
263 $result = new rcube_result_set();
264 foreach ($ids as $id)
265 if ($rec = $this->get_record($id, true))
275 $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
276 if (is_array($this->prop['search_fields']))
278 foreach ($this->prop['search_fields'] as $k => $field)
279 $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
283 foreach ((array)$fields as $field)
284 if ($f = $this->_map_field($field))
285 $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
289 // add general filter to query
290 if (!empty($this->prop['filter']))
291 $filter = '(&'.$this->prop['filter'] . $filter . ')';
293 // set filter string and execute search
294 $this->set_search_set($filter);
295 $this->_exec_search();
298 $this->list_records();
300 $this->result = $this->count();
302 return $this->result;
307 * Count number of available contacts in database
309 * @return object rcube_result_set Resultset with values for 'count' and 'first'
314 if ($this->conn && $this->ldap_result)
315 $count = ldap_count_entries($this->conn, $this->ldap_result);
317 return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
322 * Return the last result set
324 * @return object rcube_result_set Current resultset or NULL if nothing selected yet
326 function get_result()
328 return $this->result;
333 * Get a specific contact record
335 * @param mixed Record identifier
336 * @param boolean Return as associative array
337 * @return mixed Hash array or rcube_result_set with all record fields
339 function get_record($dn, $assoc=false)
342 if ($this->conn && $dn)
344 $this->ldap_result = @ldap_read($this->conn, base64_decode($dn), "(objectclass=*)", array_values($this->fieldmap));
345 $entry = @ldap_first_entry($this->conn, $this->ldap_result);
347 if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
349 $res = $this->_ldap2result($rec);
350 $this->result = new rcube_result_set(1);
351 $this->result->add($res);
355 return $assoc ? $res : $this->result;
360 * Create a new contact record
362 * @param array Hash array with save data
363 * @return boolean The create record ID on success, False on error
365 function insert($save_cols)
373 * Update a specific contact record
375 * @param mixed Record identifier
376 * @param array Hash array with save data
377 * @return boolean True on success, False on error
379 function update($id, $save_cols)
387 * Mark one or more contact records as deleted
389 * @param array Record identifiers
390 * @return boolean True on success, False on error
392 function delete($ids)
400 * Execute the LDAP search based on the stored credentials
404 function _exec_search()
406 if ($this->conn && $this->filter)
408 $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
409 $this->ldap_result = $function($this->conn, $this->prop['base_dn'], $this->filter, array_values($this->fieldmap), 0, 0);
420 function _ldap2result($rec)
425 $out[$this->primary_key] = base64_encode($rec['dn']);
427 foreach ($this->fieldmap as $rf => $lf)
429 if ($rec[$lf]['count'])
430 $out[$rf] = $rec[$lf][0];
440 function _map_field($field)
442 return $this->fieldmap[$field];
449 function quote_string($str)
451 return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));