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