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