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