1<?php 2/** 3 * Authentication library 4 * 5 * Including this file will automatically try to login 6 * a user by calling auth_login() 7 * 8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 9 * @author Andreas Gohr <andi@splitbrain.org> 10 */ 11 12 if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/'); 13 require_once(DOKU_INC.'inc/common.php'); 14 require_once(DOKU_INC.'inc/io.php'); 15 16 // some ACL level defines 17 define('AUTH_NONE',0); 18 define('AUTH_READ',1); 19 define('AUTH_EDIT',2); 20 define('AUTH_CREATE',4); 21 define('AUTH_UPLOAD',8); 22 define('AUTH_DELETE',16); 23 define('AUTH_ADMIN',255); 24 25 global $conf; 26 27 if($conf['useacl']){ 28 require_once(DOKU_INC.'inc/blowfish.php'); 29 require_once(DOKU_INC.'inc/mail.php'); 30 31 global $auth; 32 33 // load the the backend auth functions and instantiate the auth object 34 if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) { 35 require_once(DOKU_INC.'inc/auth/basic.class.php'); 36 require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php'); 37 38 $auth_class = "auth_".$conf['authtype']; 39 if (class_exists($auth_class)) { 40 $auth = new $auth_class(); 41 if ($auth->success == false) { 42 unset($auth); 43 msg($lang['authtempfail'], -1); 44 45 // turn acl config setting off for the rest of this page 46 $conf['useacl'] = 0; 47 } 48 } else { 49 nice_die($lang['authmodfailed']); 50 } 51 } else { 52 nice_die($lang['authmodfailed']); 53 } 54 } 55 56 // do the login either by cookie or provided credentials 57 if($conf['useacl']){ 58 if (!isset($_REQUEST['u'])) $_REQUEST['u'] = ''; 59 if (!isset($_REQUEST['p'])) $_REQUEST['p'] = ''; 60 if (!isset($_REQUEST['r'])) $_REQUEST['r'] = ''; 61 62 // if no credentials were given try to use HTTP auth (for SSO) 63 if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){ 64 $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER']; 65 $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW']; 66 } 67 68 // external trust mechanism in place? 69 if(!is_null($auth) && $auth->canDo('external')){ 70 $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']); 71 }else{ 72 auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']); 73 } 74 75 //load ACL into a global array 76 global $AUTH_ACL; 77 if(is_readable(DOKU_CONF.'acl.auth.php')){ 78 $AUTH_ACL = file(DOKU_CONF.'acl.auth.php'); 79 if(isset($_SERVER['REMOTE_USER'])){ 80 $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); 81 } 82 }else{ 83 $AUTH_ACL = array(); 84 } 85 } 86 87/** 88 * This tries to login the user based on the sent auth credentials 89 * 90 * The authentication works like this: if a username was given 91 * a new login is assumed and user/password are checked. If they 92 * are correct the password is encrypted with blowfish and stored 93 * together with the username in a cookie - the same info is stored 94 * in the session, too. Additonally a browserID is stored in the 95 * session. 96 * 97 * If no username was given the cookie is checked: if the username, 98 * crypted password and browserID match between session and cookie 99 * no further testing is done and the user is accepted 100 * 101 * If a cookie was found but no session info was availabe the 102 * blowfish encrypted password from the cookie is decrypted and 103 * together with username rechecked by calling this function again. 104 * 105 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO 106 * are set. 107 * 108 * @author Andreas Gohr <andi@splitbrain.org> 109 * 110 * @param string $user Username 111 * @param string $pass Cleartext Password 112 * @param bool $sticky Cookie should not expire 113 * @param bool $silent Don't show error on bad auth 114 * @return bool true on successful auth 115*/ 116function auth_login($user,$pass,$sticky=false,$silent=false){ 117 global $USERINFO; 118 global $conf; 119 global $lang; 120 global $auth; 121 $sticky ? $sticky = true : $sticky = false; //sanity check 122 123 if(!empty($user)){ 124 //usual login 125 if ($auth->checkPass($user,$pass)){ 126 // make logininfo globally available 127 $_SERVER['REMOTE_USER'] = $user; 128 $USERINFO = $auth->getUserData($user); //FIXME move all references to session 129 130 // set cookie 131 $pass = PMA_blowfish_encrypt($pass,auth_cookiesalt()); 132 $cookie = base64_encode("$user|$sticky|$pass"); 133 if($sticky) $time = time()+60*60*24*365; //one year 134 setcookie(DOKU_COOKIE,$cookie,$time,'/'); 135 136 // set session 137 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user; 138 $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass; 139 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid(); 140 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO; 141 $_SESSION[DOKU_COOKIE]['auth']['time'] = time(); 142 143 return true; 144 }else{ 145 //invalid credentials - log off 146 if(!$silent) msg($lang['badlogin'],-1); 147 auth_logoff(); 148 return false; 149 } 150 }else{ 151 // read cookie information 152 $cookie = base64_decode($_COOKIE[DOKU_COOKIE]); 153 list($user,$sticky,$pass) = split('\|',$cookie,3); 154 // get session info 155 $session = $_SESSION[DOKU_COOKIE]['auth']; 156 if($user && $pass){ 157 // we got a cookie - see if we can trust it 158 if(isset($session) && 159 ($session['time'] >= time()-$conf['auth_security_timeout']) && 160 ($session['user'] == $user) && 161 ($session['pass'] == $pass) && //still crypted 162 ($session['buid'] == auth_browseruid()) ){ 163 // he has session, cookie and browser right - let him in 164 $_SERVER['REMOTE_USER'] = $user; 165 $USERINFO = $session['info']; //FIXME move all references to session 166 return true; 167 } 168 // no we don't trust it yet - recheck pass but silent 169 $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt()); 170 return auth_login($user,$pass,$sticky,true); 171 } 172 } 173 //just to be sure 174 auth_logoff(); 175 return false; 176} 177 178/** 179 * Builds a pseudo UID from browser and IP data 180 * 181 * This is neither unique nor unfakable - still it adds some 182 * security. Using the first part of the IP makes sure 183 * proxy farms like AOLs are stil okay. 184 * 185 * @author Andreas Gohr <andi@splitbrain.org> 186 * 187 * @return string a MD5 sum of various browser headers 188 */ 189function auth_browseruid(){ 190 $uid = ''; 191 $uid .= $_SERVER['HTTP_USER_AGENT']; 192 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING']; 193 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE']; 194 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET']; 195 $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.')); 196 return md5($uid); 197} 198 199/** 200 * Creates a random key to encrypt the password in cookies 201 * 202 * This function tries to read the password for encrypting 203 * cookies from $conf['metadir'].'/_htcookiesalt' 204 * if no such file is found a random key is created and 205 * and stored in this file. 206 * 207 * @author Andreas Gohr <andi@splitbrain.org> 208 * 209 * @return string 210 */ 211function auth_cookiesalt(){ 212 global $conf; 213 $file = $conf['metadir'].'/_htcookiesalt'; 214 $salt = io_readFile($file); 215 if(empty($salt)){ 216 $salt = uniqid(rand(),true); 217 io_saveFile($file,$salt); 218 } 219 return $salt; 220} 221 222/** 223 * This clears all authenticationdata and thus log the user 224 * off 225 * 226 * @author Andreas Gohr <andi@splitbrain.org> 227 */ 228function auth_logoff(){ 229 global $conf; 230 global $USERINFO; 231 global $INFO, $ID; 232 global $auth; 233 234 if(isset($_SESSION[DOKU_COOKIE]['auth']['user'])) 235 unset($_SESSION[DOKU_COOKIE]['auth']['user']); 236 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass'])) 237 unset($_SESSION[DOKU_COOKIE]['auth']['pass']); 238 if(isset($_SESSION[DOKU_COOKIE]['auth']['info'])) 239 unset($_SESSION[DOKU_COOKIE]['auth']['info']); 240 if(isset($_SERVER['REMOTE_USER'])) 241 unset($_SERVER['REMOTE_USER']); 242 $USERINFO=null; //FIXME 243 setcookie(DOKU_COOKIE,'',time()-600000,'/'); 244 245 if($auth && $auth->canDo('logoff')){ 246 $auth->logOff(); 247 } 248} 249 250/** 251 * Check if a user is a manager 252 * 253 * Should usually be called without any parameters to check the current 254 * user. 255 * 256 * The info is available through $INFO['ismanager'], too 257 * 258 * @author Andreas Gohr <andi@splitbrain.org> 259 * @see auth_isadmin 260 * @param string user - Username 261 * @param array groups - List of groups the user is in 262 * @param bool adminonly - when true checks if user is admin 263 */ 264function auth_ismanager($user=null,$groups=null,$adminonly=false){ 265 global $conf; 266 global $USERINFO; 267 268 if(!$conf['useacl']) return false; 269 if(is_null($user)) $user = $_SERVER['REMOTE_USER']; 270 if(is_null($groups)) $groups = $USERINFO['grps']; 271 $user = auth_nameencode($user); 272 273 // check username against superuser and manager 274 if(auth_nameencode($conf['superuser']) == $user) return true; 275 if(!$adminonly){ 276 if(auth_nameencode($conf['manager']) == $user) return true; 277 } 278 279 //prepend groups with @ and nameencode 280 $cnt = count($groups); 281 for($i=0; $i<$cnt; $i++){ 282 $groups[$i] = '@'.auth_nameencode($groups[$i]); 283 } 284 285 // check groups against superuser and manager 286 if(in_array(auth_nameencode($conf['superuser'],true), $groups)) return true; 287 if(!$adminonly){ 288 if(in_array(auth_nameencode($conf['manager'],true), $groups)) return true; 289 } 290 return false; 291} 292 293/** 294 * Check if a user is admin 295 * 296 * Alias to auth_ismanager with adminonly=true 297 * 298 * The info is available through $INFO['isadmin'], too 299 * 300 * @author Andreas Gohr <andi@splitbrain.org> 301 * @see auth_ismanager 302 */ 303function auth_isadmin($user=null,$groups=null){ 304 return auth_ismanager($user,$groups,true); 305} 306 307/** 308 * Convinience function for auth_aclcheck() 309 * 310 * This checks the permissions for the current user 311 * 312 * @author Andreas Gohr <andi@splitbrain.org> 313 * 314 * @param string $id page ID 315 * @return int permission level 316 */ 317function auth_quickaclcheck($id){ 318 global $conf; 319 global $USERINFO; 320 # if no ACL is used always return upload rights 321 if(!$conf['useacl']) return AUTH_UPLOAD; 322 return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']); 323} 324 325/** 326 * Returns the maximum rights a user has for 327 * the given ID or its namespace 328 * 329 * @author Andreas Gohr <andi@splitbrain.org> 330 * 331 * @param string $id page ID 332 * @param string $user Username 333 * @param array $groups Array of groups the user is in 334 * @return int permission level 335 */ 336function auth_aclcheck($id,$user,$groups){ 337 global $conf; 338 global $AUTH_ACL; 339 340 # if no ACL is used always return upload rights 341 if(!$conf['useacl']) return AUTH_UPLOAD; 342 343 $user = auth_nameencode($user); 344 345 //if user is superuser return 255 (acl_admin) 346 if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; } 347 348 //make sure groups is an array 349 if(!is_array($groups)) $groups = array(); 350 351 //prepend groups with @ and nameencode 352 $cnt = count($groups); 353 for($i=0; $i<$cnt; $i++){ 354 $groups[$i] = '@'.auth_nameencode($groups[$i]); 355 } 356 //if user is in superuser group return 255 (acl_admin) 357 if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; } 358 359 $ns = getNS($id); 360 $perm = -1; 361 362 if($user){ 363 //add ALL group 364 $groups[] = '@ALL'; 365 //add User 366 $groups[] = $user; 367 //build regexp 368 $regexp = join('|',$groups); 369 }else{ 370 $regexp = '@ALL'; 371 } 372 373 //check exact match first 374 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL); 375 if(count($matches)){ 376 foreach($matches as $match){ 377 $match = preg_replace('/#.*$/','',$match); //ignore comments 378 $acl = preg_split('/\s+/',$match); 379 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 380 if($acl[2] > $perm){ 381 $perm = $acl[2]; 382 } 383 } 384 if($perm > -1){ 385 //we had a match - return it 386 return $perm; 387 } 388 } 389 390 //still here? do the namespace checks 391 if($ns){ 392 $path = $ns.':\*'; 393 }else{ 394 $path = '\*'; //root document 395 } 396 397 do{ 398 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL); 399 if(count($matches)){ 400 foreach($matches as $match){ 401 $match = preg_replace('/#.*$/','',$match); //ignore comments 402 $acl = preg_split('/\s+/',$match); 403 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL! 404 if($acl[2] > $perm){ 405 $perm = $acl[2]; 406 } 407 } 408 //we had a match - return it 409 return $perm; 410 } 411 412 //get next higher namespace 413 $ns = getNS($ns); 414 415 if($path != '\*'){ 416 $path = $ns.':\*'; 417 if($path == ':\*') $path = '\*'; 418 }else{ 419 //we did this already 420 //looks like there is something wrong with the ACL 421 //break here 422 msg('No ACL setup yet! Denying access to everyone.'); 423 return AUTH_NONE; 424 } 425 }while(1); //this should never loop endless 426 427 //still here? return no permissions 428 return AUTH_NONE; 429} 430 431/** 432 * Encode ASCII special chars 433 * 434 * Some auth backends allow special chars in their user and groupnames 435 * The special chars are encoded with this function. Only ASCII chars 436 * are encoded UTF-8 multibyte are left as is (different from usual 437 * urlencoding!). 438 * 439 * Decoding can be done with rawurldecode 440 * 441 * @author Andreas Gohr <gohr@cosmocode.de> 442 * @see rawurldecode() 443 */ 444function auth_nameencode($name,$skip_group=false){ 445 global $cache_authname; 446 $cache =& $cache_authname; 447 $name = (string) $name; 448 449 if (!isset($cache[$name][$skip_group])) { 450 if($skip_group && $name{0} =='@'){ 451 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 452 "'%'.dechex(ord('\\1'))",substr($name,1)); 453 }else{ 454 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e', 455 "'%'.dechex(ord('\\1'))",$name); 456 } 457 } 458 459 return $cache[$name][$skip_group]; 460} 461 462/** 463 * Create a pronouncable password 464 * 465 * @author Andreas Gohr <andi@splitbrain.org> 466 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451 467 * 468 * @return string pronouncable password 469 */ 470function auth_pwgen(){ 471 $pw = ''; 472 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones 473 $v = 'aeiou'; //vowels 474 $a = $c.$v; //both 475 476 //use two syllables... 477 for($i=0;$i < 2; $i++){ 478 $pw .= $c[rand(0, strlen($c)-1)]; 479 $pw .= $v[rand(0, strlen($v)-1)]; 480 $pw .= $a[rand(0, strlen($a)-1)]; 481 } 482 //... and add a nice number 483 $pw .= rand(10,99); 484 485 return $pw; 486} 487 488/** 489 * Sends a password to the given user 490 * 491 * @author Andreas Gohr <andi@splitbrain.org> 492 * 493 * @return bool true on success 494 */ 495function auth_sendPassword($user,$password){ 496 global $conf; 497 global $lang; 498 global $auth; 499 500 $hdrs = ''; 501 $userinfo = $auth->getUserData($user); 502 503 if(!$userinfo['mail']) return false; 504 505 $text = rawLocale('password'); 506 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 507 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 508 $text = str_replace('@LOGIN@',$user,$text); 509 $text = str_replace('@PASSWORD@',$password,$text); 510 $text = str_replace('@TITLE@',$conf['title'],$text); 511 512 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 513 $lang['regpwmail'], 514 $text, 515 $conf['mailfrom']); 516} 517 518/** 519 * Register a new user 520 * 521 * This registers a new user - Data is read directly from $_POST 522 * 523 * @author Andreas Gohr <andi@splitbrain.org> 524 * 525 * @return bool true on success, false on any error 526 */ 527function register(){ 528 global $lang; 529 global $conf; 530 global $auth; 531 532 if(!$_POST['save']) return false; 533 if(!$auth->canDo('addUser')) return false; 534 535 //clean username 536 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 537 $_POST['login'] = cleanID($_POST['login']); 538 //clean fullname and email 539 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 540 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 541 542 if( empty($_POST['login']) || 543 empty($_POST['fullname']) || 544 empty($_POST['email']) ){ 545 msg($lang['regmissing'],-1); 546 return false; 547 } 548 549 if ($conf['autopasswd']) { 550 $pass = auth_pwgen(); // automatically generate password 551 } elseif (empty($_POST['pass']) || 552 empty($_POST['passchk'])) { 553 msg($lang['regmissing'], -1); // complain about missing passwords 554 return false; 555 } elseif ($_POST['pass'] != $_POST['passchk']) { 556 msg($lang['regbadpass'], -1); // complain about misspelled passwords 557 return false; 558 } else { 559 $pass = $_POST['pass']; // accept checked and valid password 560 } 561 562 //check mail 563 if(!mail_isvalid($_POST['email'])){ 564 msg($lang['regbadmail'],-1); 565 return false; 566 } 567 568 //okay try to create the user 569 if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){ 570 msg($lang['reguexists'],-1); 571 return false; 572 } 573 574 // create substitutions for use in notification email 575 $substitutions = array( 576 'NEWUSER' => $_POST['login'], 577 'NEWNAME' => $_POST['fullname'], 578 'NEWEMAIL' => $_POST['email'], 579 ); 580 581 if (!$conf['autopasswd']) { 582 msg($lang['regsuccess2'],1); 583 notify('', 'register', '', $_POST['login'], false, $substitutions); 584 return true; 585 } 586 587 // autogenerated password? then send him the password 588 if (auth_sendPassword($_POST['login'],$pass)){ 589 msg($lang['regsuccess'],1); 590 notify('', 'register', '', $_POST['login'], false, $substitutions); 591 return true; 592 }else{ 593 msg($lang['regmailfail'],-1); 594 return false; 595 } 596} 597 598/** 599 * Update user profile 600 * 601 * @author Christopher Smith <chris@jalakai.co.uk> 602 */ 603function updateprofile() { 604 global $conf; 605 global $INFO; 606 global $lang; 607 global $auth; 608 609 if(empty($_POST['save'])) return false; 610 611 // should not be able to get here without Profile being possible... 612 if(!$auth->canDo('Profile')) { 613 msg($lang['profna'],-1); 614 return false; 615 } 616 617 if ($_POST['newpass'] != $_POST['passchk']) { 618 msg($lang['regbadpass'], -1); // complain about misspelled passwords 619 return false; 620 } 621 622 //clean fullname and email 623 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname'])); 624 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email'])); 625 626 if (empty($_POST['fullname']) || empty($_POST['email'])) { 627 msg($lang['profnoempty'],-1); 628 return false; 629 } 630 631 if (!mail_isvalid($_POST['email'])){ 632 msg($lang['regbadmail'],-1); 633 return false; 634 } 635 636 if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname']; 637 if ($_POST['email'] != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email']; 638 if (!empty($_POST['newpass'])) $changes['pass'] = $_POST['newpass']; 639 640 if (!count($changes)) { 641 msg($lang['profnochange'], -1); 642 return false; 643 } 644 645 if ($conf['profileconfirm']) { 646 if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) { 647 msg($lang['badlogin'],-1); 648 return false; 649 } 650 } 651 652 return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes); 653} 654 655/** 656 * Send a new password 657 * 658 * This function handles both phases of the password reset: 659 * 660 * - handling the first request of password reset 661 * - validating the password reset auth token 662 * 663 * @author Benoit Chesneau <benoit@bchesneau.info> 664 * @author Chris Smith <chris@jalakai.co.uk> 665 * @author Andreas Gohr <andi@splitbrain.org> 666 * 667 * @return bool true on success, false on any error 668*/ 669function act_resendpwd(){ 670 global $lang; 671 global $conf; 672 global $auth; 673 674 if(!actionOK('resendpwd')) return false; 675 676 // should not be able to get here without modPass being possible... 677 if(!$auth->canDo('modPass')) { 678 msg($lang['resendna'],-1); 679 return false; 680 } 681 682 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']); 683 684 if($token){ 685 // we're in token phase 686 687 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 688 if(!@file_exists($tfile)){ 689 msg($lang['resendpwdbadauth'],-1); 690 return false; 691 } 692 $user = io_readfile($tfile); 693 @unlink($tfile); 694 $userinfo = $auth->getUserData($user); 695 if(!$userinfo['mail']) { 696 msg($lang['resendpwdnouser'], -1); 697 return false; 698 } 699 700 $pass = auth_pwgen(); 701 if (!$auth->modifyUser($user,array('pass' => $pass))) { 702 msg('error modifying user data',-1); 703 return false; 704 } 705 706 if (auth_sendPassword($user,$pass)) { 707 msg($lang['resendpwdsuccess'],1); 708 } else { 709 msg($lang['regmailfail'],-1); 710 } 711 return true; 712 713 } else { 714 // we're in request phase 715 716 if(!$_POST['save']) return false; 717 718 if (empty($_POST['login'])) { 719 msg($lang['resendpwdmissing'], -1); 720 return false; 721 } else { 722 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']); 723 $user = cleanID($_POST['login']); 724 } 725 726 $userinfo = $auth->getUserData($user); 727 if(!$userinfo['mail']) { 728 msg($lang['resendpwdnouser'], -1); 729 return false; 730 } 731 732 // generate auth token 733 $token = md5(auth_cookiesalt().$user); //secret but user based 734 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth'; 735 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&'); 736 737 io_saveFile($tfile,$user); 738 739 $text = rawLocale('pwconfirm'); 740 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text); 741 $text = str_replace('@FULLNAME@',$userinfo['name'],$text); 742 $text = str_replace('@LOGIN@',$user,$text); 743 $text = str_replace('@TITLE@',$conf['title'],$text); 744 $text = str_replace('@CONFIRM@',$url,$text); 745 746 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>', 747 $lang['regpwmail'], 748 $text, 749 $conf['mailfrom'])){ 750 msg($lang['resendpwdconfirm'],1); 751 }else{ 752 msg($lang['regmailfail'],-1); 753 } 754 return true; 755 } 756 757 return false; // never reached 758} 759 760/** 761 * Uses a regular expresion to check if a given mail address is valid 762 * 763 * May not be completly RFC conform! 764 * 765 * @link http://www.webmasterworld.com/forum88/135.htm 766 * 767 * @param string $email the address to check 768 * @return bool true if address is valid 769 */ 770function isvalidemail($email){ 771 return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email); 772} 773 774/** 775 * Encrypts a password using the given method and salt 776 * 777 * If the selected method needs a salt and none was given, a random one 778 * is chosen. 779 * 780 * The following methods are understood: 781 * 782 * smd5 - Salted MD5 hashing 783 * md5 - Simple MD5 hashing 784 * sha1 - SHA1 hashing 785 * ssha - Salted SHA1 hashing 786 * crypt - Unix crypt 787 * mysql - MySQL password (old method) 788 * my411 - MySQL 4.1.1 password 789 * 790 * @author Andreas Gohr <andi@splitbrain.org> 791 * @return string The crypted password 792 */ 793function auth_cryptPassword($clear,$method='',$salt=''){ 794 global $conf; 795 if(empty($method)) $method = $conf['passcrypt']; 796 797 //prepare a salt 798 if(empty($salt)) $salt = md5(uniqid(rand(), true)); 799 800 switch(strtolower($method)){ 801 case 'smd5': 802 return crypt($clear,'$1$'.substr($salt,0,8).'$'); 803 case 'md5': 804 return md5($clear); 805 case 'sha1': 806 return sha1($clear); 807 case 'ssha': 808 $salt=substr($salt,0,4); 809 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt); 810 case 'crypt': 811 return crypt($clear,substr($salt,0,2)); 812 case 'mysql': 813 //from http://www.php.net/mysql comment by <soren at byu dot edu> 814 $nr=0x50305735; 815 $nr2=0x12345671; 816 $add=7; 817 $charArr = preg_split("//", $clear); 818 foreach ($charArr as $char) { 819 if (($char == '') || ($char == ' ') || ($char == '\t')) continue; 820 $charVal = ord($char); 821 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 822 $nr2 += ($nr2 << 8) ^ $nr; 823 $add += $charVal; 824 } 825 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 826 case 'my411': 827 return '*'.sha1(pack("H*", sha1($clear))); 828 default: 829 msg("Unsupported crypt method $method",-1); 830 } 831} 832 833/** 834 * Verifies a cleartext password against a crypted hash 835 * 836 * The method and salt used for the crypted hash is determined automatically 837 * then the clear text password is crypted using the same method. If both hashs 838 * match true is is returned else false 839 * 840 * @author Andreas Gohr <andi@splitbrain.org> 841 * @return bool 842 */ 843function auth_verifyPassword($clear,$crypt){ 844 $method=''; 845 $salt=''; 846 847 //determine the used method and salt 848 $len = strlen($crypt); 849 if(substr($crypt,0,3) == '$1$'){ 850 $method = 'smd5'; 851 $salt = substr($crypt,3,8); 852 }elseif(substr($crypt,0,6) == '{SSHA}'){ 853 $method = 'ssha'; 854 $salt = substr(base64_decode(substr($crypt, 6)),20); 855 }elseif($len == 32){ 856 $method = 'md5'; 857 }elseif($len == 40){ 858 $method = 'sha1'; 859 }elseif($len == 16){ 860 $method = 'mysql'; 861 }elseif($len == 41 && $crypt[0] == '*'){ 862 $method = 'my411'; 863 }else{ 864 $method = 'crypt'; 865 $salt = substr($crypt,0,2); 866 } 867 868 //crypt and compare 869 if(auth_cryptPassword($clear,$method,$salt) === $crypt){ 870 return true; 871 } 872 return false; 873} 874 875//Setup VIM: ex: et ts=2 enc=utf-8 : 876