xref: /dokuwiki/inc/auth.php (revision d48698469a572f77eb556c1723e84bccc5d4393d)
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
12fa8adffeSAndreas Gohr  if(!defined('DOKU_INC')) die('meh.');
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;
6217f89d7eSMichael Klier      if (!$conf['rememberme']) $_REQUEST['r'] = false;
63bbbd6568SAndreas Gohr
64528ddc7cSAndreas Gohr      // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
6506156f3cSAndreas Gohr      if(isset($_SERVER['HTTP_AUTHORIZATION'])){
66528ddc7cSAndreas Gohr        list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
67528ddc7cSAndreas Gohr          explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
68528ddc7cSAndreas Gohr      }
69528ddc7cSAndreas Gohr
701e8c9c90SAndreas Gohr      // if no credentials were given try to use HTTP auth (for SSO)
714a26ad85Schris      if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
721e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
731e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
74b2c0d874SGina Haeussge        $_REQUEST['http_credentials'] = true;
751e8c9c90SAndreas Gohr      }
761e8c9c90SAndreas Gohr
77f13fa892SAndreas Gohr      if($_REQUEST['authtok']){
78f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
79f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
80f13fa892SAndreas Gohr      }elseif(!is_null($auth) && $auth->canDo('external')){
81f13fa892SAndreas Gohr        // external trust mechanism in place
82f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
83f5cb575dSAndreas Gohr      }else{
84b2c0d874SGina Haeussge        auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r'],$_REQUEST['http_credentials']);
85f5cb575dSAndreas Gohr      }
861ec50243SAndreas Gohr    }
87f5cb575dSAndreas Gohr
8815fae107Sandi    //load ACL into a global array
8988e6a4f2SAndreas Gohr    global $AUTH_ACL;
90e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
91e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
92f8cc3354SGuy Brand      if(isset($_SERVER['REMOTE_USER'])){
935d87b2ccSAndreas Gohr        $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
945d87b2ccSAndreas Gohr        $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
95a8fe108bSGuy Brand      }
9611799630Sandi    }else{
9711799630Sandi      $AUTH_ACL = array();
9811799630Sandi    }
99f3f0262cSandi  }
100f3f0262cSandi
101f3f0262cSandi/**
102f3f0262cSandi * This tries to login the user based on the sent auth credentials
103f3f0262cSandi *
104f3f0262cSandi * The authentication works like this: if a username was given
10515fae107Sandi * a new login is assumed and user/password are checked. If they
10615fae107Sandi * are correct the password is encrypted with blowfish and stored
10715fae107Sandi * together with the username in a cookie - the same info is stored
10815fae107Sandi * in the session, too. Additonally a browserID is stored in the
10915fae107Sandi * session.
11015fae107Sandi *
11115fae107Sandi * If no username was given the cookie is checked: if the username,
11215fae107Sandi * crypted password and browserID match between session and cookie
11315fae107Sandi * no further testing is done and the user is accepted
11415fae107Sandi *
11515fae107Sandi * If a cookie was found but no session info was availabe the
116136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
11715fae107Sandi * together with username rechecked by calling this function again.
118f3f0262cSandi *
119f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
120f3f0262cSandi * are set.
12115fae107Sandi *
12215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
12315fae107Sandi *
12415fae107Sandi * @param   string  $user    Username
12515fae107Sandi * @param   string  $pass    Cleartext Password
12615fae107Sandi * @param   bool    $sticky  Cookie should not expire
127f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
12815fae107Sandi * @return  bool             true on successful auth
129f3f0262cSandi*/
130f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
131f3f0262cSandi  global $USERINFO;
132f3f0262cSandi  global $conf;
133f3f0262cSandi  global $lang;
134cd52f92dSchris  global $auth;
135132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
136f3f0262cSandi
137bbbd6568SAndreas Gohr  if(!empty($user)){
138132bdbfeSandi    //usual login
139cd52f92dSchris    if ($auth->checkPass($user,$pass)){
140132bdbfeSandi      // make logininfo globally available
141f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
142a0b5b007SChris Smith      auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
143132bdbfeSandi      return true;
144f3f0262cSandi    }else{
145f3f0262cSandi      //invalid credentials - log off
146f112c2faSAndreas Gohr      if(!$silent) msg($lang['badlogin'],-1);
147f3f0262cSandi      auth_logoff();
148132bdbfeSandi      return false;
149f3f0262cSandi    }
150f3f0262cSandi  }else{
151132bdbfeSandi    // read cookie information
152e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
153132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
154132bdbfeSandi    // get session info
155e71ce681SAndreas Gohr    $session = $_SESSION[DOKU_COOKIE]['auth'];
156132bdbfeSandi    if($user && $pass){
157132bdbfeSandi      // we got a cookie - see if we can trust it
158132bdbfeSandi      if(isset($session) &&
1597172dbc0SAndreas Gohr        $auth->useSessionCache($user) &&
1604c989037SChris Smith        ($session['time'] >= time()-$conf['auth_security_timeout']) &&
161132bdbfeSandi        ($session['user'] == $user) &&
162132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
163132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
164132bdbfeSandi        // he has session, cookie and browser right - let him in
165132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
166132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
167132bdbfeSandi        return true;
168132bdbfeSandi      }
169f112c2faSAndreas Gohr      // no we don't trust it yet - recheck pass but silent
170132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
171f112c2faSAndreas Gohr      return auth_login($user,$pass,$sticky,true);
172132bdbfeSandi    }
173132bdbfeSandi  }
174f3f0262cSandi  //just to be sure
175883179a4SAndreas Gohr  auth_logoff(true);
176132bdbfeSandi  return false;
177f3f0262cSandi}
178132bdbfeSandi
179132bdbfeSandi/**
180f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
181f13fa892SAndreas Gohr *
182f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
183f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
184f13fa892SAndreas Gohr *
185f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
186f13fa892SAndreas Gohr * @param  string $token The authentication token
187f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
188f13fa892SAndreas Gohr */
189f13fa892SAndreas Gohrfunction auth_validateToken($token){
190f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
191f13fa892SAndreas Gohr        // bad token
192f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
193f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
194f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
195f13fa892SAndreas Gohr        exit;
196f13fa892SAndreas Gohr    }
197f13fa892SAndreas Gohr    // still here? trust the session data
198f13fa892SAndreas Gohr    global $USERINFO;
199f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
200f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
201f13fa892SAndreas Gohr    return true;
202f13fa892SAndreas Gohr}
203f13fa892SAndreas Gohr
204f13fa892SAndreas Gohr/**
205f13fa892SAndreas Gohr * Create an auth token and store it in the session
206f13fa892SAndreas Gohr *
207f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
208f13fa892SAndreas Gohr *
209f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
210f13fa892SAndreas Gohr * @return string The auth token
211f13fa892SAndreas Gohr */
212f13fa892SAndreas Gohrfunction auth_createToken(){
213f13fa892SAndreas Gohr    $token = md5(mt_rand());
21409c2d803SAndreas Gohr    @session_start(); // reopen the session if needed
215f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
21609c2d803SAndreas Gohr    session_write_close();
217f13fa892SAndreas Gohr    return $token;
218f13fa892SAndreas Gohr}
219f13fa892SAndreas Gohr
220f13fa892SAndreas Gohr/**
221136ce040Sandi * Builds a pseudo UID from browser and IP data
222132bdbfeSandi *
223132bdbfeSandi * This is neither unique nor unfakable - still it adds some
224136ce040Sandi * security. Using the first part of the IP makes sure
225136ce040Sandi * proxy farms like AOLs are stil okay.
22615fae107Sandi *
22715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
22815fae107Sandi *
22915fae107Sandi * @return  string  a MD5 sum of various browser headers
230132bdbfeSandi */
231132bdbfeSandifunction auth_browseruid(){
232132bdbfeSandi  $uid  = '';
233132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
234132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
235132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
236132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
237136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
238132bdbfeSandi  return md5($uid);
239132bdbfeSandi}
240132bdbfeSandi
241132bdbfeSandi/**
242132bdbfeSandi * Creates a random key to encrypt the password in cookies
24315fae107Sandi *
24415fae107Sandi * This function tries to read the password for encrypting
24598407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
24615fae107Sandi * if no such file is found a random key is created and
24715fae107Sandi * and stored in this file.
24815fae107Sandi *
24915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25015fae107Sandi *
25115fae107Sandi * @return  string
252132bdbfeSandi */
253132bdbfeSandifunction auth_cookiesalt(){
254132bdbfeSandi  global $conf;
25598407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
256132bdbfeSandi  $salt = io_readFile($file);
257132bdbfeSandi  if(empty($salt)){
258132bdbfeSandi    $salt = uniqid(rand(),true);
259132bdbfeSandi    io_saveFile($file,$salt);
260132bdbfeSandi  }
261132bdbfeSandi  return $salt;
262f3f0262cSandi}
263f3f0262cSandi
264f3f0262cSandi/**
265883179a4SAndreas Gohr * Log out the current user
266883179a4SAndreas Gohr *
267f3f0262cSandi * This clears all authentication data and thus log the user
268883179a4SAndreas Gohr * off. It also clears session data.
26915fae107Sandi *
27015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
271883179a4SAndreas Gohr * @param bool $keepbc - when true, the breadcrumb data is not cleared
272f3f0262cSandi */
273883179a4SAndreas Gohrfunction auth_logoff($keepbc=false){
274f3f0262cSandi  global $conf;
275f3f0262cSandi  global $USERINFO;
2768b06d178Schris  global $INFO, $ID;
2775298a619SAndreas Gohr  global $auth;
27837065e65Sandi
279*d4869846SAndreas Gohr  // make sure the session is writable (it usually is)
280e9621d07SAndreas Gohr  @session_start();
281e9621d07SAndreas Gohr
282e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
283e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['user']);
284e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
285e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
286e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
287e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['info']);
288883179a4SAndreas Gohr  if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
289e16eccb7SGuy Brand    unset($_SESSION[DOKU_COOKIE]['bc']);
29037065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
291f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
292132bdbfeSandi  $USERINFO=null; //FIXME
293f5c6743cSAndreas Gohr
294f5c6743cSAndreas Gohr  if (version_compare(PHP_VERSION, '5.2.0', '>')) {
29585c6f7d0SAndreas Gohr    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
296f5c6743cSAndreas Gohr  }else{
29785c6f7d0SAndreas Gohr    setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
298f5c6743cSAndreas Gohr  }
2995298a619SAndreas Gohr
3005298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
3015298a619SAndreas Gohr    $auth->logOff();
3025298a619SAndreas Gohr  }
303f3f0262cSandi}
304f3f0262cSandi
305f3f0262cSandi/**
306f8cc712eSAndreas Gohr * Check if a user is a manager
307f8cc712eSAndreas Gohr *
308f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
309f8cc712eSAndreas Gohr * user.
310f8cc712eSAndreas Gohr *
311f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
312f8cc712eSAndreas Gohr *
313f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
314f8cc712eSAndreas Gohr * @see    auth_isadmin
315f8cc712eSAndreas Gohr * @param  string user      - Username
316f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
317f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
318f8cc712eSAndreas Gohr */
319f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
320f8cc712eSAndreas Gohr  global $conf;
321f8cc712eSAndreas Gohr  global $USERINFO;
322f8cc712eSAndreas Gohr
323f8cc712eSAndreas Gohr  if(!$conf['useacl']) return false;
324f8cc712eSAndreas Gohr  if(is_null($user))   $user   = $_SERVER['REMOTE_USER'];
32590583e9fSAndreas Gohr  if(is_null($groups)) $groups = (array) $USERINFO['grps'];
326f8cc712eSAndreas Gohr  $user   = auth_nameencode($user);
327f8cc712eSAndreas Gohr
328f8cc712eSAndreas Gohr  // check username against superuser and manager
3297651d633SGuy Brand  $superusers = explode(',', $conf['superuser']);
3307651d633SGuy Brand  $superusers = array_unique($superusers);
3317651d633SGuy Brand  $superusers = array_map('trim', $superusers);
3327651d633SGuy Brand  // prepare an array containing only true values for array_map call
3337651d633SGuy Brand  $alltrue = array_fill(0, count($superusers), true);
3347651d633SGuy Brand  $superusers = array_map('auth_nameencode', $superusers, $alltrue);
3357651d633SGuy Brand  if(in_array($user, $superusers)) return true;
3367651d633SGuy Brand
337f8cc712eSAndreas Gohr  if(!$adminonly){
3387651d633SGuy Brand    $managers = explode(',', $conf['manager']);
3397651d633SGuy Brand    $managers = array_unique($managers);
3407651d633SGuy Brand    $managers = array_map('trim', $managers);
3417651d633SGuy Brand    // prepare an array containing only true values for array_map call
3427651d633SGuy Brand    $alltrue = array_fill(0, count($managers), true);
3437651d633SGuy Brand    $managers = array_map('auth_nameencode', $managers, $alltrue);
3447651d633SGuy Brand    if(in_array($user, $managers)) return true;
345f8cc712eSAndreas Gohr  }
346f8cc712eSAndreas Gohr
34700ce12daSChris Smith  // check user's groups against superuser and manager
34800ce12daSChris Smith  if (!empty($groups)) {
34900ce12daSChris Smith
350f8cc712eSAndreas Gohr    //prepend groups with @ and nameencode
351f8cc712eSAndreas Gohr    $cnt = count($groups);
352f8cc712eSAndreas Gohr    for($i=0; $i<$cnt; $i++){
353f8cc712eSAndreas Gohr      $groups[$i] = '@'.auth_nameencode($groups[$i]);
354f8cc712eSAndreas Gohr    }
355f8cc712eSAndreas Gohr
356f8cc712eSAndreas Gohr    // check groups against superuser and manager
3577651d633SGuy Brand    foreach($superusers as $supu)
3587651d633SGuy Brand      if(in_array($supu, $groups)) return true;
359f8cc712eSAndreas Gohr    if(!$adminonly){
3607651d633SGuy Brand      foreach($managers as $mana)
3617651d633SGuy Brand        if(in_array($mana, $groups)) return true;
362f8cc712eSAndreas Gohr    }
36300ce12daSChris Smith  }
36400ce12daSChris Smith
365f8cc712eSAndreas Gohr  return false;
366f8cc712eSAndreas Gohr}
367f8cc712eSAndreas Gohr
368f8cc712eSAndreas Gohr/**
369f8cc712eSAndreas Gohr * Check if a user is admin
370f8cc712eSAndreas Gohr *
371f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
372f8cc712eSAndreas Gohr *
373f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
374f8cc712eSAndreas Gohr *
375f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
376f8cc712eSAndreas Gohr * @see auth_ismanager
377f8cc712eSAndreas Gohr */
378f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
379f8cc712eSAndreas Gohr  return auth_ismanager($user,$groups,true);
380f8cc712eSAndreas Gohr}
381f8cc712eSAndreas Gohr
382f8cc712eSAndreas Gohr/**
38315fae107Sandi * Convinience function for auth_aclcheck()
38415fae107Sandi *
38515fae107Sandi * This checks the permissions for the current user
38615fae107Sandi *
38715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
38815fae107Sandi *
38915fae107Sandi * @param  string  $id  page ID
39015fae107Sandi * @return int          permission level
391f3f0262cSandi */
392f3f0262cSandifunction auth_quickaclcheck($id){
393f3f0262cSandi  global $conf;
394f3f0262cSandi  global $USERINFO;
395f3f0262cSandi  # if no ACL is used always return upload rights
396f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
397f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
398f3f0262cSandi}
399f3f0262cSandi
400f3f0262cSandi/**
401f3f0262cSandi * Returns the maximum rights a user has for
402f3f0262cSandi * the given ID or its namespace
40315fae107Sandi *
40415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
40515fae107Sandi *
40615fae107Sandi * @param  string  $id     page ID
40715fae107Sandi * @param  string  $user   Username
40815fae107Sandi * @param  array   $groups Array of groups the user is in
40915fae107Sandi * @return int             permission level
410f3f0262cSandi */
411f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
412f3f0262cSandi  global $conf;
413f3f0262cSandi  global $AUTH_ACL;
414f3f0262cSandi
41585d03f68SAndreas Gohr  // if no ACL is used always return upload rights
416f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
417f3f0262cSandi
418074cf26bSandi  //make sure groups is an array
419074cf26bSandi  if(!is_array($groups)) $groups = array();
420074cf26bSandi
42185d03f68SAndreas Gohr  //if user is superuser or in superusergroup return 255 (acl_admin)
42285d03f68SAndreas Gohr  if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
42385d03f68SAndreas Gohr
42485d03f68SAndreas Gohr  $user = auth_nameencode($user);
42585d03f68SAndreas Gohr
4266c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
4272cd2db38Sandi  $cnt = count($groups);
4282cd2db38Sandi  for($i=0; $i<$cnt; $i++){
4296c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
43010a76f6fSfrank  }
43110a76f6fSfrank
432f3f0262cSandi  $ns    = getNS($id);
433f3f0262cSandi  $perm  = -1;
434f3f0262cSandi
43534aeb4afSAndreas Gohr  if($user || count($groups)){
436f3f0262cSandi    //add ALL group
437f3f0262cSandi    $groups[] = '@ALL';
438f3f0262cSandi    //add User
43934aeb4afSAndreas Gohr    if($user) $groups[] = $user;
440f3f0262cSandi    //build regexp
441f3f0262cSandi    $regexp   = join('|',$groups);
442f3f0262cSandi  }else{
443f3f0262cSandi    $regexp = '@ALL';
444f3f0262cSandi  }
445f3f0262cSandi
446f3f0262cSandi  //check exact match first
44742905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
448f3f0262cSandi  if(count($matches)){
449f3f0262cSandi    foreach($matches as $match){
450f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
451f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
4528ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
453f3f0262cSandi      if($acl[2] > $perm){
454f3f0262cSandi        $perm = $acl[2];
455f3f0262cSandi      }
456f3f0262cSandi    }
457f3f0262cSandi    if($perm > -1){
458f3f0262cSandi      //we had a match - return it
459f3f0262cSandi      return $perm;
460f3f0262cSandi    }
461f3f0262cSandi  }
462f3f0262cSandi
463f3f0262cSandi  //still here? do the namespace checks
464f3f0262cSandi  if($ns){
465f3f0262cSandi    $path = $ns.':\*';
466f3f0262cSandi  }else{
467f3f0262cSandi    $path = '\*'; //root document
468f3f0262cSandi  }
469f3f0262cSandi
470f3f0262cSandi  do{
471f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
472f3f0262cSandi    if(count($matches)){
473f3f0262cSandi      foreach($matches as $match){
474f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
475f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
4768ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
477f3f0262cSandi        if($acl[2] > $perm){
478f3f0262cSandi          $perm = $acl[2];
479f3f0262cSandi        }
480f3f0262cSandi      }
481f3f0262cSandi      //we had a match - return it
482f3f0262cSandi      return $perm;
483f3f0262cSandi    }
484f3f0262cSandi
485f3f0262cSandi    //get next higher namespace
486f3f0262cSandi    $ns   = getNS($ns);
487f3f0262cSandi
488f3f0262cSandi    if($path != '\*'){
489f3f0262cSandi      $path = $ns.':\*';
490f3f0262cSandi      if($path == ':\*') $path = '\*';
491f3f0262cSandi    }else{
492f3f0262cSandi      //we did this already
493f3f0262cSandi      //looks like there is something wrong with the ACL
494f3f0262cSandi      //break here
495d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
496d5ce66f6SAndreas Gohr      return AUTH_NONE;
497f3f0262cSandi    }
498f3f0262cSandi  }while(1); //this should never loop endless
49952a5af8dSandi
50052a5af8dSandi  //still here? return no permissions
50152a5af8dSandi  return AUTH_NONE;
502f3f0262cSandi}
503f3f0262cSandi
504f3f0262cSandi/**
5056c2bb100SAndreas Gohr * Encode ASCII special chars
5066c2bb100SAndreas Gohr *
5076c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
5086c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
5096c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
5106c2bb100SAndreas Gohr * urlencoding!).
5116c2bb100SAndreas Gohr *
5126c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5136c2bb100SAndreas Gohr *
5146c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5156c2bb100SAndreas Gohr * @see rawurldecode()
5166c2bb100SAndreas Gohr */
517e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
518a424cd8eSchris  global $cache_authname;
519a424cd8eSchris  $cache =& $cache_authname;
52031784267SAndreas Gohr  $name  = (string) $name;
521a424cd8eSchris
522a424cd8eSchris  if (!isset($cache[$name][$skip_group])) {
523e838fc2eSAndreas Gohr    if($skip_group && $name{0} =='@'){
524a424cd8eSchris      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5251a9ae8e5SAndreas Gohr                                                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
526e838fc2eSAndreas Gohr    }else{
527a424cd8eSchris      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5281a9ae8e5SAndreas Gohr                                                "'%'.dechex(ord(substr('\\1',-1)))",$name);
529e838fc2eSAndreas Gohr    }
5306c2bb100SAndreas Gohr  }
5316c2bb100SAndreas Gohr
532a424cd8eSchris  return $cache[$name][$skip_group];
533a424cd8eSchris}
534a424cd8eSchris
5356c2bb100SAndreas Gohr/**
536f3f0262cSandi * Create a pronouncable password
537f3f0262cSandi *
53815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
53915fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
54015fae107Sandi *
54115fae107Sandi * @return string  pronouncable password
542f3f0262cSandi */
543f3f0262cSandifunction auth_pwgen(){
544f3f0262cSandi  $pw = '';
545f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
546f3f0262cSandi  $v  = 'aeiou';              //vowels
547f3f0262cSandi  $a  = $c.$v;                //both
548f3f0262cSandi
549f3f0262cSandi  //use two syllables...
550f3f0262cSandi  for($i=0;$i < 2; $i++){
551f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
552f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
553f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
554f3f0262cSandi  }
555f3f0262cSandi  //... and add a nice number
556f3f0262cSandi  $pw .= rand(10,99);
557f3f0262cSandi
558f3f0262cSandi  return $pw;
559f3f0262cSandi}
560f3f0262cSandi
561f3f0262cSandi/**
562f3f0262cSandi * Sends a password to the given user
563f3f0262cSandi *
56415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
56515fae107Sandi *
56615fae107Sandi * @return bool  true on success
567f3f0262cSandi */
568f3f0262cSandifunction auth_sendPassword($user,$password){
569f3f0262cSandi  global $conf;
570f3f0262cSandi  global $lang;
571cd52f92dSchris  global $auth;
572cd52f92dSchris
573f3f0262cSandi  $hdrs  = '';
574cd52f92dSchris  $userinfo = $auth->getUserData($user);
575f3f0262cSandi
57687ddda95Sandi  if(!$userinfo['mail']) return false;
577f3f0262cSandi
578f3f0262cSandi  $text = rawLocale('password');
579ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
58087ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
581f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
582f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
583f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
584f3f0262cSandi
58544f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
58644f669e9Sandi                   $lang['regpwmail'],
58744f669e9Sandi                   $text,
58844f669e9Sandi                   $conf['mailfrom']);
589f3f0262cSandi}
590f3f0262cSandi
591f3f0262cSandi/**
59215fae107Sandi * Register a new user
593f3f0262cSandi *
59415fae107Sandi * This registers a new user - Data is read directly from $_POST
59515fae107Sandi *
59615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
59715fae107Sandi *
59815fae107Sandi * @return bool  true on success, false on any error
599f3f0262cSandi */
600f3f0262cSandifunction register(){
601f3f0262cSandi  global $lang;
602eb5d07e4Sjan  global $conf;
603cd52f92dSchris  global $auth;
604f3f0262cSandi
605f3f0262cSandi  if(!$_POST['save']) return false;
60682fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
607640145a5Sandi
608f3f0262cSandi  //clean username
609f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
610f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
611f3f0262cSandi  //clean fullname and email
61254f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
61354f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
614f3f0262cSandi
615f3f0262cSandi  if( empty($_POST['login']) ||
616f3f0262cSandi      empty($_POST['fullname']) ||
617f3f0262cSandi      empty($_POST['email']) ){
618f3f0262cSandi    msg($lang['regmissing'],-1);
619f3f0262cSandi    return false;
620f3f0262cSandi  }
621f3f0262cSandi
622cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
623cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
624cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
625cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
626bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
627cab2716aSmatthias.grimm    return false;
628cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
629bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
630cab2716aSmatthias.grimm    return false;
631cab2716aSmatthias.grimm  } else {
632cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
633cab2716aSmatthias.grimm  }
634cab2716aSmatthias.grimm
635f3f0262cSandi  //check mail
63644f669e9Sandi  if(!mail_isvalid($_POST['email'])){
637f3f0262cSandi    msg($lang['regbadmail'],-1);
638f3f0262cSandi    return false;
639f3f0262cSandi  }
640f3f0262cSandi
641f3f0262cSandi  //okay try to create the user
6427d3c8d42SGabriel Birke  if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
643f3f0262cSandi    msg($lang['reguexists'],-1);
644f3f0262cSandi    return false;
645f3f0262cSandi  }
646f3f0262cSandi
64702a498e7Schris  // create substitutions for use in notification email
64802a498e7Schris  $substitutions = array(
64902a498e7Schris    'NEWUSER' => $_POST['login'],
65002a498e7Schris    'NEWNAME' => $_POST['fullname'],
65102a498e7Schris    'NEWEMAIL' => $_POST['email'],
65202a498e7Schris  );
65302a498e7Schris
654cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
655cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
65602a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
657cab2716aSmatthias.grimm    return true;
658cab2716aSmatthias.grimm  }
659cab2716aSmatthias.grimm
660cab2716aSmatthias.grimm  // autogenerated password? then send him the password
661f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
662f3f0262cSandi    msg($lang['regsuccess'],1);
66302a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
664f3f0262cSandi    return true;
665f3f0262cSandi  }else{
666f3f0262cSandi    msg($lang['regmailfail'],-1);
667f3f0262cSandi    return false;
668f3f0262cSandi  }
669f3f0262cSandi}
670f3f0262cSandi
67110a76f6fSfrank/**
6728b06d178Schris * Update user profile
6738b06d178Schris *
6748b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
6758b06d178Schris */
6768b06d178Schrisfunction updateprofile() {
6778b06d178Schris  global $conf;
6788b06d178Schris  global $INFO;
6798b06d178Schris  global $lang;
680cd52f92dSchris  global $auth;
6818b06d178Schris
682bb4866bdSchris  if(empty($_POST['save'])) return false;
6831b2a85e8SAndreas Gohr  if(!checkSecurityToken()) return false;
6848b06d178Schris
68582fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
68682fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
6878b06d178Schris    msg($lang['profna'],-1);
6888b06d178Schris    return false;
6898b06d178Schris  }
6908b06d178Schris
6918b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
6928b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
6938b06d178Schris    return false;
6948b06d178Schris  }
6958b06d178Schris
6968b06d178Schris  //clean fullname and email
69754f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
69854f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
6998b06d178Schris
7008b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
7018b06d178Schris    msg($lang['profnoempty'],-1);
7028b06d178Schris    return false;
7038b06d178Schris  }
7048b06d178Schris
7058b06d178Schris  if (!mail_isvalid($_POST['email'])){
7068b06d178Schris    msg($lang['regbadmail'],-1);
7078b06d178Schris    return false;
7088b06d178Schris  }
7098b06d178Schris
7104c21b7eeSAndreas Gohr  if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7114c21b7eeSAndreas Gohr  if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
712cf626a62SAndreas Gohr  if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7134c21b7eeSAndreas Gohr
7148b06d178Schris
7158b06d178Schris  if (!count($changes)) {
7168b06d178Schris    msg($lang['profnochange'], -1);
7178b06d178Schris    return false;
7188b06d178Schris  }
7198b06d178Schris
7208b06d178Schris  if ($conf['profileconfirm']) {
721df466c7aSAndreas Gohr    if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
7228b06d178Schris      msg($lang['badlogin'],-1);
7238b06d178Schris      return false;
7248b06d178Schris    }
7258b06d178Schris  }
7268b06d178Schris
727a0b5b007SChris Smith  if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
728a0b5b007SChris Smith    // update cookie and session with the changed data
729a0b5b007SChris Smith    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
730a0b5b007SChris Smith    list($user,$sticky,$pass) = split('\|',$cookie,3);
731a0b5b007SChris Smith    if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
732a0b5b007SChris Smith
733a0b5b007SChris Smith    auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
73425b2a98cSMichael Klier    return true;
735a0b5b007SChris Smith  }
7368b06d178Schris}
7378b06d178Schris
7388b06d178Schris/**
7398b06d178Schris * Send a  new password
7408b06d178Schris *
7411d5856cfSAndreas Gohr * This function handles both phases of the password reset:
7421d5856cfSAndreas Gohr *
7431d5856cfSAndreas Gohr *   - handling the first request of password reset
7441d5856cfSAndreas Gohr *   - validating the password reset auth token
7451d5856cfSAndreas Gohr *
7468b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
7478b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
7481d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7498b06d178Schris *
7508b06d178Schris * @return bool true on success, false on any error
7518b06d178Schris*/
7528b06d178Schrisfunction act_resendpwd(){
7538b06d178Schris    global $lang;
7548b06d178Schris    global $conf;
755cd52f92dSchris    global $auth;
7568b06d178Schris
757409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
7588b06d178Schris
75982fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
76082fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
7618b06d178Schris        msg($lang['resendna'],-1);
7628b06d178Schris        return false;
7638b06d178Schris    }
7648b06d178Schris
7651d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
7668b06d178Schris
7671d5856cfSAndreas Gohr    if($token){
7681d5856cfSAndreas Gohr        // we're in token phase
7691d5856cfSAndreas Gohr
7701d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
7711d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
7721d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
7731d5856cfSAndreas Gohr            return false;
7741d5856cfSAndreas Gohr        }
7751d5856cfSAndreas Gohr        $user = io_readfile($tfile);
7761d5856cfSAndreas Gohr        @unlink($tfile);
777cd52f92dSchris        $userinfo = $auth->getUserData($user);
7788b06d178Schris        if(!$userinfo['mail']) {
7798b06d178Schris            msg($lang['resendpwdnouser'], -1);
7808b06d178Schris            return false;
7818b06d178Schris        }
7828b06d178Schris
7838b06d178Schris        $pass = auth_pwgen();
7847d3c8d42SGabriel Birke        if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
7858b06d178Schris            msg('error modifying user data',-1);
7868b06d178Schris            return false;
7878b06d178Schris        }
7888b06d178Schris
7898b06d178Schris        if (auth_sendPassword($user,$pass)) {
7908b06d178Schris            msg($lang['resendpwdsuccess'],1);
7918b06d178Schris        } else {
7928b06d178Schris            msg($lang['regmailfail'],-1);
7938b06d178Schris        }
7948b06d178Schris        return true;
7951d5856cfSAndreas Gohr
7961d5856cfSAndreas Gohr    } else {
7971d5856cfSAndreas Gohr        // we're in request phase
7981d5856cfSAndreas Gohr
7991d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
8001d5856cfSAndreas Gohr
8011d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
8021d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
8031d5856cfSAndreas Gohr            return false;
8041d5856cfSAndreas Gohr        } else {
80516470b1dSchris            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
80616470b1dSchris            $user = cleanID($_POST['login']);
8071d5856cfSAndreas Gohr        }
8081d5856cfSAndreas Gohr
8091d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
8101d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
8111d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
8121d5856cfSAndreas Gohr            return false;
8131d5856cfSAndreas Gohr        }
8141d5856cfSAndreas Gohr
8151d5856cfSAndreas Gohr        // generate auth token
8161d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
8171d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
8181d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8191d5856cfSAndreas Gohr
8201d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
8211d5856cfSAndreas Gohr
8221d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
8231d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
8241d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
8251d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
8261d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
8271d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
8281d5856cfSAndreas Gohr
8291d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
8301d5856cfSAndreas Gohr                     $lang['regpwmail'],
8311d5856cfSAndreas Gohr                     $text,
8321d5856cfSAndreas Gohr                     $conf['mailfrom'])){
8331d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
8341d5856cfSAndreas Gohr        }else{
8351d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
8361d5856cfSAndreas Gohr        }
8371d5856cfSAndreas Gohr        return true;
8381d5856cfSAndreas Gohr    }
8391d5856cfSAndreas Gohr
8401d5856cfSAndreas Gohr    return false; // never reached
8418b06d178Schris}
8428b06d178Schris
8438b06d178Schris/**
844b0855b11Sandi * Encrypts a password using the given method and salt
845b0855b11Sandi *
846b0855b11Sandi * If the selected method needs a salt and none was given, a random one
847b0855b11Sandi * is chosen.
848b0855b11Sandi *
849b0855b11Sandi * The following methods are understood:
850b0855b11Sandi *
851b0855b11Sandi *   smd5  - Salted MD5 hashing
852577c7cdaSAndreas Gohr *   apr1  - Apache salted MD5 hashing
853b0855b11Sandi *   md5   - Simple MD5 hashing
854b0855b11Sandi *   sha1  - SHA1 hashing
855b0855b11Sandi *   ssha  - Salted SHA1 hashing
856d7be6245Sandi *   crypt - Unix crypt
857d7be6245Sandi *   mysql - MySQL password (old method)
858d7be6245Sandi *   my411 - MySQL 4.1.1 password
859b0855b11Sandi *
860b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
861b0855b11Sandi * @return  string  The crypted password
862b0855b11Sandi */
863577c7cdaSAndreas Gohrfunction auth_cryptPassword($clear,$method='',$salt=null){
864b0855b11Sandi    global $conf;
865b0855b11Sandi    if(empty($method)) $method = $conf['passcrypt'];
86610a76f6fSfrank
867b0855b11Sandi    //prepare a salt
868577c7cdaSAndreas Gohr    if(is_null($salt)) $salt = md5(uniqid(rand(), true));
869b0855b11Sandi
870b0855b11Sandi    switch(strtolower($method)){
871b0855b11Sandi        case 'smd5':
872056cb2ccSChris Smith            if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
873577c7cdaSAndreas Gohr            // when crypt can't handle SMD5, falls through to pure PHP implementation
874577c7cdaSAndreas Gohr            $magic = '1';
875577c7cdaSAndreas Gohr        case 'apr1':
876577c7cdaSAndreas Gohr            //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
877577c7cdaSAndreas Gohr            if(!$magic) $magic = 'apr1';
878577c7cdaSAndreas Gohr            $salt = substr($salt,0,8);
879577c7cdaSAndreas Gohr            $len = strlen($clear);
880577c7cdaSAndreas Gohr            $text = $clear.'$'.$magic.'$'.$salt;
881577c7cdaSAndreas Gohr            $bin = pack("H32", md5($clear.$salt.$clear));
882577c7cdaSAndreas Gohr            for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
883577c7cdaSAndreas Gohr            for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $clear{0}; }
884577c7cdaSAndreas Gohr            $bin = pack("H32", md5($text));
885577c7cdaSAndreas Gohr            for($i = 0; $i < 1000; $i++) {
886577c7cdaSAndreas Gohr                $new = ($i & 1) ? $clear : $bin;
887577c7cdaSAndreas Gohr                if ($i % 3) $new .= $salt;
888577c7cdaSAndreas Gohr                if ($i % 7) $new .= $clear;
889577c7cdaSAndreas Gohr                $new .= ($i & 1) ? $bin : $clear;
890577c7cdaSAndreas Gohr                $bin = pack("H32", md5($new));
891577c7cdaSAndreas Gohr            }
892577c7cdaSAndreas Gohr            $tmp = '';
893577c7cdaSAndreas Gohr            for ($i = 0; $i < 5; $i++) {
894577c7cdaSAndreas Gohr                $k = $i + 6;
895577c7cdaSAndreas Gohr                $j = $i + 12;
896577c7cdaSAndreas Gohr                if ($j == 16) $j = 5;
897577c7cdaSAndreas Gohr                $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
898577c7cdaSAndreas Gohr            }
899577c7cdaSAndreas Gohr            $tmp = chr(0).chr(0).$bin[11].$tmp;
900577c7cdaSAndreas Gohr            $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
901577c7cdaSAndreas Gohr                    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
902577c7cdaSAndreas Gohr                    "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
903577c7cdaSAndreas Gohr            return '$'.$magic.'$'.$salt.'$'.$tmp;
904b0855b11Sandi        case 'md5':
905b0855b11Sandi            return md5($clear);
906b0855b11Sandi        case 'sha1':
907b0855b11Sandi            return sha1($clear);
908b0855b11Sandi        case 'ssha':
909b0855b11Sandi            $salt=substr($salt,0,4);
910d6e54e02Smatthiasgrimm            return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
911b0855b11Sandi        case 'crypt':
912b0855b11Sandi            return crypt($clear,substr($salt,0,2));
913d7be6245Sandi        case 'mysql':
914d7be6245Sandi            //from http://www.php.net/mysql comment by <soren at byu dot edu>
915d7be6245Sandi            $nr=0x50305735;
916d7be6245Sandi            $nr2=0x12345671;
917d7be6245Sandi            $add=7;
918d7be6245Sandi            $charArr = preg_split("//", $clear);
919d7be6245Sandi            foreach ($charArr as $char) {
920d7be6245Sandi                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
921d7be6245Sandi                $charVal = ord($char);
922d7be6245Sandi                $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
923d7be6245Sandi                $nr2 += ($nr2 << 8) ^ $nr;
924d7be6245Sandi                $add += $charVal;
925d7be6245Sandi            }
926d7be6245Sandi            return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
927d7be6245Sandi        case 'my411':
928d7be6245Sandi            return '*'.sha1(pack("H*", sha1($clear)));
929b0855b11Sandi        default:
930b0855b11Sandi            msg("Unsupported crypt method $method",-1);
931b0855b11Sandi    }
932b0855b11Sandi}
933b0855b11Sandi
934b0855b11Sandi/**
935b0855b11Sandi * Verifies a cleartext password against a crypted hash
936b0855b11Sandi *
937b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
938b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
939b0855b11Sandi * match true is is returned else false
940b0855b11Sandi *
941b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
942b0855b11Sandi * @return  bool
943b0855b11Sandi */
944b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
945b0855b11Sandi    $method='';
946b0855b11Sandi    $salt='';
947b0855b11Sandi
948b0855b11Sandi    //determine the used method and salt
949d7be6245Sandi    $len = strlen($crypt);
950577c7cdaSAndreas Gohr    if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
951b0855b11Sandi        $method = 'smd5';
952577c7cdaSAndreas Gohr        $salt   = $m[1];
953577c7cdaSAndreas Gohr    }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
954577c7cdaSAndreas Gohr        $method = 'apr1';
955577c7cdaSAndreas Gohr        $salt   = $m[1];
956b0855b11Sandi    }elseif(substr($crypt,0,6) == '{SSHA}'){
957b0855b11Sandi        $method = 'ssha';
958b0855b11Sandi        $salt   = substr(base64_decode(substr($crypt, 6)),20);
959d7be6245Sandi    }elseif($len == 32){
960b0855b11Sandi        $method = 'md5';
961d7be6245Sandi    }elseif($len == 40){
962b0855b11Sandi        $method = 'sha1';
963d7be6245Sandi    }elseif($len == 16){
964d7be6245Sandi        $method = 'mysql';
965d7be6245Sandi    }elseif($len == 41 && $crypt[0] == '*'){
966d7be6245Sandi        $method = 'my411';
967b0855b11Sandi    }else{
968b0855b11Sandi        $method = 'crypt';
969b0855b11Sandi        $salt   = substr($crypt,0,2);
970b0855b11Sandi    }
971b0855b11Sandi
972b0855b11Sandi    //crypt and compare
973b0855b11Sandi    if(auth_cryptPassword($clear,$method,$salt) === $crypt){
974b0855b11Sandi        return true;
975b0855b11Sandi    }
976b0855b11Sandi    return false;
977b0855b11Sandi}
978340756e4Sandi
979a0b5b007SChris Smith/**
980a0b5b007SChris Smith * Set the authentication cookie and add user identification data to the session
981a0b5b007SChris Smith *
982a0b5b007SChris Smith * @param string  $user       username
983a0b5b007SChris Smith * @param string  $pass       encrypted password
984a0b5b007SChris Smith * @param bool    $sticky     whether or not the cookie will last beyond the session
985a0b5b007SChris Smith */
986a0b5b007SChris Smithfunction auth_setCookie($user,$pass,$sticky) {
987a0b5b007SChris Smith    global $conf;
988a0b5b007SChris Smith    global $auth;
98979d00841SOliver Geisen    global $USERINFO;
990a0b5b007SChris Smith
991a0b5b007SChris Smith      $USERINFO = $auth->getUserData($user);
992a0b5b007SChris Smith
993a0b5b007SChris Smith      // set cookie
994a0b5b007SChris Smith      $cookie = base64_encode("$user|$sticky|$pass");
995a0b5b007SChris Smith      if($sticky) $time = time()+60*60*24*365; //one year
996a0b5b007SChris Smith      if (version_compare(PHP_VERSION, '5.2.0', '>')) {
997a0b5b007SChris Smith          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
998a0b5b007SChris Smith      }else{
999a0b5b007SChris Smith          setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1000a0b5b007SChris Smith      }
1001a0b5b007SChris Smith      // set session
1002a0b5b007SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1003a0b5b007SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1004a0b5b007SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1005a0b5b007SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1006a0b5b007SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1007a0b5b007SChris Smith}
1008a0b5b007SChris Smith
1009340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1010