]> git.sur5r.net Git - contagged/blob - functions.php
c517e8407a25a3481f8b594e3643803b85337f8e
[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         $_SESSION[ldapab][username] = $_SERVER[PHP_AUTH_USER];
26         $_SESSION[ldapab][password] = $_SERVER[PHP_AUTH_PW];
27   }
28
29   if(!do_ldap_bind($_SESSION[ldapab][username],
30                    $_SESSION[ldapab][password],
31                    $_SESSION[ldapab][binddn])){
32     header('Location: login.php?username=');
33     exit;
34   }
35 }
36
37 /**
38  * Creates a global LDAP connection handle called $LDAP_CON
39  */
40 function do_ldap_bind($user,$pass,$dn=""){
41   global $conf;
42   global $LDAP_CON;
43   
44   //create global connection to LDAP if nessessary
45   if(!$LDAP_CON){
46     $LDAP_CON = ldap_connect($conf[ldapserver],$conf[ldapport]);
47     if(!$LDAP_CON){
48       die("couldn't connect to LDAP server");
49     }
50   }
51
52   if(empty($dn)){
53     //anonymous bind to lookup users
54     //blank binddn or blank bindpw will result in anonymous bind
55     if(!ldap_bind($LDAP_CON,$conf[anonbinddn],$conf[anonbindpw])){
56       die("can not bind anonymously");
57     }
58   
59     //when no user was given stay connected anonymous
60     if(empty($user)){
61       set_session('','','');
62       return true;
63     }
64
65     //get dn for given user
66     $filter = str_replace('%u',$user,$conf[userfilter]);
67     $sr = ldap_search($LDAP_CON, $conf[usertree], $filter);;
68     $result = ldap_get_entries($LDAP_CON, $sr);
69     if($result['count'] != 1){
70       set_session('','','');
71       return false;
72     }
73     $dn = $result[0]['dn'];
74   }
75
76   //bind with dn
77   if(ldap_bind($LDAP_CON,$dn,$pass)){
78     //bind successful -> set up session
79     set_session($user,$pass,$dn);
80     return true;
81   }
82   //bind failed -> remove session
83   set_session('','','');
84   return false;
85 }
86
87 /**
88  * saves user data to Session
89  */
90 function set_session($user,$pass,$dn){
91   $rand = rand();
92   $_SESSION[ldapab][username]=$user;
93   $_SESSION[ldapab][binddn]  =$dn;
94   $_SESSION[ldapab][password]=$pass;
95   $_SESSION[ldapab][conid]   =$rand;
96   setcookie('ldapabconid',$rand,time()+60*60*24);
97 }
98
99 /**
100  * binary safe function to get all search result data.
101  * It will use ldap_get_values_len() instead and build the array
102  * note: it's similar with the array returned by ldap_get_entries()
103  * except it has no "count" elements
104  *
105  * @author: Original code by Ovidiu Geaboc <ogeaboc@rdanet.com>
106  */
107 function ldap_get_binentries($conn,$srchRslt){
108   if(!@ldap_count_entries($conn,$srchRslt)){
109     return null;
110   }
111   $entry = ldap_first_entry($conn, $srchRslt);
112   $i=0;
113   do {
114     $dn = ldap_get_dn($conn,$entry);
115     $attrs = ldap_get_attributes($conn, $entry);
116     for($j=0; $j<$attrs['count']; $j++) {
117       $vals = ldap_get_values_len($conn, $entry,$attrs[$j]);
118       for($k=0; $k<$vals['count']; $k++){
119         $data[$i][$attrs[$j]][$k]=$vals[$k];
120       }
121     }
122     $data[$i]['dn']=$dn;
123     $i++;
124   }while ($entry = ldap_next_entry($conn, $entry));
125
126   return $data;
127 }
128
129 /**
130  * loads ldap names and their cleartext meanings from
131  * entries.conf file and returns it as hash
132  */
133 function namedentries($flip=false){
134   global $conf;
135
136   $entries[dn]                         = 'dn';
137   $entries[sn]                         = 'name';
138   $entries[givenName]                  = 'givenname';
139   $entries[title]                      = 'title';
140   $entries[o]                          = 'organization';
141   $entries[physicalDeliveryOfficeName] = 'office';
142   $entries[postalAddress]              = 'street';
143   $entries[postalCode]                 = 'zip';
144   $entries[l]                          = 'location';
145   $entries[telephoneNumber]            = 'phone';
146   $entries[facsimileTelephoneNumber]   = 'fax';
147   $entries[mobile]                     = 'mobile';
148   $entries[pager]                      = 'pager';
149   $entries[homePhone]                  = 'homephone';
150   $entries[homePostalAddress]          = 'homestreet';
151   $entries[jpegPhoto]                  = 'photo';
152   $entries[labeledURI]                 = 'url';
153   $entries[description]                = 'note';
154   $entries[manager]                    = 'manager';
155   $entries[cn]                         = 'displayname';
156
157   if($conf[extended]){
158     $entries[anniversary]              = 'anniversary';
159   }
160   if($conf[openxchange]){
161     $entries[mailDomain]               = 'domain';
162     $entries[userCountry]              = 'country';
163     $entries[birthDay]                 = 'birthday';
164     $entries[IPPhone]                  = 'ipphone';
165     $entries[OXUserCategories]         = 'categories';
166     $entries[OXUserInstantMessenger]   = 'instantmessenger';
167     $entries[OXTimeZone]               = 'timezone';
168     $entries[OXUserPosition]           = 'position';
169     $entries[relClientCert]            = 'certificate';
170   }
171
172   if($flip){
173     $entries = array_reverse($entries);
174     $entries = array_flip($entries);
175   }
176   return $entries;
177 }
178
179 /**
180  * Creates an array for submission to ldap from websitedata
181  */
182 function prepare_ldap_entry($in){
183   global $conf;
184
185   //check dateformat
186   if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in[anniversary])){
187     $in[anniversary]='';
188   }
189
190   $entries = namedentries(true);
191   foreach(array_keys($in) as $key){
192     if(empty($entries[$key])){
193       $keyname=$key;
194     }else{
195       $keyname=$entries[$key];
196     }
197     if(is_array($in[$key])){
198       $out[$keyname] = $in[$key];
199     }else{
200       $out[$keyname][] = $in[$key];
201     }
202   }
203
204   //standard Objectclass
205   $out[objectclass][] = 'inetOrgPerson';
206   if($conf[extended]){
207     $out[objectclass][] = 'contactPerson';
208   }
209   if($conf[openxchange]){
210     $out[objectclass][] = 'OXUserObject';
211   }
212
213   return clear_array($out);
214 }
215
216 /**
217  * remove empty element from arrays recursively
218  *
219  * @author Original by <xntx@msn.com>
220  */
221 function clear_array ( $a ) {
222   if ($a !== array()) {
223     $b = array();
224     foreach ( $a as $key => $value ) {
225         if (is_array($value)) {
226           if (clear_array($value) !== false) {
227             $b[$key] = clear_array ( $value );
228           }
229         } elseif ($value !== '') {
230           $b[$key] = $value;
231         }
232     }
233     if ($b !== array()) {
234         return $b;
235     } else {
236         return false;
237     }
238   } else {
239     return false;
240   }
241 }
242
243 /**
244  * deletes an entryfrom ldap - optional with recursion
245  *
246  * @author Original by <gabriel@hrz.uni-marburg.de>
247  */
248 function ldap_full_delete($ds,$dn,$recursive=false){
249   if($recursive == false){
250     return(ldap_delete($ds,$dn));
251   }else{
252     //searching for sub entries
253     $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
254     $info = ldap_get_entries($ds, $sr);
255     for($i=0;$i<$info['count'];$i++){
256       //deleting recursively sub entries
257       $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
258       if(!$result){
259         //return result code, if delete fails
260         return($result);
261       }
262     }
263     return(ldap_delete($ds,$dn));
264   }
265 }
266
267 /**
268  * Returns all User Accounts as assoziative array
269  */
270 function get_users(){
271   global $conf;
272   global $LDAP_CON;
273
274   $sr = ldap_list($LDAP_CON,$conf[usertree],"ObjectClass=inetOrgPerson");
275   $result = ldap_get_binentries($LDAP_CON, $sr);
276   if(count($result)){
277     foreach ($result as $entry){
278       if(!empty($entry[sn][0])){
279         $users[$entry[dn]] = $entry[givenName][0]." ".$entry[sn][0];
280       }
281     }
282   }
283   return $users; 
284 }
285
286 /**
287  * makes sure the given DN contains exactly one space
288  * after each ,
289  */
290 function normalize_dn($dn){
291   $dn = preg_replace('/,/',', ',$dn);
292   $dn = preg_replace('/,\s+/',', ',$dn);
293   return $dn;
294 }
295
296 /**
297  * Merges the given classes with the existing ones
298  */
299 function ldap_store_objectclasses($dn,$classes){
300   global $conf;
301   global $LDAP_CON;
302
303   $sr     = ldap_search($LDAP_CON,$dn,"objectClass=*",array('objectClass'));
304   $result = ldap_get_binentries($LDAP_CON, $sr);
305   $set    = $result[0][objectClass];
306   $set    = array_unique_renumber(array_merge($set,$classes));
307   $add[objectClass] = $set;
308
309   $r = @ldap_mod_replace($LDAP_CON,$dn,$add);
310   tpl_ldaperror();
311
312 /*  print '<pre>';
313   print_r($set);
314   print '</pre>';*/
315 }
316
317 /**
318  * Makes array unique and renumbers the entries
319  *
320  * @author <kay_rules@yahoo.com>
321  */
322 function array_unique_renumber($somearray){
323    $tmparr = array_unique($somearray);
324    $i=0;
325    foreach ($tmparr as $v) {
326        $newarr[$i] = $v;
327        $i++;
328    }
329    return $newarr;
330 }
331
332 /**
333  * Decodes UTF8 recursivly for the given array
334  */
335 function utf8_decode_array(&$array) {
336   trigger_error('deprecated utf8_decode_array called',E_USER_WARNING);
337
338   foreach (array_keys($array) as $key) {
339     if($key === 'dn') continue;
340     if($key === 'jpegPhoto') continue;
341     if (is_array($array[$key])) {
342       utf8_decode_array($array[$key]);
343     }else {
344       $array[$key] = utf8_decode($array[$key]);
345     }
346   }
347 }
348
349 /**
350  * Encodes the given array to UTF8 recursively
351  */
352 function utf8_encode_array(&$array) {
353   trigger_error('deprecated utf8_encode_array called',E_USER_WARNING);
354
355   foreach (array_keys($array) as $key) {
356     if($key === 'dn') continue;
357     if($key === 'jpegPhoto') continue;
358     if (is_array($array[$key])) {
359       utf8_encode_array($array[$key]);
360     }else {
361       $array[$key] = utf8_encode($array[$key]);
362     }
363   }
364 }
365
366 ?>