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($_COOKIE['ldapabconid'] != $_SESSION['ldapab']['conid']){
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 ($_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(!do_ldap_bind($_SESSION['ldapab']['username'],
38 $_SESSION['ldapab']['password'],
39 $_SESSION['ldapab']['binddn'])){
40 header('Location: login.php?username=');
46 * Creates a global LDAP connection handle called $LDAP_CON
48 function do_ldap_bind($user,$pass,$dn=""){
52 //create global connection to LDAP if nessessary
54 $LDAP_CON = ldap_connect($conf[ldapserver],$conf[ldapport]);
56 die("couldn't connect to LDAP server");
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");
67 //when no user was given stay connected anonymous
69 set_session('','','');
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('','','');
81 $dn = $result[0]['dn'];
85 if(ldap_bind($LDAP_CON,$dn,$pass)){
86 //bind successful -> set up session
87 set_session($user,$pass,$dn);
90 //bind failed -> remove session
91 set_session('','','');
96 * saves user data to Session and cookies
98 function set_session($user,$pass,$dn){
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);
108 // (re)set the persistant auth cookie
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);
120 * Creates a random string to encrypt persistant auth
121 * cookies the string is stored inside the cache dir
123 function get_cookie_secret(){
124 $file = dirname(__FILE__).'/cache/.htcookiesecret.php';
125 if(@file_exists($file)){
126 return md5(trim(file($file)));
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");
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
143 * @author: Original code by Ovidiu Geaboc <ogeaboc@rdanet.com>
145 function ldap_get_binentries($conn,$srchRslt){
146 if(!@ldap_count_entries($conn,$srchRslt)){
149 $entry = ldap_first_entry($conn, $srchRslt);
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];
162 }while ($entry = ldap_next_entry($conn, $entry));
168 * loads ldap names and their cleartext meanings from
169 * entries.conf file and returns it as hash
171 function namedentries($flip=false){
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';
196 $entries[anniversary] = 'anniversary';
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';
211 $entries = array_reverse($entries);
212 $entries = array_flip($entries);
218 * Creates an array for submission to ldap from websitedata
220 function prepare_ldap_entry($in){
224 if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in[anniversary])){
228 $entries = namedentries(true);
229 foreach(array_keys($in) as $key){
230 if(empty($entries[$key])){
233 $keyname=$entries[$key];
235 if(is_array($in[$key])){
236 $out[$keyname] = $in[$key];
238 $out[$keyname][] = $in[$key];
242 //standard Objectclass
243 $out[objectclass][] = 'inetOrgPerson';
245 $out[objectclass][] = 'contactPerson';
247 if($conf[openxchange]){
248 $out[objectclass][] = 'OXUserObject';
251 return clear_array($out);
255 * remove empty element from arrays recursively
257 * @author Original by <xntx@msn.com>
259 function clear_array ( $a ) {
260 if ($a !== array()) {
262 foreach ( $a as $key => $value ) {
263 if (is_array($value)) {
264 if (clear_array($value) !== false) {
265 $b[$key] = clear_array ( $value );
267 } elseif ($value !== '') {
271 if ($b !== array()) {
282 * deletes an entryfrom ldap - optional with recursion
284 * @author Original by <gabriel@hrz.uni-marburg.de>
286 function ldap_full_delete($ds,$dn,$recursive=false){
287 if($recursive == false){
288 return(ldap_delete($ds,$dn));
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);
297 //return result code, if delete fails
301 return(ldap_delete($ds,$dn));
306 * Returns all User Accounts as assoziative array
308 function get_users(){
312 $sr = ldap_list($LDAP_CON,$conf[usertree],"ObjectClass=inetOrgPerson");
313 $result = ldap_get_binentries($LDAP_CON, $sr);
315 foreach ($result as $entry){
316 if(!empty($entry[sn][0])){
317 $users[$entry[dn]] = $entry[givenName][0]." ".$entry[sn][0];
325 * makes sure the given DN contains exactly one space
328 function normalize_dn($dn){
329 $dn = preg_replace('/,/',', ',$dn);
330 $dn = preg_replace('/,\s+/',', ',$dn);
335 * Merges the given classes with the existing ones
337 function ldap_store_objectclasses($dn,$classes){
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;
347 $r = @ldap_mod_replace($LDAP_CON,$dn,$add);
356 * escape parenthesises in given string
358 function ldap_filterescape($string){
359 return strtr($string,array('('=>'\(', ')'=>'\)'));
363 * Queries public and private addressbooks, combining the
366 * @todo This function should be used where ever possible, replacing
367 * lots of duplicate code
369 function ldap_queryabooks($filter,$types){
373 // make sure $types is an array
374 if(!is_array($types)){
375 $types = explode(',',$types);
376 $types = array_map('trim',$types);
383 // public addressbook
384 $sr = ldap_list($LDAP_CON,$conf['publicbook'],
386 $result1 = ldap_get_binentries($LDAP_CON, $sr);
387 ldap_free_result($sr);
389 // private addressbook
390 if(!empty($_SESSION['ldapab']['binddn'])){
391 $sr = @ldap_list($LDAP_CON,$conf['privatebook'].
392 ','.$_SESSION['ldapab']['binddn'],
394 $result2 = ldap_get_binentries($LDAP_CON, $sr);
397 // return merged results
398 return array_merge($result1,$result2);
402 * Makes array unique and renumbers the entries
404 * @author <kay_rules@yahoo.com>
406 function array_unique_renumber($somearray){
407 $tmparr = array_unique($somearray);
409 foreach ($tmparr as $v) {
417 * Simple XOR encryption
419 * @author Dustin Schneider
420 * @link http://www.phpbuilder.com/tips/item.php?id=68
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];
432 * Simple XOR decryption
434 * @author Dustin Schneider
435 * @link http://www.phpbuilder.com/tips/item.php?id=68
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];
447 * Decodes UTF8 recursivly for the given array
451 function utf8_decode_array(&$array) {
452 trigger_error('deprecated utf8_decode_array called',E_USER_WARNING);
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]);
460 $array[$key] = utf8_decode($array[$key]);
466 * Encodes the given array to UTF8 recursively
470 function utf8_encode_array(&$array) {
471 trigger_error('deprecated utf8_encode_array called',E_USER_WARNING);
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]);
479 $array[$key] = utf8_encode($array[$key]);