alecpl
2009-08-29 0131ec9724ce5e1e1abff188a2976c447f826a04
commit | author | age
d1d2c4 1 <?php
S 2 /*
3  +-----------------------------------------------------------------------+
47124c 4  | program/include/rcube_ldap.php                                        |
d1d2c4 5  |                                                                       |
S 6  | This file is part of the RoundCube Webmail client                     |
cbbef3 7  | Copyright (C) 2006-2009, RoundCube Dev. - Switzerland                 |
d1d2c4 8  | Licensed under the GNU GPL                                            |
S 9  |                                                                       |
10  | PURPOSE:                                                              |
f11541 11  |   Interface to an LDAP address directory                              |
d1d2c4 12  |                                                                       |
S 13  +-----------------------------------------------------------------------+
f11541 14  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
d1d2c4 15  +-----------------------------------------------------------------------+
S 16
17  $Id$
18
19 */
20
6d969b 21
T 22 /**
23  * Model class to access an LDAP address directory
24  *
25  * @package Addressbook
26  */
cc97ea 27 class rcube_ldap extends rcube_addressbook
f11541 28 {
d1d2c4 29   var $conn;
f11541 30   var $prop = array();
T 31   var $fieldmap = array();
32   
33   var $filter = '';
34   var $result = null;
35   var $ldap_result = null;
36   var $sort_col = '';
37   
38   /** public properties */
39   var $primary_key = 'ID';
40   var $readonly = true;
41   var $list_page = 1;
42   var $page_size = 10;
43   var $ready = false;
44   
45   
46   /**
47    * Object constructor
48    *
49    * @param array LDAP connection properties
50    * @param integer User-ID
51    */
52   function __construct($p)
53   {
54     $this->prop = $p;
6855ce 55
f11541 56     foreach ($p as $prop => $value)
T 57       if (preg_match('/^(.+)_field$/', $prop, $matches))
0131ec 58         $this->fieldmap[$matches[1]] = strtolower($value);
4f9c83 59
0131ec 60     $this->sort_col = $p['sort'];
4f9c83 61
f11541 62     $this->connect();
d1d2c4 63   }
S 64
f11541 65
T 66   /**
67    * Establish a connection to the LDAP server
68    */
69   function connect()
70   {
b9f9f1 71     global $RCMAIL;
T 72     
f11541 73     if (!function_exists('ldap_connect'))
6710a6 74       raise_error(array('code' => 100, 'type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
f11541 75
T 76     if (is_resource($this->conn))
77       return true;
78     
79     if (!is_array($this->prop['hosts']))
80       $this->prop['hosts'] = array($this->prop['hosts']);
81
03b271 82     if (empty($this->prop['ldap_version']))
T 83       $this->prop['ldap_version'] = 3;
84
f11541 85     foreach ($this->prop['hosts'] as $host)
T 86     {
87       if ($lc = @ldap_connect($host, $this->prop['port']))
88       {
b4b31d 89         if ($this->prop['use_tls']===true)
T 90           if (!ldap_start_tls($lc))
91             continue;
cd6749 92
03b271 93         ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['ldap_version']);
f11541 94         $this->prop['host'] = $host;
T 95         $this->conn = $lc;
96         break;
97       }
98     }
99     
100     if (is_resource($this->conn))
e3caaf 101     {
f11541 102       $this->ready = true;
4f9c83 103
b9f9f1 104       // User specific access, generate the proper values to use.
0131ec 105       if ($this->prop['user_specific']) {
b9f9f1 106         // No password set, use the session password
4f9c83 107         if (empty($this->prop['bind_pass'])) {
2471d3 108           $this->prop['bind_pass'] = $RCMAIL->decrypt($_SESSION['password']);
b9f9f1 109         }
4f9c83 110
S 111         // Get the pieces needed for variable replacement.
b9f9f1 112         $fu = $RCMAIL->user->get_username();
T 113         list($u, $d) = explode('@', $fu);
114         
115         // Replace the bind_dn and base_dn variables.
116         $replaces = array('%fu' => $fu, '%u' => $u, '%d' => $d);
117         $this->prop['bind_dn'] = strtr($this->prop['bind_dn'], $replaces);
118         $this->prop['base_dn'] = strtr($this->prop['base_dn'], $replaces);
119       }
120       
121       if (!empty($this->prop['bind_dn']) && !empty($this->prop['bind_pass']))
e3caaf 122         $this->ready = $this->bind($this->prop['bind_dn'], $this->prop['bind_pass']);
T 123     }
f11541 124     else
6710a6 125       raise_error(array('code' => 100, 'type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
4f9c83 126
S 127     // See if the directory is writeable.
128     if ($this->prop['writable']) {
129       $this->readonly = false;
130     } // end if
131
f11541 132   }
T 133
134
135   /**
e3caaf 136    * Bind connection with DN and password
6d969b 137    *
T 138    * @param string Bind DN
139    * @param string Bind password
140    * @return boolean True on success, False on error
f11541 141    */
e3caaf 142   function bind($dn, $pass)
f11541 143   {
736307 144     if (!$this->conn) {
e3caaf 145       return false;
736307 146     }
e3caaf 147     
b4b31d 148     if (@ldap_bind($this->conn, $dn, $pass)) {
e3caaf 149       return true;
736307 150     }
T 151
152     raise_error(array(
e3caaf 153         'code' => ldap_errno($this->conn),
T 154         'type' => 'ldap',
155         'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
736307 156         true);
T 157
e3caaf 158     return false;
T 159   }
f11541 160
T 161
162   /**
163    * Close connection to LDAP server
164    */
165   function close()
166   {
167     if ($this->conn)
6b603d 168     {
0131ec 169       ldap_unbind($this->conn);
6b603d 170       $this->conn = null;
T 171     }
f11541 172   }
T 173
174
175   /**
176    * Set internal list page
177    *
178    * @param  number  Page number to list
179    * @access public
180    */
181   function set_page($page)
182   {
183     $this->list_page = (int)$page;
184   }
185
186
187   /**
188    * Set internal page size
189    *
190    * @param  number  Number of messages to display on one page
191    * @access public
192    */
193   function set_pagesize($size)
194   {
195     $this->page_size = (int)$size;
196   }
197
198
199   /**
200    * Save a search string for future listings
201    *
6d969b 202    * @param string Filter string
f11541 203    */
T 204   function set_search_set($filter)
205   {
206     $this->filter = $filter;
207   }
208   
209   
210   /**
211    * Getter for saved search properties
212    *
213    * @return mixed Search properties used by this class
214    */
215   function get_search_set()
216   {
217     return $this->filter;
218   }
219
220
221   /**
222    * Reset all saved results and search parameters
223    */
224   function reset()
225   {
226     $this->result = null;
227     $this->ldap_result = null;
228     $this->filter = '';
229   }
230   
231   
232   /**
233    * List the current set of contact records
234    *
235    * @param  array  List of cols to show
4f9c83 236    * @param  int    Only return this number of records
f11541 237    * @return array  Indexed list of contact records, each a hash array
T 238    */
239   function list_records($cols=null, $subset=0)
240   {
6b603d 241     // add general filter to query
3c884a 242     if (!empty($this->prop['filter']) && empty($this->filter))
6b603d 243     {
T 244       $filter = $this->prop['filter'];
245       $this->set_search_set($filter);
246     }
247     
f11541 248     // exec LDAP search if no result resource is stored
T 249     if ($this->conn && !$this->ldap_result)
250       $this->_exec_search();
251     
252     // count contacts for this user
253     $this->result = $this->count();
0131ec 254
f11541 255     // we have a search result resource
T 256     if ($this->ldap_result && $this->result->count > 0)
257     {
0131ec 258       if ($this->sort_col && $this->prop['scope'] !== 'base')
A 259         ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
4f9c83 260
S 261       $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
262       $last_row = $this->result->first + $this->page_size;
263       $last_row = $subset != 0 ? $start_row + abs($subset) : $last_row;
264
f11541 265       $entries = ldap_get_entries($this->conn, $this->ldap_result);
4f9c83 266       for ($i = $start_row; $i < min($entries['count'], $last_row); $i++)
f11541 267         $this->result->add($this->_ldap2result($entries[$i]));
T 268     }
269
270     return $this->result;
271   }
272
273
274   /**
275    * Search contacts
276    *
277    * @param array   List of fields to search in
278    * @param string  Search value
279    * @param boolean True if results are requested, False if count only
6d969b 280    * @return array  Indexed list of contact records and 'count' value
f11541 281    */
3fc00e 282   function search($fields, $value, $strict=false, $select=true)
f11541 283   {
T 284     // special treatment for ID-based search
285     if ($fields == 'ID' || $fields == $this->primary_key)
286     {
287       $ids = explode(',', $value);
288       $result = new rcube_result_set();
289       foreach ($ids as $id)
290         if ($rec = $this->get_record($id, true))
291         {
292           $result->add($rec);
293           $result->count++;
294         }
295       
296       return $result;
297     }
298     
299     $filter = '(|';
3fc00e 300     $wc = !$strict && $this->prop['fuzzy_search'] ? '*' : '';
f11541 301     if (is_array($this->prop['search_fields']))
T 302     {
303       foreach ($this->prop['search_fields'] as $k => $field)
304         $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
305     }
306     else
307     {
308       foreach ((array)$fields as $field)
309         if ($f = $this->_map_field($field))
310           $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
311     }
312     $filter .= ')';
e3caaf 313     
72c722 314     // avoid double-wildcard if $value is empty
T 315     $filter = preg_replace('/\*+/', '*', $filter);
316     
e3caaf 317     // add general filter to query
T 318     if (!empty($this->prop['filter']))
72c722 319       $filter = '(&(' . preg_replace('/^\(|\)$/', '', $this->prop['filter']) . ')' . $filter . ')';
f11541 320
T 321     // set filter string and execute search
322     $this->set_search_set($filter);
323     $this->_exec_search();
324     
325     if ($select)
326       $this->list_records();
327     else
328       $this->result = $this->count();
329    
330     return $this->result; 
331   }
332
333
334   /**
335    * Count number of available contacts in database
336    *
6d969b 337    * @return object rcube_result_set Resultset with values for 'count' and 'first'
f11541 338    */
T 339   function count()
340   {
341     $count = 0;
4f9c83 342     if ($this->conn && $this->ldap_result) {
f11541 343       $count = ldap_count_entries($this->conn, $this->ldap_result);
4f9c83 344     } // end if
S 345     elseif ($this->conn) {
346       // We have a connection but no result set, attempt to get one.
347       if (empty($this->filter)) {
348         // The filter is not set, set it.
349         $this->filter = $this->prop['filter'];
350       } // end if
351       $this->_exec_search();
352       if ($this->ldap_result) {
353         $count = ldap_count_entries($this->conn, $this->ldap_result);
354       } // end if
355     } // end else
f11541 356
T 357     return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
358   }
359
360
361   /**
362    * Return the last result set
363    *
6d969b 364    * @return object rcube_result_set Current resultset or NULL if nothing selected yet
f11541 365    */
T 366   function get_result()
367   {
368     return $this->result;
369   }
370   
371   
372   /**
373    * Get a specific contact record
374    *
6d969b 375    * @param mixed   Record identifier
T 376    * @param boolean Return as associative array
377    * @return mixed  Hash array or rcube_result_set with all record fields
f11541 378    */
T 379   function get_record($dn, $assoc=false)
380   {
381     $res = null;
382     if ($this->conn && $dn)
383     {
0131ec 384       $this->ldap_result = ldap_read($this->conn, base64_decode($dn), "(objectclass=*)", array_values($this->fieldmap));
f11541 385       $entry = @ldap_first_entry($this->conn, $this->ldap_result);
0131ec 386
f11541 387       if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
T 388       {
0131ec 389         $rec = array_change_key_case($rec, CASE_LOWER);
A 390
4f9c83 391         // Add in the dn for the entry.
0131ec 392         $rec['dn'] = base64_decode($dn);
f11541 393         $res = $this->_ldap2result($rec);
T 394         $this->result = new rcube_result_set(1);
395         $this->result->add($res);
396       }
397     }
398
399     return $assoc ? $res : $this->result;
400   }
401   
402   
403   /**
404    * Create a new contact record
405    *
6d969b 406    * @param array    Hash array with save data
4f9c83 407    * @return encoded record ID on success, False on error
f11541 408    */
T 409   function insert($save_cols)
410   {
4f9c83 411     // Map out the column names to their LDAP ones to build the new entry.
S 412     $newentry = array();
0131ec 413     $newentry['objectClass'] = $this->prop['LDAP_Object_Classes'];
4f9c83 414     foreach ($save_cols as $col => $val) {
S 415       $fld = $this->_map_field($col);
0131ec 416       if ($fld != '') {
4f9c83 417         // The field does exist, add it to the entry.
S 418         $newentry[$fld] = $val;
419       } // end if
420     } // end foreach
421
422     // Verify that the required fields are set.
423     // We know that the email address is required as a default of rcube, so
424     // we will default its value into any unfilled required fields.
0131ec 425     foreach ($this->prop['required_fields'] as $fld) {
4f9c83 426       if (!isset($newentry[$fld])) {
0131ec 427         $newentry[$fld] = $newentry[$this->_map_field('email')];
4f9c83 428       } // end if
S 429     } // end foreach
430
431     // Build the new entries DN.
0131ec 432     $dn = $this->prop['LDAP_rdn'].'='.$newentry[$this->prop['LDAP_rdn']].','.$this->prop['base_dn'];
A 433     $res = ldap_add($this->conn, $dn, $newentry);
4f9c83 434     if ($res === FALSE) {
S 435       return false;
436     } // end if
437
438     return base64_encode($dn);
f11541 439   }
T 440   
441   
442   /**
443    * Update a specific contact record
444    *
445    * @param mixed Record identifier
6d969b 446    * @param array Hash array with save data
T 447    * @return boolean True on success, False on error
f11541 448    */
T 449   function update($id, $save_cols)
450   {
4f9c83 451     $record = $this->get_record($id, true);
S 452     $result = $this->get_result();
453     $record = $result->first();
454
455     $newdata = array();
456     $replacedata = array();
457     $deletedata = array();
458     foreach ($save_cols as $col => $val) {
459       $fld = $this->_map_field($col);
0131ec 460       if ($fld != '') {
4f9c83 461         // The field does exist compare it to the ldap record.
S 462         if ($record[$col] != $val) {
463           // Changed, but find out how.
464           if (!isset($record[$col])) {
465             // Field was not set prior, need to add it.
466             $newdata[$fld] = $val;
467           } // end if
0131ec 468           elseif ($val == '') {
4f9c83 469             // Field supplied is empty, verify that it is not required.
0131ec 470             if (!in_array($fld, $this->prop['required_fields'])) {
4f9c83 471               // It is not, safe to clear.
S 472               $deletedata[$fld] = $record[$col];
473             } // end if
474           } // end elseif
475           else {
476             // The data was modified, save it out.
477             $replacedata[$fld] = $val;
478           } // end else
479         } // end if
480       } // end if
481     } // end foreach
482
483     // Update the entry as required.
484     $dn = base64_decode($id);
485     if (!empty($deletedata)) {
486       // Delete the fields.
0131ec 487       $res = ldap_mod_del($this->conn, $dn, $deletedata);
4f9c83 488       if ($res === FALSE) {
S 489         return false;
490       } // end if
491     } // end if
492
493     if (!empty($replacedata)) {
494       // Replace the fields.
0131ec 495       $res = ldap_mod_replace($this->conn, $dn, $replacedata);
4f9c83 496       if ($res === FALSE) {
S 497         return false;
498       } // end if
499     } // end if
500
501     if (!empty($newdata)) {
502       // Add the fields.
0131ec 503       $res = ldap_mod_add($this->conn, $dn, $newdata);
4f9c83 504       if ($res === FALSE) {
S 505         return false;
506       } // end if
507     } // end if
508
509     return true;
f11541 510   }
T 511   
512   
513   /**
514    * Mark one or more contact records as deleted
515    *
516    * @param array  Record identifiers
6d969b 517    * @return boolean True on success, False on error
f11541 518    */
T 519   function delete($ids)
520   {
4f9c83 521     if (!is_array($ids)) {
S 522       // Not an array, break apart the encoded DNs.
0131ec 523       $dns = explode(',', $ids);
4f9c83 524     } // end if
S 525
526     foreach ($dns as $id) {
527       $dn = base64_decode($id);
528       // Delete the record.
0131ec 529       $res = ldap_delete($this->conn, $dn);
4f9c83 530       if ($res === FALSE) {
S 531         return false;
532       } // end if
533     } // end foreach
534
535     return true;
f11541 536   }
T 537
538
539   /**
540    * Execute the LDAP search based on the stored credentials
541    *
6d969b 542    * @access private
f11541 543    */
T 544   function _exec_search()
545   {
b4b31d 546     if ($this->ready && $this->filter)
f11541 547     {
T 548       $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
e3caaf 549       $this->ldap_result = $function($this->conn, $this->prop['base_dn'], $this->filter, array_values($this->fieldmap), 0, 0);
f11541 550       return true;
T 551     }
552     else
553       return false;
554   }
555   
556   
557   /**
6d969b 558    * @access private
f11541 559    */
T 560   function _ldap2result($rec)
561   {
562     $out = array();
563     
564     if ($rec['dn'])
565       $out[$this->primary_key] = base64_encode($rec['dn']);
566     
567     foreach ($this->fieldmap as $rf => $lf)
568     {
569       if ($rec[$lf]['count'])
570         $out[$rf] = $rec[$lf][0];
571     }
572     
573     return $out;
574   }
575   
576   
577   /**
6d969b 578    * @access private
f11541 579    */
T 580   function _map_field($field)
581   {
582     return $this->fieldmap[$field];
583   }
584   
585   
586   /**
587    * @static
588    */
589   function quote_string($str)
590   {
591     return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));
592   }
593
594 }
595
0131ec 596 ?>