]> git.sur5r.net Git - contagged/blob - functions.php
4ccaae50ef6c8594144d13f5efa14d74ec7624da
[contagged] / functions.php
1 <?
2
3 /**
4  * assigns some standard variables to smarty templates
5  */
6 function smarty_std(){
7   global $smarty;
8   $smarty->assign('USER',$_SESSION[ldapab][username]);
9 }
10
11 /**
12  * Uses Username and Password from Session to initialize the LDAP handle
13  * If it fails it redirects to login.php
14  */
15 function ldap_login(){
16   global $conf;
17   if(!empty($_SESSION['ldapab']['username'])){
18     // existing session! Check if valid
19     if($_COOKIE['ldapabconid'] != $_SESSION['ldapab']['conid']){
20       //session hijacking detected
21        header('Location: login.php?username=');
22        exit;
23     }
24   } elseif ($conf['httpd_auth'] && !empty($_SERVER['PHP_AUTH_USER'])) {
25     // use HTTP auth if wanted and possible
26         $_SESSION['ldapab']['username'] = $_SERVER['PHP_AUTH_USER'];
27         $_SESSION['ldapab']['password'] = $_SERVER['PHP_AUTH_PW'];
28   } elseif ($_COOKIE['ldapabauth']) {
29     // check persistent cookie
30     $cookie = base64_decode($_COOKIE['ldapabauth']);
31     $cookie = x_Decrypt($cookie,get_cookie_secret());
32     list($u,$p) = unserialize($cookie);
33     $_SESSION['ldapab']['username'] = $u;
34     $_SESSION['ldapab']['password'] = $p;
35   }
36
37   if(!do_ldap_bind($_SESSION['ldapab']['username'],
38                    $_SESSION['ldapab']['password'],
39                    $_SESSION['ldapab']['binddn'])){
40     header('Location: login.php?username=');
41     exit;
42   }
43 }
44
45 /**
46  * Creates a global LDAP connection handle called $LDAP_CON
47  */
48 function do_ldap_bind($user,$pass,$dn=""){
49   global $conf;
50   global $LDAP_CON;
51   
52   //create global connection to LDAP if nessessary
53   if(!$LDAP_CON){
54     $LDAP_CON = ldap_connect($conf[ldapserver],$conf[ldapport]);
55     if(!$LDAP_CON){
56       die("couldn't connect to LDAP server");
57     }
58   }
59
60   if(empty($dn)){
61     //anonymous bind to lookup users
62     //blank binddn or blank bindpw will result in anonymous bind
63     if(!ldap_bind($LDAP_CON,$conf[anonbinddn],$conf[anonbindpw])){
64       die("can not bind for user lookup");
65     }
66   
67     //when no user was given stay connected anonymous
68     if(empty($user)){
69       set_session('','','');
70       return true;
71     }
72
73     //get dn for given user
74     $filter = str_replace('%u',$user,$conf[userfilter]);
75     $sr = ldap_search($LDAP_CON, $conf[usertree], $filter);;
76     $result = ldap_get_entries($LDAP_CON, $sr);
77     if($result['count'] != 1){
78       set_session('','','');
79       return false;
80     }
81     $dn = $result[0]['dn'];
82   }
83
84   //bind with dn
85   if(ldap_bind($LDAP_CON,$dn,$pass)){
86     //bind successful -> set up session
87     set_session($user,$pass,$dn);
88     return true;
89   }
90   //bind failed -> remove session
91   set_session('','','');
92   return false;
93 }
94
95 /**
96  * saves user data to Session and cookies
97  */
98 function set_session($user,$pass,$dn){
99   global $conf;
100
101   $rand = rand();
102   $_SESSION[ldapab][username]=$user;
103   $_SESSION[ldapab][binddn]  =$dn;
104   $_SESSION[ldapab][password]=$pass;
105   $_SESSION[ldapab][conid]   =$rand;
106   setcookie('ldapabconid',$rand,time()+60*60*24);
107
108   // (re)set the persistant auth cookie
109   if($user == ''){
110     setcookie('ldapabauth','',time()+60*60*24*365);
111   }elseif($_REQUEST['remember']){
112     $cookie = serialize(array($user,$pass));
113     $cookie = x_Encrypt($cookie,get_cookie_secret());
114     $cookie = base64_encode($cookie);
115     setcookie('ldapabauth',$cookie,time()+60*60*24*365);
116   }
117 }
118
119 /**
120  * Creates a random string to encrypt persistant auth
121  * cookies the string is stored inside the cache dir
122  */
123 function get_cookie_secret(){
124   $file = dirname(__FILE__).'/cache/.htcookiesecret.php';
125   if(@file_exists($file)){
126     return md5(trim(file($file)));
127   }
128
129   $secret = '<?php #'.(rand()*time()).'?>';
130   if(!$fh = fopen($file,'w')) die("Couldn't write to $file");
131   if(fwrite($fh, $secret) === FALSE) die("Couldn't write to $file");
132   fclose($fh);
133
134   return md5($secret);
135 }
136
137 /**
138  * binary safe function to get all search result data.
139  * It will use ldap_get_values_len() instead and build the array
140  * note: it's similar with the array returned by ldap_get_entries()
141  * except it has no "count" elements
142  *
143  * @author: Original code by Ovidiu Geaboc <ogeaboc@rdanet.com>
144  */
145 function ldap_get_binentries($conn,$srchRslt){
146   if(!@ldap_count_entries($conn,$srchRslt)){
147     return null;
148   }
149   $entry = ldap_first_entry($conn, $srchRslt);
150   $i=0;
151   do {
152     $dn = ldap_get_dn($conn,$entry);
153     $attrs = ldap_get_attributes($conn, $entry);
154     for($j=0; $j<$attrs['count']; $j++) {
155       $vals = ldap_get_values_len($conn, $entry,$attrs[$j]);
156       for($k=0; $k<$vals['count']; $k++){
157         $data[$i][$attrs[$j]][$k]=$vals[$k];
158       }
159     }
160     $data[$i]['dn']=$dn;
161     $i++;
162   }while ($entry = ldap_next_entry($conn, $entry));
163
164   return $data;
165 }
166
167 /**
168  * loads ldap names and their cleartext meanings from
169  * entries.conf file and returns it as hash
170  */
171 function namedentries($flip=false){
172   global $conf;
173
174   $entries[dn]                         = 'dn';
175   $entries[sn]                         = 'name';
176   $entries[givenName]                  = 'givenname';
177   $entries[title]                      = 'title';
178   $entries[o]                          = 'organization';
179   $entries[physicalDeliveryOfficeName] = 'office';
180   $entries[postalAddress]              = 'street';
181   $entries[postalCode]                 = 'zip';
182   $entries[l]                          = 'location';
183   $entries[telephoneNumber]            = 'phone';
184   $entries[facsimileTelephoneNumber]   = 'fax';
185   $entries[mobile]                     = 'mobile';
186   $entries[pager]                      = 'pager';
187   $entries[homePhone]                  = 'homephone';
188   $entries[homePostalAddress]          = 'homestreet';
189   $entries[jpegPhoto]                  = 'photo';
190   $entries[labeledURI]                 = 'url';
191   $entries[description]                = 'note';
192   $entries[manager]                    = 'manager';
193   $entries[cn]                         = 'displayname';
194
195   if($conf[extended]){
196     $entries[anniversary]              = 'anniversary';
197   }
198   if($conf[openxchange]){
199     $entries[mailDomain]               = 'domain';
200     $entries[userCountry]              = 'country';
201     $entries[birthDay]                 = 'birthday';
202     $entries[IPPhone]                  = 'ipphone';
203     $entries[OXUserCategories]         = 'categories';
204     $entries[OXUserInstantMessenger]   = 'instantmessenger';
205     $entries[OXTimeZone]               = 'timezone';
206     $entries[OXUserPosition]           = 'position';
207     $entries[relClientCert]            = 'certificate';
208   }
209
210   if($flip){
211     $entries = array_reverse($entries);
212     $entries = array_flip($entries);
213   }
214   return $entries;
215 }
216
217 /**
218  * Creates an array for submission to ldap from websitedata
219  */
220 function prepare_ldap_entry($in){
221   global $conf;
222
223   //check dateformat
224   if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in[anniversary])){
225     $in[anniversary]='';
226   }
227
228   $entries = namedentries(true);
229   foreach(array_keys($in) as $key){
230     if(empty($entries[$key])){
231       $keyname=$key;
232     }else{
233       $keyname=$entries[$key];
234     }
235     if(is_array($in[$key])){
236       $out[$keyname] = $in[$key];
237     }else{
238       $out[$keyname][] = $in[$key];
239     }
240   }
241
242   //standard Objectclass
243   $out[objectclass][] = 'inetOrgPerson';
244   if($conf[extended]){
245     $out[objectclass][] = 'contactPerson';
246   }
247   if($conf[openxchange]){
248     $out[objectclass][] = 'OXUserObject';
249   }
250
251   return clear_array($out);
252 }
253
254 /**
255  * remove empty element from arrays recursively
256  *
257  * @author Original by <xntx@msn.com>
258  */
259 function clear_array ( $a ) {
260   if ($a !== array()) {
261     $b = array();
262     foreach ( $a as $key => $value ) {
263         if (is_array($value)) {
264           if (clear_array($value) !== false) {
265             $b[$key] = clear_array ( $value );
266           }
267         } elseif ($value !== '') {
268           $b[$key] = $value;
269         }
270     }
271     if ($b !== array()) {
272         return $b;
273     } else {
274         return false;
275     }
276   } else {
277     return false;
278   }
279 }
280
281 /**
282  * deletes an entryfrom ldap - optional with recursion
283  *
284  * @author Original by <gabriel@hrz.uni-marburg.de>
285  */
286 function ldap_full_delete($ds,$dn,$recursive=false){
287   if($recursive == false){
288     return(ldap_delete($ds,$dn));
289   }else{
290     //searching for sub entries
291     $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
292     $info = ldap_get_entries($ds, $sr);
293     for($i=0;$i<$info['count'];$i++){
294       //deleting recursively sub entries
295       $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
296       if(!$result){
297         //return result code, if delete fails
298         return($result);
299       }
300     }
301     return(ldap_delete($ds,$dn));
302   }
303 }
304
305 /**
306  * Returns all User Accounts as assoziative array
307  */
308 function get_users(){
309   global $conf;
310   global $LDAP_CON;
311
312   $sr = ldap_list($LDAP_CON,$conf[usertree],"ObjectClass=inetOrgPerson");
313   $result = ldap_get_binentries($LDAP_CON, $sr);
314   if(count($result)){
315     foreach ($result as $entry){
316       if(!empty($entry[sn][0])){
317         $users[$entry[dn]] = $entry[givenName][0]." ".$entry[sn][0];
318       }
319     }
320   }
321   return $users; 
322 }
323
324 /**
325  * makes sure the given DN contains exactly one space
326  * after each ,
327  */
328 function normalize_dn($dn){
329   $dn = preg_replace('/,/',', ',$dn);
330   $dn = preg_replace('/,\s+/',', ',$dn);
331   return $dn;
332 }
333
334 /**
335  * Merges the given classes with the existing ones
336  */
337 function ldap_store_objectclasses($dn,$classes){
338   global $conf;
339   global $LDAP_CON;
340
341   $sr     = ldap_search($LDAP_CON,$dn,"objectClass=*",array('objectClass'));
342   $result = ldap_get_binentries($LDAP_CON, $sr);
343   $set    = $result[0][objectClass];
344   $set    = array_unique_renumber(array_merge($set,$classes));
345   $add[objectClass] = $set;
346
347   $r = @ldap_mod_replace($LDAP_CON,$dn,$add);
348   tpl_ldaperror();
349
350 /*  print '<pre>';
351   print_r($set);
352   print '</pre>';*/
353 }
354
355 /**
356  * escape parenthesises in given string
357  */
358 function ldap_filterescape($string){
359   return strtr($string,array('('=>'\(', ')'=>'\)'));
360 }
361
362 /**
363  * Queries public and private addressbooks, combining the
364  * results
365  *
366  * @todo This function should be used where ever possible, replacing
367  *       lots of duplicate code
368  */
369 function ldap_queryabooks($filter,$types){
370   global $conf;
371   global $LDAP_CON;
372
373   // make sure $types is an array
374   if(!is_array($types)){
375     $types = explode(',',$types);
376     $types = array_map('trim',$types);
377   }
378
379   $results = array();
380   $result1 = array();
381   $result2 = array();
382
383   // public addressbook
384   $sr      = ldap_list($LDAP_CON,$conf['publicbook'],
385                        $filter,$types);
386   $result1 = ldap_get_binentries($LDAP_CON, $sr);
387   ldap_free_result($sr);
388
389   // private addressbook
390   if(!empty($_SESSION['ldapab']['binddn'])){
391     $sr      = @ldap_list($LDAP_CON,$conf['privatebook'].
392                           ','.$_SESSION['ldapab']['binddn'],
393                           $filter,$types);
394     $result2 = ldap_get_binentries($LDAP_CON, $sr);
395   }
396
397   // return merged results
398   return array_merge($result1,$result2);
399 }
400
401 /**
402  * Makes array unique and renumbers the entries
403  *
404  * @author <kay_rules@yahoo.com>
405  */
406 function array_unique_renumber($somearray){
407    $tmparr = array_unique($somearray);
408    $i=0;
409    foreach ($tmparr as $v) {
410        $newarr[$i] = $v;
411        $i++;
412    }
413    return $newarr;
414 }
415
416 /**
417  * Simple XOR encryption
418  *
419  * @author Dustin Schneider
420  * @link http://www.phpbuilder.com/tips/item.php?id=68
421  */
422 function x_Encrypt($string, $key){
423     for($i=0; $i<strlen($string); $i++){
424         for($j=0; $j<strlen($key); $j++){
425             $string[$i] = $string[$i]^$key[$j];
426         }
427     }
428     return $string;
429 }
430
431 /**
432  * Simple XOR decryption
433  *
434  * @author Dustin Schneider
435  * @link http://www.phpbuilder.com/tips/item.php?id=68
436  */
437 function x_Decrypt($string, $key){
438     for($i=0; $i<strlen($string); $i++){
439         for($j=0; $j<strlen($key); $j++){
440             $string[$i] = $key[$j]^$string[$i];
441         }
442     }
443     return $string;
444 }
445
446 /**
447  * Decodes UTF8 recursivly for the given array
448  *
449  * @deprecated
450  */
451 function utf8_decode_array(&$array) {
452   trigger_error('deprecated utf8_decode_array called',E_USER_WARNING);
453
454   foreach (array_keys($array) as $key) {
455     if($key === 'dn') continue;
456     if($key === 'jpegPhoto') continue;
457     if (is_array($array[$key])) {
458       utf8_decode_array($array[$key]);
459     }else {
460       $array[$key] = utf8_decode($array[$key]);
461     }
462   }
463 }
464
465 /**
466  * Encodes the given array to UTF8 recursively
467  *
468  * @deprecated
469  */
470 function utf8_encode_array(&$array) {
471   trigger_error('deprecated utf8_encode_array called',E_USER_WARNING);
472
473   foreach (array_keys($array) as $key) {
474     if($key === 'dn') continue;
475     if($key === 'jpegPhoto') continue;
476     if (is_array($array[$key])) {
477       utf8_encode_array($array[$key]);
478     }else {
479       $array[$key] = utf8_encode($array[$key]);
480     }
481   }
482 }
483
484
485 ?>