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