<?php
ob_start();
if(!(is_readable(realpath(dirname(__FILE__))."/include/includesroutines.inc"))) {
    die("Error - Could not open or read file ".realpath(dirname(__FILE__))."/include/includesroutines.inc");
} else {
    include_once(realpath(dirname(__FILE__))."/include/includesroutines.inc");
}

if(!(is_readable(realpath(dirname(__FILE__))."/include/bsservice.inc"))) {
    die("Error - Could not open or read file ".realpath(dirname(__FILE__))."/include/bsservice.inc");
} else {
    include_once(realpath(dirname(__FILE__))."/include/bsservice.inc");
}

if(!(is_readable(realpath(dirname(__FILE__))."/classes/AES.class.php"))) {
    die("Error - Could not open or read file ".realpath(dirname(__FILE__))."/classes/AES.class.php");
} else {
    include_once(realpath(dirname(__FILE__))."/classes/AES.class.php");
}

if(!(is_readable(realpath(dirname(__FILE__))."/classes/AESCipher.class.php"))) {
    die("Error - Could not open or read file ".realpath(dirname(__FILE__))."/classes/AESCipher.class.php");
} else {
    include_once(realpath(dirname(__FILE__))."/classes/AESCipher.class.php");
}

checkLanguage();

if ( getSetting('portal','useRights', 0) == 1 ){
	if( IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/personal.php");
		ob_end_flush();
		exit;
	}
} else {
	if (isset($_COOKIE['mobilemode']) && $_COOKIE['mobilemode'] == 1) {
		header("Location: ".getCurPageURLWO()."/mnavigator.php");
	} else {
		header("Location: ".getCurPageURLWO()."/businessmodel.php");
	}
	ob_end_flush();
	exit;
}


function addpadding($string, $blocksize = 32)
{
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad), $pad);
    return $string;
}

function strippadding($string)
{
    $slast = ord(substr($string, -1));
    $slastc = chr($slast);
    $pcheck = substr($string, -$slast);
    if(preg_match("/$slastc{".$slast."}/", $string)){
        $string = substr($string, 0, strlen($string)-$slast);
        return $string;
    } else {
        return false;
    }
}


$cn = db_connect();
$userlang = '';
$contentlang = '';
$servicemsg = '';

function trylogin($cn, $result){
	logOut();
	$res = false;
    if ( strlen(trim($result)) > 0) {
		$xml = simplexml_load_string($result);
		$elem = $xml->xpath('//login');
  		$elem = $elem[0];

	    global $servicemsg;
		$msg = $elem->xpath('//message');
		$sz = sizeof($msg);
		if ($sz > 0){
		 	$servicemsg = $msg[0][0];
		}

		if (strlen($elem["login"])>0 && $elem["auth"] == 1) {
			if (isset($_REQUEST['remember'])){
				$cookieshash = $elem->xpath('//cookieshash');
				setCookieHash(encrypt($cookieshash[0][0]));
			} 

			$ticket = $elem->xpath('//authticket');
			$sz = sizeof($ticket);
			if ($sz > 0){
			 	setAuthTicket(''.$ticket[0][0]);
			} else {
				setAuthTicket("");
			}

			$uhashfakexml = $elem->xpath('//uhashfake');
			$uhashfake = '';
			$sz = sizeof($uhashfakexml);
			if ($sz > 0){
				$uhashfake = ''.$uhashfakexml[0][0];
			}

			$bsuhashxml = $elem->xpath('//bsuhash');
			$bsuhash = '';
			$sz = sizeof($bsuhashxml);
			if ($sz > 0){
				$bsuhash = ''.$bsuhashxml[0][0];
			}

			$elem = $elem->xpath('//uhash');
			$sz = sizeof($elem);
			if ($sz > 0){
				$user_ids = array();

				for($i=0; $i<$sz; $i++) {
					if ($i==0) {
						$user = db_getUserDataByHash($cn,$elem[$i]);
						$uid = (is_array($user) ? $user['iduser'] : NULL);
					}else{
						$uid = db_getUserIDByHash($cn,$elem[$i]);
					}
					if($uid) {
						array_push($user_ids, $uid);
					}
				}
				if (is_array($user)){
					$GLOBALS['userlang'] = db_getLanguageShortByID($cn, $user['user_idlanguageinterface'], true);
					$GLOBALS['contentlang'] = db_getLanguageShortByID($cn, $user['user_idlanguagecontent']);
					$user_name = db_getUserNameByID($cn, $uid, $user['user_idlanguagecontent']); // 59865
					if ($user['user_isactive'] == 1) {
						Login($user_ids, (($user['user_isadmin'] == 1) ? true : false), $GLOBALS['userlang'], $GLOBALS['contentlang'], $uhashfake, $bsuhash, $user_name );
						$res = true;
					} else {
						$user_ids = array();
						$res = false;
					}
				} else {
					$user_ids = array();
					$res = false;
				}
	        }
	        unset($xml);
	        unset($elem);
		}
	}
	return $res;
}

$ticket = getAuthTicket();
$cookieshash = (isset($_COOKIE['uhash']) && strlen($_COOKIE['uhash']) > 0 ? $_COOKIE['uhash'] : '');

// try to get SSPI authorization on client
if (getSetting('portal','useSSPIAuth', 0) == 1 && !isset($_SESSION['sspi_loginfailed'])) {
	if (isset($_REQUEST['token']) && trim($_REQUEST['token']) != '' && isset($_SESSION['sspi_key']) && trim($_SESSION['sspi_key']) == trim($_REQUEST['token']) && trim($_SESSION['sspi_user']) != ''  ){
		$cryptsspiuser = encrypt($_SESSION['sspi_user']);
		$result = sendSSPIAuthCall($cn, $ticket, $cryptsspiuser);
		if (!$result) {
		 	$url = getCurPageURLWO()."/bsserviceerror.php";
			header("Location: ".$url);
			ob_end_flush();
			exit;
		}
		if (trylogin($cn, decrypt($result))){
			unset($_SESSION['sspi_loginfailed']);
			if ( isset($_REQUEST['returl'])){
				header("Location: ".getPageDencodeParams($_REQUEST['returl']));
				ob_end_flush();
				exit;
			} else {
				header("Location: ".getCurPageURLWO()."/personal.php");
				ob_end_flush();
				exit;
			}
		} else {
			$_SESSION['sspi_loginfailed'] = true;
		}
	}
}

// Пробуем авторизоваться автоматом если ранее установили "запомнить"
if ( strlen($cookieshash) > 0 ) {
	$result = sendAuthCall($cn, $cookieshash,  $ticket);
	if (!$result) {
	 	$url = getCurPageURLWO()."/bsserviceerror.php";
		header("Location: ".$url);
		ob_end_flush();
		exit;
	}

	if (trylogin($cn,decrypt($result))){
		if ( isset($_REQUEST['returl'])){
			header("Location: ".getPageDencodeParams($_REQUEST['returl']));
			ob_end_flush();
			exit;
		} else {
			header("Location: ".getCurPageURLWO()."/personal.php");
			ob_end_flush();
			exit;
		}
	}
}

if (isset($_REQUEST['login']) && isset($_REQUEST['userlogin']) && trim($_REQUEST['userlogin']) != ''){

	$cryplogin = encrypt($_REQUEST['userlogin']);
	$cryppassword = (isset($_REQUEST['password']) && trim($_REQUEST['password']) != '' ? encrypt($_REQUEST['password']) : '');
	$result = sendAuthCall($cn, $cookieshash, $ticket, $cryplogin, $cryppassword);
	if (!$result) {
	 	$url = getCurPageURLWO()."/bsserviceerror.php";
		header("Location: ".$url);
		ob_end_flush();
		exit;
	}
	if (trylogin($cn, decrypt($result))){
		if ( isset($_REQUEST['returl'])){
			header("Location: ".getPageDencodeParams($_REQUEST['returl']));
			ob_end_flush();
			exit;
		} else {
			header("Location: ".getCurPageURLWO()."/personal.php");
			ob_end_flush();
			exit;
		}
	}
}

?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	renderCommonCSS(); 
	?>
    <script src="js/libs/jquery-1.8.0.min.js"></script>
	<script>
		parent.postMessage('reload','*');
	</script>
</head>
<body id="page-login">

<div id="container">

	<div id="header">
		<div id="header-h2">Business Studio Portal</div>
	</div>

	<div id="main" role="main">

		<div id="box-login">
			<form action="" method="post" class="clearfix" onsubmit="document.getElementById('loginbtn').disabled=true;">
					 <input type="hidden" name="login" value="true">
					<label for="text-username"><?php getResource('field.login');?></label><input type="text" id="text-username" name="userlogin"/>
					<label for="text-password"><?php getResource('field.password');?></label><input type="password" id="text-password" name="password"/>
					<label>&nbsp;</label><input type="checkbox" id="checkbox-remember" name="remember"/><label for="checkbox-remember" id="checkbox-remember-label"><?php getResource('field.rememberMe');?></label>

					<button name="loginbtn" id="loginbtn" class="btn-main" title="<?php getResource('button.login');?>"><span><?php getResource('button.login');?></span></button>
			</form>
<?php if (isset($_REQUEST['login']) && isset($_REQUEST['userlogin']) && isset($_REQUEST['password']) && !IsUserLogin()) { ?>
			<div id="user-login-error">
				<?php if(strlen($servicemsg)>0) { echo $servicemsg; } else { getResource("message.worngLogin");} ?>
			</div>
			<div id="user-login-copyright-error">
<?php } else { ?>
			<div id="user-login-copyright">
<?php }?>
				&copy;&nbsp;<?php echo str_replace("[YYYY]", date("Y"), returnResource("copyright")) /* 67563 */;?>
			</div>

		</div>

	</div>

</div>
<?php renderFooterTemplate(); ?>
<?php if ( getSetting('portal','useSSPIAuth', 0) == 1 && !isset($_REQUEST['sspiauth']) && !isset($_SESSION['sspi_loginfailed'])){ ?>
<script>
	$(document).ready(function(){
		$('#container').hide();
		$.ajax({
            type: "POST",
            url: "<?php  echo getCurPageURLWO();?>/sspi/",
            dataType: 'text',
            success: function (response) {
				if (response.trim().length > 0) {
            		  <?
						          if (!$_SERVER["QUERY_STRING"]){
							          echo 'var url = \''.getCurPageURL().'?token=\' + response;';
						          }else{
							          echo 'var url = \''.getCurPageURL().'&token=\' + response;';
                  }
                  ?>
              // var url = '<?php echo getCurPageURL();?>&token=' + response;//STU Иначе не срабатывает возвращение по ссылки при включеной SSPI
            		window.location.href = url;
            	}
  			},
            statusCode: {
            	400:function() {
      				$('#container').show();
      			},
      			500:function() {
      				$('#container').show();
      			},
      			401:function() {
      				$('#container').show();
      			}
      		}
        });
	});
</script>
<?php } ?>
</body>
</html>

<?php
db_disconnect($cn);
ob_end_flush();
?>



