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