xref: /dokuwiki/inc/auth.php (revision e838fc2e58c8da15c084e275cfa3d423b56e4b28)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Authentication library
415fae107Sandi *
515fae107Sandi * Including this file will automatically try to login
615fae107Sandi * a user by calling auth_login()
715fae107Sandi *
815fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
915fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1015fae107Sandi */
1115fae107Sandi
12ed7b5f09Sandi  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
13ed7b5f09Sandi  require_once(DOKU_INC.'inc/common.php');
14ed7b5f09Sandi  require_once(DOKU_INC.'inc/io.php');
151c73890cSAndreas Gohr
161c73890cSAndreas Gohr  if($conf['useacl']){
17ed7b5f09Sandi    require_once(DOKU_INC.'inc/blowfish.php');
18ed7b5f09Sandi    require_once(DOKU_INC.'inc/mail.php');
198b06d178Schris
208b06d178Schris    // load the the backend auth functions and instantiate the auth object
218b06d178Schris    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
228b06d178Schris      require_once(DOKU_INC.'inc/auth/basic.class.php');
238b06d178Schris      require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
248b06d178Schris
258b06d178Schris      $auth_class = "auth_".$conf['authtype'];
26cd52f92dSchris      if (class_exists($auth_class)) {
278b06d178Schris        $auth = new $auth_class();
28d2dde4ebSMatthias Grimm        if ($auth->success == false) {
29d2dde4ebSMatthias Grimm          unset($auth);
30cd52f92dSchris          msg($lang['authtempfail'], -1);
31cd52f92dSchris
32cd52f92dSchris          // turn acl config setting off for the rest of this page
33cd52f92dSchris          $conf['useacl'] = 0;
34d2dde4ebSMatthias Grimm        }
358b06d178Schris      } else {
363816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
37cd52f92dSchris      }
38cd52f92dSchris    } else {
393816dcbcSAndreas Gohr      nice_die($lang['authmodfailed']);
408b06d178Schris    }
411c73890cSAndreas Gohr  }
42f3f0262cSandi
431e866646Sandi  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
44e65afed4SSameer D. Sahasrabuddhe
4515fae107Sandi  // some ACL level defines
46f3f0262cSandi  define('AUTH_NONE',0);
47f3f0262cSandi  define('AUTH_READ',1);
48f3f0262cSandi  define('AUTH_EDIT',2);
49f3f0262cSandi  define('AUTH_CREATE',4);
50f3f0262cSandi  define('AUTH_UPLOAD',8);
518ef6b7caSandi  define('AUTH_DELETE',16);
5210a76f6fSfrank  define('AUTH_ADMIN',255);
53f3f0262cSandi
54f5cb575dSAndreas Gohr  // do the login either by cookie or provided credentials
55f3f0262cSandi  if($conf['useacl']){
56f5cb575dSAndreas Gohr    // external trust mechanism in place?
5782fd59b6SAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')){
58f5cb575dSAndreas Gohr      $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
59f5cb575dSAndreas Gohr    }else{
60132bdbfeSandi      auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
61f5cb575dSAndreas Gohr    }
62f5cb575dSAndreas Gohr
6315fae107Sandi    //load ACL into a global array
64e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
65e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
6611799630Sandi    }else{
6711799630Sandi      $AUTH_ACL = array();
6811799630Sandi    }
69f3f0262cSandi  }
70f3f0262cSandi
71f3f0262cSandi/**
72f3f0262cSandi * This tries to login the user based on the sent auth credentials
73f3f0262cSandi *
74f3f0262cSandi * The authentication works like this: if a username was given
7515fae107Sandi * a new login is assumed and user/password are checked. If they
7615fae107Sandi * are correct the password is encrypted with blowfish and stored
7715fae107Sandi * together with the username in a cookie - the same info is stored
7815fae107Sandi * in the session, too. Additonally a browserID is stored in the
7915fae107Sandi * session.
8015fae107Sandi *
8115fae107Sandi * If no username was given the cookie is checked: if the username,
8215fae107Sandi * crypted password and browserID match between session and cookie
8315fae107Sandi * no further testing is done and the user is accepted
8415fae107Sandi *
8515fae107Sandi * If a cookie was found but no session info was availabe the
86136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
8715fae107Sandi * together with username rechecked by calling this function again.
88f3f0262cSandi *
89f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
90f3f0262cSandi * are set.
9115fae107Sandi *
9215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
9315fae107Sandi *
9415fae107Sandi * @param   string  $user    Username
9515fae107Sandi * @param   string  $pass    Cleartext Password
9615fae107Sandi * @param   bool    $sticky  Cookie should not expire
9715fae107Sandi * @return  bool             true on successful auth
98f3f0262cSandi*/
99132bdbfeSandifunction auth_login($user,$pass,$sticky=false){
100f3f0262cSandi  global $USERINFO;
101f3f0262cSandi  global $conf;
102f3f0262cSandi  global $lang;
103cd52f92dSchris  global $auth;
104132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
105f3f0262cSandi
106f3f0262cSandi  if(isset($user)){
107132bdbfeSandi    //usual login
108cd52f92dSchris    if ($auth->checkPass($user,$pass)){
109132bdbfeSandi      // make logininfo globally available
110f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
111cd52f92dSchris      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
112132bdbfeSandi
113132bdbfeSandi      // set cookie
114132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
115132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
116132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
117e65afed4SSameer D. Sahasrabuddhe      setcookie(DOKU_COOKIE,$cookie,$time,'/');
118132bdbfeSandi
119132bdbfeSandi      // set session
120132bdbfeSandi      $_SESSION[$conf['title']]['auth']['user'] = $user;
121132bdbfeSandi      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
122132bdbfeSandi      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
123132bdbfeSandi      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
124132bdbfeSandi      return true;
125f3f0262cSandi    }else{
126f3f0262cSandi      //invalid credentials - log off
127f3f0262cSandi      msg($lang['badlogin'],-1);
128f3f0262cSandi      auth_logoff();
129132bdbfeSandi      return false;
130f3f0262cSandi    }
131f3f0262cSandi  }else{
132132bdbfeSandi    // read cookie information
133e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
134132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
135132bdbfeSandi    // get session info
136132bdbfeSandi    $session = $_SESSION[$conf['title']]['auth'];
137132bdbfeSandi
138132bdbfeSandi    if($user && $pass){
139132bdbfeSandi      // we got a cookie - see if we can trust it
140132bdbfeSandi      if(isset($session) &&
141132bdbfeSandi        ($session['user'] == $user) &&
142132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
143132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
144132bdbfeSandi        // he has session, cookie and browser right - let him in
145132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
146132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
147132bdbfeSandi        return true;
148132bdbfeSandi      }
149132bdbfeSandi      // no we don't trust it yet - recheck pass
150132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
151132bdbfeSandi      return auth_login($user,$pass,$sticky);
152132bdbfeSandi    }
153132bdbfeSandi  }
154f3f0262cSandi  //just to be sure
155f3f0262cSandi  auth_logoff();
156132bdbfeSandi  return false;
157f3f0262cSandi}
158132bdbfeSandi
159132bdbfeSandi/**
160136ce040Sandi * Builds a pseudo UID from browser and IP data
161132bdbfeSandi *
162132bdbfeSandi * This is neither unique nor unfakable - still it adds some
163136ce040Sandi * security. Using the first part of the IP makes sure
164136ce040Sandi * proxy farms like AOLs are stil okay.
16515fae107Sandi *
16615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
16715fae107Sandi *
16815fae107Sandi * @return  string  a MD5 sum of various browser headers
169132bdbfeSandi */
170132bdbfeSandifunction auth_browseruid(){
171132bdbfeSandi  $uid  = '';
172132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
173132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
174132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
175132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
176136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
177132bdbfeSandi  return md5($uid);
178132bdbfeSandi}
179132bdbfeSandi
180132bdbfeSandi/**
181132bdbfeSandi * Creates a random key to encrypt the password in cookies
18215fae107Sandi *
18315fae107Sandi * This function tries to read the password for encrypting
18498407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
18515fae107Sandi * if no such file is found a random key is created and
18615fae107Sandi * and stored in this file.
18715fae107Sandi *
18815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
18915fae107Sandi *
19015fae107Sandi * @return  string
191132bdbfeSandi */
192132bdbfeSandifunction auth_cookiesalt(){
193132bdbfeSandi  global $conf;
19498407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
195132bdbfeSandi  $salt = io_readFile($file);
196132bdbfeSandi  if(empty($salt)){
197132bdbfeSandi    $salt = uniqid(rand(),true);
198132bdbfeSandi    io_saveFile($file,$salt);
199132bdbfeSandi  }
200132bdbfeSandi  return $salt;
201f3f0262cSandi}
202f3f0262cSandi
203f3f0262cSandi/**
204f3f0262cSandi * This clears all authenticationdata and thus log the user
205f3f0262cSandi * off
20615fae107Sandi *
20715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
208f3f0262cSandi */
209f3f0262cSandifunction auth_logoff(){
210f3f0262cSandi  global $conf;
211f3f0262cSandi  global $USERINFO;
2128b06d178Schris  global $INFO, $ID;
2135298a619SAndreas Gohr  global $auth;
21437065e65Sandi
21537065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['user']))
216132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['user']);
21737065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['pass']))
218132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['pass']);
21937065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['info']))
220132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['info']);
22137065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
222f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
223132bdbfeSandi  $USERINFO=null; //FIXME
2241e866646Sandi  setcookie(DOKU_COOKIE,'',time()-600000,'/');
2255298a619SAndreas Gohr
2265298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
2275298a619SAndreas Gohr    $auth->logOff();
2285298a619SAndreas Gohr  }
229f3f0262cSandi}
230f3f0262cSandi
231f3f0262cSandi/**
23215fae107Sandi * Convinience function for auth_aclcheck()
23315fae107Sandi *
23415fae107Sandi * This checks the permissions for the current user
23515fae107Sandi *
23615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
23715fae107Sandi *
23815fae107Sandi * @param  string  $id  page ID
23915fae107Sandi * @return int          permission level
240f3f0262cSandi */
241f3f0262cSandifunction auth_quickaclcheck($id){
242f3f0262cSandi  global $conf;
243f3f0262cSandi  global $USERINFO;
244f3f0262cSandi  # if no ACL is used always return upload rights
245f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
246f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
247f3f0262cSandi}
248f3f0262cSandi
249f3f0262cSandi/**
250f3f0262cSandi * Returns the maximum rights a user has for
251f3f0262cSandi * the given ID or its namespace
25215fae107Sandi *
25315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25415fae107Sandi *
25515fae107Sandi * @param  string  $id     page ID
25615fae107Sandi * @param  string  $user   Username
25715fae107Sandi * @param  array   $groups Array of groups the user is in
25815fae107Sandi * @return int             permission level
259f3f0262cSandi */
260f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
261f3f0262cSandi  global $conf;
262f3f0262cSandi  global $AUTH_ACL;
263f3f0262cSandi
264f3f0262cSandi  # if no ACL is used always return upload rights
265f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
266f3f0262cSandi
2676c2bb100SAndreas Gohr  $user = auth_nameencode($user);
2686c2bb100SAndreas Gohr
26910a76f6fSfrank  //if user is superuser return 255 (acl_admin)
270*e838fc2eSAndreas Gohr  if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; }
27110a76f6fSfrank
272074cf26bSandi  //make sure groups is an array
273074cf26bSandi  if(!is_array($groups)) $groups = array();
274074cf26bSandi
2756c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
2762cd2db38Sandi  $cnt = count($groups);
2772cd2db38Sandi  for($i=0; $i<$cnt; $i++){
2786c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
27910a76f6fSfrank  }
28010a76f6fSfrank  //if user is in superuser group return 255 (acl_admin)
281*e838fc2eSAndreas Gohr  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; }
28210a76f6fSfrank
283f3f0262cSandi  $ns    = getNS($id);
284f3f0262cSandi  $perm  = -1;
285f3f0262cSandi
286f3f0262cSandi  if($user){
287f3f0262cSandi    //add ALL group
288f3f0262cSandi    $groups[] = '@ALL';
289f3f0262cSandi    //add User
290f3f0262cSandi    $groups[] = $user;
291f3f0262cSandi    //build regexp
292f3f0262cSandi    $regexp   = join('|',$groups);
293f3f0262cSandi  }else{
294f3f0262cSandi    $regexp = '@ALL';
295f3f0262cSandi  }
296f3f0262cSandi
297f3f0262cSandi  //check exact match first
29842905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
299f3f0262cSandi  if(count($matches)){
300f3f0262cSandi    foreach($matches as $match){
301f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
302f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
3038ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
304f3f0262cSandi      if($acl[2] > $perm){
305f3f0262cSandi        $perm = $acl[2];
306f3f0262cSandi      }
307f3f0262cSandi    }
308f3f0262cSandi    if($perm > -1){
309f3f0262cSandi      //we had a match - return it
310f3f0262cSandi      return $perm;
311f3f0262cSandi    }
312f3f0262cSandi  }
313f3f0262cSandi
314f3f0262cSandi  //still here? do the namespace checks
315f3f0262cSandi  if($ns){
316f3f0262cSandi    $path = $ns.':\*';
317f3f0262cSandi  }else{
318f3f0262cSandi    $path = '\*'; //root document
319f3f0262cSandi  }
320f3f0262cSandi
321f3f0262cSandi  do{
322f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
323f3f0262cSandi    if(count($matches)){
324f3f0262cSandi      foreach($matches as $match){
325f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
326f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
3278ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
328f3f0262cSandi        if($acl[2] > $perm){
329f3f0262cSandi          $perm = $acl[2];
330f3f0262cSandi        }
331f3f0262cSandi      }
332f3f0262cSandi      //we had a match - return it
333f3f0262cSandi      return $perm;
334f3f0262cSandi    }
335f3f0262cSandi
336f3f0262cSandi    //get next higher namespace
337f3f0262cSandi    $ns   = getNS($ns);
338f3f0262cSandi
339f3f0262cSandi    if($path != '\*'){
340f3f0262cSandi      $path = $ns.':\*';
341f3f0262cSandi      if($path == ':\*') $path = '\*';
342f3f0262cSandi    }else{
343f3f0262cSandi      //we did this already
344f3f0262cSandi      //looks like there is something wrong with the ACL
345f3f0262cSandi      //break here
346d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
347d5ce66f6SAndreas Gohr      return AUTH_NONE;
348f3f0262cSandi    }
349f3f0262cSandi  }while(1); //this should never loop endless
35052a5af8dSandi
35152a5af8dSandi  //still here? return no permissions
35252a5af8dSandi  return AUTH_NONE;
353f3f0262cSandi}
354f3f0262cSandi
355f3f0262cSandi/**
3566c2bb100SAndreas Gohr * Encode ASCII special chars
3576c2bb100SAndreas Gohr *
3586c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
3596c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
3606c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
3616c2bb100SAndreas Gohr * urlencoding!).
3626c2bb100SAndreas Gohr *
3636c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
3646c2bb100SAndreas Gohr *
3656c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
3666c2bb100SAndreas Gohr * @see rawurldecode()
3676c2bb100SAndreas Gohr */
368*e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
369*e838fc2eSAndreas Gohr  if($skip_group && $name{0} =='@'){
370*e838fc2eSAndreas Gohr    return '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
371*e838fc2eSAndreas Gohr                            "'%'.dechex(ord('\\1'))",substr($name,1));
372*e838fc2eSAndreas Gohr  }else{
373*e838fc2eSAndreas Gohr    return preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
374*e838fc2eSAndreas Gohr                        "'%'.dechex(ord('\\1'))",$name);
375*e838fc2eSAndreas Gohr  }
3766c2bb100SAndreas Gohr}
3776c2bb100SAndreas Gohr
3786c2bb100SAndreas Gohr/**
379f3f0262cSandi * Create a pronouncable password
380f3f0262cSandi *
38115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
38215fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
38315fae107Sandi *
38415fae107Sandi * @return string  pronouncable password
385f3f0262cSandi */
386f3f0262cSandifunction auth_pwgen(){
387f3f0262cSandi  $pw = '';
388f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
389f3f0262cSandi  $v  = 'aeiou';              //vowels
390f3f0262cSandi  $a  = $c.$v;                //both
391f3f0262cSandi
392f3f0262cSandi  //use two syllables...
393f3f0262cSandi  for($i=0;$i < 2; $i++){
394f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
395f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
396f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
397f3f0262cSandi  }
398f3f0262cSandi  //... and add a nice number
399f3f0262cSandi  $pw .= rand(10,99);
400f3f0262cSandi
401f3f0262cSandi  return $pw;
402f3f0262cSandi}
403f3f0262cSandi
404f3f0262cSandi/**
405f3f0262cSandi * Sends a password to the given user
406f3f0262cSandi *
40715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40815fae107Sandi *
40915fae107Sandi * @return bool  true on success
410f3f0262cSandi */
411f3f0262cSandifunction auth_sendPassword($user,$password){
412f3f0262cSandi  global $conf;
413f3f0262cSandi  global $lang;
414cd52f92dSchris  global $auth;
415cd52f92dSchris
416f3f0262cSandi  $hdrs  = '';
417cd52f92dSchris  $userinfo = $auth->getUserData($user);
418f3f0262cSandi
41987ddda95Sandi  if(!$userinfo['mail']) return false;
420f3f0262cSandi
421f3f0262cSandi  $text = rawLocale('password');
422ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
42387ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
424f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
425f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
426f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
427f3f0262cSandi
42844f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
42944f669e9Sandi                   $lang['regpwmail'],
43044f669e9Sandi                   $text,
43144f669e9Sandi                   $conf['mailfrom']);
432f3f0262cSandi}
433f3f0262cSandi
434f3f0262cSandi/**
43515fae107Sandi * Register a new user
436f3f0262cSandi *
43715fae107Sandi * This registers a new user - Data is read directly from $_POST
43815fae107Sandi *
43915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
44015fae107Sandi *
44115fae107Sandi * @return bool  true on success, false on any error
442f3f0262cSandi */
443f3f0262cSandifunction register(){
444f3f0262cSandi  global $lang;
445eb5d07e4Sjan  global $conf;
446cd52f92dSchris  global $auth;
447f3f0262cSandi
448f3f0262cSandi  if(!$_POST['save']) return false;
44982fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
450640145a5Sandi
451f3f0262cSandi  //clean username
452f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
453f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
454f3f0262cSandi  //clean fullname and email
455f3f0262cSandi  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
456f3f0262cSandi  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
457f3f0262cSandi
458f3f0262cSandi  if( empty($_POST['login']) ||
459f3f0262cSandi      empty($_POST['fullname']) ||
460f3f0262cSandi      empty($_POST['email']) ){
461f3f0262cSandi    msg($lang['regmissing'],-1);
462f3f0262cSandi    return false;
463f3f0262cSandi  }
464f3f0262cSandi
465cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
466cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
467cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
468cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
469bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
470cab2716aSmatthias.grimm    return false;
471cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
472bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
473cab2716aSmatthias.grimm    return false;
474cab2716aSmatthias.grimm  } else {
475cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
476cab2716aSmatthias.grimm  }
477cab2716aSmatthias.grimm
478f3f0262cSandi  //check mail
47944f669e9Sandi  if(!mail_isvalid($_POST['email'])){
480f3f0262cSandi    msg($lang['regbadmail'],-1);
481f3f0262cSandi    return false;
482f3f0262cSandi  }
483f3f0262cSandi
484f3f0262cSandi  //okay try to create the user
4851d096a10SAndreas Gohr  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
486f3f0262cSandi    msg($lang['reguexists'],-1);
487f3f0262cSandi    return false;
488f3f0262cSandi  }
489f3f0262cSandi
490cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
491cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
492cab2716aSmatthias.grimm    return true;
493cab2716aSmatthias.grimm  }
494cab2716aSmatthias.grimm
495cab2716aSmatthias.grimm  // autogenerated password? then send him the password
496f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
497f3f0262cSandi    msg($lang['regsuccess'],1);
498f3f0262cSandi    return true;
499f3f0262cSandi  }else{
500f3f0262cSandi    msg($lang['regmailfail'],-1);
501f3f0262cSandi    return false;
502f3f0262cSandi  }
503f3f0262cSandi}
504f3f0262cSandi
50510a76f6fSfrank/**
5068b06d178Schris * Update user profile
5078b06d178Schris *
5088b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
5098b06d178Schris */
5108b06d178Schrisfunction updateprofile() {
5118b06d178Schris  global $conf;
5128b06d178Schris  global $INFO;
5138b06d178Schris  global $lang;
514cd52f92dSchris  global $auth;
5158b06d178Schris
5168b06d178Schris  if(!$_POST['save']) return false;
5178b06d178Schris
51882fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
51982fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
5208b06d178Schris    msg($lang['profna'],-1);
5218b06d178Schris    return false;
5228b06d178Schris  }
5238b06d178Schris
5248b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
5258b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
5268b06d178Schris    return false;
5278b06d178Schris  }
5288b06d178Schris
5298b06d178Schris  //clean fullname and email
5308b06d178Schris  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
5318b06d178Schris  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
5328b06d178Schris
5338b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
5348b06d178Schris    msg($lang['profnoempty'],-1);
5358b06d178Schris    return false;
5368b06d178Schris  }
5378b06d178Schris
5388b06d178Schris  if (!mail_isvalid($_POST['email'])){
5398b06d178Schris    msg($lang['regbadmail'],-1);
5408b06d178Schris    return false;
5418b06d178Schris  }
5428b06d178Schris
5438b06d178Schris  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
5448b06d178Schris  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
5458b06d178Schris  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
5468b06d178Schris
5478b06d178Schris  if (!count($changes)) {
5488b06d178Schris    msg($lang['profnochange'], -1);
5498b06d178Schris    return false;
5508b06d178Schris  }
5518b06d178Schris
5528b06d178Schris  if ($conf['profileconfirm']) {
5538b06d178Schris      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
5548b06d178Schris      msg($lang['badlogin'],-1);
5558b06d178Schris      return false;
5568b06d178Schris    }
5578b06d178Schris  }
5588b06d178Schris
559cd52f92dSchris  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
5608b06d178Schris}
5618b06d178Schris
5628b06d178Schris/**
5638b06d178Schris * Send a  new password
5648b06d178Schris *
5658b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
5668b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
5678b06d178Schris *
5688b06d178Schris * @return bool true on success, false on any error
5698b06d178Schris*/
5708b06d178Schrisfunction act_resendpwd(){
5718b06d178Schris    global $lang;
5728b06d178Schris    global $conf;
573cd52f92dSchris    global $auth;
5748b06d178Schris
5758b06d178Schris    if(!$_POST['save']) return false;
5768fd2f03aSAndreas Gohr    if(!$conf['resendpasswd']) return false;
5778b06d178Schris
57882fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
57982fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
5808b06d178Schris      msg($lang['resendna'],-1);
5818b06d178Schris      return false;
5828b06d178Schris    }
5838b06d178Schris
5848b06d178Schris    if (empty($_POST['login'])) {
5858b06d178Schris      msg($lang['resendpwdmissing'], -1);
5868b06d178Schris      return false;
5878b06d178Schris    } else {
5888b06d178Schris      $user = $_POST['login'];
5898b06d178Schris    }
5908b06d178Schris
591cd52f92dSchris    $userinfo = $auth->getUserData($user);
5928b06d178Schris    if(!$userinfo['mail']) {
5938b06d178Schris      msg($lang['resendpwdnouser'], -1);
5948b06d178Schris      return false;
5958b06d178Schris    }
5968b06d178Schris
5978b06d178Schris    $pass = auth_pwgen();
598cd52f92dSchris    if (!$auth->modifyUser($user,array('pass' => $pass))) {
5998b06d178Schris      msg('error modifying user data',-1);
6008b06d178Schris      return false;
6018b06d178Schris    }
6028b06d178Schris
6038b06d178Schris    if (auth_sendPassword($user,$pass)) {
6048b06d178Schris      msg($lang['resendpwdsuccess'],1);
6058b06d178Schris    } else {
6068b06d178Schris      msg($lang['regmailfail'],-1);
6078b06d178Schris    }
6088b06d178Schris    return true;
6098b06d178Schris}
6108b06d178Schris
6118b06d178Schris/**
61210a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
61310a76f6fSfrank *
61410a76f6fSfrank * May not be completly RFC conform!
61510a76f6fSfrank *
61610a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
61710a76f6fSfrank *
61810a76f6fSfrank * @param   string $email the address to check
61910a76f6fSfrank * @return  bool          true if address is valid
62010a76f6fSfrank */
62110a76f6fSfrankfunction isvalidemail($email){
62210a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
62310a76f6fSfrank}
62410a76f6fSfrank
625b0855b11Sandi/**
626b0855b11Sandi * Encrypts a password using the given method and salt
627b0855b11Sandi *
628b0855b11Sandi * If the selected method needs a salt and none was given, a random one
629b0855b11Sandi * is chosen.
630b0855b11Sandi *
631b0855b11Sandi * The following methods are understood:
632b0855b11Sandi *
633b0855b11Sandi *   smd5  - Salted MD5 hashing
634b0855b11Sandi *   md5   - Simple MD5 hashing
635b0855b11Sandi *   sha1  - SHA1 hashing
636b0855b11Sandi *   ssha  - Salted SHA1 hashing
637d7be6245Sandi *   crypt - Unix crypt
638d7be6245Sandi *   mysql - MySQL password (old method)
639d7be6245Sandi *   my411 - MySQL 4.1.1 password
640b0855b11Sandi *
641b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
642b0855b11Sandi * @return  string  The crypted password
643b0855b11Sandi */
644b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
645b0855b11Sandi  global $conf;
646b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
64710a76f6fSfrank
648b0855b11Sandi  //prepare a salt
649b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
650b0855b11Sandi
651b0855b11Sandi  switch(strtolower($method)){
652b0855b11Sandi    case 'smd5':
653b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
654b0855b11Sandi    case 'md5':
655b0855b11Sandi      return md5($clear);
656b0855b11Sandi    case 'sha1':
657b0855b11Sandi      return sha1($clear);
658b0855b11Sandi    case 'ssha':
659b0855b11Sandi      $salt=substr($salt,0,4);
660d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
661b0855b11Sandi    case 'crypt':
662b0855b11Sandi      return crypt($clear,substr($salt,0,2));
663d7be6245Sandi    case 'mysql':
664d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
665d7be6245Sandi      $nr=0x50305735;
666d7be6245Sandi      $nr2=0x12345671;
667d7be6245Sandi      $add=7;
668d7be6245Sandi      $charArr = preg_split("//", $clear);
669d7be6245Sandi      foreach ($charArr as $char) {
670d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
671d7be6245Sandi        $charVal = ord($char);
672d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
673d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
674d7be6245Sandi        $add += $charVal;
675d7be6245Sandi      }
676d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
677d7be6245Sandi    case 'my411':
678d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
679b0855b11Sandi    default:
680b0855b11Sandi      msg("Unsupported crypt method $method",-1);
681b0855b11Sandi  }
682b0855b11Sandi}
683b0855b11Sandi
684b0855b11Sandi/**
685b0855b11Sandi * Verifies a cleartext password against a crypted hash
686b0855b11Sandi *
687b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
688b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
689b0855b11Sandi * match true is is returned else false
690b0855b11Sandi *
691b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
692b0855b11Sandi * @return  bool
693b0855b11Sandi */
694b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
695b0855b11Sandi  $method='';
696b0855b11Sandi  $salt='';
697b0855b11Sandi
698b0855b11Sandi  //determine the used method and salt
699d7be6245Sandi  $len = strlen($crypt);
700b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
701b0855b11Sandi    $method = 'smd5';
702b0855b11Sandi    $salt   = substr($crypt,3,8);
703b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
704b0855b11Sandi    $method = 'ssha';
705b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
706d7be6245Sandi  }elseif($len == 32){
707b0855b11Sandi    $method = 'md5';
708d7be6245Sandi  }elseif($len == 40){
709b0855b11Sandi    $method = 'sha1';
710d7be6245Sandi  }elseif($len == 16){
711d7be6245Sandi    $method = 'mysql';
712d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
713d7be6245Sandi    $method = 'my411';
714b0855b11Sandi  }else{
715b0855b11Sandi    $method = 'crypt';
716b0855b11Sandi    $salt   = substr($crypt,0,2);
717b0855b11Sandi  }
718b0855b11Sandi
719b0855b11Sandi  //crypt and compare
720b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
721b0855b11Sandi    return true;
722b0855b11Sandi  }
723b0855b11Sandi  return false;
724b0855b11Sandi}
725340756e4Sandi
726340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
727