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