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