xref: /dokuwiki/inc/auth.php (revision 88e6a4f27638db93e9ca8ca28ea1710343c34701)
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
16ebf97c8fSAndreas Gohr  // some ACL level defines
17ebf97c8fSAndreas Gohr  define('AUTH_NONE',0);
18ebf97c8fSAndreas Gohr  define('AUTH_READ',1);
19ebf97c8fSAndreas Gohr  define('AUTH_EDIT',2);
20ebf97c8fSAndreas Gohr  define('AUTH_CREATE',4);
21ebf97c8fSAndreas Gohr  define('AUTH_UPLOAD',8);
22ebf97c8fSAndreas Gohr  define('AUTH_DELETE',16);
23ebf97c8fSAndreas Gohr  define('AUTH_ADMIN',255);
24ebf97c8fSAndreas Gohr
25742c66f8Schris  global $conf;
26742c66f8Schris
271c73890cSAndreas Gohr  if($conf['useacl']){
28ed7b5f09Sandi    require_once(DOKU_INC.'inc/blowfish.php');
29ed7b5f09Sandi    require_once(DOKU_INC.'inc/mail.php');
308b06d178Schris
3103c4aec3Schris    global $auth;
3203c4aec3Schris
338b06d178Schris    // load the the backend auth functions and instantiate the auth object
348b06d178Schris    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
358b06d178Schris      require_once(DOKU_INC.'inc/auth/basic.class.php');
368b06d178Schris      require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
378b06d178Schris
388b06d178Schris      $auth_class = "auth_".$conf['authtype'];
39cd52f92dSchris      if (class_exists($auth_class)) {
408b06d178Schris        $auth = new $auth_class();
41d2dde4ebSMatthias Grimm        if ($auth->success == false) {
42d2dde4ebSMatthias Grimm          unset($auth);
43cd52f92dSchris          msg($lang['authtempfail'], -1);
44cd52f92dSchris
45cd52f92dSchris          // turn acl config setting off for the rest of this page
46cd52f92dSchris          $conf['useacl'] = 0;
47d2dde4ebSMatthias Grimm        }
488b06d178Schris      } else {
493816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
50cd52f92dSchris      }
51cd52f92dSchris    } else {
523816dcbcSAndreas Gohr      nice_die($lang['authmodfailed']);
538b06d178Schris    }
541c73890cSAndreas Gohr  }
55f3f0262cSandi
56f5cb575dSAndreas Gohr  // do the login either by cookie or provided credentials
57f3f0262cSandi  if($conf['useacl']){
58bbbd6568SAndreas Gohr    if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59bbbd6568SAndreas Gohr    if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60bbbd6568SAndreas Gohr    if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61bbbd6568SAndreas Gohr
621e8c9c90SAndreas Gohr    // if no credentials were given try to use HTTP auth (for SSO)
634a26ad85Schris    if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
641e8c9c90SAndreas Gohr      $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
651e8c9c90SAndreas Gohr      $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
661e8c9c90SAndreas Gohr    }
671e8c9c90SAndreas Gohr
68f5cb575dSAndreas Gohr    // external trust mechanism in place?
6982fd59b6SAndreas Gohr    if(!is_null($auth) && $auth->canDo('external')){
70f5cb575dSAndreas Gohr      $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
71f5cb575dSAndreas Gohr    }else{
72132bdbfeSandi      auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
73f5cb575dSAndreas Gohr    }
74f5cb575dSAndreas Gohr
7515fae107Sandi    //load ACL into a global array
76*88e6a4f2SAndreas Gohr    global $AUTH_ACL;
77e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
78e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
7911799630Sandi    }else{
8011799630Sandi      $AUTH_ACL = array();
8111799630Sandi    }
82f3f0262cSandi  }
83f3f0262cSandi
84f3f0262cSandi/**
85f3f0262cSandi * This tries to login the user based on the sent auth credentials
86f3f0262cSandi *
87f3f0262cSandi * The authentication works like this: if a username was given
8815fae107Sandi * a new login is assumed and user/password are checked. If they
8915fae107Sandi * are correct the password is encrypted with blowfish and stored
9015fae107Sandi * together with the username in a cookie - the same info is stored
9115fae107Sandi * in the session, too. Additonally a browserID is stored in the
9215fae107Sandi * session.
9315fae107Sandi *
9415fae107Sandi * If no username was given the cookie is checked: if the username,
9515fae107Sandi * crypted password and browserID match between session and cookie
9615fae107Sandi * no further testing is done and the user is accepted
9715fae107Sandi *
9815fae107Sandi * If a cookie was found but no session info was availabe the
99136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
10015fae107Sandi * together with username rechecked by calling this function again.
101f3f0262cSandi *
102f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
103f3f0262cSandi * are set.
10415fae107Sandi *
10515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
10615fae107Sandi *
10715fae107Sandi * @param   string  $user    Username
10815fae107Sandi * @param   string  $pass    Cleartext Password
10915fae107Sandi * @param   bool    $sticky  Cookie should not expire
11015fae107Sandi * @return  bool             true on successful auth
111f3f0262cSandi*/
112132bdbfeSandifunction auth_login($user,$pass,$sticky=false){
113f3f0262cSandi  global $USERINFO;
114f3f0262cSandi  global $conf;
115f3f0262cSandi  global $lang;
116cd52f92dSchris  global $auth;
117132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
118f3f0262cSandi
119bbbd6568SAndreas Gohr  if(!empty($user)){
120132bdbfeSandi    //usual login
121cd52f92dSchris    if ($auth->checkPass($user,$pass)){
122132bdbfeSandi      // make logininfo globally available
123f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
124cd52f92dSchris      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
125132bdbfeSandi
126132bdbfeSandi      // set cookie
127132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
128132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
129132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
130e65afed4SSameer D. Sahasrabuddhe      setcookie(DOKU_COOKIE,$cookie,$time,'/');
131132bdbfeSandi
132132bdbfeSandi      // set session
133e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
134e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
135e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
136e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
137132bdbfeSandi      return true;
138f3f0262cSandi    }else{
139f3f0262cSandi      //invalid credentials - log off
140f3f0262cSandi      msg($lang['badlogin'],-1);
141f3f0262cSandi      auth_logoff();
142132bdbfeSandi      return false;
143f3f0262cSandi    }
144f3f0262cSandi  }else{
145132bdbfeSandi    // read cookie information
146e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
147132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
148132bdbfeSandi    // get session info
149e71ce681SAndreas Gohr    $session = $_SESSION[DOKU_COOKIE]['auth'];
150132bdbfeSandi
151132bdbfeSandi    if($user && $pass){
152132bdbfeSandi      // we got a cookie - see if we can trust it
153132bdbfeSandi      if(isset($session) &&
154132bdbfeSandi        ($session['user'] == $user) &&
155132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
156132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
157132bdbfeSandi        // he has session, cookie and browser right - let him in
158132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
159132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
160132bdbfeSandi        return true;
161132bdbfeSandi      }
162132bdbfeSandi      // no we don't trust it yet - recheck pass
163132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
164132bdbfeSandi      return auth_login($user,$pass,$sticky);
165132bdbfeSandi    }
166132bdbfeSandi  }
167f3f0262cSandi  //just to be sure
168f3f0262cSandi  auth_logoff();
169132bdbfeSandi  return false;
170f3f0262cSandi}
171132bdbfeSandi
172132bdbfeSandi/**
173136ce040Sandi * Builds a pseudo UID from browser and IP data
174132bdbfeSandi *
175132bdbfeSandi * This is neither unique nor unfakable - still it adds some
176136ce040Sandi * security. Using the first part of the IP makes sure
177136ce040Sandi * proxy farms like AOLs are stil okay.
17815fae107Sandi *
17915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
18015fae107Sandi *
18115fae107Sandi * @return  string  a MD5 sum of various browser headers
182132bdbfeSandi */
183132bdbfeSandifunction auth_browseruid(){
184132bdbfeSandi  $uid  = '';
185132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
186132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
187132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
188132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
189136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
190132bdbfeSandi  return md5($uid);
191132bdbfeSandi}
192132bdbfeSandi
193132bdbfeSandi/**
194132bdbfeSandi * Creates a random key to encrypt the password in cookies
19515fae107Sandi *
19615fae107Sandi * This function tries to read the password for encrypting
19798407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
19815fae107Sandi * if no such file is found a random key is created and
19915fae107Sandi * and stored in this file.
20015fae107Sandi *
20115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20215fae107Sandi *
20315fae107Sandi * @return  string
204132bdbfeSandi */
205132bdbfeSandifunction auth_cookiesalt(){
206132bdbfeSandi  global $conf;
20798407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
208132bdbfeSandi  $salt = io_readFile($file);
209132bdbfeSandi  if(empty($salt)){
210132bdbfeSandi    $salt = uniqid(rand(),true);
211132bdbfeSandi    io_saveFile($file,$salt);
212132bdbfeSandi  }
213132bdbfeSandi  return $salt;
214f3f0262cSandi}
215f3f0262cSandi
216f3f0262cSandi/**
217f3f0262cSandi * This clears all authenticationdata and thus log the user
218f3f0262cSandi * off
21915fae107Sandi *
22015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
221f3f0262cSandi */
222f3f0262cSandifunction auth_logoff(){
223f3f0262cSandi  global $conf;
224f3f0262cSandi  global $USERINFO;
2258b06d178Schris  global $INFO, $ID;
2265298a619SAndreas Gohr  global $auth;
22737065e65Sandi
228e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
229e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['user']);
230e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
231e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
232e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
233e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['info']);
23437065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
235f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
236132bdbfeSandi  $USERINFO=null; //FIXME
2371e866646Sandi  setcookie(DOKU_COOKIE,'',time()-600000,'/');
2385298a619SAndreas Gohr
2395298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
2405298a619SAndreas Gohr    $auth->logOff();
2415298a619SAndreas Gohr  }
242f3f0262cSandi}
243f3f0262cSandi
244f3f0262cSandi/**
24515fae107Sandi * Convinience function for auth_aclcheck()
24615fae107Sandi *
24715fae107Sandi * This checks the permissions for the current user
24815fae107Sandi *
24915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25015fae107Sandi *
25115fae107Sandi * @param  string  $id  page ID
25215fae107Sandi * @return int          permission level
253f3f0262cSandi */
254f3f0262cSandifunction auth_quickaclcheck($id){
255f3f0262cSandi  global $conf;
256f3f0262cSandi  global $USERINFO;
257f3f0262cSandi  # if no ACL is used always return upload rights
258f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
259f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
260f3f0262cSandi}
261f3f0262cSandi
262f3f0262cSandi/**
263f3f0262cSandi * Returns the maximum rights a user has for
264f3f0262cSandi * the given ID or its namespace
26515fae107Sandi *
26615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26715fae107Sandi *
26815fae107Sandi * @param  string  $id     page ID
26915fae107Sandi * @param  string  $user   Username
27015fae107Sandi * @param  array   $groups Array of groups the user is in
27115fae107Sandi * @return int             permission level
272f3f0262cSandi */
273f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
274f3f0262cSandi  global $conf;
275f3f0262cSandi  global $AUTH_ACL;
276f3f0262cSandi
277f3f0262cSandi  # if no ACL is used always return upload rights
278f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
279f3f0262cSandi
2806c2bb100SAndreas Gohr  $user = auth_nameencode($user);
2816c2bb100SAndreas Gohr
28210a76f6fSfrank  //if user is superuser return 255 (acl_admin)
283e838fc2eSAndreas Gohr  if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; }
28410a76f6fSfrank
285074cf26bSandi  //make sure groups is an array
286074cf26bSandi  if(!is_array($groups)) $groups = array();
287074cf26bSandi
2886c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
2892cd2db38Sandi  $cnt = count($groups);
2902cd2db38Sandi  for($i=0; $i<$cnt; $i++){
2916c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
29210a76f6fSfrank  }
29310a76f6fSfrank  //if user is in superuser group return 255 (acl_admin)
294e838fc2eSAndreas Gohr  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; }
29510a76f6fSfrank
296f3f0262cSandi  $ns    = getNS($id);
297f3f0262cSandi  $perm  = -1;
298f3f0262cSandi
299f3f0262cSandi  if($user){
300f3f0262cSandi    //add ALL group
301f3f0262cSandi    $groups[] = '@ALL';
302f3f0262cSandi    //add User
303f3f0262cSandi    $groups[] = $user;
304f3f0262cSandi    //build regexp
305f3f0262cSandi    $regexp   = join('|',$groups);
306f3f0262cSandi  }else{
307f3f0262cSandi    $regexp = '@ALL';
308f3f0262cSandi  }
309f3f0262cSandi
310f3f0262cSandi  //check exact match first
31142905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
312f3f0262cSandi  if(count($matches)){
313f3f0262cSandi    foreach($matches as $match){
314f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
315f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
3168ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
317f3f0262cSandi      if($acl[2] > $perm){
318f3f0262cSandi        $perm = $acl[2];
319f3f0262cSandi      }
320f3f0262cSandi    }
321f3f0262cSandi    if($perm > -1){
322f3f0262cSandi      //we had a match - return it
323f3f0262cSandi      return $perm;
324f3f0262cSandi    }
325f3f0262cSandi  }
326f3f0262cSandi
327f3f0262cSandi  //still here? do the namespace checks
328f3f0262cSandi  if($ns){
329f3f0262cSandi    $path = $ns.':\*';
330f3f0262cSandi  }else{
331f3f0262cSandi    $path = '\*'; //root document
332f3f0262cSandi  }
333f3f0262cSandi
334f3f0262cSandi  do{
335f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
336f3f0262cSandi    if(count($matches)){
337f3f0262cSandi      foreach($matches as $match){
338f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
339f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
3408ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
341f3f0262cSandi        if($acl[2] > $perm){
342f3f0262cSandi          $perm = $acl[2];
343f3f0262cSandi        }
344f3f0262cSandi      }
345f3f0262cSandi      //we had a match - return it
346f3f0262cSandi      return $perm;
347f3f0262cSandi    }
348f3f0262cSandi
349f3f0262cSandi    //get next higher namespace
350f3f0262cSandi    $ns   = getNS($ns);
351f3f0262cSandi
352f3f0262cSandi    if($path != '\*'){
353f3f0262cSandi      $path = $ns.':\*';
354f3f0262cSandi      if($path == ':\*') $path = '\*';
355f3f0262cSandi    }else{
356f3f0262cSandi      //we did this already
357f3f0262cSandi      //looks like there is something wrong with the ACL
358f3f0262cSandi      //break here
359d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
360d5ce66f6SAndreas Gohr      return AUTH_NONE;
361f3f0262cSandi    }
362f3f0262cSandi  }while(1); //this should never loop endless
36352a5af8dSandi
36452a5af8dSandi  //still here? return no permissions
36552a5af8dSandi  return AUTH_NONE;
366f3f0262cSandi}
367f3f0262cSandi
368f3f0262cSandi/**
3696c2bb100SAndreas Gohr * Encode ASCII special chars
3706c2bb100SAndreas Gohr *
3716c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
3726c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
3736c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
3746c2bb100SAndreas Gohr * urlencoding!).
3756c2bb100SAndreas Gohr *
3766c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
3776c2bb100SAndreas Gohr *
3786c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
3796c2bb100SAndreas Gohr * @see rawurldecode()
3806c2bb100SAndreas Gohr */
381e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
382a424cd8eSchris  global $cache_authname;
383a424cd8eSchris  $cache =& $cache_authname;
384a424cd8eSchris
385a424cd8eSchris  if (!isset($cache[$name][$skip_group])) {
386e838fc2eSAndreas Gohr    if($skip_group && $name{0} =='@'){
387a424cd8eSchris      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
388e838fc2eSAndreas Gohr                                                    "'%'.dechex(ord('\\1'))",substr($name,1));
389e838fc2eSAndreas Gohr    }else{
390a424cd8eSchris      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
391e838fc2eSAndreas Gohr                                                "'%'.dechex(ord('\\1'))",$name);
392e838fc2eSAndreas Gohr    }
3936c2bb100SAndreas Gohr  }
3946c2bb100SAndreas Gohr
395a424cd8eSchris  return $cache[$name][$skip_group];
396a424cd8eSchris}
397a424cd8eSchris
3986c2bb100SAndreas Gohr/**
399f3f0262cSandi * Create a pronouncable password
400f3f0262cSandi *
40115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40215fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
40315fae107Sandi *
40415fae107Sandi * @return string  pronouncable password
405f3f0262cSandi */
406f3f0262cSandifunction auth_pwgen(){
407f3f0262cSandi  $pw = '';
408f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
409f3f0262cSandi  $v  = 'aeiou';              //vowels
410f3f0262cSandi  $a  = $c.$v;                //both
411f3f0262cSandi
412f3f0262cSandi  //use two syllables...
413f3f0262cSandi  for($i=0;$i < 2; $i++){
414f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
415f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
416f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
417f3f0262cSandi  }
418f3f0262cSandi  //... and add a nice number
419f3f0262cSandi  $pw .= rand(10,99);
420f3f0262cSandi
421f3f0262cSandi  return $pw;
422f3f0262cSandi}
423f3f0262cSandi
424f3f0262cSandi/**
425f3f0262cSandi * Sends a password to the given user
426f3f0262cSandi *
42715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
42815fae107Sandi *
42915fae107Sandi * @return bool  true on success
430f3f0262cSandi */
431f3f0262cSandifunction auth_sendPassword($user,$password){
432f3f0262cSandi  global $conf;
433f3f0262cSandi  global $lang;
434cd52f92dSchris  global $auth;
435cd52f92dSchris
436f3f0262cSandi  $hdrs  = '';
437cd52f92dSchris  $userinfo = $auth->getUserData($user);
438f3f0262cSandi
43987ddda95Sandi  if(!$userinfo['mail']) return false;
440f3f0262cSandi
441f3f0262cSandi  $text = rawLocale('password');
442ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
44387ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
444f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
445f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
446f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
447f3f0262cSandi
44844f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
44944f669e9Sandi                   $lang['regpwmail'],
45044f669e9Sandi                   $text,
45144f669e9Sandi                   $conf['mailfrom']);
452f3f0262cSandi}
453f3f0262cSandi
454f3f0262cSandi/**
45515fae107Sandi * Register a new user
456f3f0262cSandi *
45715fae107Sandi * This registers a new user - Data is read directly from $_POST
45815fae107Sandi *
45915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
46015fae107Sandi *
46115fae107Sandi * @return bool  true on success, false on any error
462f3f0262cSandi */
463f3f0262cSandifunction register(){
464f3f0262cSandi  global $lang;
465eb5d07e4Sjan  global $conf;
466cd52f92dSchris  global $auth;
467f3f0262cSandi
468f3f0262cSandi  if(!$_POST['save']) return false;
46982fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
470640145a5Sandi
471f3f0262cSandi  //clean username
472f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
473f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
474f3f0262cSandi  //clean fullname and email
47554f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
47654f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
477f3f0262cSandi
478f3f0262cSandi  if( empty($_POST['login']) ||
479f3f0262cSandi      empty($_POST['fullname']) ||
480f3f0262cSandi      empty($_POST['email']) ){
481f3f0262cSandi    msg($lang['regmissing'],-1);
482f3f0262cSandi    return false;
483f3f0262cSandi  }
484f3f0262cSandi
485cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
486cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
487cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
488cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
489bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
490cab2716aSmatthias.grimm    return false;
491cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
492bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
493cab2716aSmatthias.grimm    return false;
494cab2716aSmatthias.grimm  } else {
495cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
496cab2716aSmatthias.grimm  }
497cab2716aSmatthias.grimm
498f3f0262cSandi  //check mail
49944f669e9Sandi  if(!mail_isvalid($_POST['email'])){
500f3f0262cSandi    msg($lang['regbadmail'],-1);
501f3f0262cSandi    return false;
502f3f0262cSandi  }
503f3f0262cSandi
504f3f0262cSandi  //okay try to create the user
5051d096a10SAndreas Gohr  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
506f3f0262cSandi    msg($lang['reguexists'],-1);
507f3f0262cSandi    return false;
508f3f0262cSandi  }
509f3f0262cSandi
51002a498e7Schris  // create substitutions for use in notification email
51102a498e7Schris  $substitutions = array(
51202a498e7Schris    'NEWUSER' => $_POST['login'],
51302a498e7Schris    'NEWNAME' => $_POST['fullname'],
51402a498e7Schris    'NEWEMAIL' => $_POST['email'],
51502a498e7Schris  );
51602a498e7Schris
517cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
518cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
51902a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
520cab2716aSmatthias.grimm    return true;
521cab2716aSmatthias.grimm  }
522cab2716aSmatthias.grimm
523cab2716aSmatthias.grimm  // autogenerated password? then send him the password
524f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
525f3f0262cSandi    msg($lang['regsuccess'],1);
52602a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
527f3f0262cSandi    return true;
528f3f0262cSandi  }else{
529f3f0262cSandi    msg($lang['regmailfail'],-1);
530f3f0262cSandi    return false;
531f3f0262cSandi  }
532f3f0262cSandi}
533f3f0262cSandi
53410a76f6fSfrank/**
5358b06d178Schris * Update user profile
5368b06d178Schris *
5378b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
5388b06d178Schris */
5398b06d178Schrisfunction updateprofile() {
5408b06d178Schris  global $conf;
5418b06d178Schris  global $INFO;
5428b06d178Schris  global $lang;
543cd52f92dSchris  global $auth;
5448b06d178Schris
545bb4866bdSchris  if(empty($_POST['save'])) return false;
5468b06d178Schris
54782fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
54882fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
5498b06d178Schris    msg($lang['profna'],-1);
5508b06d178Schris    return false;
5518b06d178Schris  }
5528b06d178Schris
5538b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
5548b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
5558b06d178Schris    return false;
5568b06d178Schris  }
5578b06d178Schris
5588b06d178Schris  //clean fullname and email
55954f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
56054f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
5618b06d178Schris
5628b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
5638b06d178Schris    msg($lang['profnoempty'],-1);
5648b06d178Schris    return false;
5658b06d178Schris  }
5668b06d178Schris
5678b06d178Schris  if (!mail_isvalid($_POST['email'])){
5688b06d178Schris    msg($lang['regbadmail'],-1);
5698b06d178Schris    return false;
5708b06d178Schris  }
5718b06d178Schris
5728b06d178Schris  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
5738b06d178Schris  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
5748b06d178Schris  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
5758b06d178Schris
5768b06d178Schris  if (!count($changes)) {
5778b06d178Schris    msg($lang['profnochange'], -1);
5788b06d178Schris    return false;
5798b06d178Schris  }
5808b06d178Schris
5818b06d178Schris  if ($conf['profileconfirm']) {
5828b06d178Schris      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
5838b06d178Schris      msg($lang['badlogin'],-1);
5848b06d178Schris      return false;
5858b06d178Schris    }
5868b06d178Schris  }
5878b06d178Schris
588cd52f92dSchris  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
5898b06d178Schris}
5908b06d178Schris
5918b06d178Schris/**
5928b06d178Schris * Send a  new password
5938b06d178Schris *
5941d5856cfSAndreas Gohr * This function handles both phases of the password reset:
5951d5856cfSAndreas Gohr *
5961d5856cfSAndreas Gohr *   - handling the first request of password reset
5971d5856cfSAndreas Gohr *   - validating the password reset auth token
5981d5856cfSAndreas Gohr *
5998b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
6008b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
6011d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6028b06d178Schris *
6038b06d178Schris * @return bool true on success, false on any error
6048b06d178Schris*/
6058b06d178Schrisfunction act_resendpwd(){
6068b06d178Schris    global $lang;
6078b06d178Schris    global $conf;
608cd52f92dSchris    global $auth;
6098b06d178Schris
610409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
6118b06d178Schris
61282fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
61382fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
6148b06d178Schris        msg($lang['resendna'],-1);
6158b06d178Schris        return false;
6168b06d178Schris    }
6178b06d178Schris
6181d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
6198b06d178Schris
6201d5856cfSAndreas Gohr    if($token){
6211d5856cfSAndreas Gohr        // we're in token phase
6221d5856cfSAndreas Gohr
6231d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
6241d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
6251d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
6261d5856cfSAndreas Gohr            return false;
6271d5856cfSAndreas Gohr        }
6281d5856cfSAndreas Gohr        $user = io_readfile($tfile);
6291d5856cfSAndreas Gohr        @unlink($tfile);
630cd52f92dSchris        $userinfo = $auth->getUserData($user);
6318b06d178Schris        if(!$userinfo['mail']) {
6328b06d178Schris            msg($lang['resendpwdnouser'], -1);
6338b06d178Schris            return false;
6348b06d178Schris        }
6358b06d178Schris
6368b06d178Schris        $pass = auth_pwgen();
637cd52f92dSchris        if (!$auth->modifyUser($user,array('pass' => $pass))) {
6388b06d178Schris            msg('error modifying user data',-1);
6398b06d178Schris            return false;
6408b06d178Schris        }
6418b06d178Schris
6428b06d178Schris        if (auth_sendPassword($user,$pass)) {
6438b06d178Schris            msg($lang['resendpwdsuccess'],1);
6448b06d178Schris        } else {
6458b06d178Schris            msg($lang['regmailfail'],-1);
6468b06d178Schris        }
6478b06d178Schris        return true;
6481d5856cfSAndreas Gohr
6491d5856cfSAndreas Gohr    } else {
6501d5856cfSAndreas Gohr        // we're in request phase
6511d5856cfSAndreas Gohr
6521d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
6531d5856cfSAndreas Gohr
6541d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
6551d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
6561d5856cfSAndreas Gohr            return false;
6571d5856cfSAndreas Gohr        } else {
65816470b1dSchris            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
65916470b1dSchris            $user = cleanID($_POST['login']);
6601d5856cfSAndreas Gohr        }
6611d5856cfSAndreas Gohr
6621d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
6631d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
6641d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
6651d5856cfSAndreas Gohr            return false;
6661d5856cfSAndreas Gohr        }
6671d5856cfSAndreas Gohr
6681d5856cfSAndreas Gohr        // generate auth token
6691d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
6701d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
6711d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
6721d5856cfSAndreas Gohr
6731d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
6741d5856cfSAndreas Gohr
6751d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
6761d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
6771d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
6781d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
6791d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
6801d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
6811d5856cfSAndreas Gohr
6821d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
6831d5856cfSAndreas Gohr                     $lang['regpwmail'],
6841d5856cfSAndreas Gohr                     $text,
6851d5856cfSAndreas Gohr                     $conf['mailfrom'])){
6861d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
6871d5856cfSAndreas Gohr        }else{
6881d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
6891d5856cfSAndreas Gohr        }
6901d5856cfSAndreas Gohr        return true;
6911d5856cfSAndreas Gohr    }
6921d5856cfSAndreas Gohr
6931d5856cfSAndreas Gohr    return false; // never reached
6948b06d178Schris}
6958b06d178Schris
6968b06d178Schris/**
69710a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
69810a76f6fSfrank *
69910a76f6fSfrank * May not be completly RFC conform!
70010a76f6fSfrank *
70110a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
70210a76f6fSfrank *
70310a76f6fSfrank * @param   string $email the address to check
70410a76f6fSfrank * @return  bool          true if address is valid
70510a76f6fSfrank */
70610a76f6fSfrankfunction isvalidemail($email){
70710a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
70810a76f6fSfrank}
70910a76f6fSfrank
710b0855b11Sandi/**
711b0855b11Sandi * Encrypts a password using the given method and salt
712b0855b11Sandi *
713b0855b11Sandi * If the selected method needs a salt and none was given, a random one
714b0855b11Sandi * is chosen.
715b0855b11Sandi *
716b0855b11Sandi * The following methods are understood:
717b0855b11Sandi *
718b0855b11Sandi *   smd5  - Salted MD5 hashing
719b0855b11Sandi *   md5   - Simple MD5 hashing
720b0855b11Sandi *   sha1  - SHA1 hashing
721b0855b11Sandi *   ssha  - Salted SHA1 hashing
722d7be6245Sandi *   crypt - Unix crypt
723d7be6245Sandi *   mysql - MySQL password (old method)
724d7be6245Sandi *   my411 - MySQL 4.1.1 password
725b0855b11Sandi *
726b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
727b0855b11Sandi * @return  string  The crypted password
728b0855b11Sandi */
729b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
730b0855b11Sandi  global $conf;
731b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
73210a76f6fSfrank
733b0855b11Sandi  //prepare a salt
734b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
735b0855b11Sandi
736b0855b11Sandi  switch(strtolower($method)){
737b0855b11Sandi    case 'smd5':
738b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
739b0855b11Sandi    case 'md5':
740b0855b11Sandi      return md5($clear);
741b0855b11Sandi    case 'sha1':
742b0855b11Sandi      return sha1($clear);
743b0855b11Sandi    case 'ssha':
744b0855b11Sandi      $salt=substr($salt,0,4);
745d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
746b0855b11Sandi    case 'crypt':
747b0855b11Sandi      return crypt($clear,substr($salt,0,2));
748d7be6245Sandi    case 'mysql':
749d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
750d7be6245Sandi      $nr=0x50305735;
751d7be6245Sandi      $nr2=0x12345671;
752d7be6245Sandi      $add=7;
753d7be6245Sandi      $charArr = preg_split("//", $clear);
754d7be6245Sandi      foreach ($charArr as $char) {
755d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
756d7be6245Sandi        $charVal = ord($char);
757d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
758d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
759d7be6245Sandi        $add += $charVal;
760d7be6245Sandi      }
761d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
762d7be6245Sandi    case 'my411':
763d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
764b0855b11Sandi    default:
765b0855b11Sandi      msg("Unsupported crypt method $method",-1);
766b0855b11Sandi  }
767b0855b11Sandi}
768b0855b11Sandi
769b0855b11Sandi/**
770b0855b11Sandi * Verifies a cleartext password against a crypted hash
771b0855b11Sandi *
772b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
773b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
774b0855b11Sandi * match true is is returned else false
775b0855b11Sandi *
776b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
777b0855b11Sandi * @return  bool
778b0855b11Sandi */
779b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
780b0855b11Sandi  $method='';
781b0855b11Sandi  $salt='';
782b0855b11Sandi
783b0855b11Sandi  //determine the used method and salt
784d7be6245Sandi  $len = strlen($crypt);
785b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
786b0855b11Sandi    $method = 'smd5';
787b0855b11Sandi    $salt   = substr($crypt,3,8);
788b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
789b0855b11Sandi    $method = 'ssha';
790b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
791d7be6245Sandi  }elseif($len == 32){
792b0855b11Sandi    $method = 'md5';
793d7be6245Sandi  }elseif($len == 40){
794b0855b11Sandi    $method = 'sha1';
795d7be6245Sandi  }elseif($len == 16){
796d7be6245Sandi    $method = 'mysql';
797d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
798d7be6245Sandi    $method = 'my411';
799b0855b11Sandi  }else{
800b0855b11Sandi    $method = 'crypt';
801b0855b11Sandi    $salt   = substr($crypt,0,2);
802b0855b11Sandi  }
803b0855b11Sandi
804b0855b11Sandi  //crypt and compare
805b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
806b0855b11Sandi    return true;
807b0855b11Sandi  }
808b0855b11Sandi  return false;
809b0855b11Sandi}
810340756e4Sandi
811340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
812