xref: /dokuwiki/inc/auth.php (revision 1d5856cfe64e778c70fece0d08d36f153be16600)
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']){
561e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
571e8c9c90SAndreas Gohr    if(!$_REQUEST['u'] && !$_COOKIE[DOKU_COOKIE] && $_SERVER['PHP_AUTH_USER']){
581e8c9c90SAndreas Gohr      $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
591e8c9c90SAndreas Gohr      $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
601e8c9c90SAndreas Gohr    }
611e8c9c90SAndreas Gohr
62f5cb575dSAndreas Gohr    // external trust mechanism in place?
6382fd59b6SAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')){
64f5cb575dSAndreas Gohr      $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
65f5cb575dSAndreas Gohr    }else{
66132bdbfeSandi      auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
67f5cb575dSAndreas Gohr    }
68f5cb575dSAndreas Gohr
6915fae107Sandi    //load ACL into a global array
70e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
71e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
7211799630Sandi    }else{
7311799630Sandi      $AUTH_ACL = array();
7411799630Sandi    }
75f3f0262cSandi  }
76f3f0262cSandi
77f3f0262cSandi/**
78f3f0262cSandi * This tries to login the user based on the sent auth credentials
79f3f0262cSandi *
80f3f0262cSandi * The authentication works like this: if a username was given
8115fae107Sandi * a new login is assumed and user/password are checked. If they
8215fae107Sandi * are correct the password is encrypted with blowfish and stored
8315fae107Sandi * together with the username in a cookie - the same info is stored
8415fae107Sandi * in the session, too. Additonally a browserID is stored in the
8515fae107Sandi * session.
8615fae107Sandi *
8715fae107Sandi * If no username was given the cookie is checked: if the username,
8815fae107Sandi * crypted password and browserID match between session and cookie
8915fae107Sandi * no further testing is done and the user is accepted
9015fae107Sandi *
9115fae107Sandi * If a cookie was found but no session info was availabe the
92136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
9315fae107Sandi * together with username rechecked by calling this function again.
94f3f0262cSandi *
95f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
96f3f0262cSandi * are set.
9715fae107Sandi *
9815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
9915fae107Sandi *
10015fae107Sandi * @param   string  $user    Username
10115fae107Sandi * @param   string  $pass    Cleartext Password
10215fae107Sandi * @param   bool    $sticky  Cookie should not expire
10315fae107Sandi * @return  bool             true on successful auth
104f3f0262cSandi*/
105132bdbfeSandifunction auth_login($user,$pass,$sticky=false){
106f3f0262cSandi  global $USERINFO;
107f3f0262cSandi  global $conf;
108f3f0262cSandi  global $lang;
109cd52f92dSchris  global $auth;
110132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
111f3f0262cSandi
112f3f0262cSandi  if(isset($user)){
113132bdbfeSandi    //usual login
114cd52f92dSchris    if ($auth->checkPass($user,$pass)){
115132bdbfeSandi      // make logininfo globally available
116f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
117cd52f92dSchris      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
118132bdbfeSandi
119132bdbfeSandi      // set cookie
120132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
121132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
122132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
123e65afed4SSameer D. Sahasrabuddhe      setcookie(DOKU_COOKIE,$cookie,$time,'/');
124132bdbfeSandi
125132bdbfeSandi      // set session
126132bdbfeSandi      $_SESSION[$conf['title']]['auth']['user'] = $user;
127132bdbfeSandi      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
128132bdbfeSandi      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
129132bdbfeSandi      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
130132bdbfeSandi      return true;
131f3f0262cSandi    }else{
132f3f0262cSandi      //invalid credentials - log off
133f3f0262cSandi      msg($lang['badlogin'],-1);
134f3f0262cSandi      auth_logoff();
135132bdbfeSandi      return false;
136f3f0262cSandi    }
137f3f0262cSandi  }else{
138132bdbfeSandi    // read cookie information
139e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
140132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
141132bdbfeSandi    // get session info
142132bdbfeSandi    $session = $_SESSION[$conf['title']]['auth'];
143132bdbfeSandi
144132bdbfeSandi    if($user && $pass){
145132bdbfeSandi      // we got a cookie - see if we can trust it
146132bdbfeSandi      if(isset($session) &&
147132bdbfeSandi        ($session['user'] == $user) &&
148132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
149132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
150132bdbfeSandi        // he has session, cookie and browser right - let him in
151132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
152132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
153132bdbfeSandi        return true;
154132bdbfeSandi      }
155132bdbfeSandi      // no we don't trust it yet - recheck pass
156132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
157132bdbfeSandi      return auth_login($user,$pass,$sticky);
158132bdbfeSandi    }
159132bdbfeSandi  }
160f3f0262cSandi  //just to be sure
161f3f0262cSandi  auth_logoff();
162132bdbfeSandi  return false;
163f3f0262cSandi}
164132bdbfeSandi
165132bdbfeSandi/**
166136ce040Sandi * Builds a pseudo UID from browser and IP data
167132bdbfeSandi *
168132bdbfeSandi * This is neither unique nor unfakable - still it adds some
169136ce040Sandi * security. Using the first part of the IP makes sure
170136ce040Sandi * proxy farms like AOLs are stil okay.
17115fae107Sandi *
17215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
17315fae107Sandi *
17415fae107Sandi * @return  string  a MD5 sum of various browser headers
175132bdbfeSandi */
176132bdbfeSandifunction auth_browseruid(){
177132bdbfeSandi  $uid  = '';
178132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
179132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
180132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
181132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
182136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
183132bdbfeSandi  return md5($uid);
184132bdbfeSandi}
185132bdbfeSandi
186132bdbfeSandi/**
187132bdbfeSandi * Creates a random key to encrypt the password in cookies
18815fae107Sandi *
18915fae107Sandi * This function tries to read the password for encrypting
19098407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
19115fae107Sandi * if no such file is found a random key is created and
19215fae107Sandi * and stored in this file.
19315fae107Sandi *
19415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19515fae107Sandi *
19615fae107Sandi * @return  string
197132bdbfeSandi */
198132bdbfeSandifunction auth_cookiesalt(){
199132bdbfeSandi  global $conf;
20098407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
201132bdbfeSandi  $salt = io_readFile($file);
202132bdbfeSandi  if(empty($salt)){
203132bdbfeSandi    $salt = uniqid(rand(),true);
204132bdbfeSandi    io_saveFile($file,$salt);
205132bdbfeSandi  }
206132bdbfeSandi  return $salt;
207f3f0262cSandi}
208f3f0262cSandi
209f3f0262cSandi/**
210f3f0262cSandi * This clears all authenticationdata and thus log the user
211f3f0262cSandi * off
21215fae107Sandi *
21315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
214f3f0262cSandi */
215f3f0262cSandifunction auth_logoff(){
216f3f0262cSandi  global $conf;
217f3f0262cSandi  global $USERINFO;
2188b06d178Schris  global $INFO, $ID;
2195298a619SAndreas Gohr  global $auth;
22037065e65Sandi
22137065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['user']))
222132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['user']);
22337065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['pass']))
224132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['pass']);
22537065e65Sandi  if(isset($_SESSION[$conf['title']]['auth']['info']))
226132bdbfeSandi    unset($_SESSION[$conf['title']]['auth']['info']);
22737065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
228f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
229132bdbfeSandi  $USERINFO=null; //FIXME
2301e866646Sandi  setcookie(DOKU_COOKIE,'',time()-600000,'/');
2315298a619SAndreas Gohr
2325298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
2335298a619SAndreas Gohr    $auth->logOff();
2345298a619SAndreas Gohr  }
235f3f0262cSandi}
236f3f0262cSandi
237f3f0262cSandi/**
23815fae107Sandi * Convinience function for auth_aclcheck()
23915fae107Sandi *
24015fae107Sandi * This checks the permissions for the current user
24115fae107Sandi *
24215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
24315fae107Sandi *
24415fae107Sandi * @param  string  $id  page ID
24515fae107Sandi * @return int          permission level
246f3f0262cSandi */
247f3f0262cSandifunction auth_quickaclcheck($id){
248f3f0262cSandi  global $conf;
249f3f0262cSandi  global $USERINFO;
250f3f0262cSandi  # if no ACL is used always return upload rights
251f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
252f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
253f3f0262cSandi}
254f3f0262cSandi
255f3f0262cSandi/**
256f3f0262cSandi * Returns the maximum rights a user has for
257f3f0262cSandi * the given ID or its namespace
25815fae107Sandi *
25915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26015fae107Sandi *
26115fae107Sandi * @param  string  $id     page ID
26215fae107Sandi * @param  string  $user   Username
26315fae107Sandi * @param  array   $groups Array of groups the user is in
26415fae107Sandi * @return int             permission level
265f3f0262cSandi */
266f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
267f3f0262cSandi  global $conf;
268f3f0262cSandi  global $AUTH_ACL;
269f3f0262cSandi
270f3f0262cSandi  # if no ACL is used always return upload rights
271f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
272f3f0262cSandi
2736c2bb100SAndreas Gohr  $user = auth_nameencode($user);
2746c2bb100SAndreas Gohr
27510a76f6fSfrank  //if user is superuser return 255 (acl_admin)
276e838fc2eSAndreas Gohr  if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; }
27710a76f6fSfrank
278074cf26bSandi  //make sure groups is an array
279074cf26bSandi  if(!is_array($groups)) $groups = array();
280074cf26bSandi
2816c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
2822cd2db38Sandi  $cnt = count($groups);
2832cd2db38Sandi  for($i=0; $i<$cnt; $i++){
2846c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
28510a76f6fSfrank  }
28610a76f6fSfrank  //if user is in superuser group return 255 (acl_admin)
287e838fc2eSAndreas Gohr  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; }
28810a76f6fSfrank
289f3f0262cSandi  $ns    = getNS($id);
290f3f0262cSandi  $perm  = -1;
291f3f0262cSandi
292f3f0262cSandi  if($user){
293f3f0262cSandi    //add ALL group
294f3f0262cSandi    $groups[] = '@ALL';
295f3f0262cSandi    //add User
296f3f0262cSandi    $groups[] = $user;
297f3f0262cSandi    //build regexp
298f3f0262cSandi    $regexp   = join('|',$groups);
299f3f0262cSandi  }else{
300f3f0262cSandi    $regexp = '@ALL';
301f3f0262cSandi  }
302f3f0262cSandi
303f3f0262cSandi  //check exact match first
30442905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
305f3f0262cSandi  if(count($matches)){
306f3f0262cSandi    foreach($matches as $match){
307f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
308f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
3098ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
310f3f0262cSandi      if($acl[2] > $perm){
311f3f0262cSandi        $perm = $acl[2];
312f3f0262cSandi      }
313f3f0262cSandi    }
314f3f0262cSandi    if($perm > -1){
315f3f0262cSandi      //we had a match - return it
316f3f0262cSandi      return $perm;
317f3f0262cSandi    }
318f3f0262cSandi  }
319f3f0262cSandi
320f3f0262cSandi  //still here? do the namespace checks
321f3f0262cSandi  if($ns){
322f3f0262cSandi    $path = $ns.':\*';
323f3f0262cSandi  }else{
324f3f0262cSandi    $path = '\*'; //root document
325f3f0262cSandi  }
326f3f0262cSandi
327f3f0262cSandi  do{
328f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
329f3f0262cSandi    if(count($matches)){
330f3f0262cSandi      foreach($matches as $match){
331f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
332f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
3338ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
334f3f0262cSandi        if($acl[2] > $perm){
335f3f0262cSandi          $perm = $acl[2];
336f3f0262cSandi        }
337f3f0262cSandi      }
338f3f0262cSandi      //we had a match - return it
339f3f0262cSandi      return $perm;
340f3f0262cSandi    }
341f3f0262cSandi
342f3f0262cSandi    //get next higher namespace
343f3f0262cSandi    $ns   = getNS($ns);
344f3f0262cSandi
345f3f0262cSandi    if($path != '\*'){
346f3f0262cSandi      $path = $ns.':\*';
347f3f0262cSandi      if($path == ':\*') $path = '\*';
348f3f0262cSandi    }else{
349f3f0262cSandi      //we did this already
350f3f0262cSandi      //looks like there is something wrong with the ACL
351f3f0262cSandi      //break here
352d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
353d5ce66f6SAndreas Gohr      return AUTH_NONE;
354f3f0262cSandi    }
355f3f0262cSandi  }while(1); //this should never loop endless
35652a5af8dSandi
35752a5af8dSandi  //still here? return no permissions
35852a5af8dSandi  return AUTH_NONE;
359f3f0262cSandi}
360f3f0262cSandi
361f3f0262cSandi/**
3626c2bb100SAndreas Gohr * Encode ASCII special chars
3636c2bb100SAndreas Gohr *
3646c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
3656c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
3666c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
3676c2bb100SAndreas Gohr * urlencoding!).
3686c2bb100SAndreas Gohr *
3696c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
3706c2bb100SAndreas Gohr *
3716c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
3726c2bb100SAndreas Gohr * @see rawurldecode()
3736c2bb100SAndreas Gohr */
374e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
375e838fc2eSAndreas Gohr  if($skip_group && $name{0} =='@'){
376e838fc2eSAndreas Gohr    return '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
377e838fc2eSAndreas Gohr                            "'%'.dechex(ord('\\1'))",substr($name,1));
378e838fc2eSAndreas Gohr  }else{
379e838fc2eSAndreas Gohr    return preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
380e838fc2eSAndreas Gohr                        "'%'.dechex(ord('\\1'))",$name);
381e838fc2eSAndreas Gohr  }
3826c2bb100SAndreas Gohr}
3836c2bb100SAndreas Gohr
3846c2bb100SAndreas Gohr/**
385f3f0262cSandi * Create a pronouncable password
386f3f0262cSandi *
38715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
38815fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
38915fae107Sandi *
39015fae107Sandi * @return string  pronouncable password
391f3f0262cSandi */
392f3f0262cSandifunction auth_pwgen(){
393f3f0262cSandi  $pw = '';
394f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
395f3f0262cSandi  $v  = 'aeiou';              //vowels
396f3f0262cSandi  $a  = $c.$v;                //both
397f3f0262cSandi
398f3f0262cSandi  //use two syllables...
399f3f0262cSandi  for($i=0;$i < 2; $i++){
400f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
401f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
402f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
403f3f0262cSandi  }
404f3f0262cSandi  //... and add a nice number
405f3f0262cSandi  $pw .= rand(10,99);
406f3f0262cSandi
407f3f0262cSandi  return $pw;
408f3f0262cSandi}
409f3f0262cSandi
410f3f0262cSandi/**
411f3f0262cSandi * Sends a password to the given user
412f3f0262cSandi *
41315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
41415fae107Sandi *
41515fae107Sandi * @return bool  true on success
416f3f0262cSandi */
417f3f0262cSandifunction auth_sendPassword($user,$password){
418f3f0262cSandi  global $conf;
419f3f0262cSandi  global $lang;
420cd52f92dSchris  global $auth;
421cd52f92dSchris
422f3f0262cSandi  $hdrs  = '';
423cd52f92dSchris  $userinfo = $auth->getUserData($user);
424f3f0262cSandi
42587ddda95Sandi  if(!$userinfo['mail']) return false;
426f3f0262cSandi
427f3f0262cSandi  $text = rawLocale('password');
428ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
42987ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
430f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
431f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
432f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
433f3f0262cSandi
43444f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
43544f669e9Sandi                   $lang['regpwmail'],
43644f669e9Sandi                   $text,
43744f669e9Sandi                   $conf['mailfrom']);
438f3f0262cSandi}
439f3f0262cSandi
440f3f0262cSandi/**
44115fae107Sandi * Register a new user
442f3f0262cSandi *
44315fae107Sandi * This registers a new user - Data is read directly from $_POST
44415fae107Sandi *
44515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
44615fae107Sandi *
44715fae107Sandi * @return bool  true on success, false on any error
448f3f0262cSandi */
449f3f0262cSandifunction register(){
450f3f0262cSandi  global $lang;
451eb5d07e4Sjan  global $conf;
452cd52f92dSchris  global $auth;
453f3f0262cSandi
454f3f0262cSandi  if(!$_POST['save']) return false;
45582fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
456640145a5Sandi
457f3f0262cSandi  //clean username
458f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
459f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
460f3f0262cSandi  //clean fullname and email
46111d989c3SAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
46211d989c3SAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
463f3f0262cSandi
464f3f0262cSandi  if( empty($_POST['login']) ||
465f3f0262cSandi      empty($_POST['fullname']) ||
466f3f0262cSandi      empty($_POST['email']) ){
467f3f0262cSandi    msg($lang['regmissing'],-1);
468f3f0262cSandi    return false;
469f3f0262cSandi  }
470f3f0262cSandi
471cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
472cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
473cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
474cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
475bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
476cab2716aSmatthias.grimm    return false;
477cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
478bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
479cab2716aSmatthias.grimm    return false;
480cab2716aSmatthias.grimm  } else {
481cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
482cab2716aSmatthias.grimm  }
483cab2716aSmatthias.grimm
484f3f0262cSandi  //check mail
48544f669e9Sandi  if(!mail_isvalid($_POST['email'])){
486f3f0262cSandi    msg($lang['regbadmail'],-1);
487f3f0262cSandi    return false;
488f3f0262cSandi  }
489f3f0262cSandi
490f3f0262cSandi  //okay try to create the user
4911d096a10SAndreas Gohr  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
492f3f0262cSandi    msg($lang['reguexists'],-1);
493f3f0262cSandi    return false;
494f3f0262cSandi  }
495f3f0262cSandi
496cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
497cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
498a06e4bdbSSebastian Harl    notify('', 'register', '', $_POST['login'], false);
499cab2716aSmatthias.grimm    return true;
500cab2716aSmatthias.grimm  }
501cab2716aSmatthias.grimm
502cab2716aSmatthias.grimm  // autogenerated password? then send him the password
503f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
504f3f0262cSandi    msg($lang['regsuccess'],1);
505a06e4bdbSSebastian Harl    notify('', 'register', '', $_POST['login'], false);
506f3f0262cSandi    return true;
507f3f0262cSandi  }else{
508f3f0262cSandi    msg($lang['regmailfail'],-1);
509f3f0262cSandi    return false;
510f3f0262cSandi  }
511f3f0262cSandi}
512f3f0262cSandi
51310a76f6fSfrank/**
5148b06d178Schris * Update user profile
5158b06d178Schris *
5168b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
5178b06d178Schris */
5188b06d178Schrisfunction updateprofile() {
5198b06d178Schris  global $conf;
5208b06d178Schris  global $INFO;
5218b06d178Schris  global $lang;
522cd52f92dSchris  global $auth;
5238b06d178Schris
5248b06d178Schris  if(!$_POST['save']) return false;
5258b06d178Schris
52682fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
52782fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
5288b06d178Schris    msg($lang['profna'],-1);
5298b06d178Schris    return false;
5308b06d178Schris  }
5318b06d178Schris
5328b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
5338b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
5348b06d178Schris    return false;
5358b06d178Schris  }
5368b06d178Schris
5378b06d178Schris  //clean fullname and email
53811d989c3SAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
53911d989c3SAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
5408b06d178Schris
5418b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
5428b06d178Schris    msg($lang['profnoempty'],-1);
5438b06d178Schris    return false;
5448b06d178Schris  }
5458b06d178Schris
5468b06d178Schris  if (!mail_isvalid($_POST['email'])){
5478b06d178Schris    msg($lang['regbadmail'],-1);
5488b06d178Schris    return false;
5498b06d178Schris  }
5508b06d178Schris
5518b06d178Schris  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
5528b06d178Schris  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
5538b06d178Schris  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
5548b06d178Schris
5558b06d178Schris  if (!count($changes)) {
5568b06d178Schris    msg($lang['profnochange'], -1);
5578b06d178Schris    return false;
5588b06d178Schris  }
5598b06d178Schris
5608b06d178Schris  if ($conf['profileconfirm']) {
5618b06d178Schris      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
5628b06d178Schris      msg($lang['badlogin'],-1);
5638b06d178Schris      return false;
5648b06d178Schris    }
5658b06d178Schris  }
5668b06d178Schris
567cd52f92dSchris  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
5688b06d178Schris}
5698b06d178Schris
5708b06d178Schris/**
5718b06d178Schris * Send a  new password
5728b06d178Schris *
573*1d5856cfSAndreas Gohr * This function handles both phases of the password reset:
574*1d5856cfSAndreas Gohr *
575*1d5856cfSAndreas Gohr *   - handling the first request of password reset
576*1d5856cfSAndreas Gohr *   - validating the password reset auth token
577*1d5856cfSAndreas Gohr *
5788b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
5798b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
580*1d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5818b06d178Schris *
5828b06d178Schris * @return bool true on success, false on any error
5838b06d178Schris*/
5848b06d178Schrisfunction act_resendpwd(){
5858b06d178Schris    global $lang;
5868b06d178Schris    global $conf;
587cd52f92dSchris    global $auth;
5888b06d178Schris
589409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
5908b06d178Schris
59182fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
59282fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
5938b06d178Schris        msg($lang['resendna'],-1);
5948b06d178Schris        return false;
5958b06d178Schris    }
5968b06d178Schris
597*1d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
5988b06d178Schris
599*1d5856cfSAndreas Gohr    if($token){
600*1d5856cfSAndreas Gohr        // we're in token phase
601*1d5856cfSAndreas Gohr
602*1d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
603*1d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
604*1d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
605*1d5856cfSAndreas Gohr            return false;
606*1d5856cfSAndreas Gohr        }
607*1d5856cfSAndreas Gohr        $user = io_readfile($tfile);
608*1d5856cfSAndreas Gohr        @unlink($tfile);
609cd52f92dSchris        $userinfo = $auth->getUserData($user);
6108b06d178Schris        if(!$userinfo['mail']) {
6118b06d178Schris            msg($lang['resendpwdnouser'], -1);
6128b06d178Schris            return false;
6138b06d178Schris        }
6148b06d178Schris
6158b06d178Schris        $pass = auth_pwgen();
616cd52f92dSchris        if (!$auth->modifyUser($user,array('pass' => $pass))) {
6178b06d178Schris            msg('error modifying user data',-1);
6188b06d178Schris            return false;
6198b06d178Schris        }
6208b06d178Schris
6218b06d178Schris        if (auth_sendPassword($user,$pass)) {
6228b06d178Schris            msg($lang['resendpwdsuccess'],1);
6238b06d178Schris        } else {
6248b06d178Schris            msg($lang['regmailfail'],-1);
6258b06d178Schris        }
6268b06d178Schris        return true;
627*1d5856cfSAndreas Gohr
628*1d5856cfSAndreas Gohr    } else {
629*1d5856cfSAndreas Gohr        // we're in request phase
630*1d5856cfSAndreas Gohr
631*1d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
632*1d5856cfSAndreas Gohr
633*1d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
634*1d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
635*1d5856cfSAndreas Gohr            return false;
636*1d5856cfSAndreas Gohr        } else {
637*1d5856cfSAndreas Gohr            $user = $_POST['login'];
638*1d5856cfSAndreas Gohr        }
639*1d5856cfSAndreas Gohr
640*1d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
641*1d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
642*1d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
643*1d5856cfSAndreas Gohr            return false;
644*1d5856cfSAndreas Gohr        }
645*1d5856cfSAndreas Gohr
646*1d5856cfSAndreas Gohr        // generate auth token
647*1d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
648*1d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
649*1d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
650*1d5856cfSAndreas Gohr
651*1d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
652*1d5856cfSAndreas Gohr
653*1d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
654*1d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
655*1d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
656*1d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
657*1d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
658*1d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
659*1d5856cfSAndreas Gohr
660*1d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
661*1d5856cfSAndreas Gohr                     $lang['regpwmail'],
662*1d5856cfSAndreas Gohr                     $text,
663*1d5856cfSAndreas Gohr                     $conf['mailfrom'])){
664*1d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
665*1d5856cfSAndreas Gohr        }else{
666*1d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
667*1d5856cfSAndreas Gohr        }
668*1d5856cfSAndreas Gohr        return true;
669*1d5856cfSAndreas Gohr    }
670*1d5856cfSAndreas Gohr
671*1d5856cfSAndreas Gohr    return false; // never reached
6728b06d178Schris}
6738b06d178Schris
6748b06d178Schris/**
67510a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
67610a76f6fSfrank *
67710a76f6fSfrank * May not be completly RFC conform!
67810a76f6fSfrank *
67910a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
68010a76f6fSfrank *
68110a76f6fSfrank * @param   string $email the address to check
68210a76f6fSfrank * @return  bool          true if address is valid
68310a76f6fSfrank */
68410a76f6fSfrankfunction isvalidemail($email){
68510a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
68610a76f6fSfrank}
68710a76f6fSfrank
688b0855b11Sandi/**
689b0855b11Sandi * Encrypts a password using the given method and salt
690b0855b11Sandi *
691b0855b11Sandi * If the selected method needs a salt and none was given, a random one
692b0855b11Sandi * is chosen.
693b0855b11Sandi *
694b0855b11Sandi * The following methods are understood:
695b0855b11Sandi *
696b0855b11Sandi *   smd5  - Salted MD5 hashing
697b0855b11Sandi *   md5   - Simple MD5 hashing
698b0855b11Sandi *   sha1  - SHA1 hashing
699b0855b11Sandi *   ssha  - Salted SHA1 hashing
700d7be6245Sandi *   crypt - Unix crypt
701d7be6245Sandi *   mysql - MySQL password (old method)
702d7be6245Sandi *   my411 - MySQL 4.1.1 password
703b0855b11Sandi *
704b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
705b0855b11Sandi * @return  string  The crypted password
706b0855b11Sandi */
707b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
708b0855b11Sandi  global $conf;
709b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
71010a76f6fSfrank
711b0855b11Sandi  //prepare a salt
712b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
713b0855b11Sandi
714b0855b11Sandi  switch(strtolower($method)){
715b0855b11Sandi    case 'smd5':
716b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
717b0855b11Sandi    case 'md5':
718b0855b11Sandi      return md5($clear);
719b0855b11Sandi    case 'sha1':
720b0855b11Sandi      return sha1($clear);
721b0855b11Sandi    case 'ssha':
722b0855b11Sandi      $salt=substr($salt,0,4);
723d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
724b0855b11Sandi    case 'crypt':
725b0855b11Sandi      return crypt($clear,substr($salt,0,2));
726d7be6245Sandi    case 'mysql':
727d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
728d7be6245Sandi      $nr=0x50305735;
729d7be6245Sandi      $nr2=0x12345671;
730d7be6245Sandi      $add=7;
731d7be6245Sandi      $charArr = preg_split("//", $clear);
732d7be6245Sandi      foreach ($charArr as $char) {
733d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
734d7be6245Sandi        $charVal = ord($char);
735d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
736d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
737d7be6245Sandi        $add += $charVal;
738d7be6245Sandi      }
739d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
740d7be6245Sandi    case 'my411':
741d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
742b0855b11Sandi    default:
743b0855b11Sandi      msg("Unsupported crypt method $method",-1);
744b0855b11Sandi  }
745b0855b11Sandi}
746b0855b11Sandi
747b0855b11Sandi/**
748b0855b11Sandi * Verifies a cleartext password against a crypted hash
749b0855b11Sandi *
750b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
751b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
752b0855b11Sandi * match true is is returned else false
753b0855b11Sandi *
754b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
755b0855b11Sandi * @return  bool
756b0855b11Sandi */
757b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
758b0855b11Sandi  $method='';
759b0855b11Sandi  $salt='';
760b0855b11Sandi
761b0855b11Sandi  //determine the used method and salt
762d7be6245Sandi  $len = strlen($crypt);
763b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
764b0855b11Sandi    $method = 'smd5';
765b0855b11Sandi    $salt   = substr($crypt,3,8);
766b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
767b0855b11Sandi    $method = 'ssha';
768b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
769d7be6245Sandi  }elseif($len == 32){
770b0855b11Sandi    $method = 'md5';
771d7be6245Sandi  }elseif($len == 40){
772b0855b11Sandi    $method = 'sha1';
773d7be6245Sandi  }elseif($len == 16){
774d7be6245Sandi    $method = 'mysql';
775d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
776d7be6245Sandi    $method = 'my411';
777b0855b11Sandi  }else{
778b0855b11Sandi    $method = 'crypt';
779b0855b11Sandi    $salt   = substr($crypt,0,2);
780b0855b11Sandi  }
781b0855b11Sandi
782b0855b11Sandi  //crypt and compare
783b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
784b0855b11Sandi    return true;
785b0855b11Sandi  }
786b0855b11Sandi  return false;
787b0855b11Sandi}
788340756e4Sandi
789340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
790