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 ($_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 necessary
54 if (!empty($conf['ldapurl'])){
55 $LDAP_CON = ldap_connect($conf['ldapurl']);
57 $LDAP_CON = ldap_connect($conf['ldapserver'],$conf['ldapport']);
60 die("couldn't connect to LDAP server");
65 //anonymous bind to lookup users
66 //blank binddn or blank bindpw will result in anonymous bind
67 if(!ldap_bind($LDAP_CON,$conf['anonbinddn'],$conf['anonbindpw'])){
68 die("can not bind for user lookup");
71 //when no user was given stay connected anonymous
73 set_session('','','');
77 //get dn for given user
78 $filter = str_replace('%u',$user,$conf['userfilter']);
79 $sr = ldap_search($LDAP_CON, $conf['usertree'], $filter);;
80 $result = ldap_get_entries($LDAP_CON, $sr);
81 if($result['count'] != 1){
82 set_session('','','');
85 $dn = $result[0]['dn'];
89 if(ldap_bind($LDAP_CON,$dn,$pass)){
90 //bind successful -> set up session
91 set_session($user,$pass,$dn);
94 //bind failed -> remove session
95 set_session('','','');
100 * Builds a pseudo UID from browser and IP data
102 * This is neither unique nor unfakable - still it adds some
103 * security. Using the first part of the IP makes sure
104 * proxy farms like AOLs are stil okay.
106 * @author Andreas Gohr <andi@splitbrain.org>
108 * @return string a MD5 sum of various browser headers
110 function auth_browseruid(){
112 $uid .= $_SERVER['HTTP_USER_AGENT'];
113 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
114 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
115 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
116 $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
122 * saves user data to Session and cookies
124 function set_session($user,$pass,$dn){
128 $_SESSION['ldapab']['username'] = $user;
129 $_SESSION['ldapab']['binddn'] = $dn;
130 $_SESSION['ldapab']['password'] = $pass;
131 $_SESSION['ldapab']['browserid'] = auth_browseruid();
133 // (re)set the persistant auth cookie
135 setcookie('ldapabauth','',time()+60*60*24*365);
136 }elseif($_REQUEST['remember']){
137 $cookie = serialize(array($user,$pass));
138 $cookie = x_Encrypt($cookie,get_cookie_secret());
139 $cookie = base64_encode($cookie);
140 setcookie('ldapabauth',$cookie,time()+60*60*24*365);
145 * Creates a random string to encrypt persistant auth
146 * cookies the string is stored inside the cache dir
148 function get_cookie_secret(){
149 $file = dirname(__FILE__).'/cache/.htcookiesecret.php';
150 if(@file_exists($file)){
151 return md5(trim(file($file)));
154 $secret = '<?php #'.(rand()*time()).'?>';
155 if(!$fh = fopen($file,'w')) die("Couldn't write to $file");
156 if(fwrite($fh, $secret) === FALSE) die("Couldn't write to $file");
163 * binary safe function to get all search result data.
164 * It will use ldap_get_values_len() instead and build the array
165 * note: it's similar with the array returned by ldap_get_entries()
166 * except it has no "count" elements
168 * @author: Original code by Ovidiu Geaboc <ogeaboc@rdanet.com>
170 function ldap_get_binentries($conn,$srchRslt){
171 if(!@ldap_count_entries($conn,$srchRslt)){
174 $entry = ldap_first_entry($conn, $srchRslt);
177 $dn = ldap_get_dn($conn,$entry);
178 $attrs = ldap_get_attributes($conn, $entry);
179 for($j=0; $j<$attrs['count']; $j++) {
180 $vals = ldap_get_values_len($conn, $entry,$attrs[$j]);
181 for($k=0; $k<$vals['count']; $k++){
182 $data[$i][$attrs[$j]][$k]=$vals[$k];
187 }while ($entry = ldap_next_entry($conn, $entry));
193 * loads ldap names and their cleartext meanings from
194 * entries.conf file and returns it as hash
196 function namedentries($flip=false){
199 $entries['dn'] = 'dn';
200 $entries['sn'] = 'name';
201 $entries['givenName'] = 'givenname';
202 $entries['title'] = 'title';
203 $entries['o'] = 'organization';
204 $entries['physicalDeliveryOfficeName'] = 'office';
205 $entries['postalAddress'] = 'street';
206 $entries['postalCode'] = 'zip';
207 $entries['l'] = 'location';
208 $entries['telephoneNumber'] = 'phone';
209 $entries['facsimileTelephoneNumber'] = 'fax';
210 $entries['mobile'] = 'mobile';
211 $entries['pager'] = 'pager';
212 $entries['homePhone'] = 'homephone';
213 $entries['homePostalAddress'] = 'homestreet';
214 $entries['jpegPhoto'] = 'photo';
215 $entries['labeledURI'] = 'url';
216 $entries['description'] = 'note';
217 $entries['manager'] = 'manager';
218 $entries['cn'] = 'displayname';
220 if($conf['extended']){
221 $entries['anniversary'] = 'anniversary';
223 if($conf['openxchange']){
224 $entries['mailDomain'] = 'domain';
225 $entries['userCountry'] = 'country';
226 $entries['birthDay'] = 'birthday';
227 $entries['IPPhone'] = 'ipphone';
228 $entries['OXUserCategories'] = 'categories';
229 $entries['OXUserInstantMessenger'] = 'instantmessenger';
230 $entries['OXTimeZone'] = 'timezone';
231 $entries['OXUserPosition'] = 'position';
232 $entries['relClientCert'] = 'certificate';
236 $entries = array_reverse($entries);
237 $entries = array_flip($entries);
243 * Creates an array for submission to ldap from websitedata
245 function prepare_ldap_entry($in){
249 if(!preg_match('/\d\d\d\d-\d\d-\d\d/',$in['anniversary'])){
250 $in['anniversary']='';
253 $entries = namedentries(true);
254 foreach(array_keys($in) as $key){
255 if(empty($entries[$key])){
258 $keyname=$entries[$key];
260 if(is_array($in[$key])){
261 $out[$keyname] = $in[$key];
263 $out[$keyname][] = $in[$key];
267 //standard Objectclass
268 $out['objectclass'][] = 'inetOrgPerson';
269 if($conf['extended']){
270 $out['objectclass'][] = 'contactPerson';
272 if($conf['openxchange']){
273 $out['objectclass'][] = 'OXUserObject';
276 return clear_array($out);
280 * remove empty element from arrays recursively
282 * @author Original by <xntx@msn.com>
284 function clear_array ( $a ) {
285 if ($a !== array()) {
287 foreach ( $a as $key => $value ) {
288 if (is_array($value)) {
289 if (clear_array($value) !== false) {
290 $b[$key] = clear_array ( $value );
292 } elseif ($value !== '') {
296 if ($b !== array()) {
307 * deletes an entryfrom ldap - optional with recursion
309 * @author Original by <gabriel@hrz.uni-marburg.de>
311 function ldap_full_delete($ds,$dn,$recursive=false){
312 if($recursive == false){
313 return(ldap_delete($ds,$dn));
315 //searching for sub entries
316 $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
317 $info = ldap_get_entries($ds, $sr);
318 for($i=0;$i<$info['count'];$i++){
319 //deleting recursively sub entries
320 $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
322 //return result code, if delete fails
326 return(ldap_delete($ds,$dn));
331 * Returns all User Accounts as assoziative array
333 function get_users(){
337 $sr = ldap_list($LDAP_CON,$conf['usertree'],"ObjectClass=inetOrgPerson");
338 $result = ldap_get_binentries($LDAP_CON, $sr);
340 foreach ($result as $entry){
341 if(!empty($entry['sn'][0])){
342 $users[$entry['dn']] = $entry['givenName'][0]." ".$entry['sn'][0];
350 * makes sure the given DN contains exactly one space
353 function normalize_dn($dn){
354 $dn = preg_replace('/,/',', ',$dn);
355 $dn = preg_replace('/,\s+/',', ',$dn);
360 * Merges the given classes with the existing ones
362 function ldap_store_objectclasses($dn,$classes){
366 $sr = ldap_search($LDAP_CON,$dn,"objectClass=*",array('objectClass'));
367 $result = ldap_get_binentries($LDAP_CON, $sr);
368 $set = $result[0]['objectClass'];
369 $set = array_unique_renumber(array_merge((array)$set,(array)$classes));
370 $add['objectClass'] = $set;
372 $r = @ldap_mod_replace($LDAP_CON,$dn,$add);
381 * escape parenthesises in given string
383 function ldap_filterescape($string){
384 return strtr($string,array('('=>'\(', ')'=>'\)'));
388 * Queries public and private addressbooks, combining the
391 * @todo This function should be used where ever possible, replacing
392 * lots of duplicate code
394 function ldap_queryabooks($filter,$types){
398 // make sure $types is an array
399 if(!is_array($types)){
400 $types = explode(',',$types);
401 $types = array_map('trim',$types);
408 // public addressbook
409 $sr = ldap_list($LDAP_CON,$conf['publicbook'],
411 $result1 = ldap_get_binentries($LDAP_CON, $sr);
412 ldap_free_result($sr);
414 // private addressbook
415 if(!empty($_SESSION['ldapab']['binddn'])){
416 $sr = @ldap_list($LDAP_CON,$conf['privatebook'].
417 ','.$_SESSION['ldapab']['binddn'],
419 $result2 = ldap_get_binentries($LDAP_CON, $sr);
422 // return merged results
423 return array_merge((array)$result1,(array)$result2);
427 * Makes array unique and renumbers the entries
429 * @author <kay_rules@yahoo.com>
431 function array_unique_renumber($somearray){
432 $tmparr = array_unique($somearray);
434 foreach ($tmparr as $v) {
442 * Simple XOR encryption
444 * @author Dustin Schneider
445 * @link http://www.phpbuilder.com/tips/item.php?id=68
447 function x_Encrypt($string, $key){
448 for($i=0; $i<strlen($string); $i++){
449 for($j=0; $j<strlen($key); $j++){
450 $string[$i] = $string[$i]^$key[$j];
457 * Simple XOR decryption
459 * @author Dustin Schneider
460 * @link http://www.phpbuilder.com/tips/item.php?id=68
462 function x_Decrypt($string, $key){
463 for($i=0; $i<strlen($string); $i++){
464 for($j=0; $j<strlen($key); $j++){
465 $string[$i] = $key[$j]^$string[$i];
472 * Decodes UTF8 recursivly for the given array
476 function utf8_decode_array(&$array) {
477 trigger_error('deprecated utf8_decode_array called',E_USER_WARNING);
479 foreach (array_keys($array) as $key) {
480 if($key === 'dn') continue;
481 if($key === 'jpegPhoto') continue;
482 if (is_array($array[$key])) {
483 utf8_decode_array($array[$key]);
485 $array[$key] = utf8_decode($array[$key]);
491 * Encodes the given array to UTF8 recursively
495 function utf8_encode_array(&$array) {
496 trigger_error('deprecated utf8_encode_array called',E_USER_WARNING);
498 foreach (array_keys($array) as $key) {
499 if($key === 'dn') continue;
500 if($key === 'jpegPhoto') continue;
501 if (is_array($array[$key])) {
502 utf8_encode_array($array[$key]);
504 $array[$key] = utf8_encode($array[$key]);