<?php
/****************************************************************************************
SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV

Version 0.9.9

Copyright (C) 2006-2009  Sylvain FATOME
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; 
either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program
(in the directory docs); 
if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 
Boston, MA  02110-1301, USA.

Contact : galawa@free.fr

Web : http://smitst.homelinux.com
****************************************************************************************/

session_start(); 

// Détection de l'OS du serveur
$windows = 0;
$unix = 0;
$os = getenv('OS');
if (empty($os))
{ 
	$os = php_uname();
}
if(empty($os))
{
	$os ="-"; $unix=1;
}
else
{
	if (@eregi("^win",$os))
		$windows = 1; 
	else
		$unix = 1;
}

// On vérifie si prm.inc.php a bien été créé
if (!file_exists("inc/prm.inc.php"))
{
	if (file_exists("./install/install.php"))
		header("Location: ./install/install.php");
	else
	{
		exit("Fichier prm.inc.php non créé.<br><br>Impossible de trouver le script d'installation.<br><br>Merci de procéder manuellement à l'installation.");
	}
}
else
{
	include_once("inc/config.inc.php");
	include_once("inc/func_lng.inc.php");
	if (isset($_GET['lng']))
		$lng_appli = setlng(@$_GET['lng'],TRUE);
	if (isset($_POST['lng']))
		$lng_appli = setlng(@$_POST['lng'],TRUE);
	include_once("lng/".$lng_appli.".inc.php"); // Fichier de language
	if (($admin_code=="") OR ($admin_mdp=="") OR (DBUSER=="") OR (DBPASS=="") OR (DBHOST==""))
	{
		if (file_exists("./install/install.php"))
			header("Location: ./install/install.php");
		else
			exit("SMI n'a manifestement pas été installé.<br><br>Impossible de trouver le script d'installation.<br><br>Merci de procéder manuellement à l'installation.");
	}
}

// Fileperms ne fonctionne correctement que sous Unix/Linux
if ($unix==1)
{
	// On vérifie que les droits le répertoire inc sont ok
	$droits=substr(sprintf('%o', fileperms("./inc")), -4);
	if (($droits=="0775") OR ($droits=="0757") OR ($droits=="0777"))
	{
		exit("Les droits sur le répertoire inc ne sont pas corrects (".$droits."). Merci de ne pas utiliser '0775', '0757', ou '0777'.");
	}

	// On vérifie que les droits sur prm.inc.php sont ok
	$droits=substr(sprintf('%o', fileperms("./inc/prm.inc.php")), -4);
	if ($droits!="0644")
	{
		exit("Les droits sur le fichier prm.inc.php ne sont pas corrects (actuellement : ".$droits.").<br><br>Merci de corriger en '0644'.");
	}
}

// On vérifie que le répertoire install a bien été renommé  
if (is_dir("./install"))
{
	exit("Vous n'avez pas renommé le répertoire 'install'.<br><br>Impossible de lancer le logiciel.<br><br>Merci de corriger.");
}

// Tout est ok...on démarre
include_once("inc/func_log.inc.php");
include_once("inc/func_txt.inc.php");

// Archivage du log	
Archivelog(@$_SESSION["code_log"]);

$log_ip = $_SERVER['REMOTE_ADDR']; // Récupération adresse IP

// Vérifie si l'administrateur a été créé (si non, il est créé)
$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
mysql_select_db(DBNAME);
$rech = "SELECT * FROM `" .TBPW. "` WHERE `pw_code` = '" .$admin_code. "'";
$rs = mysql_query($rech) or die(mysql_error());
if (mysql_num_rows($rs) == 0)
{
	$pass = md5($admin_mdp); // Cryptage du mot de passe administrateur
	
	$rech2 = "INSERT INTO " .TBPW;
	$rech2 .= " (pw_code,pw_pass,pw_level,pw_lastsuccess,pw_lastip,pw_actif) VALUES";
	$rech2 .= " ('$admin_code','$pass','9','$dateheurea','$log_ip','1')";
	$rs2 = mysql_query($rech2) or die(mysql_error());
}
// On crée le répertoire imports pour l'administrateur et le siège
// Si le sous-répertoire spécifique aux imports n'existe pas, on le crée
$tab_gfc=explode("/",eregi_replace($root,"",$url_gfc));
$chemin=substr($root,0,strlen($root));
foreach ($tab_gfc as $idx=>$value)
{
	$chemin=$chemin."/".$value;
	if (!is_dir($chemin))
		$result=@mkdir($chemin);
}
$rep = $url_gfc."/imports";
if (!is_dir($rep))
{
	$cree_rep=@mkdir($rep);
	if ($cree_rep)
	{
		$desc = "Répertoire pour imports administrateur & centre de gestion";
		$detail = "Répertoire pour stockers les fichiers à importer administrateur et centre de gestion.";
		$rech2 = "INSERT INTO " .TBFIC;
		$rech2 .= " (fic_nom,fic_type,fic_desc,fic_detail,fic_datecrea,fic_codecrea,fic_nbtel) VALUES";
		$rech2 .= " ('$rep','0','$desc','$detail','$datea','$admin_code','')";
		$rs2 = mysql_query($rech2) or die(mysql_error());
	}
}

// On crée le répertoire pièce jointes pour l'administrateur et le siège
// Si le sous-répertoire spécifique aux pièces n'existe pas, on le crée
$rep = $url_gfc."/pj";
if (!is_dir($rep))
{
	$cree_rep=@mkdir($rep);
	if ($cree_rep)
	{
		$desc = "Répertoire pour pièces jointes administrateur & centre de gestion";
		$detail = "Répertoire pour stockers les pièces jointes administrateur et centre de gestion.";
		$rech2 = "INSERT INTO " .TBFIC;
		$rech2 .= " (fic_nom,fic_type,fic_desc,fic_detail,fic_datecrea,fic_codecrea,fic_nbtel) VALUES";
		$rech2 .= " ('$rep','0','$desc','$detail','$datea','$admin_code','0')";
		$rs2 = mysql_query($rech2) or die(mysql_error());
	}
}
mysql_free_result($rs);
mysql_close($conn);

$validpwd = False;
$desactive = False;

// Formulaire validé
if (@$_POST["submit"] == html_entity_decode($but_cnx))
{	
	// Récupération Variables Formulaire
	$con_code = str_escape(strip_tags(trim(@$_POST["con_code"])));
	$con_pass = md5(str_escape(strip_tags(trim(@$_POST["con_pass"]))));
	
	if (!$validpwd) 
	{	
		// Contrôle du mot de passe
		$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
		mysql_select_db(DBNAME);
		$rech = "SELECT * FROM `" .TBPW. "` WHERE `pw_code` = '" .$con_code. "'";
		$rs = mysql_query($rech) or die(mysql_error());
		if (mysql_num_rows($rs) == 1) // Il ne peut y avoir qu'un seul résultat
		{
			if ($row = mysql_fetch_array($rs))
			{
				extract ($row);
				if ($con_code == $pw_code) // Le code entré doit correspondre exactement au code stocké (majuscules/minuscules)
				{
					if ($pw_pass == $con_pass) // Le mot de passe doit correspondre exactement
					{
						if ($pw_actif == 1) // Le compte doit être actif
						{
							$_SESSION["lng"] = strtolower($pw_lng);
							$_SESSION["etat_log"] = "connecte";
							$_SESSION["niv_log"] = $pw_level;
							$_SESSION["code_log"] = $con_code;
							// Codes session complémentaires
							switch ($pw_level)
							{
								// Code agence
								case 4 :
									$_SESSION["code_age"] = $con_code;
									break;
								// Code technicien agence
								case 3 :
									$rech2 = "SELECT tec_codeage FROM `" .TBTEC. "` WHERE `tec_code` = '".$con_code."'";
									$rs2 = mysql_query($rech2) or die(mysql_error());
									if ($row2 = mysql_fetch_array($rs2))
									{
										extract ($row2);
										$_SESSION["code_age"] = $tec_codeage;
									}
									break;
								// Code donneur d'ordres
								case 6 :
									$_SESSION["code_do"] = $con_code;
									break;
								// Code technicien donneur d'ordres
								case 7 :
									$rech2 = "SELECT tec_codedo FROM `" .TBTEC. "` WHERE `tec_code` = '".$con_code."'";
									$rs2 = mysql_query($rech2) or die(mysql_error());
									if ($row2 = mysql_fetch_array($rs2))
									{
										extract ($row2);
										$_SESSION["code_do"] = $tec_codedo;
									}
									break;
								// Code Sous-traitant
								case 10 :
									$_SESSION["code_st"] = $con_code;
									break;
								// Code technicien sous-traitant
								case 11 :
									$rech2 = "SELECT tec_codest FROM `" .TBTEC. "` WHERE `tec_code` = '".$con_code."'";
									$rs2 = mysql_query($rech2) or die(mysql_error());
									if ($row2 = mysql_fetch_array($rs2))
									{
										extract ($row2);
										$_SESSION["code_st"] = $tec_codest;
									}
									break;
							}
							$rech2 = "UPDATE `" .TBPW. "` SET `pw_lastsuccess`='" .$dateheurea.  "', `pw_lastip`='" .$log_ip. "' WHERE `pw_id`='" .$pw_id. "'";
							$rs2 = mysql_query($rech2) or die(mysql_error());
							$validpwd = True;
						}
						else
							$desactive=TRUE;
					}
				}
			}
		}
		mysql_free_result($rs);
		mysql_close($conn);
	}
} 

if ($validpwd) 
{
	if (@$_SESSION["etat_log"] == "connecte")
	{
		switch (@$_SESSION["niv_log"])
		{
			case 1 :
				header("Location: ".$rep_appli."/cli/index.php");
				break;
			case 2 : 
				header("Location: ".$rep_appli."/ope/index.php?tl=1");
				break;
			case 3 : 
				header("Location: ".$rep_appli."/age/index.php");
				break;
			case 4 : 
				header("Location: ".$rep_appli."/age/index.php");
				break;
			case 5 : 
				header("Location: ".$rep_appli."/admin/index.php");
				break;
			case 6 : 
				header("Location: ".$rep_appli."/do/index.php");
				break;
			case 7 : 
				header("Location: ".$rep_appli."/do/index.php");
				break;
			case 9 :
				header("Location: ".$rep_appli."/admin/index.php");
				 break;
			case 10 : 
				header("Location: ".$rep_appli."/st/index.php");
				break;
			case 11 : 
				header("Location: ".$rep_appli."/st/index.php");
				break;
					 
			default :
				header("Location: index.php");
				break;
		}
	}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<NOSCRIPT>
<meta http-equiv="refresh" content="0;URL=<?PHP echo $rep_appli; ?>/nojs.php">
</NOSCRIPT>
<title>SMI : <?PHP echo $title_esp_prive; ?></title>

<!-- Feuille de style pour les affichages -->
<link href="css/smi.css" rel="stylesheet" type="text/css">

<script language="JavaScript" src="jscript/divers.js"></script>

<script language="JavaScript" src="jscript/fen.js"></script>

</head>

<body onLoad="testres();metFocus();">

<table width="100%" height="300" border="0" cellspacing="0" cellpadding="0">
<tr>
	<td width="150" valign="top">&nbsp;</td>
	<td width="10">&nbsp;</td>
	<td valign="top">
		<form name="con" action="index.php" method="post" >
		<input type="hidden" name="lng" id="lng" value="<?PHP echo $lng_appli; ?>">
			<div align="center">
			<p><img src="img/logo.gif" alt="logo SMI"></p>
			<p><img src="img/login.png" alt="connexion"></p>
			<p class="annot_std_it"><?PHP echo $cnx_warnlog; ?></p>
		  </div>
			<table width="366" border="0" align="center">
			<tr bgcolor="#FF0000">
				<td colspan="2" align="center" class="titre_std_gras_jaune_frouge"><strong><?PHP echo $cnx_title; ?></strong></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td>&nbsp;</td>
			</tr>
			<tr>
				<td width="50%" align="right" class="rubfrm"><?PHP echo $cnx_login; ?></td>
				<td>
				<input name="con_code" type="text" id="con_code" size="26" maxlength="20">
				</td>
			</tr>
			<tr>
				<td align="right" class="rubfrm"><?PHP echo $cnx_pwd; ?></td>
				<td>
				<input name="con_pass" type="password" id="con_pass" size="26" maxlength="20">
				</td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td>&nbsp;</td>
			</tr>
			</table>
			<p align="center">
			<input name="RAZ" type="reset" class="bton_std" id="RAZ" value="<?PHP echo $but_reinit; ?>">
			<input type="submit" class="bton_std" name="submit" value="<?PHP echo $but_cnx; ?>">
			</p>
			<p align="center"><a href="pass.php"><?PHP echo $cnx_lostpwd; ?></a></p>
		</form>
		<?php if ($validpwd == 0) 
			{
				if ($desactive == FALSE)
				{
					if (@$_POST["submit"] == html_entity_decode($but_cnx)) 
					{
		?>
		
					<p align="center"><font color="#FF0000"><font size="-1"><strong><?PHP echo $cnx_badlogin; ?></strong></font></font></p>
		
		<?php
					} 
				}
				else
				{
		?>
				<p align="center"><font color="#FF0000"><font size="-1"><strong><?PHP $cnx_comptedes; ?></strong></font></font></p>
				<?php
				}
				
			} 
		?>
		<br /><br /><br />
		<p align="center"><a href="http://smitst.homelinux.com"><span  class="annot_petit_it">S.M.I. (Services Maintenance Interventions) <?PHP echo str_replace("S.M.I. ","",$smiver); ?></span></a></p>
		<div align="center">
		<br /><br /><br /><br /><br />
		<span class="annot_petit_it"><?PHP echo $cnx_suppprojsmi; ?></span><br/>
		<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
		<input type="hidden" name="cmd" value="_s-xclick" />
		<input type="image" src="https://www.paypal.com/fr_FR/i/btn/x-click-but04.gif" style="border:none" name="submit" alt="<?PHP echo $suppdevsmi; ?>" />
		<img alt="" border="0" src="https://www.paypal.com/fr_FR/i/scr/pixel.gif" width="1" height="1" />
		<input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----MIIHwQYJKoZIhvcNAQcEoIIHsjCCB64CAQExggEwMIIBLAIBADCBlDCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJKoZIhvcNAQEBBQAEgYA+bPlwzK4PQGK+qTgPhHFCisGZMTU2/wUb9MRU4kZs7obkuxsW+/i4ZDV9j0R/aiPYKn576MgxNqeTY26S/utP4uiQhqzWt+ojbNefSc8PRLkzFWspl7TTSt9HTfCO38nczcgeJAZBJlVPPaPPpLbuSMzgC43Nj2jjxalMM6GN8jELMAkGBSsOAwIaBQAwggE9BgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcECEathV399G3dgIIBGNAI3i1y8CGHnc/rQmjmL+PNDFLqSJPuZwunP2MkKAYZoVC8NMavAPJM/WX9x+KmthjbaNlo40TF1Z4jyZ4BgVOpYQzKs9SV3irW28sl5lyZ59VdbUMivg5kmRHgHA9TAhAOCee9on9RCVRCPq77SdHoij3S2/wn6uurd9Rg2sOMVQ6Wr94cCuqZrumJhTIwz/1TOHO8RMkFjgRbcskeDFHUzWsvW1X9ybM2oBYp3WNhOJo7/NGPs94HeO8I0MehpUZj7d45ixmTeGoDpQOIuuHhBiNiNsd3CHTeSiMMjS1YSVqHvuVV7A7c6gS+5oN6WrA1eBiDzZbMUaRuLcCB4+zYPyDNV3B5C6Gdar9L6J8ChB6S1SxJgHegggOHMIIDgzCCAuygAwIBAgIBADANBgkqhkiG9w0BAQUF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2TWbQYDwcp129OPIbD9epdr4tJOUNiSojw7BHwYRiPh58S1xGlFgHFXwrEBb3dgNbMUa+u4qectsMAXpVHnD9wIyfmHMYIBmjCCAZYCAQEwgZQwgY4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLUGF5UGFsIEluYy4xEzARBgNVBAsUCmxpdmVfY2VydHMxETAPBgNVBAMUCGxpdmVfYXBpMRwwGgYJKoZIhvcNAQkBFg1yZUBwYXlwYWwuY29tAgEAMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wNzAyMTAxNTE4MTFaMCMGCSqGSIb3DQEJBDEWBBQ2gsiM0qr9ue1+IYVbq5lA7AZuQjANBgkqhkiG9w0BAQEFAASBgG7mF7lp4YjXQw2Z4psmCmX3rzV3XfucM5TaqgcW+fV4wduWHR7lu8BFmbWOCrHGFZP9+1LxZA7I4XruJX6V7rMs2IC2aCqngfaTz75ARVfHcx33c7oKcBvPHtpA2koCf8DVRlWIjepakB3uyYukbDuhmkpJBgoptGrLKtwIxtVG-----END PKCS7-----
		" />
		</form>
		</div>
	</td>
	<td width="10">&nbsp;</td>
    <td width="250" valign="top">&nbsp;</td>
</tr>
</table>
</body>
</html>
