xref: /dokuwiki/inc/auth.php (revision 17f89d7e697c716eb2ba57544d2b4d4394ce7ef4)
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
1200976812SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(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) {
420f4f4adfSAndreas Gohr          // degrade to unauthenticated user
43d2dde4ebSMatthias Grimm          unset($auth);
440f4f4adfSAndreas Gohr          auth_logoff();
45cd52f92dSchris          msg($lang['authtempfail'], -1);
46d2dde4ebSMatthias Grimm        }
478b06d178Schris      } else {
483816dcbcSAndreas Gohr        nice_die($lang['authmodfailed']);
49cd52f92dSchris      }
50cd52f92dSchris    } else {
513816dcbcSAndreas Gohr      nice_die($lang['authmodfailed']);
528b06d178Schris    }
531c73890cSAndreas Gohr  }
54f3f0262cSandi
55f5cb575dSAndreas Gohr  // do the login either by cookie or provided credentials
561ec50243SAndreas Gohr  if($conf['useacl']){
571ec50243SAndreas Gohr    if($auth){
58bbbd6568SAndreas Gohr      if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59bbbd6568SAndreas Gohr      if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60bbbd6568SAndreas Gohr      if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61b2c0d874SGina Haeussge      $_REQUEST['http_credentials'] = false;
62*17f89d7eSMichael Klier      if (!$conf['rememberme']) $_REQUEST['r'] = false;
63bbbd6568SAndreas Gohr
641e8c9c90SAndreas Gohr      // if no credentials were given try to use HTTP auth (for SSO)
654a26ad85Schris      if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
661e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
671e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
68b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = true;
691e8c9c90SAndreas Gohr      }
701e8c9c90SAndreas Gohr
71f13fa892SAndreas Gohr      if($_REQUEST['authtok']){
72f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
73f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
74f13fa892SAndreas Gohr      }elseif(!is_null($auth) && $auth->canDo('external')){
75f13fa892SAndreas Gohr        // external trust mechanism in place
76f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
77f5cb575dSAndreas Gohr      }else{
78b2c0d874SGina Haeussge        auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r'],$_REQUEST['http_credentials']);
79f5cb575dSAndreas Gohr      }
801ec50243SAndreas Gohr    }
81f5cb575dSAndreas Gohr
8215fae107Sandi    //load ACL into a global array
8388e6a4f2SAndreas Gohr    global $AUTH_ACL;
84e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
85e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
86f8cc3354SGuy Brand      if(isset($_SERVER['REMOTE_USER'])){
87a8fe108bSGuy Brand        $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL);
88a8fe108bSGuy Brand      }
8911799630Sandi    }else{
9011799630Sandi      $AUTH_ACL = array();
9111799630Sandi    }
92f3f0262cSandi  }
93f3f0262cSandi
94f3f0262cSandi/**
95f3f0262cSandi * This tries to login the user based on the sent auth credentials
96f3f0262cSandi *
97f3f0262cSandi * The authentication works like this: if a username was given
9815fae107Sandi * a new login is assumed and user/password are checked. If they
9915fae107Sandi * are correct the password is encrypted with blowfish and stored
10015fae107Sandi * together with the username in a cookie - the same info is stored
10115fae107Sandi * in the session, too. Additonally a browserID is stored in the
10215fae107Sandi * session.
10315fae107Sandi *
10415fae107Sandi * If no username was given the cookie is checked: if the username,
10515fae107Sandi * crypted password and browserID match between session and cookie
10615fae107Sandi * no further testing is done and the user is accepted
10715fae107Sandi *
10815fae107Sandi * If a cookie was found but no session info was availabe the
109136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
11015fae107Sandi * together with username rechecked by calling this function again.
111f3f0262cSandi *
112f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
113f3f0262cSandi * are set.
11415fae107Sandi *
11515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
11615fae107Sandi *
11715fae107Sandi * @param   string  $user    Username
11815fae107Sandi * @param   string  $pass    Cleartext Password
11915fae107Sandi * @param   bool    $sticky  Cookie should not expire
120f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
12115fae107Sandi * @return  bool             true on successful auth
122f3f0262cSandi*/
123f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
124f3f0262cSandi  global $USERINFO;
125f3f0262cSandi  global $conf;
126f3f0262cSandi  global $lang;
127cd52f92dSchris  global $auth;
128132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
129f3f0262cSandi
130bbbd6568SAndreas Gohr  if(!empty($user)){
131132bdbfeSandi    //usual login
132cd52f92dSchris    if ($auth->checkPass($user,$pass)){
133132bdbfeSandi      // make logininfo globally available
134f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
1350f4f4adfSAndreas Gohr      $USERINFO = $auth->getUserData($user);
136132bdbfeSandi
137132bdbfeSandi      // set cookie
138132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
139132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
140132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
141f5c6743cSAndreas Gohr      if (version_compare(PHP_VERSION, '5.2.0', '>')) {
142f5c6743cSAndreas Gohr          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
143f5c6743cSAndreas Gohr      }else{
144f5c6743cSAndreas Gohr          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
145f5c6743cSAndreas Gohr      }
146132bdbfeSandi
147132bdbfeSandi      // set session
148e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
149e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
150e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
151e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1524c989037SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1534c989037SChris Smith
154132bdbfeSandi      return true;
155f3f0262cSandi    }else{
156f3f0262cSandi      //invalid credentials - log off
157f112c2faSAndreas Gohr      if(!$silent) msg($lang['badlogin'],-1);
158f3f0262cSandi      auth_logoff();
159132bdbfeSandi      return false;
160f3f0262cSandi    }
161f3f0262cSandi  }else{
162132bdbfeSandi    // read cookie information
163e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
164132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
165132bdbfeSandi    // get session info
166e71ce681SAndreas Gohr    $session = $_SESSION[DOKU_COOKIE]['auth'];
167132bdbfeSandi    if($user && $pass){
168132bdbfeSandi      // we got a cookie - see if we can trust it
169132bdbfeSandi      if(isset($session) &&
1707172dbc0SAndreas Gohr        $auth->useSessionCache($user) &&
1714c989037SChris Smith        ($session['time'] >= time()-$conf['auth_security_timeout']) &&
172132bdbfeSandi        ($session['user'] == $user) &&
173132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
174132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
175132bdbfeSandi        // he has session, cookie and browser right - let him in
176132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
177132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
178132bdbfeSandi        return true;
179132bdbfeSandi      }
180f112c2faSAndreas Gohr      // no we don't trust it yet - recheck pass but silent
181132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
182f112c2faSAndreas Gohr      return auth_login($user,$pass,$sticky,true);
183132bdbfeSandi    }
184132bdbfeSandi  }
185f3f0262cSandi  //just to be sure
186f3f0262cSandi  auth_logoff();
187132bdbfeSandi  return false;
188f3f0262cSandi}
189132bdbfeSandi
190132bdbfeSandi/**
191f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
192f13fa892SAndreas Gohr *
193f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
194f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
195f13fa892SAndreas Gohr *
196f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
197f13fa892SAndreas Gohr * @param  string $token The authentication token
198f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
199f13fa892SAndreas Gohr */
200f13fa892SAndreas Gohrfunction auth_validateToken($token){
201f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
202f13fa892SAndreas Gohr        // bad token
203f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
204f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
205f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
206f13fa892SAndreas Gohr        exit;
207f13fa892SAndreas Gohr    }
208f13fa892SAndreas Gohr    // still here? trust the session data
209f13fa892SAndreas Gohr    global $USERINFO;
210f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
211f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
212f13fa892SAndreas Gohr    return true;
213f13fa892SAndreas Gohr}
214f13fa892SAndreas Gohr
215f13fa892SAndreas Gohr/**
216f13fa892SAndreas Gohr * Create an auth token and store it in the session
217f13fa892SAndreas Gohr *
218f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
219f13fa892SAndreas Gohr *
220f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
221f13fa892SAndreas Gohr * @return string The auth token
222f13fa892SAndreas Gohr */
223f13fa892SAndreas Gohrfunction auth_createToken(){
224f13fa892SAndreas Gohr    $token = md5(mt_rand());
22509c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
226f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
22709c2d803SAndreas Gohr    session_write_close();
228f13fa892SAndreas Gohr    return $token;
229f13fa892SAndreas Gohr}
230f13fa892SAndreas Gohr
231f13fa892SAndreas Gohr/**
232136ce040Sandi * Builds a pseudo UID from browser and IP data
233132bdbfeSandi *
234132bdbfeSandi * This is neither unique nor unfakable - still it adds some
235136ce040Sandi * security. Using the first part of the IP makes sure
236136ce040Sandi * proxy farms like AOLs are stil okay.
23715fae107Sandi *
23815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
23915fae107Sandi *
24015fae107Sandi * @return  string  a MD5 sum of various browser headers
241132bdbfeSandi */
242132bdbfeSandifunction auth_browseruid(){
243132bdbfeSandi  $uid  = '';
244132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
245132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
246132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
247132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
248136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
249132bdbfeSandi  return md5($uid);
250132bdbfeSandi}
251132bdbfeSandi
252132bdbfeSandi/**
253132bdbfeSandi * Creates a random key to encrypt the password in cookies
25415fae107Sandi *
25515fae107Sandi * This function tries to read the password for encrypting
25698407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
25715fae107Sandi * if no such file is found a random key is created and
25815fae107Sandi * and stored in this file.
25915fae107Sandi *
26015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
26115fae107Sandi *
26215fae107Sandi * @return  string
263132bdbfeSandi */
264132bdbfeSandifunction auth_cookiesalt(){
265132bdbfeSandi  global $conf;
26698407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
267132bdbfeSandi  $salt = io_readFile($file);
268132bdbfeSandi  if(empty($salt)){
269132bdbfeSandi    $salt = uniqid(rand(),true);
270132bdbfeSandi    io_saveFile($file,$salt);
271132bdbfeSandi  }
272132bdbfeSandi  return $salt;
273f3f0262cSandi}
274f3f0262cSandi
275f3f0262cSandi/**
276f3f0262cSandi * This clears all authenticationdata and thus log the user
277f3f0262cSandi * off
27815fae107Sandi *
27915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
280f3f0262cSandi */
281f3f0262cSandifunction auth_logoff(){
282f3f0262cSandi  global $conf;
283f3f0262cSandi  global $USERINFO;
2848b06d178Schris  global $INFO, $ID;
2855298a619SAndreas Gohr  global $auth;
28637065e65Sandi
287e9621d07SAndreas Gohr  // reopen session
288e9621d07SAndreas Gohr  @session_start();
289e9621d07SAndreas Gohr
290e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
291e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['user']);
292e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
293e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
294e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
295e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['info']);
296e16eccb7SGuy Brand  if(isset($_SESSION[DOKU_COOKIE]['bc']))
297e16eccb7SGuy Brand    unset($_SESSION[DOKU_COOKIE]['bc']);
29837065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
299f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
300132bdbfeSandi  $USERINFO=null; //FIXME
301f5c6743cSAndreas Gohr
302f5c6743cSAndreas Gohr  if (version_compare(PHP_VERSION, '5.2.0', '>')) {
303f5c6743cSAndreas Gohr    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,($conf['securecookie'] && is_ssl()),true);
304f5c6743cSAndreas Gohr  }else{
305f5c6743cSAndreas Gohr    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,($conf['securecookie'] && is_ssl()));
306f5c6743cSAndreas Gohr  }
3075298a619SAndreas Gohr
3085298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
3095298a619SAndreas Gohr    $auth->logOff();
3105298a619SAndreas Gohr  }
311e9621d07SAndreas Gohr
312e9621d07SAndreas Gohr  // close session again
313e9621d07SAndreas Gohr  session_write_close();
314f3f0262cSandi}
315f3f0262cSandi
316f3f0262cSandi/**
317f8cc712eSAndreas Gohr * Check if a user is a manager
318f8cc712eSAndreas Gohr *
319f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
320f8cc712eSAndreas Gohr * user.
321f8cc712eSAndreas Gohr *
322f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
323f8cc712eSAndreas Gohr *
324f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
325f8cc712eSAndreas Gohr * @see    auth_isadmin
326f8cc712eSAndreas Gohr * @param  string user      - Username
327f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
328f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
329f8cc712eSAndreas Gohr */
330f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
331f8cc712eSAndreas Gohr  global $conf;
332f8cc712eSAndreas Gohr  global $USERINFO;
333f8cc712eSAndreas Gohr
334f8cc712eSAndreas Gohr  if(!$conf['useacl']) return false;
335f8cc712eSAndreas Gohr  if(is_null($user))   $user   = $_SERVER['REMOTE_USER'];
33690583e9fSAndreas Gohr  if(is_null($groups)) $groups = (array) $USERINFO['grps'];
337f8cc712eSAndreas Gohr  $user   = auth_nameencode($user);
338f8cc712eSAndreas Gohr
339f8cc712eSAndreas Gohr  // check username against superuser and manager
3407651d633SGuy Brand  $superusers = explode(',', $conf['superuser']);
3417651d633SGuy Brand  $superusers = array_unique($superusers);
3427651d633SGuy Brand  $superusers = array_map('trim', $superusers);
3437651d633SGuy Brand  // prepare an array containing only true values for array_map call
3447651d633SGuy Brand  $alltrue = array_fill(0, count($superusers), true);
3457651d633SGuy Brand  $superusers = array_map('auth_nameencode', $superusers, $alltrue);
3467651d633SGuy Brand  if(in_array($user, $superusers)) return true;
3477651d633SGuy Brand
348f8cc712eSAndreas Gohr  if(!$adminonly){
3497651d633SGuy Brand    $managers = explode(',', $conf['manager']);
3507651d633SGuy Brand    $managers = array_unique($managers);
3517651d633SGuy Brand    $managers = array_map('trim', $managers);
3527651d633SGuy Brand    // prepare an array containing only true values for array_map call
3537651d633SGuy Brand    $alltrue = array_fill(0, count($managers), true);
3547651d633SGuy Brand    $managers = array_map('auth_nameencode', $managers, $alltrue);
3557651d633SGuy Brand    if(in_array($user, $managers)) return true;
356f8cc712eSAndreas Gohr  }
357f8cc712eSAndreas Gohr
35800ce12daSChris Smith  // check user's groups against superuser and manager
35900ce12daSChris Smith  if (!empty($groups)) {
36000ce12daSChris Smith
361f8cc712eSAndreas Gohr    //prepend groups with @ and nameencode
362f8cc712eSAndreas Gohr    $cnt = count($groups);
363f8cc712eSAndreas Gohr    for($i=0; $i<$cnt; $i++){
364f8cc712eSAndreas Gohr      $groups[$i] = '@'.auth_nameencode($groups[$i]);
365f8cc712eSAndreas Gohr    }
366f8cc712eSAndreas Gohr
367f8cc712eSAndreas Gohr    // check groups against superuser and manager
3687651d633SGuy Brand    foreach($superusers as $supu)
3697651d633SGuy Brand      if(in_array($supu, $groups)) return true;
370f8cc712eSAndreas Gohr    if(!$adminonly){
3717651d633SGuy Brand      foreach($managers as $mana)
3727651d633SGuy Brand        if(in_array($mana, $groups)) return true;
373f8cc712eSAndreas Gohr    }
37400ce12daSChris Smith  }
37500ce12daSChris Smith
376f8cc712eSAndreas Gohr  return false;
377f8cc712eSAndreas Gohr}
378f8cc712eSAndreas Gohr
379f8cc712eSAndreas Gohr/**
380f8cc712eSAndreas Gohr * Check if a user is admin
381f8cc712eSAndreas Gohr *
382f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
383f8cc712eSAndreas Gohr *
384f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
385f8cc712eSAndreas Gohr *
386f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
387f8cc712eSAndreas Gohr * @see auth_ismanager
388f8cc712eSAndreas Gohr */
389f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
390f8cc712eSAndreas Gohr  return auth_ismanager($user,$groups,true);
391f8cc712eSAndreas Gohr}
392f8cc712eSAndreas Gohr
393f8cc712eSAndreas Gohr/**
39415fae107Sandi * Convinience function for auth_aclcheck()
39515fae107Sandi *
39615fae107Sandi * This checks the permissions for the current user
39715fae107Sandi *
39815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
39915fae107Sandi *
40015fae107Sandi * @param  string  $id  page ID
40115fae107Sandi * @return int          permission level
402f3f0262cSandi */
403f3f0262cSandifunction auth_quickaclcheck($id){
404f3f0262cSandi  global $conf;
405f3f0262cSandi  global $USERINFO;
406f3f0262cSandi  # if no ACL is used always return upload rights
407f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
408f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
409f3f0262cSandi}
410f3f0262cSandi
411f3f0262cSandi/**
412f3f0262cSandi * Returns the maximum rights a user has for
413f3f0262cSandi * the given ID or its namespace
41415fae107Sandi *
41515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
41615fae107Sandi *
41715fae107Sandi * @param  string  $id     page ID
41815fae107Sandi * @param  string  $user   Username
41915fae107Sandi * @param  array   $groups Array of groups the user is in
42015fae107Sandi * @return int             permission level
421f3f0262cSandi */
422f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
423f3f0262cSandi  global $conf;
424f3f0262cSandi  global $AUTH_ACL;
425f3f0262cSandi
42685d03f68SAndreas Gohr  // if no ACL is used always return upload rights
427f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
428f3f0262cSandi
429074cf26bSandi  //make sure groups is an array
430074cf26bSandi  if(!is_array($groups)) $groups = array();
431074cf26bSandi
43285d03f68SAndreas Gohr  //if user is superuser or in superusergroup return 255 (acl_admin)
43385d03f68SAndreas Gohr  if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
43485d03f68SAndreas Gohr
43585d03f68SAndreas Gohr  $user = auth_nameencode($user);
43685d03f68SAndreas Gohr
4376c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
4382cd2db38Sandi  $cnt = count($groups);
4392cd2db38Sandi  for($i=0; $i<$cnt; $i++){
4406c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
44110a76f6fSfrank  }
44210a76f6fSfrank
443f3f0262cSandi  $ns    = getNS($id);
444f3f0262cSandi  $perm  = -1;
445f3f0262cSandi
44634aeb4afSAndreas Gohr  if($user || count($groups)){
447f3f0262cSandi    //add ALL group
448f3f0262cSandi    $groups[] = '@ALL';
449f3f0262cSandi    //add User
45034aeb4afSAndreas Gohr    if($user) $groups[] = $user;
451f3f0262cSandi    //build regexp
452f3f0262cSandi    $regexp   = join('|',$groups);
453f3f0262cSandi  }else{
454f3f0262cSandi    $regexp = '@ALL';
455f3f0262cSandi  }
456f3f0262cSandi
457f3f0262cSandi  //check exact match first
45842905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
459f3f0262cSandi  if(count($matches)){
460f3f0262cSandi    foreach($matches as $match){
461f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
462f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
4638ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
464f3f0262cSandi      if($acl[2] > $perm){
465f3f0262cSandi        $perm = $acl[2];
466f3f0262cSandi      }
467f3f0262cSandi    }
468f3f0262cSandi    if($perm > -1){
469f3f0262cSandi      //we had a match - return it
470f3f0262cSandi      return $perm;
471f3f0262cSandi    }
472f3f0262cSandi  }
473f3f0262cSandi
474f3f0262cSandi  //still here? do the namespace checks
475f3f0262cSandi  if($ns){
476f3f0262cSandi    $path = $ns.':\*';
477f3f0262cSandi  }else{
478f3f0262cSandi    $path = '\*'; //root document
479f3f0262cSandi  }
480f3f0262cSandi
481f3f0262cSandi  do{
482f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
483f3f0262cSandi    if(count($matches)){
484f3f0262cSandi      foreach($matches as $match){
485f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
486f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
4878ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
488f3f0262cSandi        if($acl[2] > $perm){
489f3f0262cSandi          $perm = $acl[2];
490f3f0262cSandi        }
491f3f0262cSandi      }
492f3f0262cSandi      //we had a match - return it
493f3f0262cSandi      return $perm;
494f3f0262cSandi    }
495f3f0262cSandi
496f3f0262cSandi    //get next higher namespace
497f3f0262cSandi    $ns   = getNS($ns);
498f3f0262cSandi
499f3f0262cSandi    if($path != '\*'){
500f3f0262cSandi      $path = $ns.':\*';
501f3f0262cSandi      if($path == ':\*') $path = '\*';
502f3f0262cSandi    }else{
503f3f0262cSandi      //we did this already
504f3f0262cSandi      //looks like there is something wrong with the ACL
505f3f0262cSandi      //break here
506d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
507d5ce66f6SAndreas Gohr      return AUTH_NONE;
508f3f0262cSandi    }
509f3f0262cSandi  }while(1); //this should never loop endless
51052a5af8dSandi
51152a5af8dSandi  //still here? return no permissions
51252a5af8dSandi  return AUTH_NONE;
513f3f0262cSandi}
514f3f0262cSandi
515f3f0262cSandi/**
5166c2bb100SAndreas Gohr * Encode ASCII special chars
5176c2bb100SAndreas Gohr *
5186c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5196c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5206c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5216c2bb100SAndreas Gohr * urlencoding!).
5226c2bb100SAndreas Gohr *
5236c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5246c2bb100SAndreas Gohr *
5256c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5266c2bb100SAndreas Gohr * @see rawurldecode()
5276c2bb100SAndreas Gohr */
528e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
529a424cd8eSchris  global $cache_authname;
530a424cd8eSchris  $cache =& $cache_authname;
53131784267SAndreas Gohr  $name  = (string) $name;
532a424cd8eSchris
533a424cd8eSchris  if (!isset($cache[$name][$skip_group])) {
534e838fc2eSAndreas Gohr    if($skip_group && $name{0} =='@'){
535a424cd8eSchris      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5361a9ae8e5SAndreas Gohr                                                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
537e838fc2eSAndreas Gohr    }else{
538a424cd8eSchris      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5391a9ae8e5SAndreas Gohr                                                "'%'.dechex(ord(substr('\\1',-1)))",$name);
540e838fc2eSAndreas Gohr    }
5416c2bb100SAndreas Gohr  }
5426c2bb100SAndreas Gohr
543a424cd8eSchris  return $cache[$name][$skip_group];
544a424cd8eSchris}
545a424cd8eSchris
5466c2bb100SAndreas Gohr/**
547f3f0262cSandi * Create a pronouncable password
548f3f0262cSandi *
54915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
55015fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
55115fae107Sandi *
55215fae107Sandi * @return string  pronouncable password
553f3f0262cSandi */
554f3f0262cSandifunction auth_pwgen(){
555f3f0262cSandi  $pw = '';
556f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
557f3f0262cSandi  $v  = 'aeiou';              //vowels
558f3f0262cSandi  $a  = $c.$v;                //both
559f3f0262cSandi
560f3f0262cSandi  //use two syllables...
561f3f0262cSandi  for($i=0;$i < 2; $i++){
562f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
563f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
564f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
565f3f0262cSandi  }
566f3f0262cSandi  //... and add a nice number
567f3f0262cSandi  $pw .= rand(10,99);
568f3f0262cSandi
569f3f0262cSandi  return $pw;
570f3f0262cSandi}
571f3f0262cSandi
572f3f0262cSandi/**
573f3f0262cSandi * Sends a password to the given user
574f3f0262cSandi *
57515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
57615fae107Sandi *
57715fae107Sandi * @return bool  true on success
578f3f0262cSandi */
579f3f0262cSandifunction auth_sendPassword($user,$password){
580f3f0262cSandi  global $conf;
581f3f0262cSandi  global $lang;
582cd52f92dSchris  global $auth;
583cd52f92dSchris
584f3f0262cSandi  $hdrs  = '';
585cd52f92dSchris  $userinfo = $auth->getUserData($user);
586f3f0262cSandi
58787ddda95Sandi  if(!$userinfo['mail']) return false;
588f3f0262cSandi
589f3f0262cSandi  $text = rawLocale('password');
590ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
59187ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
592f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
593f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
594f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
595f3f0262cSandi
59644f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
59744f669e9Sandi                   $lang['regpwmail'],
59844f669e9Sandi                   $text,
59944f669e9Sandi                   $conf['mailfrom']);
600f3f0262cSandi}
601f3f0262cSandi
602f3f0262cSandi/**
60315fae107Sandi * Register a new user
604f3f0262cSandi *
60515fae107Sandi * This registers a new user - Data is read directly from $_POST
60615fae107Sandi *
60715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
60815fae107Sandi *
60915fae107Sandi * @return bool  true on success, false on any error
610f3f0262cSandi */
611f3f0262cSandifunction register(){
612f3f0262cSandi  global $lang;
613eb5d07e4Sjan  global $conf;
614cd52f92dSchris  global $auth;
615f3f0262cSandi
616f3f0262cSandi  if(!$_POST['save']) return false;
61782fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
618640145a5Sandi
619f3f0262cSandi  //clean username
620f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
621f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
622f3f0262cSandi  //clean fullname and email
62354f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
62454f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
625f3f0262cSandi
626f3f0262cSandi  if( empty($_POST['login']) ||
627f3f0262cSandi      empty($_POST['fullname']) ||
628f3f0262cSandi      empty($_POST['email']) ){
629f3f0262cSandi    msg($lang['regmissing'],-1);
630f3f0262cSandi    return false;
631f3f0262cSandi  }
632f3f0262cSandi
633cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
634cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
635cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
636cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
637bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
638cab2716aSmatthias.grimm    return false;
639cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
640bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
641cab2716aSmatthias.grimm    return false;
642cab2716aSmatthias.grimm  } else {
643cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
644cab2716aSmatthias.grimm  }
645cab2716aSmatthias.grimm
646f3f0262cSandi  //check mail
64744f669e9Sandi  if(!mail_isvalid($_POST['email'])){
648f3f0262cSandi    msg($lang['regbadmail'],-1);
649f3f0262cSandi    return false;
650f3f0262cSandi  }
651f3f0262cSandi
652f3f0262cSandi  //okay try to create the user
6537d3c8d42SGabriel Birke  if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
654f3f0262cSandi    msg($lang['reguexists'],-1);
655f3f0262cSandi    return false;
656f3f0262cSandi  }
657f3f0262cSandi
65802a498e7Schris  // create substitutions for use in notification email
65902a498e7Schris  $substitutions = array(
66002a498e7Schris    'NEWUSER' => $_POST['login'],
66102a498e7Schris    'NEWNAME' => $_POST['fullname'],
66202a498e7Schris    'NEWEMAIL' => $_POST['email'],
66302a498e7Schris  );
66402a498e7Schris
665cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
666cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
66702a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
668cab2716aSmatthias.grimm    return true;
669cab2716aSmatthias.grimm  }
670cab2716aSmatthias.grimm
671cab2716aSmatthias.grimm  // autogenerated password? then send him the password
672f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
673f3f0262cSandi    msg($lang['regsuccess'],1);
67402a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
675f3f0262cSandi    return true;
676f3f0262cSandi  }else{
677f3f0262cSandi    msg($lang['regmailfail'],-1);
678f3f0262cSandi    return false;
679f3f0262cSandi  }
680f3f0262cSandi}
681f3f0262cSandi
68210a76f6fSfrank/**
6838b06d178Schris * Update user profile
6848b06d178Schris *
6858b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
6868b06d178Schris */
6878b06d178Schrisfunction updateprofile() {
6888b06d178Schris  global $conf;
6898b06d178Schris  global $INFO;
6908b06d178Schris  global $lang;
691cd52f92dSchris  global $auth;
6928b06d178Schris
693bb4866bdSchris  if(empty($_POST['save'])) return false;
6941b2a85e8SAndreas Gohr  if(!checkSecurityToken()) return false;
6958b06d178Schris
69682fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
69782fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
6988b06d178Schris    msg($lang['profna'],-1);
6998b06d178Schris    return false;
7008b06d178Schris  }
7018b06d178Schris
7028b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
7038b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
7048b06d178Schris    return false;
7058b06d178Schris  }
7068b06d178Schris
7078b06d178Schris  //clean fullname and email
70854f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
70954f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
7108b06d178Schris
7118b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
7128b06d178Schris    msg($lang['profnoempty'],-1);
7138b06d178Schris    return false;
7148b06d178Schris  }
7158b06d178Schris
7168b06d178Schris  if (!mail_isvalid($_POST['email'])){
7178b06d178Schris    msg($lang['regbadmail'],-1);
7188b06d178Schris    return false;
7198b06d178Schris  }
7208b06d178Schris
7214c21b7eeSAndreas Gohr  if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7224c21b7eeSAndreas Gohr  if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
723cf626a62SAndreas Gohr  if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7244c21b7eeSAndreas Gohr
7258b06d178Schris
7268b06d178Schris  if (!count($changes)) {
7278b06d178Schris    msg($lang['profnochange'], -1);
7288b06d178Schris    return false;
7298b06d178Schris  }
7308b06d178Schris
7318b06d178Schris  if ($conf['profileconfirm']) {
732df466c7aSAndreas Gohr    if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
7338b06d178Schris      msg($lang['badlogin'],-1);
7348b06d178Schris      return false;
7358b06d178Schris    }
7368b06d178Schris  }
7378b06d178Schris
7387d3c8d42SGabriel Birke  return $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes));
7398b06d178Schris}
7408b06d178Schris
7418b06d178Schris/**
7428b06d178Schris * Send a  new password
7438b06d178Schris *
7441d5856cfSAndreas Gohr * This function handles both phases of the password reset:
7451d5856cfSAndreas Gohr *
7461d5856cfSAndreas Gohr *   - handling the first request of password reset
7471d5856cfSAndreas Gohr *   - validating the password reset auth token
7481d5856cfSAndreas Gohr *
7498b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
7508b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
7511d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7528b06d178Schris *
7538b06d178Schris * @return bool true on success, false on any error
7548b06d178Schris*/
7558b06d178Schrisfunction act_resendpwd(){
7568b06d178Schris    global $lang;
7578b06d178Schris    global $conf;
758cd52f92dSchris    global $auth;
7598b06d178Schris
760409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
7618b06d178Schris
76282fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
76382fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
7648b06d178Schris        msg($lang['resendna'],-1);
7658b06d178Schris        return false;
7668b06d178Schris    }
7678b06d178Schris
7681d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
7698b06d178Schris
7701d5856cfSAndreas Gohr    if($token){
7711d5856cfSAndreas Gohr        // we're in token phase
7721d5856cfSAndreas Gohr
7731d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
7741d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
7751d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
7761d5856cfSAndreas Gohr            return false;
7771d5856cfSAndreas Gohr        }
7781d5856cfSAndreas Gohr        $user = io_readfile($tfile);
7791d5856cfSAndreas Gohr        @unlink($tfile);
780cd52f92dSchris        $userinfo = $auth->getUserData($user);
7818b06d178Schris        if(!$userinfo['mail']) {
7828b06d178Schris            msg($lang['resendpwdnouser'], -1);
7838b06d178Schris            return false;
7848b06d178Schris        }
7858b06d178Schris
7868b06d178Schris        $pass = auth_pwgen();
7877d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
7888b06d178Schris            msg('error modifying user data',-1);
7898b06d178Schris            return false;
7908b06d178Schris        }
7918b06d178Schris
7928b06d178Schris        if (auth_sendPassword($user,$pass)) {
7938b06d178Schris            msg($lang['resendpwdsuccess'],1);
7948b06d178Schris        } else {
7958b06d178Schris            msg($lang['regmailfail'],-1);
7968b06d178Schris        }
7978b06d178Schris        return true;
7981d5856cfSAndreas Gohr
7991d5856cfSAndreas Gohr    } else {
8001d5856cfSAndreas Gohr        // we're in request phase
8011d5856cfSAndreas Gohr
8021d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8031d5856cfSAndreas Gohr
8041d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8051d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8061d5856cfSAndreas Gohr            return false;
8071d5856cfSAndreas Gohr        } else {
80816470b1dSchris            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
80916470b1dSchris            $user = cleanID($_POST['login']);
8101d5856cfSAndreas Gohr        }
8111d5856cfSAndreas Gohr
8121d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8131d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8141d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8151d5856cfSAndreas Gohr            return false;
8161d5856cfSAndreas Gohr        }
8171d5856cfSAndreas Gohr
8181d5856cfSAndreas Gohr        // generate auth token
8191d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8201d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8211d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8221d5856cfSAndreas Gohr
8231d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
8241d5856cfSAndreas Gohr
8251d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
8261d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
8271d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
8281d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
8291d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
8301d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
8311d5856cfSAndreas Gohr
8321d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
8331d5856cfSAndreas Gohr                     $lang['regpwmail'],
8341d5856cfSAndreas Gohr                     $text,
8351d5856cfSAndreas Gohr                     $conf['mailfrom'])){
8361d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
8371d5856cfSAndreas Gohr        }else{
8381d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
8391d5856cfSAndreas Gohr        }
8401d5856cfSAndreas Gohr        return true;
8411d5856cfSAndreas Gohr    }
8421d5856cfSAndreas Gohr
8431d5856cfSAndreas Gohr    return false; // never reached
8448b06d178Schris}
8458b06d178Schris
8468b06d178Schris/**
84710a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
84810a76f6fSfrank *
84910a76f6fSfrank * May not be completly RFC conform!
85010a76f6fSfrank *
85110a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
85210a76f6fSfrank *
85310a76f6fSfrank * @param   string $email the address to check
85410a76f6fSfrank * @return  bool          true if address is valid
85510a76f6fSfrank */
85610a76f6fSfrankfunction isvalidemail($email){
85710a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
85810a76f6fSfrank}
85910a76f6fSfrank
860b0855b11Sandi/**
861b0855b11Sandi * Encrypts a password using the given method and salt
862b0855b11Sandi *
863b0855b11Sandi * If the selected method needs a salt and none was given, a random one
864b0855b11Sandi * is chosen.
865b0855b11Sandi *
866b0855b11Sandi * The following methods are understood:
867b0855b11Sandi *
868b0855b11Sandi *   smd5  - Salted MD5 hashing
869577c7cdaSAndreas Gohr *   apr1  - Apache salted MD5 hashing
870b0855b11Sandi *   md5   - Simple MD5 hashing
871b0855b11Sandi *   sha1  - SHA1 hashing
872b0855b11Sandi *   ssha  - Salted SHA1 hashing
873d7be6245Sandi *   crypt - Unix crypt
874d7be6245Sandi *   mysql - MySQL password (old method)
875d7be6245Sandi *   my411 - MySQL 4.1.1 password
876b0855b11Sandi *
877b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
878b0855b11Sandi * @return  string  The crypted password
879b0855b11Sandi */
880577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
881b0855b11Sandi    global $conf;
882b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
88310a76f6fSfrank
884b0855b11Sandi    //prepare a salt
885577c7cdaSAndreas Gohr    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
886b0855b11Sandi
887b0855b11Sandi    switch(strtolower($method)){
888b0855b11Sandi        case 'smd5':
889577c7cdaSAndreas Gohr            if(defined('CRYPT_MD5')) return crypt($clear,'$1$'.substr($salt,0,8).'$');
890577c7cdaSAndreas Gohr            // when crypt can't handle SMD5, falls through to pure PHP implementation
891577c7cdaSAndreas Gohr            $magic = '1';
892577c7cdaSAndreas Gohr        case 'apr1':
893577c7cdaSAndreas Gohr            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
894577c7cdaSAndreas Gohr            if(!$magic) $magic = 'apr1';
895577c7cdaSAndreas Gohr            $salt = substr($salt,0,8);
896577c7cdaSAndreas Gohr            $len = strlen($clear);
897577c7cdaSAndreas Gohr            $text = $clear.'$'.$magic.'$'.$salt;
898577c7cdaSAndreas Gohr            $bin = pack("H32", md5($clear.$salt.$clear));
899577c7cdaSAndreas Gohr            for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
900577c7cdaSAndreas Gohr            for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $clear{0}; }
901577c7cdaSAndreas Gohr            $bin = pack("H32", md5($text));
902577c7cdaSAndreas Gohr            for($i = 0; $i < 1000; $i++) {
903577c7cdaSAndreas Gohr                $new = ($i & 1) ? $clear : $bin;
904577c7cdaSAndreas Gohr                if ($i % 3) $new .= $salt;
905577c7cdaSAndreas Gohr                if ($i % 7) $new .= $clear;
906577c7cdaSAndreas Gohr                $new .= ($i & 1) ? $bin : $clear;
907577c7cdaSAndreas Gohr                $bin = pack("H32", md5($new));
908577c7cdaSAndreas Gohr            }
909577c7cdaSAndreas Gohr            $tmp = '';
910577c7cdaSAndreas Gohr            for ($i = 0; $i < 5; $i++) {
911577c7cdaSAndreas Gohr                $k = $i + 6;
912577c7cdaSAndreas Gohr                $j = $i + 12;
913577c7cdaSAndreas Gohr                if ($j == 16) $j = 5;
914577c7cdaSAndreas Gohr                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
915577c7cdaSAndreas Gohr            }
916577c7cdaSAndreas Gohr            $tmp = chr(0).chr(0).$bin[11].$tmp;
917577c7cdaSAndreas Gohr            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
918577c7cdaSAndreas Gohr                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
919577c7cdaSAndreas Gohr                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
920577c7cdaSAndreas Gohr            return '$'.$magic.'$'.$salt.'$'.$tmp;
921b0855b11Sandi        case 'md5':
922b0855b11Sandi            return md5($clear);
923b0855b11Sandi        case 'sha1':
924b0855b11Sandi            return sha1($clear);
925b0855b11Sandi        case 'ssha':
926b0855b11Sandi            $salt=substr($salt,0,4);
927d6e54e02Smatthiasgrimm            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
928b0855b11Sandi        case 'crypt':
929b0855b11Sandi            return crypt($clear,substr($salt,0,2));
930d7be6245Sandi        case 'mysql':
931d7be6245Sandi            //from http://www.php.net/mysql comment by <soren at byu dot edu>
932d7be6245Sandi            $nr=0x50305735;
933d7be6245Sandi            $nr2=0x12345671;
934d7be6245Sandi            $add=7;
935d7be6245Sandi            $charArr = preg_split("//", $clear);
936d7be6245Sandi            foreach ($charArr as $char) {
937d7be6245Sandi                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
938d7be6245Sandi                $charVal = ord($char);
939d7be6245Sandi                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
940d7be6245Sandi                $nr2 += ($nr2 << 8) ^ $nr;
941d7be6245Sandi                $add += $charVal;
942d7be6245Sandi            }
943d7be6245Sandi            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
944d7be6245Sandi        case 'my411':
945d7be6245Sandi            return '*'.sha1(pack("H*", sha1($clear)));
946b0855b11Sandi        default:
947b0855b11Sandi            msg("Unsupported crypt method $method",-1);
948b0855b11Sandi    }
949b0855b11Sandi}
950b0855b11Sandi
951b0855b11Sandi/**
952b0855b11Sandi * Verifies a cleartext password against a crypted hash
953b0855b11Sandi *
954b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
955b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
956b0855b11Sandi * match true is is returned else false
957b0855b11Sandi *
958b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
959b0855b11Sandi * @return  bool
960b0855b11Sandi */
961b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
962b0855b11Sandi    $method='';
963b0855b11Sandi    $salt='';
964b0855b11Sandi
965b0855b11Sandi    //determine the used method and salt
966d7be6245Sandi    $len = strlen($crypt);
967577c7cdaSAndreas Gohr    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
968b0855b11Sandi        $method = 'smd5';
969577c7cdaSAndreas Gohr        $salt   = $m[1];
970577c7cdaSAndreas Gohr    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
971577c7cdaSAndreas Gohr        $method = 'apr1';
972577c7cdaSAndreas Gohr        $salt   = $m[1];
973b0855b11Sandi    }elseif(substr($crypt,0,6) == '{SSHA}'){
974b0855b11Sandi        $method = 'ssha';
975b0855b11Sandi        $salt   = substr(base64_decode(substr($crypt, 6)),20);
976d7be6245Sandi    }elseif($len == 32){
977b0855b11Sandi        $method = 'md5';
978d7be6245Sandi    }elseif($len == 40){
979b0855b11Sandi        $method = 'sha1';
980d7be6245Sandi    }elseif($len == 16){
981d7be6245Sandi        $method = 'mysql';
982d7be6245Sandi    }elseif($len == 41 && $crypt[0] == '*'){
983d7be6245Sandi        $method = 'my411';
984b0855b11Sandi    }else{
985b0855b11Sandi        $method = 'crypt';
986b0855b11Sandi        $salt   = substr($crypt,0,2);
987b0855b11Sandi    }
988b0855b11Sandi
989b0855b11Sandi    //crypt and compare
990b0855b11Sandi    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
991b0855b11Sandi        return true;
992b0855b11Sandi    }
993b0855b11Sandi    return false;
994b0855b11Sandi}
995340756e4Sandi
996340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
997