<?
########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####

$sMaxLifeLime = 1800;

if(!defined('SESSIONS_INC')){

  define('USERTYPE_ADMIN', 1);
  define('USERTYPE_RESELLER', 2);
  define('USERTYPE_USER', 3);
  define('USERTYPE_POPUSER', 4);
  define('USERTYPE_FTPUSER', 5);

  function sessao_start(){
	session_name('SID');
	if(isset($_GET['SID']) && $_GET['SID'] != ''){
            session_id($_GET['SID']);
	}
	session_start();
	if(!session_is_registered('_error'))
	{
		session_register('_error');
		$_SESSION['_error'] = false;
	}
  }

  function sessao_open($aSavaPath, $aSessionName){
	//global $aTime;
	session_log("sessao_open: $aSavaPath, $aSessionName");
	sessao_gc($GLOBALS['sMaxLifeLime']);
	return True;
  }

  function sessao_close(){
	session_log("sessao_close");
	return True;
  }

  function sessao_read( $sKey ){
		$loKey = new SQLString( $sKey );
		$query = "SELECT sdata FROM sessions WHERE id=?";
		session_log("sessao_read: $query ($sKey)");
		$id = safe_query2( $query, $loKey);

		if( db_num_rows( $id ) == 1 ){
			$r = db_fetch_array($id);
			return $r['sdata'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
			$loIP = new  SQLString( $ip );
		//if ($_SERVER['HTTP_X_FORWARDED_FOR'])
		//{
		//	$ip .= '::' . $_SERVER['HTTP_X_FORWARDED_FOR'];
		//}
			$t = time();
			$users = '';
			if( is_array( $_SESSION['_users'] ) ) {
				$users = implode(',', array_keys($_SESSION['_users']));
			}
			$loUsers = new SQLString( $users );

		//$user = $_SESSION['admin_user']?$_SESSION['admin_user']:$GLOBALS['PHP_AUTH_USER'];
			global $db_type;
			if($db_type=='mysql'){    
				$query = "INSERT INTO sessions (id, startdate, lastupdate, sdata, user, ip) ";
			}else{
				$query = "INSERT INTO sessions (id, startdate, lastupdate, sdata, \"user\", ip) ";
			}
			$query .="VALUES ( ?, $t, $t, '', ?, ?)";
			session_log( "sessao_read: $query ( $sKey, $users, $ip )" );
			safe_query2( $query, $loKey, $loUsers, $loIP );
			return '';
		}
  }

  function sessao_write( $sKey, $sVal ) {

		$loKey = new SQLString( $sKey );
		$loVal = new SQLString( $sVal );
		$sVal = addslashes( $sVal );
		
		$users = '';
		if (isset($_SESSION) 
				&& array_key_exists('_users', $_SESSION) && is_array($_SESSION['_users'])){
			$users = implode(',', array_keys($_SESSION['_users']));
		}
		$loUsers = new SQLString( $users );
		global $db_type;
		$query = "UPDATE sessions SET sdata = ?, lastupdate = " . time();
		if($db_type=='mysql'){    
			$query .= ", user = ? WHERE id = ?";
		} else {
			$query .=  ", \"user\" = ? WHERE id = ?";
		}
		session_log("sessao_write: $query ( $sVal, $users, $sKey )");
		safe_query2( $query, $loVal, $loUsers, $loKey );
		return True;
  }

  function sessao_destroy( $sKey ) {
		$loKey = new SQLString( $sKey );

		$query = "DELETE FROM sessions WHERE id = ?";
		session_log("sessao_destroy: $query ( $sKey )");
		safe_query2( $query, $loKey );
		return True;
  }

  function sessao_gc( $sMaxLifeTime ) {
		$query = "DELETE FROM sessions WHERE " . time() . " - lastupdate > $sMaxLifeTime";
		session_log("sessao_gc: $query");
		db_query($query);
		return True;
  }

  function session_log($data) {
		return; //no log
		$fname = ini_get('upload_tmp_dir')	. '/session_log';
		$data = $_SERVER['PHP_SELF'] . "# $data\n\n";
		if ( $fp = fopen( $fname, 'a' ) ) {
			fwrite( $fp, $data);
			fclose( $fp );
		}
  }

  function addSUser($user, $pass, $type)
  {
	if(!session_is_registered('_users'))
	{
		session_register('_users');
	}
	$_SESSION['_users'][$user] = array('password' => $pass, 'type' => $type);
  }

  function isSUserLogged($user)
  {
	if(is_array($_SESSION['_users']))
	{
		if(array_key_exists($user, $_SESSION['_users']))
		{
			//return $_SESSION['_users'][$user]['type'];
			return getUserParam($user, 'type');
		}
	}
	return false;
  }

  function deleteSUser($user)
  {
	unset($_SESSION['_users'][$user]);
	if(session_is_registered('_del_settings'))
	{
		unset($_SESSION['_del_settings'][$user]);
	}
  }

  function setUserParam($user, $param, $value)
  {
	if(array_key_exists('_users', $_SESSION) && array_key_exists($user, $_SESSION['_users']))
	{
		$_SESSION['_users'][$user][$param] = $value;
	}
  }

  function getUserParam($user, $param)
  {
	if(isUserParamExists($user, $param))
	{
		return $_SESSION['_users'][$user][$param];
	}
	return false;
  }

  function delUserParam($user, $param)
  {
	if(isUserParamExists($user, $param))
	{
		unset($_SESSION['_users'][$user][$param]);	
	}	
  }

  function isUserParamExists($user, $param)
  {
	return array_key_exists('_users', $_SESSION) && array_key_exists($user, $_SESSION['_users']) && array_key_exists($param, $_SESSION['_users'][$user]);
  }

  function setPwdFromForgot($user, $pass, $type)
  {
	$pwd = addslashes(crypt_pw($pass));
	switch ($type)
	{
		case USERTYPE_ADMIN:
			db_query("UPDATE admin SET longpw='$pwd'");
		break;
		
		case USERTYPE_RESELLER:
			db_query("UPDATE anbieter SET longpw='$pwd' WHERE anbieter='" . addslashes($user) . "'");
		break;
		
		case USERTYPE_USER:
			db_query("UPDATE kunden SET longpw='$pwd' WHERE kunde='" . addslashes($user) . "'");
		break;	
	}
  }

  function clearForgotPwd($user)
  {
	global $db_type;
	if($db_type=='mysql'){    
	  db_query("DELETE FROM pwdreminder WHERE user='" . addslashes($user) . "'");
	}else{
	  db_query("DELETE FROM pwdreminder WHERE \"user\"='" . addslashes($user) . "'");
	}
  }

  function checkCryptPwd($pw, $dbpw)
  {
	return (crypt($pw, $dbpw) == $dbpw);
  }

  function checkForgotPwd($user, $pass)
  {
    global $db_type;
		$loUser = new SQLString( $user );
		$loPass = new SQLString( $pass );
		if($db_type=='mysql'){
  	  $sql="SELECT usertype FROM pwdreminder WHERE user=" ;
		}else{
  	  $sql="SELECT usertype FROM pwdreminder WHERE \"user\"=" ;
		}  
		$sql .= '? AND password=?';	
		$id = safe_query2( $sql, $loUser, $loPass ); 

		if( db_num_rows( $id ) ) {
			$werte = db_fetch_array($id);
			setPwdFromForgot($user, $pass, $werte['usertype']);
			return $werte['usertype'];
		}
		return false;
  }

  function checkPwd($pass, $sql)
  {
	$id = db_query($sql);
	if(db_num_rows($id))
	{
		$werte = db_fetch_array($id);
		return checkCryptPwd($pass, $werte['longpw']);
	}
	return false;
  }

  function checkAdminLogin($user, $pass)
  {
	$sql = "SELECT longpw FROM admin WHERE login = '" . addslashes($user) . "'";
	return checkPwd($pass, $sql);
  }

  function checkResellerLogin($user, $pass)
  {
	$sql = "SELECT longpw FROM anbieter WHERE gesperrt = 0 AND anbieter = '" . addslashes($user) . "'";
	if ( checkPwd($pass, $sql) )
		return true;
	$sql = "SELECT admin.longpw FROM admin, anbieter WHERE anbieter.gesperrt = 0 AND anbieter = '" .
		addslashes($user) . "'";
	return checkPwd($pass, $sql);
  }

  	// the real login name of user is returned in $user 
	function checkUserLogin(&$user, $pass)
	{
		// the code below allows end-users to login using 
		// their domain names as login name
		if (preg_match('/\./', $user)) { 
			// if a domain name specified ...
			$res = safe_query("SELECT kunde FROM domains WHERE domain = ?", TRUE, new SQLString($user));
			if (db_num_rows($res)) {
				$row = db_fetch_array($res);
				$user = $row['kunde'];
			}
		}

		$sql = "SELECT longpw FROM kunden WHERE gesperrt = 0 AND kunde = '" . addslashes($user) . "'";
		if ( checkPwd($pass, $sql) ) {
			return true;
		}

		$sql = "SELECT anbieter.longpw FROM kunden, anbieter WHERE kunden.kunde = '" . addslashes($user) .
		"' AND kunden.anbieter = anbieter.anbieter AND kunden.gesperrt = 0 AND anbieter.gesperrt = 0";
		if ( checkPwd($pass,$sql) ) {
			return true;
		}

		$sql = "SELECT admin.longpw FROM admin, kunden WHERE kunden.gesperrt = 0 AND kunde = '" . addslashes($user) . "'";
		if ( checkPwd($pass,$sql) ) {
			return true;
		}

		return false;
	}

  function checkFtpLogin($user, $pass)
  {
	$sql = "SELECT longpw FROM ftp WHERE gesperrt = 0 AND account = '" . addslashes($user) . "'";
	return checkPwd($pass, $sql);
  }

  	// the real login name of user is returned in $user 
  function checkPopLogin(&$user, $pass)
  {
	// the code below makes pop3-users able to login 
	// using their email addresses as login names
	if(preg_match('/^[\w.-]+\@(?:[\w-]+\.)+\w+$/', $user))
	{
		$email = explode('@', $user);
		$id = db_query("SELECT pop3 FROM email WHERE prefix = '" . addslashes($email[0]) . "' AND domain = '" . addslashes($email[1]) . "'");
		if(db_num_rows($id))
		{
			$res = db_fetch_array($id);
			$user = $res['pop3'];
		}
	}
	$sql = "SELECT longpw FROM pop3 WHERE gesperrt = 0 AND account = '" . addslashes($user) . "'";
	return checkPwd($pass, $sql);
  }

function getAdminAccountInfo($user = NULL) { 
	// if no argument set - return admin info
	$id = ($user !== NULL)
	? safe_query2("SELECT login, longpw FROM admin WHERE login=?", $user)
	: safe_query2("SELECT login, longpw FROM admin");
	
	if (!db_num_rows($id))
		return false;
	$row = db_fetch_array($id);
	$info = array(
		'type' => USERTYPE_ADMIN, 
		'login' => $row['login'], 
		'longpw' => $row['longpw'], 
		'locked' => false 
	);
	return $info;
}

function getResellerAccountInfo($user) { 
	$id = safe_query2("SELECT anbieter, longpw, gesperrt, emailadresse FROM anbieter WHERE anbieter=?", 
		$user);
	if (!db_num_rows($id))
		return false;
	$row = db_fetch_array($id);
	$info = array(
		'type' => USERTYPE_RESELLER, 
		'login' => $row['anbieter'], 
		'longpw' => $row['longpw'], 
		'locked' => $row['gesperrt'],
		'email' => $row['emailadresse']
	);
	return $info;
}

function getUserAccountInfo($user) {
	$id = safe_query2("SELECT kunde, longpw, gesperrt, anbieter, emailadresse, webftp, webmail FROM kunden WHERE kunde=?", 
		$user);
	if (!db_num_rows($id))
		return false;
	$row = db_fetch_array($id);
	$info = array(
		'type' => USERTYPE_USER, 
		'login' => $row['kunde'], 
		'longpw' => $row['longpw'], 
		'reseller' => $row['anbieter'],
		'locked' => $row['gesperrt'],
		'email' => $row['emailadresse'],
		'webftp' => $row['webftp'],
		'webmail' => $row['webmail']
	);

	// lock regular ftp user if webftp is off
 	if(array_key_exists('_cat', $_POST) && $_POST['_cat'] == 'ftp' && !$info['webftp'])
 		$info['locked'] = 1;
 	                 	
	// "lock" users of a locked reseller
	$res_info = getResellerAccountInfo($info['reseller']);
	if ($res_info['locked']) 
		$info['locked'] = 1;
		
	return $info;
}

function getFtpUserAccountInfo($user) { 
	$id = safe_query2("SELECT account, longpw, gesperrt, kunde FROM ftp WHERE account = ?", 
		$user);
	if (!db_num_rows($id))
		return false;
	$row = db_fetch_array($id);
	$info = array(
		'type' => USERTYPE_FTPUSER, 
		'login' => $row['account'], 
		'longpw' => $row['longpw'], 
		'locked' => $row['gesperrt'],
		'user' => $row['kunde']
	);

	// "lock" ftp user of a locked user and if webftp is off
	$user_info = getUserAccountInfo($info['user']);
	if ($user_info['locked'] || !$user_info['webftp']) 
		$info['locked'] = 1;
		
	return $info;
}

function getPop3UserAccountInfo($user) {
	
	// provide ability of loging under email@domain.tld login names
	if(preg_match('/^[\w.-]+\@(?:[\w-]+\.)+\w+$/', $user))
	{
		list($userpart, $domain) = explode('@', $user);
		$id = safe_query2("SELECT pop3, pop3x FROM email WHERE prefix = ? AND domain = ?",
			$userpart, $domain);
		if(db_num_rows($id))
		{
			$res = db_fetch_array($id);
			if($res['pop3x']) return false;			
			$user = $res['pop3'];
		}
	}
	
	$id = safe_query2("SELECT account, longpw, gesperrt, kunde FROM pop3 WHERE account = ?",
		$user);
	if (!db_num_rows($id))
		return false;
	$row = db_fetch_array($id);
	$info = array(
		'type' => USERTYPE_POPUSER, 
		'login' => $row['account'], 
		'longpw' => $row['longpw'], 
		'locked' => $row['gesperrt'],
		'user' => $row['kunde']
	);
	
	// "lock" pop3 user of a locked user and if webmail is off
	$user_info = getUserAccountInfo($info['user']);
	if ($user_info['locked'] || !$user_info['webmail'])
		$info['locked'] = 1;
		
	return $info;
}

/**
 * Check if the user login is correct.
 * arg: 	$user 	the login name entered
 * arg: 	$pass	the password entered
 
 * return:  array('type' => ?, 'login' => ?, 'longpw' => ?, 'locked' => ?) or false
 */
 
function checkLogin($user)
{
	if (!$user)
		return false; // do not allow empty username
		
	$info = array();
	if ($info = getAdminAccountInfo($user)) { // assingment in 'if'
		return $info;
	}
	if ($info = getResellerAccountInfo($user)) { // assingment in 'if'
		return $info;
	}
	if ($info = getUserAccountInfo($user)) { // assingment in 'if'
		return $info;
	}
	if ($info = getFtpUserAccountInfo($user)) { // assingment in 'if'
		return $info;
	}
	if ($info = getPop3UserAccountInfo($user)) { // assingment in 'if'
		return $info;
	}
	return false;
}

/**
 * Check if the user authorisation is correct.
 * arg: 	$account_info 	the account info array
 * arg: 	$pass			the password entered
 
 * return:  bool
 */
 
function checkPassword($account_info, $pass)
{
	
	if (!$account_info)
		return false; // no user found
	
	// check regular password
	$is_correct_passwd = false;
	switch($account_info['type']) {
	case USERTYPE_ADMIN:
		$is_correct_passwd = (bool)(checkCryptPwd($pass, $account_info['longpw']));
		break;
	case USERTYPE_RESELLER:
		$admin_account_info = getAdminAccountInfo();
		$is_correct_passwd = (bool)(
			checkCryptPwd($pass, $account_info['longpw']) ||
			checkCryptPwd($pass, $admin_account_info['longpw'])
		);
		break;
	case USERTYPE_USER:
		$admin_account_info = getAdminAccountInfo();
		$reseller_account_info = getResellerAccountInfo($account_info['reseller']);		
		if(array_key_exists('_cat', $_POST) && $_POST['_cat'] == 'ftp')
			$is_correct_passwd = (bool)(checkCryptPwd($pass, $account_info['longpw']));
		else
			$is_correct_passwd = (bool)(
				checkCryptPwd($pass, $account_info['longpw']) ||
				checkCryptPwd($pass, $reseller_account_info['longpw']) ||
				checkCryptPwd($pass, $admin_account_info['longpw'])
			);
		break;
	case USERTYPE_FTPUSER:
	case USERTYPE_POPUSER:	
		$is_correct_passwd = (bool)(checkCryptPwd($pass, $account_info['longpw']));
		break;
	default:
		log_debug_message('Session module: unknown account type when login checking');
		return false;	// unknown user type
	}
	
	// check temporary passwords
	if ($is_correct_passwd || checkForgotPwd($account_info['login'], $pass)) {
		return true;	// user has temporary password generated
	}
	
	return false;
}

  function checkIPMask($ip, $mask)
  {
	$mask = str_replace('*', '\d{1,3}', $mask);
	$mask = '/' . str_replace('.', '\\.', $mask) . '/';
	return preg_match($mask, $ip);
  }

  function checkIPRest($ip)
  {
	$ret = true;
	$id = db_query('SELECT ip FROM iprestriction WHERE rest=\'deny\'');
	while($res = db_fetch_array($id))
	{
		if(checkIPMask($ip, $res['ip']))
		{
			$ret = false;
			break;
		}
	}
	
	$id = db_query('SELECT ip FROM iprestriction WHERE rest=\'accept\'');
	while($res = db_fetch_array($id))
	{
		if(checkIPMask($ip, $res['ip']))
		{
			$ret = true;
			break;
		}
	}

	return $ret;
  }

  session_set_save_handler("sessao_open", "sessao_close", "sessao_read", "sessao_write", "sessao_destroy", "sessao_gc");
  define('SESSIONS_INC', 1);
}


?>
