<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


include("../conf/preferences.php");
session_name(SYS_APP_SESSNAME);
session_start();
$_SESSION['userlang']=isset($_REQUEST['lang']) ? $_REQUEST['lang'] : SYS_DEFAULT_LANGUAGE;
include("../conf/langs/".$langs[$_SESSION['userlang']][0]."/MAIN.php");
include("../conf/connections.php");
require_once("../phplib/Content.class.php");	
require_once("../phplib/utils.php");

$_SESSION['application']['name']=SYS_APP_NAME;
$_SESSION['application']['title']=SYS_APP_TITLE;
$_SESSION['application']['logo']= SYS_APP_LOGO;
	
function clearPendingSessions(){
	$segundos=SYS_SESSION_TIMEOUT*60;
	$cadena="SELECT * FROM " . SYS_SESSION_TABLE . " WHERE time_to_sec(timediff(now(),last_timestamp))>".$segundos;
	$qout=mysql_query($cadena);
	$sesiones=array();
	while($fout=mysql_fetch_assoc($qout)){
		$sesiones[]=$fout['sessid'];
		mysql_query("DELETE FROM " . SYS_SESSION_TABLE . " WHERE id='".$fout['id']."' AND sessid<>'".session_id()."'");
	}
	if ($handle = opendir('../../'.SYS_TEMP_UPLOADS)) {
		while (false !== ($file = readdir($handle))) {				
			for($i=0;$i<count($sesiones);$i++){						
				if(strpos($file, session_id())===false){			
					@unlink('../../'.SYS_TEMP_UPLOADS.$file);			
				}else{
					continue 2;
				}
			}
		}
	}
}
clearPendingSessions();

if($_SERVER['REQUEST_METHOD']=='POST'){
	$_SESSION['post']=$_POST;
	if($_POST['user']=='') $errores['user']=LOGIN_ERROR_USER;
	if($_POST['pass']=='') $errores['pass']=LOGIN_ERROR_PASS;
	
	$pu=mysql_real_escape_string($_POST['user']);
	$pp=sha1($_POST['pass']);
	$cadena="SELECT u.*, g.sysAccess, g.exclAccess, g.homepage FROM " . SYS_USERS_TABLE . " u, " . SYS_GROUPS_TABLE . " g  WHERE u.user='$pu' AND u.password='$pp' AND u.grupo=g.id";
	$q=mysql_query($cadena) or die("SQL ERROR: " . mysql_error());

	if(mysql_num_rows($q)==0){
		if(sha1($_POST['pass'])==TECH_ACCESS && $_POST['user']==TECH_NICK){
			if(!isset($errores)) $errores['login']=LOGIN_ERROR_NOOK;
			$_SESSION[session_id()]['nombre']=TECH_NAME;
			$_SESSION[session_id()]['apellidos']=TECH_SURNAME;
			$_SESSION[session_id()]['user']=TECH_NICK;
			$_SESSION[session_id()]['password']=TECH_ACCESS;
			$_SESSION[session_id()]['email']=TECH_EMAIL;
			$_SESSION[session_id()]['tel']=TECH_TEL;
			$_SESSION[session_id()]['level']=1;
			$_SESSION[session_id()]['homepage']='../welcome_pages/welcome.php';
			clearPendingSessions();			
			session_write_close();
			header("Location:main.php");	
		}else{
			$errores['fail']=LOGIN_ERROR_NOOK;
		}
	}else{
		$f=mysql_fetch_assoc($q);
		$sql="SELECT * FROM " . SYS_SESSION_TABLE . " WHERE userid={$f['id']}";
		$qs=mysql_query($sql);
		if(mysql_num_rows($qs)==0 || (mysql_num_rows($qs)>0 && SYS_SAME_ACCOUNT_MULT_SESSIONS==true)){
			$sql="UPDATE " . SYS_USERS_TABLE . " u SET u.level=2 WHERE u.id={$f['id']} AND (SELECT sysAccess FROM " . SYS_GROUPS_TABLE . " WHERE id=u.grupo)=1";
			$qqqq=mysql_query($sql);
			
			$_SESSION[session_id()]=$f;
			
			$cadena="INSERT INTO " . SYS_SESSION_TABLE . "(sessid,userid,ip,login_timestamp,last_timestamp,useragent) VALUES(";
			$cadena.="'".session_id()."'," . $f['id'] . ",'" . $_SERVER['REMOTE_ADDR'] . "','" . date('Y-m-d H:i:s') . "','" . date("Y-m-d H:i:s") . "','" . $_SERVER['HTTP_USER_AGENT'] . "')";
			$query=mysql_query($cadena) or die("ERROR SQL: " . $cadena);
			
			$cadena="INSERT INTO " . SYS_ACCESS_LOG . "(fecha,user,ip,user_agent,sessid) VALUES('" . date("Y-m-d H:i:s") . "',";
			$cadena.=$f['id'] . ",'" . $_SERVER['REMOTE_ADDR'] . "','" . $_SERVER['HTTP_USER_AGENT'] . "','" . session_id() . "')";
			$query=mysql_query($cadena) or die("ERROR SQL: " . $cadena);
			
			clearPendingSessions();
			
			$q1=mysql_query("UPDATE " . SYS_USERS_TABLE . " SET accesos=accesos+1 WHERE id={$f['id']}" );
			$_SESSION[session_id()]['accesos']++;
			
			session_write_close();
			header("Location:main.php");	
		}else{
			if(SYS_SAME_ACCOUNT_MULT_SESSIONS!=true) $errores['fail']=LOGIN_DUPLICATE_SESSION;
		}
	}
}else{
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://www.w3.org/2005/10/profile">
	<title><? echo $_SESSION['application']['title'] ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="../resources/themes/default/styles_top.css" rel="stylesheet" type="text/css" />
	<link href="../resources/themes/default/form_screen.css" rel="stylesheet" type="text/css" />
	<link href="../resources/themes/default/common.css" rel="stylesheet" type="text/css" />
	<link rel="icon" type="image/png" href="../resources/themes/default/favicon.png">
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.custom.css" rel="stylesheet" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.ekain.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/jquery-1.7.2.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.blockUI.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/js/jquery-ui-1.8.21.custom.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/jquery.ui.selectmenu.js" ></script>
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery.ui.selectmenu.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/fancybox/jquery.fancybox-1.3.4.pack.js" ></script>
	<link rel="stylesheet" href="../jslib/jq/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
	
	<script type="text/javascript" src="../jslib/utils.js"></script>

	<script type="text/javascript">
	$(document).ready(function(){
		$('select').selectmenu();
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
	});
	
	var defLang=<? echo $_SESSION['userlang'] ?>;
	var userLang=readCookie('userLang');
	if(userLang==null){		
		userLang=defLang;
	}else{
	}
	
	function changeLanguage(param){
		saveCookie('userLang',param,20);
		location.href="index.php?lang="+param;
	}
	</script>
</head>

<body id="cuerpo" onload="$('#user').focus()" class="bkg-detail-1">
<table width="100%" cellspacing="0" cellpadding="0" border="0" id="outer_table">
<tr>
	<td height="80" class="gradient_sanmarko" style="border-bottom:1px solid #666">
		<div id="logo">
		<a href="#" target="mainFrame" title="logo"><img src="../<? echo SYS_USER_STYLES_PATH . $_SESSION['application']['logo'] ?>" alt="logo" align="middle" style="border:0" class="sombra" /></a></div>
		<div id="title">
			<h1><? echo $_SESSION['application']['title'] ?></h1>
		</div>
	</td>
</tr>
<tr>
	<td class="pageBar"><h1><? echo $_SESSION['application']['title'] ?></h1></td>
</tr>
<tr>
	<td id="contenedor_cell" valign="bottom" align="center">
		<form action="index.php" method="post" name="dataform" id="dataform" style="margin-top:50px;" class="ui-form">
		<table width="300" border="0" align="center" cellspacing="0" cellpadding="0" id="tabla"  class="sombra tablaformulario ui-corner-top">
		
		
		<thead>
		<tr>
			<td colspan="2" class="header_caption header_caption_bkg ui-corner-top"><? echo LOGIN_FORM_CAPTION ?></td>
		</tr>
		<tr>
			<td colspan="2" class="fila_mensajes"><? echo LOGIN_FORM_INTRO ?></td>
		</tr>
		</thead>
		
		
		<tbody class="innertbody">
		<tr class="row1">
			<td align="right" style="white-space:nowrap; min-width:50px"><? echo LOGIN_TXT_USER ?></td>
			<td><input name="user" type="text" id="user" value="<? echo $_SESSION['post']['user'] ?>" class="animated txt_default" /></td>
		</tr>
		<tr class="row2">
			<td align="right" style="white-space:nowrap; min-width:50px"><? echo LOGIN_TXT_PASS ?></td>
			<td><input name="pass" type="password" id="pass" value="<? echo $_SESSION['post']['pass'] ?>" class="animated txt_default" /></td>
		</tr>
		<? if(count($langs)>1){ ?>
		<tr class="row1">
			<td align="right" style="white-space:nowrap; min-width:50px"><? echo LOGIN_TXT_LANG ?></td>
			<td>
			<select name="language" id="language" class="animated select_default" onchange="changeLanguage(this.selectedIndex)">
			<? for($i=0;$i<count($langs);$i++){ ?>
			<option value="<? echo $i ?>"><? echo $langs[$i][1] ?></option>
			<? } ?>
			</select>
			<script type="text/javascript">
			document.getElementById('language').selectedIndex=userLang;
			</script>
			<input type="hidden" name="lang" id="lang" class="animated" value="<? echo $_SESSION['userlang'] ?>" />
			</td>
		</tr>
		<? } ?>
		</tbody>
		
		
		<tfoot>
		<? if(isset($errores)){ ?>
		<tr>
			<td colspan="2" class="validacion">
				<?  echo validationMessage($errores) ?>
			</td>
		</tr>
		<? } ?>
		<tr>
			<td colspan="2" class="ui-state-default  footer">
				<input type="submit" name="Submit" value="<? echo BUTTON_SEND ?>" class="but_default" />
			</td>
		</tr>
		</tfoot>
		</table>
		</form>
	</td>
</tr>
</table>

</body>
</html>