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