]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_ldap.inc
Imported Upstream version 0.1~rc2
[roundcube.git] / program / include / rcube_ldap.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_ldap.inc                                        |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2006-2007, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Interface to an LDAP address directory                              |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: rcube_ldap.inc 787 2007-09-09 17:58:13Z thomasb $
19
20 */
21
22
23 /**
24  * Model class to access an LDAP address directory
25  *
26  * @package Addressbook
27  */
28 class rcube_ldap
29 {
30   var $conn;
31   var $prop = array();
32   var $fieldmap = array();
33   
34   var $filter = '';
35   var $result = null;
36   var $ldap_result = null;
37   var $sort_col = '';
38   
39   /** public properties */
40   var $primary_key = 'ID';
41   var $readonly = true;
42   var $list_page = 1;
43   var $page_size = 10;
44   var $ready = false;
45   
46   
47   /**
48    * Object constructor
49    *
50    * @param array LDAP connection properties
51    * @param integer User-ID
52    */
53   function __construct($p)
54   {
55     $this->prop = $p;
56     
57     foreach ($p as $prop => $value)
58       if (preg_match('/^(.+)_field$/', $prop, $matches))
59         $this->fieldmap[$matches[1]] = $value;
60     
61     $this->connect();
62   }
63
64   /**
65    * PHP 4 object constructor
66    *
67    * @see  rcube_ldap::__construct()
68    */
69   function rcube_ldap($p)
70   {
71     $this->__construct($p);
72   }
73   
74
75   /**
76    * Establish a connection to the LDAP server
77    */
78   function connect()
79   {
80     if (!function_exists('ldap_connect'))
81       raise_error(array('type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
82
83     if (is_resource($this->conn))
84       return true;
85     
86     if (!is_array($this->prop['hosts']))
87       $this->prop['hosts'] = array($this->prop['hosts']);
88
89     if (empty($this->prop['ldap_version']))
90       $this->prop['ldap_version'] = 3;
91
92     foreach ($this->prop['hosts'] as $host)
93     {
94       if ($lc = @ldap_connect($host, $this->prop['port']))
95       {
96         ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
97         $this->prop['host'] = $host;
98         $this->conn = $lc;
99         break;
100       }
101     }
102     
103     if (is_resource($this->conn))
104     {
105       $this->ready = true;
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']);
108     }
109     else
110       raise_error(array('type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
111   }
112
113
114   /**
115    * Bind connection with DN and password
116    *
117    * @param string Bind DN
118    * @param string Bind password
119    * @return boolean True on success, False on error
120    */
121   function bind($dn, $pass)
122   {
123     if (!$this->conn)
124       return false;
125     
126     if (@ldap_bind($this->conn, $dn, $pass))
127       return true;
128     else
129     {
130       raise_error(array(
131         'code' => ldap_errno($this->conn),
132         'type' => 'ldap',
133         'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
134       true);
135     }
136     
137     return false;
138   }
139
140
141   /**
142    * Close connection to LDAP server
143    */
144   function close()
145   {
146     if ($this->conn)
147     {
148       @ldap_unbind($this->conn);
149       $this->conn = null;
150     }
151   }
152
153
154   /**
155    * Set internal list page
156    *
157    * @param  number  Page number to list
158    * @access public
159    */
160   function set_page($page)
161   {
162     $this->list_page = (int)$page;
163   }
164
165
166   /**
167    * Set internal page size
168    *
169    * @param  number  Number of messages to display on one page
170    * @access public
171    */
172   function set_pagesize($size)
173   {
174     $this->page_size = (int)$size;
175   }
176
177
178   /**
179    * Save a search string for future listings
180    *
181    * @param string Filter string
182    */
183   function set_search_set($filter)
184   {
185     $this->filter = $filter;
186   }
187   
188   
189   /**
190    * Getter for saved search properties
191    *
192    * @return mixed Search properties used by this class
193    */
194   function get_search_set()
195   {
196     return $this->filter;
197   }
198
199
200   /**
201    * Reset all saved results and search parameters
202    */
203   function reset()
204   {
205     $this->result = null;
206     $this->ldap_result = null;
207     $this->filter = '';
208   }
209   
210   
211   /**
212    * List the current set of contact records
213    *
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
217    */
218   function list_records($cols=null, $subset=0)
219   {
220     // add general filter to query
221     if (!empty($this->prop['filter']))
222     {
223       $filter = $this->prop['filter'];
224       $this->set_search_set($filter);
225     }
226     
227     // exec LDAP search if no result resource is stored
228     if ($this->conn && !$this->ldap_result)
229       $this->_exec_search();
230     
231     // count contacts for this user
232     $this->result = $this->count();
233     
234     // we have a search result resource
235     if ($this->ldap_result && $this->result->count > 0)
236     {
237       if ($this->sort_col && $this->prop['scope'] !== "base")
238         @ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
239         
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]));
243     }
244
245     return $this->result;
246   }
247
248
249   /**
250    * Search contacts
251    *
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
256    */
257   function search($fields, $value, $strict=false, $select=true)
258   {
259     // special treatment for ID-based search
260     if ($fields == 'ID' || $fields == $this->primary_key)
261     {
262       $ids = explode(',', $value);
263       $result = new rcube_result_set();
264       foreach ($ids as $id)
265         if ($rec = $this->get_record($id, true))
266         {
267           $result->add($rec);
268           $result->count++;
269         }
270       
271       return $result;
272     }
273     
274     $filter = '(|';
275     $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
276     if (is_array($this->prop['search_fields']))
277     {
278       foreach ($this->prop['search_fields'] as $k => $field)
279         $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
280     }
281     else
282     {
283       foreach ((array)$fields as $field)
284         if ($f = $this->_map_field($field))
285           $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
286     }
287     $filter .= ')';
288     
289     // add general filter to query
290     if (!empty($this->prop['filter']))
291       $filter = '(&'.$this->prop['filter'] . $filter . ')';
292
293     // set filter string and execute search
294     $this->set_search_set($filter);
295     $this->_exec_search();
296     
297     if ($select)
298       $this->list_records();
299     else
300       $this->result = $this->count();
301    
302     return $this->result; 
303   }
304
305
306   /**
307    * Count number of available contacts in database
308    *
309    * @return object rcube_result_set Resultset with values for 'count' and 'first'
310    */
311   function count()
312   {
313     $count = 0;
314     if ($this->conn && $this->ldap_result)
315       $count = ldap_count_entries($this->conn, $this->ldap_result);
316
317     return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
318   }
319
320
321   /**
322    * Return the last result set
323    *
324    * @return object rcube_result_set Current resultset or NULL if nothing selected yet
325    */
326   function get_result()
327   {
328     return $this->result;
329   }
330   
331   
332   /**
333    * Get a specific contact record
334    *
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
338    */
339   function get_record($dn, $assoc=false)
340   {
341     $res = null;
342     if ($this->conn && $dn)
343     {
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);
346       
347       if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
348       {
349         $res = $this->_ldap2result($rec);
350         $this->result = new rcube_result_set(1);
351         $this->result->add($res);
352       }
353     }
354
355     return $assoc ? $res : $this->result;
356   }
357   
358   
359   /**
360    * Create a new contact record
361    *
362    * @param array    Hash array with save data
363    * @return boolean The create record ID on success, False on error
364    */
365   function insert($save_cols)
366   {
367     // TODO
368     return false;
369   }
370   
371   
372   /**
373    * Update a specific contact record
374    *
375    * @param mixed Record identifier
376    * @param array Hash array with save data
377    * @return boolean True on success, False on error
378    */
379   function update($id, $save_cols)
380   {
381     // TODO    
382     return false;
383   }
384   
385   
386   /**
387    * Mark one or more contact records as deleted
388    *
389    * @param array  Record identifiers
390    * @return boolean True on success, False on error
391    */
392   function delete($ids)
393   {
394     // TODO
395     return false;
396   }
397
398
399   /**
400    * Execute the LDAP search based on the stored credentials
401    *
402    * @access private
403    */
404   function _exec_search()
405   {
406     if ($this->conn && $this->filter)
407     {
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);
410       return true;
411     }
412     else
413       return false;
414   }
415   
416   
417   /**
418    * @access private
419    */
420   function _ldap2result($rec)
421   {
422     $out = array();
423     
424     if ($rec['dn'])
425       $out[$this->primary_key] = base64_encode($rec['dn']);
426     
427     foreach ($this->fieldmap as $rf => $lf)
428     {
429       if ($rec[$lf]['count'])
430         $out[$rf] = $rec[$lf][0];
431     }
432     
433     return $out;
434   }
435   
436   
437   /**
438    * @access private
439    */
440   function _map_field($field)
441   {
442     return $this->fieldmap[$field];
443   }
444   
445   
446   /**
447    * @static
448    */
449   function quote_string($str)
450   {
451     return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));
452   }
453
454
455 }
456
457 ?>