4 * assigns some standard variables to smarty templates
8 $smarty->assign('USER',$_SESSION['ldapab']['username']);
12 * Uses Username and Password from Session to initialize the LDAP handle
13 * If it fails it redirects to login.php
15 function ldap_login(){
17 if(!empty($_SESSION['ldapab']['username'])){
18 // existing session! Check if valid
19 if($_SESSION['ldapab']['browserid'] != auth_browseruid()){
20 //session hijacking detected
21 header('Location: login.php?username=');
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 (!empty($_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;
37 if(empty($_SESSION['ldapab']) ||
38 !do_ldap_bind($_SESSION['ldapab']['username'],
39 $_SESSION['ldapab']['password'],
40 $_SESSION['ldapab']['binddn'])){
41 header('Location: login.php?username=');
47 * Creates a global LDAP connection handle called $LDAP_CON
49 function do_ldap_bind($user,$pass,$dn=""){
53 //create global connection to LDAP if necessary
55 if (!empty($conf['ldapurl'])){
56 $LDAP_CON = ldap_connect($conf['ldapurl']);
58 $LDAP_CON = ldap_connect($conf['ldapserver'],$conf['ldapport']);
61 die("couldn't connect to LDAP server");
65 if($conf['ldapv3']) ldap_set_option($LDAP_CON, LDAP_OPT_PROTOCOL_VERSION, 3);
68 //anonymous bind to lookup users
69 //blank binddn or blank bindpw will result in anonymous bind
70 if(!ldap_bind($LDAP_CON,$conf['anonbinddn'],$conf['anonbindpw'])){
71 die("can not bind for user lookup");
74 //when no user was given stay connected anonymous
76 set_session('','','');
80 //get dn for given user
81 $filter = str_replace('%u',$user,$conf['userfilter']);
82 $sr = ldap_search($LDAP_CON, $conf['usertree'], $filter);;
83 $result = ldap_get_entries($LDAP_CON, $sr);
84 if($result['count'] != 1){
85 set_session('','','');
88 $dn = $result[0]['dn'];
92 if(ldap_bind($LDAP_CON,$dn,$pass)){
93 //bind successful -> set up session
94 set_session($user,$pass,$dn);
97 //bind failed -> remove session
98 set_session('','','');
103 * Builds a pseudo UID from browser and IP data
105 * This is neither unique nor unfakable - still it adds some
106 * security. Using the first part of the IP makes sure
107 * proxy farms like AOLs are stil okay.
109 * @author Andreas Gohr <andi@splitbrain.org>
111 * @return string a MD5 sum of various browser headers
113 function auth_browseruid(){
115 if (empty($_SERVER['HTTP_USER_AGENT'])) { $_SERVER['HTTP_USER_AGENT']='USER_AGENT'; }
116 if (empty($_SERVER['HTTP_ACCEPT_ENCODING'])) { $_SERVER['HTTP_ACCEPT_ENCODING']='ACCEPT_ENCODING'; }
117 if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $_SERVER['HTTP_ACCEPT_LANGUAGE']='ACCEPT_LANGUAGE'; }
118 if (empty($_SERVER['HTTP_ACCEPT_CHARSET'])) { $_SERVER['HTTP_ACCEPT_CHARSET']='ACCEPT_CHARSET'; }
119 $uid .= $_SERVER['HTTP_USER_AGENT'];
120 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
121 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
122 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
123 $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
129 * saves user data to Session and cookies
131 function set_session($user,$pass,$dn){
135 $_SESSION['ldapab']['username'] = $user;
136 $_SESSION['ldapab']['binddn'] = $dn;
137 $_SESSION['ldapab']['password'] = $pass;
138 $_SESSION['ldapab']['browserid'] = auth_browseruid();
140 // (re)set the persistent auth cookie
142 setcookie('ldapabauth','',time()+60*60*24*365);
143 }elseif(!empty($_REQUEST['remember'])){
144 $cookie = serialize(array($user,$pass));
145 $cookie = x_Encrypt($cookie,get_cookie_secret());
146 $cookie = base64_encode($cookie);
147 setcookie('ldapabauth',$cookie,time()+60*60*24*365);
152 * Creates a random string to encrypt persistent auth
153 * cookies; the string is stored inside the cache dir
155 function get_cookie_secret(){
156 $file = dirname(__FILE__).'/cache/.htcookiesecret.php';
157 if(@file_exists($file)){
158 return md5(trim(file($file)));
161 $secret = '<?php #'.(rand()*time()).'?>';
162 if(!$fh = fopen($file,'w')) die("Couldn't write to $file");
163 if(fwrite($fh, $secret) === FALSE) die("Couldn't write to $file");
170 * binary safe function to get all search result data.
171 * It will use ldap_get_values_len() instead and build the array
172 * note: it's similar with the array returned by ldap_get_entries()
173 * except it has no "count" elements
175 * @author: Original code by Ovidiu Geaboc <ogeaboc@rdanet.com>
177 function ldap_get_binentries($conn,$srchRslt){
178 if(!@ldap_count_entries($conn,$srchRslt)){
181 $entry = ldap_first_entry($conn, $srchRslt);
184 $dn = ldap_get_dn($conn,$entry);
185 $attrs = ldap_get_attributes($conn, $entry);
186 for($j=0; $j<$attrs['count']; $j++) {
187 $vals = ldap_get_values_len($conn, $entry,$attrs[$j]);
188 for($k=0; $k<$vals['count']; $k++){
189 $data[$i][$attrs[$j]][$k]=$vals[$k];
194 }while ($entry = ldap_next_entry($conn, $entry));
201 * loads ldap names and their cleartext meanings from
202 * entries.conf file and returns it as hash
204 function namedentries($flip=false){
205 trigger_error('deprecated namedentries called',E_USER_WARNING);
209 * Creates an array for submission to ldap from websitedata
211 function prepare_ldap_entry($in){
217 if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in['anniversary'])) $in['anniversary']='';
218 if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in['birthday'])) $in['birthday']='';
220 // we map all internal names to the configured LDAP attributes here
221 foreach($in as $key => $value){
223 // normal mapped field
224 $out[$FIELDS[$key]][] = $value;
225 }elseif($FIELDS["_$key"]){
226 // mapped multi field
227 if(is_array($value)){
228 $out[$FIELDS["_$key"]] = $value;
230 $out[$FIELDS["_$key"]][] = $value; //shouldn't happen, but to be sure
233 // no mapping found - assume it to be a LDAP attribute (shouldn't happen)
234 if(is_array($value)){
237 $out[$key][] = $value;
242 // add the Objectclasses
243 $out['objectclass'] = $OCLASSES;
245 return clear_array($out);
249 * remove empty element from arrays recursively
251 * @author Original by <xntx@msn.com>
253 function clear_array ( $a ) {
254 if ($a !== array()) {
256 foreach ( $a as $key => $value ) {
257 if (is_array($value)) {
258 if (clear_array($value) !== false) {
259 $b[$key] = clear_array ( $value );
261 } elseif ($value !== '') {
265 if ($b !== array()) {
276 * deletes an entryfrom ldap - optional with recursion
278 * @author Original by <gabriel@hrz.uni-marburg.de>
280 function ldap_full_delete($ds,$dn,$recursive=false){
281 if($recursive == false){
282 return(ldap_delete($ds,$dn));
284 //searching for sub entries
285 $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
286 $info = ldap_get_entries($ds, $sr);
287 for($i=0;$i<$info['count'];$i++){
288 //deleting recursively sub entries
289 $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
291 //return result code, if delete fails
295 return(ldap_delete($ds,$dn));
300 * Returns all User Accounts as assoziative array
302 function get_users(){
306 $sr = ldap_list($LDAP_CON,$conf['usertree'],"ObjectClass=inetOrgPerson");
307 $result = ldap_get_binentries($LDAP_CON, $sr);
310 foreach ($result as $entry){
311 if(!empty($entry['sn'][0])){
312 $users[$entry['dn']] = $entry['givenName'][0]." ".$entry['sn'][0];
320 * makes sure the given DN contains exactly one space
323 function normalize_dn($dn){
324 $dn = preg_replace('/,/',', ',$dn);
325 $dn = preg_replace('/,\s+/',', ',$dn);
330 * Merges the given classes with the existing ones
332 function ldap_store_objectclasses($dn,$classes){
336 $sr = ldap_search($LDAP_CON,$dn,"objectClass=*",array('objectClass'));
337 $result = ldap_get_binentries($LDAP_CON, $sr);
338 $set = $result[0]['objectClass'];
339 $set = array_unique_renumber(array_merge((array)$set,(array)$classes));
340 $add['objectClass'] = $set;
342 $r = @ldap_mod_replace($LDAP_CON,$dn,$add);
351 * escape parenthesises in given string
353 function ldap_filterescape($string){
354 return strtr($string,array('('=>'\(', ')'=>'\)'));
358 * Queries public and private addressbooks, combining the
361 * @todo This function should be used where ever possible, replacing
362 * lots of duplicate code
364 function ldap_queryabooks($filter,$types){
368 // make sure $types is an array
369 if(!is_array($types)){
370 $types = explode(',',$types);
371 $types = array_map('trim',$types);
378 // public addressbook
379 $sr = ldap_list($LDAP_CON,$conf['publicbook'],
381 $result1 = ldap_get_binentries($LDAP_CON, $sr);
382 ldap_free_result($sr);
384 // private addressbook
385 if(!empty($_SESSION['ldapab']['binddn'])){
386 $sr = @ldap_list($LDAP_CON,$conf['privatebook'].
387 ','.$_SESSION['ldapab']['binddn'],
389 $result2 = ldap_get_binentries($LDAP_CON, $sr);
392 // return merged results
393 return array_merge((array)$result1,(array)$result2);
397 * Makes array unique and renumbers the entries
399 * @author <kay_rules@yahoo.com>
401 function array_unique_renumber($somearray){
402 $tmparr = array_unique($somearray);
404 foreach ($tmparr as $v) {
412 * Simple XOR encryption
414 * @author Dustin Schneider
415 * @link http://www.phpbuilder.com/tips/item.php?id=68
417 function x_Encrypt($string, $key){
418 for($i=0; $i<strlen($string); $i++){
419 for($j=0; $j<strlen($key); $j++){
420 $string[$i] = $string[$i]^$key[$j];
427 * Simple XOR decryption
429 * @author Dustin Schneider
430 * @link http://www.phpbuilder.com/tips/item.php?id=68
432 function x_Decrypt($string, $key){
433 for($i=0; $i<strlen($string); $i++){
434 for($j=0; $j<strlen($key); $j++){
435 $string[$i] = $key[$j]^$string[$i];
442 * Decodes UTF8 recursivly for the given array
446 function utf8_decode_array(&$array) {
447 trigger_error('deprecated utf8_decode_array called',E_USER_WARNING);
449 foreach (array_keys($array) as $key) {
450 if($key === 'dn') continue;
451 if($key === 'jpegPhoto') continue;
452 if (is_array($array[$key])) {
453 utf8_decode_array($array[$key]);
455 $array[$key] = utf8_decode($array[$key]);
461 * Encodes the given array to UTF8 recursively
465 function utf8_encode_array(&$array) {
466 trigger_error('deprecated utf8_encode_array called',E_USER_WARNING);
468 foreach (array_keys($array) as $key) {
469 if($key === 'dn') continue;
470 if($key === 'jpegPhoto') continue;
471 if (is_array($array[$key])) {
472 utf8_encode_array($array[$key]);
474 $array[$key] = utf8_encode($array[$key]);