xref: /dokuwiki/inc/auth.php (revision f13fa892aab9df4b816e1227fe328acd7ba9b35b)
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'] = '';
61bbbd6568SAndreas Gohr
621e8c9c90SAndreas Gohr      // if no credentials were given try to use HTTP auth (for SSO)
634a26ad85Schris      if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
641e8c9c90SAndreas Gohr        $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
651e8c9c90SAndreas Gohr        $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
661e8c9c90SAndreas Gohr      }
671e8c9c90SAndreas Gohr
68*f13fa892SAndreas Gohr      if($_REQUEST['authtok']){
69*f13fa892SAndreas Gohr        // when an authentication token is given, trust the session
70*f13fa892SAndreas Gohr        auth_validateToken($_REQUEST['authtok']);
71*f13fa892SAndreas Gohr      }elseif(!is_null($auth) && $auth->canDo('external')){
72*f13fa892SAndreas Gohr        // external trust mechanism in place
73f5cb575dSAndreas Gohr        $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
74f5cb575dSAndreas Gohr      }else{
75132bdbfeSandi        auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
76f5cb575dSAndreas Gohr      }
771ec50243SAndreas Gohr    }
78f5cb575dSAndreas Gohr
7915fae107Sandi    //load ACL into a global array
8088e6a4f2SAndreas Gohr    global $AUTH_ACL;
81e7cb32dcSAndreas Gohr    if(is_readable(DOKU_CONF.'acl.auth.php')){
82e7cb32dcSAndreas Gohr      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
83f8cc3354SGuy Brand      if(isset($_SERVER['REMOTE_USER'])){
84a8fe108bSGuy Brand        $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL);
85a8fe108bSGuy Brand      }
8611799630Sandi    }else{
8711799630Sandi      $AUTH_ACL = array();
8811799630Sandi    }
89f3f0262cSandi  }
90f3f0262cSandi
91f3f0262cSandi/**
92f3f0262cSandi * This tries to login the user based on the sent auth credentials
93f3f0262cSandi *
94f3f0262cSandi * The authentication works like this: if a username was given
9515fae107Sandi * a new login is assumed and user/password are checked. If they
9615fae107Sandi * are correct the password is encrypted with blowfish and stored
9715fae107Sandi * together with the username in a cookie - the same info is stored
9815fae107Sandi * in the session, too. Additonally a browserID is stored in the
9915fae107Sandi * session.
10015fae107Sandi *
10115fae107Sandi * If no username was given the cookie is checked: if the username,
10215fae107Sandi * crypted password and browserID match between session and cookie
10315fae107Sandi * no further testing is done and the user is accepted
10415fae107Sandi *
10515fae107Sandi * If a cookie was found but no session info was availabe the
106136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
10715fae107Sandi * together with username rechecked by calling this function again.
108f3f0262cSandi *
109f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
110f3f0262cSandi * are set.
11115fae107Sandi *
11215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
11315fae107Sandi *
11415fae107Sandi * @param   string  $user    Username
11515fae107Sandi * @param   string  $pass    Cleartext Password
11615fae107Sandi * @param   bool    $sticky  Cookie should not expire
117f112c2faSAndreas Gohr * @param   bool    $silent  Don't show error on bad auth
11815fae107Sandi * @return  bool             true on successful auth
119f3f0262cSandi*/
120f112c2faSAndreas Gohrfunction auth_login($user,$pass,$sticky=false,$silent=false){
121f3f0262cSandi  global $USERINFO;
122f3f0262cSandi  global $conf;
123f3f0262cSandi  global $lang;
124cd52f92dSchris  global $auth;
125132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
126f3f0262cSandi
127bbbd6568SAndreas Gohr  if(!empty($user)){
128132bdbfeSandi    //usual login
129cd52f92dSchris    if ($auth->checkPass($user,$pass)){
130132bdbfeSandi      // make logininfo globally available
131f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
1320f4f4adfSAndreas Gohr      $USERINFO = $auth->getUserData($user);
133132bdbfeSandi
134132bdbfeSandi      // set cookie
135132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
136132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
137132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
1384b1a4e04SAndreas Gohr      setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL);
139132bdbfeSandi
140132bdbfeSandi      // set session
141e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
142e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
143e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
144e71ce681SAndreas Gohr      $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1454c989037SChris Smith      $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1464c989037SChris Smith
147132bdbfeSandi      return true;
148f3f0262cSandi    }else{
149f3f0262cSandi      //invalid credentials - log off
150f112c2faSAndreas Gohr      if(!$silent) msg($lang['badlogin'],-1);
151f3f0262cSandi      auth_logoff();
152132bdbfeSandi      return false;
153f3f0262cSandi    }
154f3f0262cSandi  }else{
155132bdbfeSandi    // read cookie information
156e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
157132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
158132bdbfeSandi    // get session info
159e71ce681SAndreas Gohr    $session = $_SESSION[DOKU_COOKIE]['auth'];
160132bdbfeSandi    if($user && $pass){
161132bdbfeSandi      // we got a cookie - see if we can trust it
162132bdbfeSandi      if(isset($session) &&
1637172dbc0SAndreas Gohr        $auth->useSessionCache($user) &&
1644c989037SChris Smith        ($session['time'] >= time()-$conf['auth_security_timeout']) &&
165132bdbfeSandi        ($session['user'] == $user) &&
166132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
167132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
168132bdbfeSandi        // he has session, cookie and browser right - let him in
169132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
170132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
171132bdbfeSandi        return true;
172132bdbfeSandi      }
173f112c2faSAndreas Gohr      // no we don't trust it yet - recheck pass but silent
174132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
175f112c2faSAndreas Gohr      return auth_login($user,$pass,$sticky,true);
176132bdbfeSandi    }
177132bdbfeSandi  }
178f3f0262cSandi  //just to be sure
179f3f0262cSandi  auth_logoff();
180132bdbfeSandi  return false;
181f3f0262cSandi}
182132bdbfeSandi
183132bdbfeSandi/**
184*f13fa892SAndreas Gohr * Checks if a given authentication token was stored in the session
185*f13fa892SAndreas Gohr *
186*f13fa892SAndreas Gohr * Will setup authentication data using data from the session if the
187*f13fa892SAndreas Gohr * token is correct. Will exit with a 401 Status if not.
188*f13fa892SAndreas Gohr *
189*f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
190*f13fa892SAndreas Gohr * @param  string $token The authentication token
191*f13fa892SAndreas Gohr * @return boolean true (or will exit on failure)
192*f13fa892SAndreas Gohr */
193*f13fa892SAndreas Gohrfunction auth_validateToken($token){
194*f13fa892SAndreas Gohr    if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
195*f13fa892SAndreas Gohr        // bad token
196*f13fa892SAndreas Gohr        header("HTTP/1.0 401 Unauthorized");
197*f13fa892SAndreas Gohr        print 'Invalid auth token - maybe the session timed out';
198*f13fa892SAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
199*f13fa892SAndreas Gohr        exit;
200*f13fa892SAndreas Gohr    }
201*f13fa892SAndreas Gohr    // still here? trust the session data
202*f13fa892SAndreas Gohr    global $USERINFO;
203*f13fa892SAndreas Gohr    $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
204*f13fa892SAndreas Gohr    $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
205*f13fa892SAndreas Gohr    return true;
206*f13fa892SAndreas Gohr}
207*f13fa892SAndreas Gohr
208*f13fa892SAndreas Gohr/**
209*f13fa892SAndreas Gohr * Create an auth token and store it in the session
210*f13fa892SAndreas Gohr *
211*f13fa892SAndreas Gohr * NOTE: this is completely unrelated to the getSecurityToken() function
212*f13fa892SAndreas Gohr *
213*f13fa892SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
214*f13fa892SAndreas Gohr * @return string The auth token
215*f13fa892SAndreas Gohr */
216*f13fa892SAndreas Gohrfunction auth_createToken(){
217*f13fa892SAndreas Gohr    $token = md5(mt_rand());
218*f13fa892SAndreas Gohr    $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
219*f13fa892SAndreas Gohr    return $token;
220*f13fa892SAndreas Gohr}
221*f13fa892SAndreas Gohr
222*f13fa892SAndreas Gohr/**
223136ce040Sandi * Builds a pseudo UID from browser and IP data
224132bdbfeSandi *
225132bdbfeSandi * This is neither unique nor unfakable - still it adds some
226136ce040Sandi * security. Using the first part of the IP makes sure
227136ce040Sandi * proxy farms like AOLs are stil okay.
22815fae107Sandi *
22915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
23015fae107Sandi *
23115fae107Sandi * @return  string  a MD5 sum of various browser headers
232132bdbfeSandi */
233132bdbfeSandifunction auth_browseruid(){
234132bdbfeSandi  $uid  = '';
235132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
236132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
237132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
238132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
239136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
240132bdbfeSandi  return md5($uid);
241132bdbfeSandi}
242132bdbfeSandi
243132bdbfeSandi/**
244132bdbfeSandi * Creates a random key to encrypt the password in cookies
24515fae107Sandi *
24615fae107Sandi * This function tries to read the password for encrypting
24798407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
24815fae107Sandi * if no such file is found a random key is created and
24915fae107Sandi * and stored in this file.
25015fae107Sandi *
25115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
25215fae107Sandi *
25315fae107Sandi * @return  string
254132bdbfeSandi */
255132bdbfeSandifunction auth_cookiesalt(){
256132bdbfeSandi  global $conf;
25798407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
258132bdbfeSandi  $salt = io_readFile($file);
259132bdbfeSandi  if(empty($salt)){
260132bdbfeSandi    $salt = uniqid(rand(),true);
261132bdbfeSandi    io_saveFile($file,$salt);
262132bdbfeSandi  }
263132bdbfeSandi  return $salt;
264f3f0262cSandi}
265f3f0262cSandi
266f3f0262cSandi/**
267f3f0262cSandi * This clears all authenticationdata and thus log the user
268f3f0262cSandi * off
26915fae107Sandi *
27015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
271f3f0262cSandi */
272f3f0262cSandifunction auth_logoff(){
273f3f0262cSandi  global $conf;
274f3f0262cSandi  global $USERINFO;
2758b06d178Schris  global $INFO, $ID;
2765298a619SAndreas Gohr  global $auth;
27737065e65Sandi
278e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
279e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['user']);
280e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
281e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
282e71ce681SAndreas Gohr  if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
283e71ce681SAndreas Gohr    unset($_SESSION[DOKU_COOKIE]['auth']['info']);
28437065e65Sandi  if(isset($_SERVER['REMOTE_USER']))
285f3f0262cSandi    unset($_SERVER['REMOTE_USER']);
286132bdbfeSandi  $USERINFO=null; //FIXME
2874b1a4e04SAndreas Gohr  setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL);
2885298a619SAndreas Gohr
2895298a619SAndreas Gohr  if($auth && $auth->canDo('logoff')){
2905298a619SAndreas Gohr    $auth->logOff();
2915298a619SAndreas Gohr  }
292f3f0262cSandi}
293f3f0262cSandi
294f3f0262cSandi/**
295f8cc712eSAndreas Gohr * Check if a user is a manager
296f8cc712eSAndreas Gohr *
297f8cc712eSAndreas Gohr * Should usually be called without any parameters to check the current
298f8cc712eSAndreas Gohr * user.
299f8cc712eSAndreas Gohr *
300f8cc712eSAndreas Gohr * The info is available through $INFO['ismanager'], too
301f8cc712eSAndreas Gohr *
302f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
303f8cc712eSAndreas Gohr * @see    auth_isadmin
304f8cc712eSAndreas Gohr * @param  string user      - Username
305f8cc712eSAndreas Gohr * @param  array  groups    - List of groups the user is in
306f8cc712eSAndreas Gohr * @param  bool   adminonly - when true checks if user is admin
307f8cc712eSAndreas Gohr */
308f8cc712eSAndreas Gohrfunction auth_ismanager($user=null,$groups=null,$adminonly=false){
309f8cc712eSAndreas Gohr  global $conf;
310f8cc712eSAndreas Gohr  global $USERINFO;
311f8cc712eSAndreas Gohr
312f8cc712eSAndreas Gohr  if(!$conf['useacl']) return false;
313f8cc712eSAndreas Gohr  if(is_null($user))   $user   = $_SERVER['REMOTE_USER'];
31490583e9fSAndreas Gohr  if(is_null($groups)) $groups = (array) $USERINFO['grps'];
315f8cc712eSAndreas Gohr  $user   = auth_nameencode($user);
316f8cc712eSAndreas Gohr
317f8cc712eSAndreas Gohr  // check username against superuser and manager
3187651d633SGuy Brand  $superusers = explode(',', $conf['superuser']);
3197651d633SGuy Brand  $superusers = array_unique($superusers);
3207651d633SGuy Brand  $superusers = array_map('trim', $superusers);
3217651d633SGuy Brand  // prepare an array containing only true values for array_map call
3227651d633SGuy Brand  $alltrue = array_fill(0, count($superusers), true);
3237651d633SGuy Brand  $superusers = array_map('auth_nameencode', $superusers, $alltrue);
3247651d633SGuy Brand  if(in_array($user, $superusers)) return true;
3257651d633SGuy Brand
326f8cc712eSAndreas Gohr  if(!$adminonly){
3277651d633SGuy Brand    $managers = explode(',', $conf['manager']);
3287651d633SGuy Brand    $managers = array_unique($managers);
3297651d633SGuy Brand    $managers = array_map('trim', $managers);
3307651d633SGuy Brand    // prepare an array containing only true values for array_map call
3317651d633SGuy Brand    $alltrue = array_fill(0, count($managers), true);
3327651d633SGuy Brand    $managers = array_map('auth_nameencode', $managers, $alltrue);
3337651d633SGuy Brand    if(in_array($user, $managers)) return true;
334f8cc712eSAndreas Gohr  }
335f8cc712eSAndreas Gohr
33600ce12daSChris Smith  // check user's groups against superuser and manager
33700ce12daSChris Smith  if (!empty($groups)) {
33800ce12daSChris Smith
339f8cc712eSAndreas Gohr    //prepend groups with @ and nameencode
340f8cc712eSAndreas Gohr    $cnt = count($groups);
341f8cc712eSAndreas Gohr    for($i=0; $i<$cnt; $i++){
342f8cc712eSAndreas Gohr      $groups[$i] = '@'.auth_nameencode($groups[$i]);
343f8cc712eSAndreas Gohr    }
344f8cc712eSAndreas Gohr
345f8cc712eSAndreas Gohr    // check groups against superuser and manager
3467651d633SGuy Brand    foreach($superusers as $supu)
3477651d633SGuy Brand      if(in_array($supu, $groups)) return true;
348f8cc712eSAndreas Gohr    if(!$adminonly){
3497651d633SGuy Brand      foreach($managers as $mana)
3507651d633SGuy Brand        if(in_array($mana, $groups)) return true;
351f8cc712eSAndreas Gohr    }
35200ce12daSChris Smith  }
35300ce12daSChris Smith
354f8cc712eSAndreas Gohr  return false;
355f8cc712eSAndreas Gohr}
356f8cc712eSAndreas Gohr
357f8cc712eSAndreas Gohr/**
358f8cc712eSAndreas Gohr * Check if a user is admin
359f8cc712eSAndreas Gohr *
360f8cc712eSAndreas Gohr * Alias to auth_ismanager with adminonly=true
361f8cc712eSAndreas Gohr *
362f8cc712eSAndreas Gohr * The info is available through $INFO['isadmin'], too
363f8cc712eSAndreas Gohr *
364f8cc712eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
365f8cc712eSAndreas Gohr * @see auth_ismanager
366f8cc712eSAndreas Gohr */
367f8cc712eSAndreas Gohrfunction auth_isadmin($user=null,$groups=null){
368f8cc712eSAndreas Gohr  return auth_ismanager($user,$groups,true);
369f8cc712eSAndreas Gohr}
370f8cc712eSAndreas Gohr
371f8cc712eSAndreas Gohr/**
37215fae107Sandi * Convinience function for auth_aclcheck()
37315fae107Sandi *
37415fae107Sandi * This checks the permissions for the current user
37515fae107Sandi *
37615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
37715fae107Sandi *
37815fae107Sandi * @param  string  $id  page ID
37915fae107Sandi * @return int          permission level
380f3f0262cSandi */
381f3f0262cSandifunction auth_quickaclcheck($id){
382f3f0262cSandi  global $conf;
383f3f0262cSandi  global $USERINFO;
384f3f0262cSandi  # if no ACL is used always return upload rights
385f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
386f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
387f3f0262cSandi}
388f3f0262cSandi
389f3f0262cSandi/**
390f3f0262cSandi * Returns the maximum rights a user has for
391f3f0262cSandi * the given ID or its namespace
39215fae107Sandi *
39315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
39415fae107Sandi *
39515fae107Sandi * @param  string  $id     page ID
39615fae107Sandi * @param  string  $user   Username
39715fae107Sandi * @param  array   $groups Array of groups the user is in
39815fae107Sandi * @return int             permission level
399f3f0262cSandi */
400f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
401f3f0262cSandi  global $conf;
402f3f0262cSandi  global $AUTH_ACL;
403f3f0262cSandi
40485d03f68SAndreas Gohr  // if no ACL is used always return upload rights
405f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
406f3f0262cSandi
407074cf26bSandi  //make sure groups is an array
408074cf26bSandi  if(!is_array($groups)) $groups = array();
409074cf26bSandi
41085d03f68SAndreas Gohr  //if user is superuser or in superusergroup return 255 (acl_admin)
41185d03f68SAndreas Gohr  if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
41285d03f68SAndreas Gohr
41385d03f68SAndreas Gohr  $user = auth_nameencode($user);
41485d03f68SAndreas Gohr
4156c2bb100SAndreas Gohr  //prepend groups with @ and nameencode
4162cd2db38Sandi  $cnt = count($groups);
4172cd2db38Sandi  for($i=0; $i<$cnt; $i++){
4186c2bb100SAndreas Gohr    $groups[$i] = '@'.auth_nameencode($groups[$i]);
41910a76f6fSfrank  }
42010a76f6fSfrank
421f3f0262cSandi  $ns    = getNS($id);
422f3f0262cSandi  $perm  = -1;
423f3f0262cSandi
424f3f0262cSandi  if($user){
425f3f0262cSandi    //add ALL group
426f3f0262cSandi    $groups[] = '@ALL';
427f3f0262cSandi    //add User
428f3f0262cSandi    $groups[] = $user;
429f3f0262cSandi    //build regexp
430f3f0262cSandi    $regexp   = join('|',$groups);
431f3f0262cSandi  }else{
432f3f0262cSandi    $regexp = '@ALL';
433f3f0262cSandi  }
434f3f0262cSandi
435f3f0262cSandi  //check exact match first
43642905504SAndreas Gohr  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
437f3f0262cSandi  if(count($matches)){
438f3f0262cSandi    foreach($matches as $match){
439f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
440f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
4418ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
442f3f0262cSandi      if($acl[2] > $perm){
443f3f0262cSandi        $perm = $acl[2];
444f3f0262cSandi      }
445f3f0262cSandi    }
446f3f0262cSandi    if($perm > -1){
447f3f0262cSandi      //we had a match - return it
448f3f0262cSandi      return $perm;
449f3f0262cSandi    }
450f3f0262cSandi  }
451f3f0262cSandi
452f3f0262cSandi  //still here? do the namespace checks
453f3f0262cSandi  if($ns){
454f3f0262cSandi    $path = $ns.':\*';
455f3f0262cSandi  }else{
456f3f0262cSandi    $path = '\*'; //root document
457f3f0262cSandi  }
458f3f0262cSandi
459f3f0262cSandi  do{
460f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
461f3f0262cSandi    if(count($matches)){
462f3f0262cSandi      foreach($matches as $match){
463f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
464f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
4658ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
466f3f0262cSandi        if($acl[2] > $perm){
467f3f0262cSandi          $perm = $acl[2];
468f3f0262cSandi        }
469f3f0262cSandi      }
470f3f0262cSandi      //we had a match - return it
471f3f0262cSandi      return $perm;
472f3f0262cSandi    }
473f3f0262cSandi
474f3f0262cSandi    //get next higher namespace
475f3f0262cSandi    $ns   = getNS($ns);
476f3f0262cSandi
477f3f0262cSandi    if($path != '\*'){
478f3f0262cSandi      $path = $ns.':\*';
479f3f0262cSandi      if($path == ':\*') $path = '\*';
480f3f0262cSandi    }else{
481f3f0262cSandi      //we did this already
482f3f0262cSandi      //looks like there is something wrong with the ACL
483f3f0262cSandi      //break here
484d5ce66f6SAndreas Gohr      msg('No ACL setup yet! Denying access to everyone.');
485d5ce66f6SAndreas Gohr      return AUTH_NONE;
486f3f0262cSandi    }
487f3f0262cSandi  }while(1); //this should never loop endless
48852a5af8dSandi
48952a5af8dSandi  //still here? return no permissions
49052a5af8dSandi  return AUTH_NONE;
491f3f0262cSandi}
492f3f0262cSandi
493f3f0262cSandi/**
4946c2bb100SAndreas Gohr * Encode ASCII special chars
4956c2bb100SAndreas Gohr *
4966c2bb100SAndreas Gohr * Some auth backends allow special chars in their user and groupnames
4976c2bb100SAndreas Gohr * The special chars are encoded with this function. Only ASCII chars
4986c2bb100SAndreas Gohr * are encoded UTF-8 multibyte are left as is (different from usual
4996c2bb100SAndreas Gohr * urlencoding!).
5006c2bb100SAndreas Gohr *
5016c2bb100SAndreas Gohr * Decoding can be done with rawurldecode
5026c2bb100SAndreas Gohr *
5036c2bb100SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
5046c2bb100SAndreas Gohr * @see rawurldecode()
5056c2bb100SAndreas Gohr */
506e838fc2eSAndreas Gohrfunction auth_nameencode($name,$skip_group=false){
507a424cd8eSchris  global $cache_authname;
508a424cd8eSchris  $cache =& $cache_authname;
50931784267SAndreas Gohr  $name  = (string) $name;
510a424cd8eSchris
511a424cd8eSchris  if (!isset($cache[$name][$skip_group])) {
512e838fc2eSAndreas Gohr    if($skip_group && $name{0} =='@'){
513a424cd8eSchris      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5141a9ae8e5SAndreas Gohr                                                    "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
515e838fc2eSAndreas Gohr    }else{
516a424cd8eSchris      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
5171a9ae8e5SAndreas Gohr                                                "'%'.dechex(ord(substr('\\1',-1)))",$name);
518e838fc2eSAndreas Gohr    }
5196c2bb100SAndreas Gohr  }
5206c2bb100SAndreas Gohr
521a424cd8eSchris  return $cache[$name][$skip_group];
522a424cd8eSchris}
523a424cd8eSchris
5246c2bb100SAndreas Gohr/**
525f3f0262cSandi * Create a pronouncable password
526f3f0262cSandi *
52715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
52815fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
52915fae107Sandi *
53015fae107Sandi * @return string  pronouncable password
531f3f0262cSandi */
532f3f0262cSandifunction auth_pwgen(){
533f3f0262cSandi  $pw = '';
534f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
535f3f0262cSandi  $v  = 'aeiou';              //vowels
536f3f0262cSandi  $a  = $c.$v;                //both
537f3f0262cSandi
538f3f0262cSandi  //use two syllables...
539f3f0262cSandi  for($i=0;$i < 2; $i++){
540f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
541f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
542f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
543f3f0262cSandi  }
544f3f0262cSandi  //... and add a nice number
545f3f0262cSandi  $pw .= rand(10,99);
546f3f0262cSandi
547f3f0262cSandi  return $pw;
548f3f0262cSandi}
549f3f0262cSandi
550f3f0262cSandi/**
551f3f0262cSandi * Sends a password to the given user
552f3f0262cSandi *
55315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
55415fae107Sandi *
55515fae107Sandi * @return bool  true on success
556f3f0262cSandi */
557f3f0262cSandifunction auth_sendPassword($user,$password){
558f3f0262cSandi  global $conf;
559f3f0262cSandi  global $lang;
560cd52f92dSchris  global $auth;
561cd52f92dSchris
562f3f0262cSandi  $hdrs  = '';
563cd52f92dSchris  $userinfo = $auth->getUserData($user);
564f3f0262cSandi
56587ddda95Sandi  if(!$userinfo['mail']) return false;
566f3f0262cSandi
567f3f0262cSandi  $text = rawLocale('password');
568ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
56987ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
570f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
571f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
572f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
573f3f0262cSandi
57444f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
57544f669e9Sandi                   $lang['regpwmail'],
57644f669e9Sandi                   $text,
57744f669e9Sandi                   $conf['mailfrom']);
578f3f0262cSandi}
579f3f0262cSandi
580f3f0262cSandi/**
58115fae107Sandi * Register a new user
582f3f0262cSandi *
58315fae107Sandi * This registers a new user - Data is read directly from $_POST
58415fae107Sandi *
58515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
58615fae107Sandi *
58715fae107Sandi * @return bool  true on success, false on any error
588f3f0262cSandi */
589f3f0262cSandifunction register(){
590f3f0262cSandi  global $lang;
591eb5d07e4Sjan  global $conf;
592cd52f92dSchris  global $auth;
593f3f0262cSandi
594f3f0262cSandi  if(!$_POST['save']) return false;
59582fd59b6SAndreas Gohr  if(!$auth->canDo('addUser')) return false;
596640145a5Sandi
597f3f0262cSandi  //clean username
598f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
599f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
600f3f0262cSandi  //clean fullname and email
60154f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
60254f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
603f3f0262cSandi
604f3f0262cSandi  if( empty($_POST['login']) ||
605f3f0262cSandi      empty($_POST['fullname']) ||
606f3f0262cSandi      empty($_POST['email']) ){
607f3f0262cSandi    msg($lang['regmissing'],-1);
608f3f0262cSandi    return false;
609f3f0262cSandi  }
610f3f0262cSandi
611cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
612cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
613cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
614cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
615bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
616cab2716aSmatthias.grimm    return false;
617cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
618bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
619cab2716aSmatthias.grimm    return false;
620cab2716aSmatthias.grimm  } else {
621cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
622cab2716aSmatthias.grimm  }
623cab2716aSmatthias.grimm
624f3f0262cSandi  //check mail
62544f669e9Sandi  if(!mail_isvalid($_POST['email'])){
626f3f0262cSandi    msg($lang['regbadmail'],-1);
627f3f0262cSandi    return false;
628f3f0262cSandi  }
629f3f0262cSandi
630f3f0262cSandi  //okay try to create the user
6311d096a10SAndreas Gohr  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
632f3f0262cSandi    msg($lang['reguexists'],-1);
633f3f0262cSandi    return false;
634f3f0262cSandi  }
635f3f0262cSandi
63602a498e7Schris  // create substitutions for use in notification email
63702a498e7Schris  $substitutions = array(
63802a498e7Schris    'NEWUSER' => $_POST['login'],
63902a498e7Schris    'NEWNAME' => $_POST['fullname'],
64002a498e7Schris    'NEWEMAIL' => $_POST['email'],
64102a498e7Schris  );
64202a498e7Schris
643cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
644cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
64502a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
646cab2716aSmatthias.grimm    return true;
647cab2716aSmatthias.grimm  }
648cab2716aSmatthias.grimm
649cab2716aSmatthias.grimm  // autogenerated password? then send him the password
650f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
651f3f0262cSandi    msg($lang['regsuccess'],1);
65202a498e7Schris    notify('', 'register', '', $_POST['login'], false, $substitutions);
653f3f0262cSandi    return true;
654f3f0262cSandi  }else{
655f3f0262cSandi    msg($lang['regmailfail'],-1);
656f3f0262cSandi    return false;
657f3f0262cSandi  }
658f3f0262cSandi}
659f3f0262cSandi
66010a76f6fSfrank/**
6618b06d178Schris * Update user profile
6628b06d178Schris *
6638b06d178Schris * @author    Christopher Smith <chris@jalakai.co.uk>
6648b06d178Schris */
6658b06d178Schrisfunction updateprofile() {
6668b06d178Schris  global $conf;
6678b06d178Schris  global $INFO;
6688b06d178Schris  global $lang;
669cd52f92dSchris  global $auth;
6708b06d178Schris
671bb4866bdSchris  if(empty($_POST['save'])) return false;
6721b2a85e8SAndreas Gohr  if(!checkSecurityToken()) return false;
6738b06d178Schris
67482fd59b6SAndreas Gohr  // should not be able to get here without Profile being possible...
67582fd59b6SAndreas Gohr  if(!$auth->canDo('Profile')) {
6768b06d178Schris    msg($lang['profna'],-1);
6778b06d178Schris    return false;
6788b06d178Schris  }
6798b06d178Schris
6808b06d178Schris  if ($_POST['newpass'] != $_POST['passchk']) {
6818b06d178Schris    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
6828b06d178Schris    return false;
6838b06d178Schris  }
6848b06d178Schris
6858b06d178Schris  //clean fullname and email
68654f0e6eaSAndreas Gohr  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
68754f0e6eaSAndreas Gohr  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
6888b06d178Schris
6898b06d178Schris  if (empty($_POST['fullname']) || empty($_POST['email'])) {
6908b06d178Schris    msg($lang['profnoempty'],-1);
6918b06d178Schris    return false;
6928b06d178Schris  }
6938b06d178Schris
6948b06d178Schris  if (!mail_isvalid($_POST['email'])){
6958b06d178Schris    msg($lang['regbadmail'],-1);
6968b06d178Schris    return false;
6978b06d178Schris  }
6988b06d178Schris
6994c21b7eeSAndreas Gohr  if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
7004c21b7eeSAndreas Gohr  if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
701cf626a62SAndreas Gohr  if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
7024c21b7eeSAndreas Gohr
7038b06d178Schris
7048b06d178Schris  if (!count($changes)) {
7058b06d178Schris    msg($lang['profnochange'], -1);
7068b06d178Schris    return false;
7078b06d178Schris  }
7088b06d178Schris
7098b06d178Schris  if ($conf['profileconfirm']) {
710df466c7aSAndreas Gohr    if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
7118b06d178Schris      msg($lang['badlogin'],-1);
7128b06d178Schris      return false;
7138b06d178Schris    }
7148b06d178Schris  }
7158b06d178Schris
716cd52f92dSchris  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
7178b06d178Schris}
7188b06d178Schris
7198b06d178Schris/**
7208b06d178Schris * Send a  new password
7218b06d178Schris *
7221d5856cfSAndreas Gohr * This function handles both phases of the password reset:
7231d5856cfSAndreas Gohr *
7241d5856cfSAndreas Gohr *   - handling the first request of password reset
7251d5856cfSAndreas Gohr *   - validating the password reset auth token
7261d5856cfSAndreas Gohr *
7278b06d178Schris * @author Benoit Chesneau <benoit@bchesneau.info>
7288b06d178Schris * @author Chris Smith <chris@jalakai.co.uk>
7291d5856cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7308b06d178Schris *
7318b06d178Schris * @return bool true on success, false on any error
7328b06d178Schris*/
7338b06d178Schrisfunction act_resendpwd(){
7348b06d178Schris    global $lang;
7358b06d178Schris    global $conf;
736cd52f92dSchris    global $auth;
7378b06d178Schris
738409d7af7SAndreas Gohr    if(!actionOK('resendpwd')) return false;
7398b06d178Schris
74082fd59b6SAndreas Gohr    // should not be able to get here without modPass being possible...
74182fd59b6SAndreas Gohr    if(!$auth->canDo('modPass')) {
7428b06d178Schris        msg($lang['resendna'],-1);
7438b06d178Schris        return false;
7448b06d178Schris    }
7458b06d178Schris
7461d5856cfSAndreas Gohr    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
7478b06d178Schris
7481d5856cfSAndreas Gohr    if($token){
7491d5856cfSAndreas Gohr        // we're in token phase
7501d5856cfSAndreas Gohr
7511d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
7521d5856cfSAndreas Gohr        if(!@file_exists($tfile)){
7531d5856cfSAndreas Gohr            msg($lang['resendpwdbadauth'],-1);
7541d5856cfSAndreas Gohr            return false;
7551d5856cfSAndreas Gohr        }
7561d5856cfSAndreas Gohr        $user = io_readfile($tfile);
7571d5856cfSAndreas Gohr        @unlink($tfile);
758cd52f92dSchris        $userinfo = $auth->getUserData($user);
7598b06d178Schris        if(!$userinfo['mail']) {
7608b06d178Schris            msg($lang['resendpwdnouser'], -1);
7618b06d178Schris            return false;
7628b06d178Schris        }
7638b06d178Schris
7648b06d178Schris        $pass = auth_pwgen();
765cd52f92dSchris        if (!$auth->modifyUser($user,array('pass' => $pass))) {
7668b06d178Schris            msg('error modifying user data',-1);
7678b06d178Schris            return false;
7688b06d178Schris        }
7698b06d178Schris
7708b06d178Schris        if (auth_sendPassword($user,$pass)) {
7718b06d178Schris            msg($lang['resendpwdsuccess'],1);
7728b06d178Schris        } else {
7738b06d178Schris            msg($lang['regmailfail'],-1);
7748b06d178Schris        }
7758b06d178Schris        return true;
7761d5856cfSAndreas Gohr
7771d5856cfSAndreas Gohr    } else {
7781d5856cfSAndreas Gohr        // we're in request phase
7791d5856cfSAndreas Gohr
7801d5856cfSAndreas Gohr        if(!$_POST['save']) return false;
7811d5856cfSAndreas Gohr
7821d5856cfSAndreas Gohr        if (empty($_POST['login'])) {
7831d5856cfSAndreas Gohr            msg($lang['resendpwdmissing'], -1);
7841d5856cfSAndreas Gohr            return false;
7851d5856cfSAndreas Gohr        } else {
78616470b1dSchris            $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
78716470b1dSchris            $user = cleanID($_POST['login']);
7881d5856cfSAndreas Gohr        }
7891d5856cfSAndreas Gohr
7901d5856cfSAndreas Gohr        $userinfo = $auth->getUserData($user);
7911d5856cfSAndreas Gohr        if(!$userinfo['mail']) {
7921d5856cfSAndreas Gohr            msg($lang['resendpwdnouser'], -1);
7931d5856cfSAndreas Gohr            return false;
7941d5856cfSAndreas Gohr        }
7951d5856cfSAndreas Gohr
7961d5856cfSAndreas Gohr        // generate auth token
7971d5856cfSAndreas Gohr        $token = md5(auth_cookiesalt().$user); //secret but user based
7981d5856cfSAndreas Gohr        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
7991d5856cfSAndreas Gohr        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
8001d5856cfSAndreas Gohr
8011d5856cfSAndreas Gohr        io_saveFile($tfile,$user);
8021d5856cfSAndreas Gohr
8031d5856cfSAndreas Gohr        $text = rawLocale('pwconfirm');
8041d5856cfSAndreas Gohr        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
8051d5856cfSAndreas Gohr        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
8061d5856cfSAndreas Gohr        $text = str_replace('@LOGIN@',$user,$text);
8071d5856cfSAndreas Gohr        $text = str_replace('@TITLE@',$conf['title'],$text);
8081d5856cfSAndreas Gohr        $text = str_replace('@CONFIRM@',$url,$text);
8091d5856cfSAndreas Gohr
8101d5856cfSAndreas Gohr        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
8111d5856cfSAndreas Gohr                     $lang['regpwmail'],
8121d5856cfSAndreas Gohr                     $text,
8131d5856cfSAndreas Gohr                     $conf['mailfrom'])){
8141d5856cfSAndreas Gohr            msg($lang['resendpwdconfirm'],1);
8151d5856cfSAndreas Gohr        }else{
8161d5856cfSAndreas Gohr            msg($lang['regmailfail'],-1);
8171d5856cfSAndreas Gohr        }
8181d5856cfSAndreas Gohr        return true;
8191d5856cfSAndreas Gohr    }
8201d5856cfSAndreas Gohr
8211d5856cfSAndreas Gohr    return false; // never reached
8228b06d178Schris}
8238b06d178Schris
8248b06d178Schris/**
82510a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
82610a76f6fSfrank *
82710a76f6fSfrank * May not be completly RFC conform!
82810a76f6fSfrank *
82910a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
83010a76f6fSfrank *
83110a76f6fSfrank * @param   string $email the address to check
83210a76f6fSfrank * @return  bool          true if address is valid
83310a76f6fSfrank */
83410a76f6fSfrankfunction isvalidemail($email){
83510a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
83610a76f6fSfrank}
83710a76f6fSfrank
838b0855b11Sandi/**
839b0855b11Sandi * Encrypts a password using the given method and salt
840b0855b11Sandi *
841b0855b11Sandi * If the selected method needs a salt and none was given, a random one
842b0855b11Sandi * is chosen.
843b0855b11Sandi *
844b0855b11Sandi * The following methods are understood:
845b0855b11Sandi *
846b0855b11Sandi *   smd5  - Salted MD5 hashing
847b0855b11Sandi *   md5   - Simple MD5 hashing
848b0855b11Sandi *   sha1  - SHA1 hashing
849b0855b11Sandi *   ssha  - Salted SHA1 hashing
850d7be6245Sandi *   crypt - Unix crypt
851d7be6245Sandi *   mysql - MySQL password (old method)
852d7be6245Sandi *   my411 - MySQL 4.1.1 password
853b0855b11Sandi *
854b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
855b0855b11Sandi * @return  string  The crypted password
856b0855b11Sandi */
857b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
858b0855b11Sandi  global $conf;
859b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
86010a76f6fSfrank
861b0855b11Sandi  //prepare a salt
862b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
863b0855b11Sandi
864b0855b11Sandi  switch(strtolower($method)){
865b0855b11Sandi    case 'smd5':
866b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
867b0855b11Sandi    case 'md5':
868b0855b11Sandi      return md5($clear);
869b0855b11Sandi    case 'sha1':
870b0855b11Sandi      return sha1($clear);
871b0855b11Sandi    case 'ssha':
872b0855b11Sandi      $salt=substr($salt,0,4);
873d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
874b0855b11Sandi    case 'crypt':
875b0855b11Sandi      return crypt($clear,substr($salt,0,2));
876d7be6245Sandi    case 'mysql':
877d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
878d7be6245Sandi      $nr=0x50305735;
879d7be6245Sandi      $nr2=0x12345671;
880d7be6245Sandi      $add=7;
881d7be6245Sandi      $charArr = preg_split("//", $clear);
882d7be6245Sandi      foreach ($charArr as $char) {
883d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
884d7be6245Sandi        $charVal = ord($char);
885d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
886d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
887d7be6245Sandi        $add += $charVal;
888d7be6245Sandi      }
889d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
890d7be6245Sandi    case 'my411':
891d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
892b0855b11Sandi    default:
893b0855b11Sandi      msg("Unsupported crypt method $method",-1);
894b0855b11Sandi  }
895b0855b11Sandi}
896b0855b11Sandi
897b0855b11Sandi/**
898b0855b11Sandi * Verifies a cleartext password against a crypted hash
899b0855b11Sandi *
900b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
901b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
902b0855b11Sandi * match true is is returned else false
903b0855b11Sandi *
904b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
905b0855b11Sandi * @return  bool
906b0855b11Sandi */
907b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
908b0855b11Sandi  $method='';
909b0855b11Sandi  $salt='';
910b0855b11Sandi
911b0855b11Sandi  //determine the used method and salt
912d7be6245Sandi  $len = strlen($crypt);
913b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
914b0855b11Sandi    $method = 'smd5';
915b0855b11Sandi    $salt   = substr($crypt,3,8);
916b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
917b0855b11Sandi    $method = 'ssha';
918b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
919d7be6245Sandi  }elseif($len == 32){
920b0855b11Sandi    $method = 'md5';
921d7be6245Sandi  }elseif($len == 40){
922b0855b11Sandi    $method = 'sha1';
923d7be6245Sandi  }elseif($len == 16){
924d7be6245Sandi    $method = 'mysql';
925d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
926d7be6245Sandi    $method = 'my411';
927b0855b11Sandi  }else{
928b0855b11Sandi    $method = 'crypt';
929b0855b11Sandi    $salt   = substr($crypt,0,2);
930b0855b11Sandi  }
931b0855b11Sandi
932b0855b11Sandi  //crypt and compare
933b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
934b0855b11Sandi    return true;
935b0855b11Sandi  }
936b0855b11Sandi  return false;
937b0855b11Sandi}
938340756e4Sandi
939340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
940