Skip to content
Snippets Groups Projects
Commit ab5d26da authored by Andreas Gohr's avatar Andreas Gohr
Browse files

code cleanup

parent ff1769de
No related branches found
No related tags found
No related merge requests found
......@@ -12,13 +12,13 @@
if(!defined('DOKU_INC')) die('meh.');
// some ACL level defines
define('AUTH_NONE',0);
define('AUTH_READ',1);
define('AUTH_EDIT',2);
define('AUTH_CREATE',4);
define('AUTH_UPLOAD',8);
define('AUTH_DELETE',16);
define('AUTH_ADMIN',255);
define('AUTH_NONE', 0);
define('AUTH_READ', 1);
define('AUTH_EDIT', 2);
define('AUTH_CREATE', 4);
define('AUTH_UPLOAD', 8);
define('AUTH_DELETE', 16);
define('AUTH_ADMIN', 255);
/**
* Initialize the auth system.
......@@ -29,26 +29,28 @@ define('AUTH_ADMIN',255);
*
* @todo backend loading maybe should be handled by the class autoloader
* @todo maybe split into multiple functions at the XXX marked positions
* @triggers AUTH_LOGIN_CHECK
* @return bool
*/
function auth_setup(){
function auth_setup() {
global $conf;
/* @var auth_basic $auth */
global $auth;
global $AUTH_ACL;
global $lang;
global $config_cascade;
$AUTH_ACL = array();
if(!$conf['useacl']) return false;
// load the the backend auth functions and instantiate the auth object XXX
if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
if(@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
require_once(DOKU_INC.'inc/auth/basic.class.php');
require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
$auth_class = "auth_".$conf['authtype'];
if (class_exists($auth_class)) {
if(class_exists($auth_class)) {
$auth = new $auth_class();
if ($auth->success == false) {
if($auth->success == false) {
// degrade to unauthenticated user
unset($auth);
auth_logoff();
......@@ -61,14 +63,14 @@ function auth_setup(){
nice_die($lang['authmodfailed']);
}
if(!$auth) return;
if(!$auth) return false;
// do the login either by cookie or provided credentials XXX
if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
if(!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
if(!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
if(!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
$_REQUEST['http_credentials'] = false;
if (!$conf['rememberme']) $_REQUEST['r'] = false;
if(!$conf['rememberme']) $_REQUEST['r'] = false;
// handle renamed HTTP_AUTHORIZATION variable (can happen when a fix like
// the one presented at
......@@ -77,48 +79,50 @@ function auth_setup(){
if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
// streamline HTTP auth credentials (IIS/rewrite -> mod_php)
if(isset($_SERVER['HTTP_AUTHORIZATION'])){
list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
}
// if no credentials were given try to use HTTP auth (for SSO)
if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
$_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
$_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])) {
$_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
$_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
$_REQUEST['http_credentials'] = true;
}
// apply cleaning
$_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
if(isset($_REQUEST['authtok'])){
if(isset($_REQUEST['authtok'])) {
// when an authentication token is given, trust the session
auth_validateToken($_REQUEST['authtok']);
}elseif(!is_null($auth) && $auth->canDo('external')){
} elseif(!is_null($auth) && $auth->canDo('external')) {
// external trust mechanism in place
$auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
}else{
$auth->trustExternal($_REQUEST['u'], $_REQUEST['p'], $_REQUEST['r']);
} else {
$evdata = array(
'user' => $_REQUEST['u'],
'password' => $_REQUEST['p'],
'sticky' => $_REQUEST['r'],
'silent' => $_REQUEST['http_credentials'],
);
'user' => $_REQUEST['u'],
'password' => $_REQUEST['p'],
'sticky' => $_REQUEST['r'],
'silent' => $_REQUEST['http_credentials'],
);
trigger_event('AUTH_LOGIN_CHECK', $evdata, 'auth_login_wrapper');
}
//load ACL into a global array XXX
$AUTH_ACL = auth_loadACL();
return true;
}
/**
* Loads the ACL setup and handle user wildcards
*
* @author Andreas Gohr <andi@splitbrain.org>
* @returns array
* @return array
*/
function auth_loadACL(){
function auth_loadACL() {
global $config_cascade;
if(!is_readable($config_cascade['acl']['default'])) return array();
......@@ -126,24 +130,32 @@ function auth_loadACL(){
$acl = file($config_cascade['acl']['default']);
//support user wildcard
if(isset($_SERVER['REMOTE_USER'])){
if(isset($_SERVER['REMOTE_USER'])) {
$len = count($acl);
for($i=0; $i<$len; $i++){
for($i = 0; $i < $len; $i++) {
if($acl[$i]{0} == '#') continue;
list($id,$rest) = preg_split('/\s+/',$acl[$i],2);
$id = str_replace('%USER%',cleanID($_SERVER['REMOTE_USER']),$id);
$rest = str_replace('%USER%',auth_nameencode($_SERVER['REMOTE_USER']),$rest);
list($id, $rest) = preg_split('/\s+/', $acl[$i], 2);
$id = str_replace('%USER%', cleanID($_SERVER['REMOTE_USER']), $id);
$rest = str_replace('%USER%', auth_nameencode($_SERVER['REMOTE_USER']), $rest);
$acl[$i] = "$id\t$rest";
}
}
return $acl;
}
/**
* Event hook callback for AUTH_LOGIN_CHECK
*
* @param $evdata
* @return bool
*/
function auth_login_wrapper($evdata) {
return auth_login($evdata['user'],
$evdata['password'],
$evdata['sticky'],
$evdata['silent']);
return auth_login(
$evdata['user'],
$evdata['password'],
$evdata['sticky'],
$evdata['silent']
);
}
/**
......@@ -175,53 +187,56 @@ function auth_login_wrapper($evdata) {
* @param bool $silent Don't show error on bad auth
* @return bool true on successful auth
*/
function auth_login($user,$pass,$sticky=false,$silent=false){
function auth_login($user, $pass, $sticky = false, $silent = false) {
global $USERINFO;
global $conf;
global $lang;
/* @var auth_basic $auth */
global $auth;
$sticky ? $sticky = true : $sticky = false; //sanity check
if (!$auth) return false;
if(!$auth) return false;
if(!empty($user)){
if(!empty($user)) {
//usual login
if ($auth->checkPass($user,$pass)){
if($auth->checkPass($user, $pass)) {
// make logininfo globally available
$_SERVER['REMOTE_USER'] = $user;
$secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
auth_setCookie($user,PMA_blowfish_encrypt($pass,$secret),$sticky);
$secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
auth_setCookie($user, PMA_blowfish_encrypt($pass, $secret), $sticky);
return true;
}else{
} else {
//invalid credentials - log off
if(!$silent) msg($lang['badlogin'],-1);
if(!$silent) msg($lang['badlogin'], -1);
auth_logoff();
return false;
}
}else{
} else {
// read cookie information
list($user,$sticky,$pass) = auth_getCookie();
if($user && $pass){
list($user, $sticky, $pass) = auth_getCookie();
if($user && $pass) {
// we got a cookie - see if we can trust it
// get session info
$session = $_SESSION[DOKU_COOKIE]['auth'];
if(isset($session) &&
$auth->useSessionCache($user) &&
($session['time'] >= time()-$conf['auth_security_timeout']) &&
($session['user'] == $user) &&
($session['pass'] == sha1($pass)) && //still crypted
($session['buid'] == auth_browseruid()) ){
$auth->useSessionCache($user) &&
($session['time'] >= time() - $conf['auth_security_timeout']) &&
($session['user'] == $user) &&
($session['pass'] == sha1($pass)) && //still crypted
($session['buid'] == auth_browseruid())
) {
// he has session, cookie and browser right - let him in
$_SERVER['REMOTE_USER'] = $user;
$USERINFO = $session['info']; //FIXME move all references to session
$USERINFO = $session['info']; //FIXME move all references to session
return true;
}
// no we don't trust it yet - recheck pass but silent
$secret = auth_cookiesalt(!$sticky); //bind non-sticky to session
$pass = PMA_blowfish_decrypt($pass,$secret);
return auth_login($user,$pass,$sticky,true);
$pass = PMA_blowfish_decrypt($pass, $secret);
return auth_login($user, $pass, $sticky, true);
}
}
//just to be sure
......@@ -239,8 +254,8 @@ function auth_login($user,$pass,$sticky=false,$silent=false){
* @param string $token The authentication token
* @return boolean true (or will exit on failure)
*/
function auth_validateToken($token){
if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
function auth_validateToken($token) {
if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']) {
// bad token
header("HTTP/1.0 401 Unauthorized");
print 'Invalid auth token - maybe the session timed out';
......@@ -250,7 +265,7 @@ function auth_validateToken($token){
// still here? trust the session data
global $USERINFO;
$_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
$USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
$USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
return true;
}
......@@ -262,7 +277,7 @@ function auth_validateToken($token){
* @author Andreas Gohr <andi@splitbrain.org>
* @return string The auth token
*/
function auth_createToken(){
function auth_createToken() {
$token = md5(mt_rand());
@session_start(); // reopen the session if needed
$_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
......@@ -281,14 +296,14 @@ function auth_createToken(){
*
* @return string a MD5 sum of various browser headers
*/
function auth_browseruid(){
$ip = clientIP(true);
$uid = '';
function auth_browseruid() {
$ip = clientIP(true);
$uid = '';
$uid .= $_SERVER['HTTP_USER_AGENT'];
$uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
$uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
$uid .= substr($ip,0,strpos($ip,'.'));
$uid .= substr($ip, 0, strpos($ip, '.'));
return md5($uid);
}
......@@ -304,15 +319,15 @@ function auth_browseruid(){
* @param bool $addsession if true, the sessionid is added to the salt
* @return string
*/
function auth_cookiesalt($addsession=false){
function auth_cookiesalt($addsession = false) {
global $conf;
$file = $conf['metadir'].'/_htcookiesalt';
$salt = io_readFile($file);
if(empty($salt)){
$salt = uniqid(rand(),true);
io_saveFile($file,$salt);
if(empty($salt)) {
$salt = uniqid(rand(), true);
io_saveFile($file, $salt);
}
if($addsession){
if($addsession) {
$salt .= session_id();
}
return $salt;
......@@ -327,10 +342,10 @@ function auth_cookiesalt($addsession=false){
* @author Andreas Gohr <andi@splitbrain.org>
* @param bool $keepbc - when true, the breadcrumb data is not cleared
*/
function auth_logoff($keepbc=false){
function auth_logoff($keepbc = false) {
global $conf;
global $USERINFO;
global $INFO, $ID;
/* @var auth_basic $auth */
global $auth;
// make sure the session is writable (it usually is)
......@@ -346,13 +361,13 @@ function auth_logoff($keepbc=false){
unset($_SESSION[DOKU_COOKIE]['bc']);
if(isset($_SERVER['REMOTE_USER']))
unset($_SERVER['REMOTE_USER']);
$USERINFO=null; //FIXME
$USERINFO = null; //FIXME
$cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
if (version_compare(PHP_VERSION, '5.2.0', '>')) {
setcookie(DOKU_COOKIE,'',time()-600000,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
}else{
setcookie(DOKU_COOKIE,'',time()-600000,$cookieDir,'',($conf['securecookie'] && is_ssl()));
if(version_compare(PHP_VERSION, '5.2.0', '>')) {
setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
} else {
setcookie(DOKU_COOKIE, '', time() - 600000, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
}
if($auth) $auth->logOff();
......@@ -368,32 +383,34 @@ function auth_logoff($keepbc=false){
*
* @author Andreas Gohr <andi@splitbrain.org>
* @see auth_isadmin
* @param string user - Username
* @param array groups - List of groups the user is in
* @param bool adminonly - when true checks if user is admin
* @param string $user Username
* @param array $groups List of groups the user is in
* @param bool $adminonly when true checks if user is admin
* @return bool
*/
function auth_ismanager($user=null,$groups=null,$adminonly=false){
function auth_ismanager($user = null, $groups = null, $adminonly = false) {
global $conf;
global $USERINFO;
/* @var auth_basic $auth */
global $auth;
if (!$auth) return false;
if(!$auth) return false;
if(is_null($user)) {
if (!isset($_SERVER['REMOTE_USER'])) {
if(!isset($_SERVER['REMOTE_USER'])) {
return false;
} else {
$user = $_SERVER['REMOTE_USER'];
}
}
if(is_null($groups)){
if(is_null($groups)) {
$groups = (array) $USERINFO['grps'];
}
// check superuser match
if(auth_isMember($conf['superuser'],$user, $groups)) return true;
if(auth_isMember($conf['superuser'], $user, $groups)) return true;
if($adminonly) return false;
// check managers
if(auth_isMember($conf['manager'],$user, $groups)) return true;
if(auth_isMember($conf['manager'], $user, $groups)) return true;
return false;
}
......@@ -406,13 +423,15 @@ function auth_ismanager($user=null,$groups=null,$adminonly=false){
* The info is available through $INFO['isadmin'], too
*
* @author Andreas Gohr <andi@splitbrain.org>
* @see auth_ismanager
* @see auth_ismanager()
* @param string $user Username
* @param array $groups List of groups the user is in
* @return bool
*/
function auth_isadmin($user=null,$groups=null){
return auth_ismanager($user,$groups,true);
function auth_isadmin($user = null, $groups = null) {
return auth_ismanager($user, $groups, true);
}
/**
* Match a user and his groups against a comma separated list of
* users and groups to determine membership status
......@@ -424,31 +443,32 @@ function auth_isadmin($user=null,$groups=null){
* @param $groups array groups the user is member of
* @return bool true for membership acknowledged
*/
function auth_isMember($memberlist,$user,array $groups){
function auth_isMember($memberlist, $user, array $groups) {
/* @var auth_basic $auth */
global $auth;
if (!$auth) return false;
if(!$auth) return false;
// clean user and groups
if(!$auth->isCaseSensitive()){
$user = utf8_strtolower($user);
$groups = array_map('utf8_strtolower',$groups);
if(!$auth->isCaseSensitive()) {
$user = utf8_strtolower($user);
$groups = array_map('utf8_strtolower', $groups);
}
$user = $auth->cleanUser($user);
$groups = array_map(array($auth,'cleanGroup'),$groups);
$user = $auth->cleanUser($user);
$groups = array_map(array($auth, 'cleanGroup'), $groups);
// extract the memberlist
$members = explode(',',$memberlist);
$members = array_map('trim',$members);
$members = explode(',', $memberlist);
$members = array_map('trim', $members);
$members = array_unique($members);
$members = array_filter($members);
// compare cleaned values
foreach($members as $member){
foreach($members as $member) {
if(!$auth->isCaseSensitive()) $member = utf8_strtolower($member);
if($member[0] == '@'){
$member = $auth->cleanGroup(substr($member,1));
if($member[0] == '@') {
$member = $auth->cleanGroup(substr($member, 1));
if(in_array($member, $groups)) return true;
}else{
} else {
$member = $auth->cleanUser($member);
if($member == $user) return true;
}
......@@ -468,12 +488,12 @@ function auth_isMember($memberlist,$user,array $groups){
* @param string $id page ID (needs to be resolved and cleaned)
* @return int permission level
*/
function auth_quickaclcheck($id){
function auth_quickaclcheck($id) {
global $conf;
global $USERINFO;
# if no ACL is used always return upload rights
if(!$conf['useacl']) return AUTH_UPLOAD;
return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
return auth_aclcheck($id, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
}
/**
......@@ -487,106 +507,110 @@ function auth_quickaclcheck($id){
* @param array $groups Array of groups the user is in
* @return int permission level
*/
function auth_aclcheck($id,$user,$groups){
function auth_aclcheck($id, $user, $groups) {
global $conf;
global $AUTH_ACL;
/* @var auth_basic $auth */
global $auth;
// if no ACL is used always return upload rights
if(!$conf['useacl']) return AUTH_UPLOAD;
if (!$auth) return AUTH_NONE;
if(!$auth) return AUTH_NONE;
//make sure groups is an array
if(!is_array($groups)) $groups = array();
//if user is superuser or in superusergroup return 255 (acl_admin)
if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
if(auth_isadmin($user, $groups)) {
return AUTH_ADMIN;
}
$ci = '';
if(!$auth->isCaseSensitive()) $ci = 'ui';
$user = $auth->cleanUser($user);
$groups = array_map(array($auth,'cleanGroup'),(array)$groups);
$user = auth_nameencode($user);
$user = $auth->cleanUser($user);
$groups = array_map(array($auth, 'cleanGroup'), (array) $groups);
$user = auth_nameencode($user);
//prepend groups with @ and nameencode
$cnt = count($groups);
for($i=0; $i<$cnt; $i++){
for($i = 0; $i < $cnt; $i++) {
$groups[$i] = '@'.auth_nameencode($groups[$i]);
}
$ns = getNS($id);
$perm = -1;
$ns = getNS($id);
$perm = -1;
if($user || count($groups)){
if($user || count($groups)) {
//add ALL group
$groups[] = '@ALL';
//add User
if($user) $groups[] = $user;
}else{
} else {
$groups[] = '@ALL';
}
//check exact match first
$matches = preg_grep('/^'.preg_quote($id,'/').'\s+(\S+)\s+/'.$ci,$AUTH_ACL);
if(count($matches)){
foreach($matches as $match){
$match = preg_replace('/#.*$/','',$match); //ignore comments
$acl = preg_split('/\s+/',$match);
if (!in_array($acl[1], $groups)) {
$matches = preg_grep('/^'.preg_quote($id, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
if(count($matches)) {
foreach($matches as $match) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/\s+/', $match);
if(!in_array($acl[1], $groups)) {
continue;
}
if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if($acl[2] > $perm){
if($acl[2] > $perm) {
$perm = $acl[2];
}
}
if($perm > -1){
if($perm > -1) {
//we had a match - return it
return $perm;
}
}
//still here? do the namespace checks
if($ns){
if($ns) {
$path = $ns.':*';
}else{
} else {
$path = '*'; //root document
}
do{
$matches = preg_grep('/^'.preg_quote($path,'/').'\s+(\S+)\s+/'.$ci,$AUTH_ACL);
if(count($matches)){
foreach($matches as $match){
$match = preg_replace('/#.*$/','',$match); //ignore comments
$acl = preg_split('/\s+/',$match);
if (!in_array($acl[1], $groups)) {
do {
$matches = preg_grep('/^'.preg_quote($path, '/').'\s+(\S+)\s+/'.$ci, $AUTH_ACL);
if(count($matches)) {
foreach($matches as $match) {
$match = preg_replace('/#.*$/', '', $match); //ignore comments
$acl = preg_split('/\s+/', $match);
if(!in_array($acl[1], $groups)) {
continue;
}
if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
if($acl[2] > $perm){
if($acl[2] > $perm) {
$perm = $acl[2];
}
}
//we had a match - return it
if ($perm != -1) {
if($perm != -1) {
return $perm;
}
}
//get next higher namespace
$ns = getNS($ns);
$ns = getNS($ns);
if($path != '*'){
if($path != '*') {
$path = $ns.':*';
if($path == ':*') $path = '*';
}else{
} else {
//we did this already
//looks like there is something wrong with the ACL
//break here
msg('No ACL setup yet! Denying access to everyone.');
return AUTH_NONE;
}
}while(1); //this should never loop endless
} while(1); //this should never loop endless
return AUTH_NONE;
}
/**
......@@ -602,7 +626,7 @@ function auth_aclcheck($id,$user,$groups){
* @author Andreas Gohr <gohr@cosmocode.de>
* @see rawurldecode()
*/
function auth_nameencode($name,$skip_group=false){
function auth_nameencode($name, $skip_group = false) {
global $cache_authname;
$cache =& $cache_authname;
$name = (string) $name;
......@@ -610,13 +634,17 @@ function auth_nameencode($name,$skip_group=false){
// never encode wildcard FS#1955
if($name == '%USER%') return $name;
if (!isset($cache[$name][$skip_group])) {
if($skip_group && $name{0} =='@'){
$cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
"'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
}else{
$cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
"'%'.dechex(ord(substr('\\1',-1)))",$name);
if(!isset($cache[$name][$skip_group])) {
if($skip_group && $name{0} == '@') {
$cache[$name][$skip_group] = '@'.preg_replace(
'/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
"'%'.dechex(ord(substr('\\1',-1)))", substr($name, 1)
);
} else {
$cache[$name][$skip_group] = preg_replace(
'/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
"'%'.dechex(ord(substr('\\1',-1)))", $name
);
}
}
......@@ -631,20 +659,20 @@ function auth_nameencode($name,$skip_group=false){
*
* @return string pronouncable password
*/
function auth_pwgen(){
function auth_pwgen() {
$pw = '';
$c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
$v = 'aeiou'; //vowels
$a = $c.$v; //both
$v = 'aeiou'; //vowels
$a = $c.$v; //both
//use two syllables...
for($i=0;$i < 2; $i++){
$pw .= $c[rand(0, strlen($c)-1)];
$pw .= $v[rand(0, strlen($v)-1)];
$pw .= $a[rand(0, strlen($a)-1)];
for($i = 0; $i < 2; $i++) {
$pw .= $c[rand(0, strlen($c) - 1)];
$pw .= $v[rand(0, strlen($v) - 1)];
$pw .= $a[rand(0, strlen($a) - 1)];
}
//... and add a nice number
$pw .= rand(10,99);
$pw .= rand(10, 99);
return $pw;
}
......@@ -653,16 +681,16 @@ function auth_pwgen(){
* Sends a password to the given user
*
* @author Andreas Gohr <andi@splitbrain.org>
*
* @param string $user Login name of the user
* @param string $password The new password in clear text
* @return bool true on success
*/
function auth_sendPassword($user,$password){
global $conf;
function auth_sendPassword($user, $password) {
global $lang;
/* @var auth_basic $auth */
global $auth;
if (!$auth) return false;
if(!$auth) return false;
$hdrs = '';
$user = $auth->cleanUser($user);
$userinfo = $auth->getUserData($user);
......@@ -670,15 +698,15 @@ function auth_sendPassword($user,$password){
$text = rawLocale('password');
$trep = array(
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'PASSWORD' => $password
);
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'PASSWORD' => $password
);
$mail = new Mailer();
$mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
$mail->subject($lang['regpwmail']);
$mail->setBody($text,$trep);
$mail->setBody($text, $trep);
return $mail->send();
}
......@@ -688,12 +716,12 @@ function auth_sendPassword($user,$password){
* This registers a new user - Data is read directly from $_POST
*
* @author Andreas Gohr <andi@splitbrain.org>
*
* @return bool true on success, false on any error
*/
function register(){
function register() {
global $lang;
global $conf;
/* @var auth_basic $auth */
global $auth;
if(!$_POST['save']) return false;
......@@ -703,61 +731,63 @@ function register(){
$_POST['login'] = trim($auth->cleanUser($_POST['login']));
//clean fullname and email
$_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
$_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
$_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
$_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
if( empty($_POST['login']) ||
if(empty($_POST['login']) ||
empty($_POST['fullname']) ||
empty($_POST['email']) ){
msg($lang['regmissing'],-1);
empty($_POST['email'])
) {
msg($lang['regmissing'], -1);
return false;
}
if ($conf['autopasswd']) {
$pass = auth_pwgen(); // automatically generate password
} elseif (empty($_POST['pass']) ||
empty($_POST['passchk'])) {
msg($lang['regmissing'], -1); // complain about missing passwords
if($conf['autopasswd']) {
$pass = auth_pwgen(); // automatically generate password
} elseif(empty($_POST['pass']) ||
empty($_POST['passchk'])
) {
msg($lang['regmissing'], -1); // complain about missing passwords
return false;
} elseif ($_POST['pass'] != $_POST['passchk']) {
msg($lang['regbadpass'], -1); // complain about misspelled passwords
} elseif($_POST['pass'] != $_POST['passchk']) {
msg($lang['regbadpass'], -1); // complain about misspelled passwords
return false;
} else {
$pass = $_POST['pass']; // accept checked and valid password
$pass = $_POST['pass']; // accept checked and valid password
}
//check mail
if(!mail_isvalid($_POST['email'])){
msg($lang['regbadmail'],-1);
if(!mail_isvalid($_POST['email'])) {
msg($lang['regbadmail'], -1);
return false;
}
//okay try to create the user
if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
msg($lang['reguexists'],-1);
if(!$auth->triggerUserMod('create', array($_POST['login'], $pass, $_POST['fullname'], $_POST['email']))) {
msg($lang['reguexists'], -1);
return false;
}
// create substitutions for use in notification email
$substitutions = array(
'NEWUSER' => $_POST['login'],
'NEWNAME' => $_POST['fullname'],
'NEWEMAIL' => $_POST['email'],
);
'NEWUSER' => $_POST['login'],
'NEWNAME' => $_POST['fullname'],
'NEWEMAIL' => $_POST['email'],
);
if (!$conf['autopasswd']) {
msg($lang['regsuccess2'],1);
if(!$conf['autopasswd']) {
msg($lang['regsuccess2'], 1);
notify('', 'register', '', $_POST['login'], false, $substitutions);
return true;
}
// autogenerated password? then send him the password
if (auth_sendPassword($_POST['login'],$pass)){
msg($lang['regsuccess'],1);
if(auth_sendPassword($_POST['login'], $pass)) {
msg($lang['regsuccess'], 1);
notify('', 'register', '', $_POST['login'], false, $substitutions);
return true;
}else{
msg($lang['regmailfail'],-1);
} else {
msg($lang['regmailfail'], -1);
return false;
}
}
......@@ -771,61 +801,66 @@ function updateprofile() {
global $conf;
global $INFO;
global $lang;
/* @var auth_basic $auth */
global $auth;
if(empty($_POST['save'])) return false;
if(!checkSecurityToken()) return false;
if(!actionOK('profile')) {
msg($lang['profna'],-1);
msg($lang['profna'], -1);
return false;
}
if ($_POST['newpass'] != $_POST['passchk']) {
msg($lang['regbadpass'], -1); // complain about misspelled passwords
if($_POST['newpass'] != $_POST['passchk']) {
msg($lang['regbadpass'], -1); // complain about misspelled passwords
return false;
}
//clean fullname and email
$_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
$_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
$_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['fullname']));
$_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/', '', $_POST['email']));
if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
(empty($_POST['email']) && $auth->canDo('modMail'))) {
msg($lang['profnoempty'],-1);
if((empty($_POST['fullname']) && $auth->canDo('modName')) ||
(empty($_POST['email']) && $auth->canDo('modMail'))
) {
msg($lang['profnoempty'], -1);
return false;
}
if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
msg($lang['regbadmail'],-1);
if(!mail_isvalid($_POST['email']) && $auth->canDo('modMail')) {
msg($lang['regbadmail'], -1);
return false;
}
if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
$changes = array();
if($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
if($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
if(!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
if (!count($changes)) {
if(!count($changes)) {
msg($lang['profnochange'], -1);
return false;
}
if ($conf['profileconfirm']) {
if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
msg($lang['badlogin'],-1);
if($conf['profileconfirm']) {
if(!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
msg($lang['badlogin'], -1);
return false;
}
}
if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
if($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
// update cookie and session with the changed data
if ($changes['pass']){
list($user,$sticky,$pass) = auth_getCookie();
$pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt(!$sticky));
auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
if($changes['pass']) {
list( /*user*/, $sticky, /*pass*/) = auth_getCookie();
$pass = PMA_blowfish_encrypt($changes['pass'], auth_cookiesalt(!$sticky));
auth_setCookie($_SERVER['REMOTE_USER'], $pass, (bool) $sticky);
}
return true;
}
return false;
}
/**
......@@ -842,68 +877,69 @@ function updateprofile() {
*
* @return bool true on success, false on any error
*/
function act_resendpwd(){
function act_resendpwd() {
global $lang;
global $conf;
/* @var auth_basic $auth */
global $auth;
if(!actionOK('resendpwd')) {
msg($lang['resendna'],-1);
msg($lang['resendna'], -1);
return false;
}
$token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
$token = preg_replace('/[^a-f0-9]+/', '', $_REQUEST['pwauth']);
if($token){
if($token) {
// we're in token phase - get user info from token
$tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
if(!@file_exists($tfile)){
msg($lang['resendpwdbadauth'],-1);
if(!@file_exists($tfile)) {
msg($lang['resendpwdbadauth'], -1);
unset($_REQUEST['pwauth']);
return false;
}
// token is only valid for 3 days
if( (time() - filemtime($tfile)) > (3*60*60*24) ){
msg($lang['resendpwdbadauth'],-1);
if((time() - filemtime($tfile)) > (3 * 60 * 60 * 24)) {
msg($lang['resendpwdbadauth'], -1);
unset($_REQUEST['pwauth']);
@unlink($tfile);
return false;
}
$user = io_readfile($tfile);
$user = io_readfile($tfile);
$userinfo = $auth->getUserData($user);
if(!$userinfo['mail']) {
msg($lang['resendpwdnouser'], -1);
return false;
}
if(!$conf['autopasswd']){ // we let the user choose a password
if(!$conf['autopasswd']) { // we let the user choose a password
// password given correctly?
if(!isset($_REQUEST['pass']) || $_REQUEST['pass'] == '') return false;
if($_REQUEST['pass'] != $_REQUEST['passchk']){
msg($lang['regbadpass'],-1);
if($_REQUEST['pass'] != $_REQUEST['passchk']) {
msg($lang['regbadpass'], -1);
return false;
}
$pass = $_REQUEST['pass'];
if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
msg('error modifying user data',-1);
if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
msg('error modifying user data', -1);
return false;
}
}else{ // autogenerate the password and send by mail
} else { // autogenerate the password and send by mail
$pass = auth_pwgen();
if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
msg('error modifying user data',-1);
if(!$auth->triggerUserMod('modify', array($user, array('pass' => $pass)))) {
msg('error modifying user data', -1);
return false;
}
if (auth_sendPassword($user,$pass)) {
msg($lang['resendpwdsuccess'],1);
if(auth_sendPassword($user, $pass)) {
msg($lang['resendpwdsuccess'], 1);
} else {
msg($lang['regmailfail'],-1);
msg($lang['regmailfail'], -1);
}
}
......@@ -915,7 +951,7 @@ function act_resendpwd(){
if(!$_POST['save']) return false;
if (empty($_POST['login'])) {
if(empty($_POST['login'])) {
msg($lang['resendpwdmissing'], -1);
return false;
} else {
......@@ -931,30 +967,29 @@ function act_resendpwd(){
// generate auth token
$token = md5(auth_cookiesalt().$user); //secret but user based
$tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
$url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
$url = wl('', array('do'=> 'resendpwd', 'pwauth'=> $token), true, '&');
io_saveFile($tfile,$user);
io_saveFile($tfile, $user);
$text = rawLocale('pwconfirm');
$trep = array(
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'CONFIRM' => $url
);
'FULLNAME' => $userinfo['name'],
'LOGIN' => $user,
'CONFIRM' => $url
);
$mail = new Mailer();
$mail->to($userinfo['name'].' <'.$userinfo['mail'].'>');
$mail->subject($lang['regpwmail']);
$mail->setBody($text,$trep);
if($mail->send()){
msg($lang['resendpwdconfirm'],1);
}else{
msg($lang['regmailfail'],-1);
$mail->setBody($text, $trep);
if($mail->send()) {
msg($lang['resendpwdconfirm'], 1);
} else {
msg($lang['regmailfail'], -1);
}
return true;
}
return false; // never reached
// never reached
}
/**
......@@ -964,32 +999,37 @@ function act_resendpwd(){
* is chosen.
*
* @author Andreas Gohr <andi@splitbrain.org>
* @param string $clear The clear text password
* @param string $method The hashing method
* @param string $salt A salt, null for random
* @return string The crypted password
*/
function auth_cryptPassword($clear,$method='',$salt=null){
function auth_cryptPassword($clear, $method = '', $salt = null) {
global $conf;
if(empty($method)) $method = $conf['passcrypt'];
$pass = new PassHash();
$call = 'hash_'.$method;
$pass = new PassHash();
$call = 'hash_'.$method;
if(!method_exists($pass,$call)){
msg("Unsupported crypt method $method",-1);
if(!method_exists($pass, $call)) {
msg("Unsupported crypt method $method", -1);
return false;
}
return $pass->$call($clear,$salt);
return $pass->$call($clear, $salt);
}
/**
* Verifies a cleartext password against a crypted hash
*
* @author Andreas Gohr <andi@splitbrain.org>
* @return bool
* @author Andreas Gohr <andi@splitbrain.org>
* @param string $clear The clear text password
* @param string $crypt The hash to compare with
* @return bool true if both match
*/
function auth_verifyPassword($clear,$crypt){
function auth_verifyPassword($clear, $crypt) {
$pass = new PassHash();
return $pass->verify_hash($clear,$crypt);
return $pass->verify_hash($clear, $crypt);
}
/**
......@@ -998,23 +1038,25 @@ function auth_verifyPassword($clear,$crypt){
* @param string $user username
* @param string $pass encrypted password
* @param bool $sticky whether or not the cookie will last beyond the session
* @return bool
*/
function auth_setCookie($user,$pass,$sticky) {
function auth_setCookie($user, $pass, $sticky) {
global $conf;
/* @var auth_basic $auth */
global $auth;
global $USERINFO;
if (!$auth) return false;
if(!$auth) return false;
$USERINFO = $auth->getUserData($user);
// set cookie
$cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
$cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
$cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
$time = $sticky ? (time()+60*60*24*365) : 0; //one year
if (version_compare(PHP_VERSION, '5.2.0', '>')) {
setcookie(DOKU_COOKIE,$cookie,$time,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
}else{
setcookie(DOKU_COOKIE,$cookie,$time,$cookieDir,'',($conf['securecookie'] && is_ssl()));
$time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
if(version_compare(PHP_VERSION, '5.2.0', '>')) {
setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
} else {
setcookie(DOKU_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
}
// set session
$_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
......@@ -1022,6 +1064,8 @@ function auth_setCookie($user,$pass,$sticky) {
$_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
$_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
$_SESSION[DOKU_COOKIE]['auth']['time'] = time();
return true;
}
/**
......@@ -1029,15 +1073,15 @@ function auth_setCookie($user,$pass,$sticky) {
*
* @returns array
*/
function auth_getCookie(){
if (!isset($_COOKIE[DOKU_COOKIE])) {
function auth_getCookie() {
if(!isset($_COOKIE[DOKU_COOKIE])) {
return array(null, null, null);
}
list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
list($user, $sticky, $pass) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
$sticky = (bool) $sticky;
$pass = base64_decode($pass);
$user = base64_decode($user);
return array($user,$sticky,$pass);
return array($user, $sticky, $pass);
}
//Setup VIM: ex: et ts=2 :
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment