<?php 
require_once("../../base/php/startSession.php");
require_once("../../base/php//classDatabase.php");
require_once("../../base/php/Functions.php");
require_once("../../base/php/WebAppLog.php");

global $database;
global $finess;
global $in_file;
global $in_importFileDate;
global $temp_files_array;
global $tmp_path;

set_time_limit(3600);
ini_set('memory_limit','256M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '128M');


$importFile = @$_POST["importFile"];
if ($importFile == "") {
	$importFile = @$_GET["importFile"];
}
$in_importFileDate = @$_POST["importFileDate"];
if ($in_importFileDate == "") {
	$in_importFileDate = @$_GET["importFileDate"];
}


initializeDir();


$tmp_path = "../../../temp";
$uploadfile = $tmp_path . "/" . $importFile;


$returnCode = "OK";
$returnTexte = "";
$temp_files_array = array();

$database = new Database("iCTI");

$in_file = basename($_FILES['Filedata']['name']);

if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadfile)) {

} 
else {
	$returnTexte = "Le fichier $importFile n'a pas été téléchargé. Erreur système";
	$returnCode = "KO";
}

// controle fichier
if ($returnCode == "OK") {
	
	// Special Vitalia (tout dans un fichier)
	if (strtoupper(substr($importFile,-8,8)) == ".CTI.ZIP") {
		vitalia_control_zipfile($uploadfile, $ZIP_finess, $ZIP_annee, $ZIP_mois, $ZIP_pmsitype, $ZIP_filesize, $ZIP_filedate, $ZIP_error);
		
		if ($ZIP_error != "") {
			$returnTexte = "Le fichier $importFile n'a pas été téléchargé. $ZIP_error";
			$returnCode = "KO";
		}
	
	}
	else {
		// IN.ZIP ou OUT.ZIP
		if (strtoupper(substr($importFile,-4,4)) == ".ZIP") {
			control_zipfile($uploadfile, $ZIP_finess, $ZIP_annee, $ZIP_mois, $ZIP_pmsitype, $ZIP_filesize, $ZIP_filedate, $ZIP_error);
			
			if ($ZIP_error != "") {
				$returnTexte = "Le fichier $importFile n'a pas été téléchargé. $ZIP_error";
				$returnCode = "KO";
			}
		
		}
		// Fichiers texte
		else {
			control_txtfile($uploadfile, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype, $TXT_filesize, $TXT_filedate, $TXT_error);
			
			if ($TXT_error != "") {
				$returnTexte = "Le fichier $importFile n'a pas été téléchargé. $TXT_error";
				$returnCode = "KO";
			}
		}
	}
}




$httpString = "";
$httpString = $httpString . "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
$httpString = $httpString . "\n<HTTP_SERVICE returnCode=\"$returnCode\" returnTexte=\"$returnTexte\" >";
$httpString = $httpString . "\n</HTTP_SERVICE>";
 

$httpString = gzcompress($httpString,9);
$httpString = "_c_" . base64_encode($httpString); 

//echo "<CTICONTENT>$httpString</CTICONTENT>";
echo "$httpString";




function vitalia_control_zipfile($ZIP_filepath, &$ZIP_finess, &$ZIP_annee, &$ZIP_mois, &$ZIP_pmsitype, &$ZIP_filesize, &$ZIP_filedate, &$ZIP_error) {
	
	global $finess;
	global $typeEts;
	global $in_importFileDate;
	global $tmp_path;
	
	$ZIP_finess = "";
	$ZIP_annee = "";
	$ZIP_mois = "";
	$ZIP_pmsitype = "";
	$ZIP_filesize = 0;
	$ZIP_filedate = 0;
	$ZIP_error = "";
	
	
	if (! file_exists($ZIP_filepath)) {
		return;
	}
	
	$ZIP_filesize = filesize($ZIP_filepath);
	$ZIP_filedate = filemtime($ZIP_filepath);
	$ZIP_filedate = $in_importFileDate;
	
	$ZIP_archive = new ZipArchive();
	if ($ZIP_archive) {
	
		@$ZIP_archive->open($ZIP_filepath);
		
		
		if ($ZIP_archive->numFiles > 0) {
			for ($i=0; $i<$ZIP_archive->numFiles;$i++) {
				$ZIP_entry = $ZIP_archive->statIndex($i);
				
				$ZIP_in_filename = trim($ZIP_entry["name"]);
				$ZIP_in_filesize = $ZIP_filesize;
				$ZIP_in_filedate = floatval($ZIP_entry["mtime"]);
				
				$ZIP_in_file = $tmp_path . "/" . $ZIP_in_filename;

				// Fichiers in
				if (stripos($ZIP_in_filename,".zip") > 0) {
					@file_put_contents($ZIP_in_file, $ZIP_archive->getFromIndex($i));
					control_zipfile($ZIP_in_file, $ZIP_finess, $ZIP_annee, $ZIP_mois, $ZIP_pmsitype_cti, $ZIP_filesize, $ZIP_filedate, $ZIP_error);
					if ($ZIP_pmsitype_cti != "") {
						$ZIP_pmsitype = $ZIP_pmsitype_cti;
					}
				}
				
				// RSS
				if (stripos($ZIP_in_filename,".rss") > 0) {
					@file_put_contents($ZIP_in_file, $ZIP_archive->getFromIndex($i));
					control_txtfile($ZIP_in_file, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype_cti, $TXT_filesize, $TXT_filedate, $TXT_error);
					if ($TXT_pmsitype_cti != "") {
						$ZIP_pmsitype = $TXT_pmsitype_cti;
					}
				}
				
				
				// RSF
				if (stripos($ZIP_in_filename,".rsf") > 0) {
					@file_put_contents($ZIP_in_file, $ZIP_archive->getFromIndex($i));
					control_txtfile($ZIP_in_file, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype_cti, $TXT_filesize, $TXT_filedate, $TXT_error);
					if ($TXT_pmsitype_cti != "") {
						$ZIP_pmsitype = $TXT_pmsitype_cti;
					}
				}
				
				// Fichiers données complémentaires
				if (stripos($ZIP_in_filename,".xml") > 0) {
					@file_put_contents($ZIP_in_file, $ZIP_archive->getFromIndex($i));
					vitalia_convertDc($ZIP_in_file);
				}
			}

		}
		else {
			$ZIP_error = "Décompression impossible";
		}
		
		
		@$ZIP_archive->close();

	}
	else {
		$ZIP_error = "Décompression impossible";
	}
	
	
	
	
	
	
	if ($ZIP_error == "") {
		if ($ZIP_pmsitype == "") {
			$ZIP_error = "Données non PMSI (ni RSS, ni RSF)";
		}
	}
	

}



function control_zipfile($ZIP_filepath, &$ZIP_finess, &$ZIP_annee, &$ZIP_mois, &$ZIP_pmsitype, &$ZIP_filesize, &$ZIP_filedate, &$ZIP_error) {
	
	global $finess;
	global $typeEts;
	global $in_importFileDate;
	
	$ZIP_finess = "";
	$ZIP_annee = "";
	$ZIP_mois = "";
	$ZIP_pmsitype = "";
	$ZIP_filesize = 0;
	$ZIP_filedate = 0;
	$ZIP_error = "";
	
	
	if (! file_exists($ZIP_filepath)) {
		return;
	}
	
	$ZIP_filesize = filesize($ZIP_filepath);
	$ZIP_filedate = filemtime($ZIP_filepath);
	$ZIP_filedate = $in_importFileDate;
	
	$ZIP_archive = new ZipArchive();
	if ($ZIP_archive) {
	
		@$ZIP_archive->open($ZIP_filepath);
		
		
		if ($ZIP_archive->numFiles > 0) {
			for ($i=0; $i<$ZIP_archive->numFiles;$i++) {
				$ZIP_entry = $ZIP_archive->statIndex($i);
				
				$ZIP_in_filename = trim($ZIP_entry["name"]);
				$ZIP_in_filesize = $ZIP_filesize;
				$ZIP_in_filedate = floatval($ZIP_entry["mtime"]);

				
				if (stripos($ZIP_in_filename,".rss") > 0) {
					$ZIP_pmsitype = "ZIN";
					$array = explode(".", $ZIP_in_filename);
					$ZIP_finess = trim($array[0]);
					if (strlen(trim($array[2])) < 2) {
						$array[2] = "0" . trim($array[2]);
					}
					$ZIP_annee = trim($array[1]);
					$ZIP_mois = trim($array[1]) . trim($array[2]);
					$ZIP_filedate = $ZIP_in_filedate;
					$ZIP_filesize = $ZIP_in_filesize;
				}
			}
			
			if ($ZIP_pmsitype == "") {
				for ($i=0; $i<$ZIP_archive->numFiles;$i++) {
					$ZIP_entry = $ZIP_archive->statIndex($i);
					
					$ZIP_in_filename = trim($ZIP_entry["name"]);
					$ZIP_in_filesize = $ZIP_filesize;
					$ZIP_in_filedate = floatval($ZIP_entry["mtime"]);

					if (stripos($ZIP_in_filename,".sign") > 0) {
						if (stripos($ZIP_filepath,".SEJOURS") > 0) {
							$ZIP_pmsitype = "DRUIDE_SEJ";
						}
						if (stripos($ZIP_filepath,".RSFACE") > 0) {
							$ZIP_pmsitype = "DRUIDE_ACE";
						}
						if (stripos($ZIP_filepath,".RSFOQN") > 0) {
							$ZIP_pmsitype = "DRUIDE_OQN";
						}
						$array = explode(".", $ZIP_in_filename);
						$ZIP_finess = trim($array[0]);
						if (strlen(trim($array[2])) < 2) {
							$array[2] = "0" . trim($array[2]);
						}
						$ZIP_annee = trim($array[1]);
						$ZIP_mois = trim($array[1]) . trim($array[2]);
						$ZIP_filedate = $ZIP_in_filedate;
						$ZIP_filesize = $ZIP_in_filesize;
					}
					if (stripos($ZIP_in_filename,".rsa") > 0) {
						$ZIP_pmsitype = "ZOU";
						$array = explode(".", $ZIP_in_filename);
						$ZIP_finess = trim($array[0]);
						if (strlen(trim($array[2])) < 2) {
							$array[2] = "0" . trim($array[2]);
						}
						$ZIP_annee = trim($array[1]);
						$ZIP_mois = trim($array[1]) . trim($array[2]);
						$ZIP_filedate = $ZIP_in_filedate;
						$ZIP_filesize = $ZIP_in_filesize;
					}
					if ((stripos($ZIP_in_filename,".rsf.txt") > 0 || stripos($ZIP_in_filename,".rsf.ini.txt") > 0 )&& $ZIP_pmsitype != "ZOU") {
						$ZIP_pmsitype = "ZIF";
						$array = explode(".", $ZIP_in_filename);
						$ZIP_finess = trim($array[0]);
						if (strlen(trim($array[2])) < 2) {
							$array[2] = "0" . trim($array[2]);
						}
						$ZIP_annee = trim($array[1]);
						$ZIP_mois = trim($array[1]) . trim($array[2]);
						$ZIP_filedate = $ZIP_in_filedate;
						$ZIP_filesize = $ZIP_in_filesize;
					}
					if (stripos($ZIP_in_filename,".rsfa") > 0 && $ZIP_pmsitype != "ZOU" && $ZIP_pmsitype != "DRUIDE_ACE") {
						$ZIP_pmsitype = "ZOF";
						$array = explode(".", $ZIP_in_filename);
						$ZIP_finess = trim($array[0]);
						if (strlen(trim($array[2])) < 2) {
							$array[2] = "0" . trim($array[2]);
						}
						$ZIP_annee = trim($array[1]);
						$ZIP_mois = trim($array[1]) . trim($array[2]);
						$ZIP_filedate = $ZIP_in_filedate;
						$ZIP_filesize = $ZIP_in_filesize;
					}
				}
			}
			
			
	
	
		}
		else {
			$ZIP_error = "Décompression impossible";
		}
		
		
		
		@$ZIP_archive->close();
		
		
		
		// Si pas trouvé (norme standard, essayer de trouver selon le contenu)
		if ($ZIP_pmsitype == "") {

			@$ZIP_archive->open($ZIP_filepath);
			
			$ZIP_rss_index = -1;
			$ZIP_rsf_index = -1;
			
			for ($i=0; $i<$ZIP_archive->numFiles;$i++) {
				$ZIP_entry = $ZIP_archive->statIndex($i);
				

				$ZIP_in_filename = trim($ZIP_entry["name"]);
				$ZIP_in_filesize = $ZIP_filesize;
				$ZIP_in_filedate = floatval($ZIP_entry["mtime"]);
			
				$ZIP_in_buffer_handle = $ZIP_archive->getStream($ZIP_in_filename);
				
				$ZIP_pmsisubtype = "";
				
				if ($ZIP_in_buffer_handle) {

					$ZIP_in_buffer = fgets($ZIP_in_buffer_handle,100000);
					
					$no_ligne = 0;
				
					while (!feof($ZIP_in_buffer_handle)) {
						$buffer = fgets($ZIP_in_buffer_handle, 99999);
						
						$no_ligne++;
						if (trim($buffer) != "" && $no_ligne < 1000000000000 ) {
							if ($ZIP_pmsisubtype == "") {
								if (substr($buffer, 15 , 9) == $finess) {
									$ZIP_pmsitype = "ZIN";
									$ZIP_pmsisubtype = "RSS";
									$ZIP_finess = $finess;
									$ZIP_annee = "";
									$ZIP_mois = "";
									$ZIP_filedate = $ZIP_in_filedate;
									$ZIP_filesize = $ZIP_in_filesize;
									$ZIP_rss_index = $i;
								}
							}
							
							if ($ZIP_pmsisubtype == "") {
								if (substr($buffer, 0 , 1) == "A" && substr($buffer, 1 , 9) == $finess) {
									$ZIP_pmsitype = "ZIN";
									$ZIP_pmsisubtype = "RSF";
									$ZIP_finess = $finess;
									$ZIP_annee = "";
									$ZIP_mois = "";
									$ZIP_filedate = $ZIP_in_filedate;
									$ZIP_filesize = $ZIP_in_filesize;
									$ZIP_rsf_index = $i;
								}
							}
							
							if ($ZIP_pmsisubtype == "RSS") {
								if (floatval(substr($buffer, 106, 4)) >= 2000 && floatval(substr($buffer, 106, 4)) < 2020) {
									$mois = substr($buffer, 106, 4) . substr($buffer, 104, 2);
									if ($mois > $ZIP_mois) {
										$ZIP_mois = $mois;
									}
								}
							}
							
							if ($ZIP_pmsisubtype == "RSF") {
								if (substr($buffer, 0, 1) == "A") {
								if (floatval(substr($buffer, 89, 4)) >= 2000 && floatval(substr($buffer, 89, 4)) < 2020) {
									$mois = substr($buffer, 89, 4) . substr($buffer, 87, 2);
									if ($mois > $ZIP_mois) {
										$ZIP_mois = $mois;
									}
								}
								}
							}

						}
					
					}
					fclose($ZIP_in_buffer_handle);
				}

			}
			
			if ($ZIP_rss_index >= 0) {
				$ZIP_entry = $ZIP_archive->statIndex($ZIP_rss_index);
				$ZIP_mois_Y = substr($ZIP_mois,0,4);
				$ZIP_mois_m = substr($ZIP_mois,4,2);
				$ZIP_in_name = trim($ZIP_entry["name"]);
				$ZIP_in_newname = "$ZIP_finess.$ZIP_mois_Y.$ZIP_mois_m.rss.txt";
				@$ZIP_archive->renameName($ZIP_in_name,$ZIP_in_newname);
			}
			if ($ZIP_rsf_index >= 0) {
				$ZIP_entry = $ZIP_archive->statIndex($ZIP_rsf_index);
				$ZIP_mois_Y = substr($ZIP_mois,0,4);
				$ZIP_mois_m = substr($ZIP_mois,4,2);
				$ZIP_in_name = trim($ZIP_entry["name"]);
				$ZIP_in_newname = "$ZIP_finess.$ZIP_mois_Y.$ZIP_mois_m.rsf.txt";
				@$ZIP_archive->renameName($ZIP_in_name,$ZIP_in_newname);
			}
						
			@$ZIP_archive->close();
		
		
		}
		
	}
	else {
		$ZIP_error = "Décompression impossible";
	}
	
	
	
	
	
	
	

	
	if($ZIP_finess != $finess && isCTI_PC() !== true){ // comparaison du finess du fichier  a importer par rapport au finess de l'environnement 

		$ZIP_error = "Finess différent $ZIP_finess de $finess";

	}
	
	if ($ZIP_error == "") {
		if ($ZIP_pmsitype == "") {
			$ZIP_error = "Données non PMSI (ni RSS, ni RSF, ni RSA)";
		}
	}
	
	if ($ZIP_error == "") {
		if ($ZIP_pmsitype == "ZOF") {
			$ZIP_error = "Fichier PREFACE out.zip non supporté, veuillez importer le fichier in.zip de PREFACE";
		}
	}
	
	if ($ZIP_error == "") {
		if (alreadyTXT()) {
			$ZIP_error = "Fichier ZIP incompatible avec RSS ou RSF TXT déjà chargé";
		}
	}
	
	if ($ZIP_error == "") {
		if ($ZIP_pmsitype == "ZIF" && $typeEts != "2" && $typeEts != "3") {
			$ZIP_error = "Format RSF IN.ZIP incompatible pour exOQN";
		}
	}
	
	if ($ZIP_error == "") {
		if ($ZIP_pmsitype == "ZOU" && $typeEts != "2" && $typeEts != "3") {
			//$ZIP_error = "Format RSS OUT.ZIP incompatible pour exOQN";
		}
	}
	
	
	if ($ZIP_error == "") {
		if (alreadyTXT()) {
			$ZIP_error = "Fichier ZIP incompatible avec RSS ou RSF TXT déjà chargé";
		}
	}
	
	
	
	if ($ZIP_error != "") {
		@unlink($ZIP_filepath);
	}
	else {
		valide_file($ZIP_filepath, $ZIP_pmsitype, $ZIP_finess, $ZIP_mois, $ZIP_filedate);
	}

}




function control_txtfile($TXT_filepath, &$TXT_finess, &$TXT_annee, &$TXT_mois, &$TXT_pmsitype, &$TXT_filesize, &$TXT_filedate, &$TXT_error) {
	
	global $finess;
	global $typeEts;
	global $in_importFileDate;
	
	$TXT_finess = "";
	$TXT_annee = "";
	$TXT_mois = "";
	$TXT_pmsitype = "";
	$TXT_filesize = 0;
	$TXT_filedate = 0;
	$TXT_error = "";
	
	
	if (! file_exists($TXT_filepath)) {
		return;
	}
	
	$TXT_filesize = filesize($TXT_filepath);
	$TXT_filedate = filemtime($TXT_filepath);
	$TXT_filedate = $in_importFileDate;
	
	$no_ligne = 0;
    $buffer = "";
	
	// format RSS/RSF ?
	$TXT_handle = @fopen($TXT_filepath, "r");
	if ($TXT_handle) {
		while (!feof($TXT_handle)) {
			$buffer = fgets($TXT_handle, 99999);
			
			$no_ligne++;
			if (trim($buffer) != "" && $no_ligne < 1000000000000 ) {
				if ($TXT_pmsitype == "") {
					if (substr($buffer, 15 , 9) == $finess && strlen($buffer) > 100) {
						$TXT_pmsitype = "RSS";
						$TXT_finess = $finess;
						$TXT_annee = "";
						$TXT_mois = "";
						$TXT_filedate = $TXT_filedate;
						$TXT_filesize = $TXT_filesize;
					}
				}
				if ($TXT_pmsitype == "") {
					if (substr($buffer, 0 , 1) == "A" && substr($buffer, 1 , 9) == $finess && strlen($buffer) > 100) {
						$TXT_pmsitype = "RSF";
						$TXT_finess = $finess;
						$TXT_annee = "";
						$TXT_mois = "";
						$TXT_filedate = $TXT_filedate;
						$TXT_filesize = $TXT_filesize;
					}
				}
				if ($TXT_pmsitype == "RSS") {
					if (floatval(substr($buffer, 106, 4)) >= 2000 && floatval(substr($buffer, 106, 4)) < 2020) {
						$mois = substr($buffer, 106, 4) . substr($buffer, 104, 2);
						if ($mois > $TXT_mois) {
							$TXT_mois = $mois;
						}
					}
				}
				if ($TXT_pmsitype == "RSF") {
					if (substr($buffer, 0, 1) == "A") {
					if (floatval(substr($buffer, 89, 4)) >= 2000 && floatval(substr($buffer, 89, 4)) < 2020) {
						$mois = substr($buffer, 89, 4) . substr($buffer, 87, 2);
						if ($mois > $TXT_mois) {
							$TXT_mois = $mois;
						}
					}
					}
				}
				
			
			}
		
		}
		fclose($TXT_handle);
	}
	
	// Si pas format RSS/RSF, verifier données complémentaires
	if ($TXT_pmsitype == "") {
	
		$maxCol = 0;
        $length = 0;
        $maxLength = 0;
		$no_ligne = 0;
		
		$TXT_handle = @fopen($TXT_filepath, "r");
        $TXT_filename = basename($TXT_filepath);
		if ($TXT_handle) {
			while (!feof($TXT_handle)) {
				$buffer = fgets($TXT_handle, 99999);
				
				$no_ligne++;
				if (trim($buffer) != "" && $no_ligne < 10 ) {
					
					$array = explode("\t", $buffer);
					if (count($array) <= 1) {
						$array = explode(";", $buffer);
					}
					$nbCol = count($array);
					if ($nbCol > $maxCol) {
						$maxCol = $nbCol;
					}
                    $length = strlen(trim($buffer));
					if ($length > $maxLength) {
                        $maxLength = $length;
                    }
				}
			
			}
			fclose($TXT_handle);
		}
		
        // Fichsup transports
		if ($maxCol == 1 && $maxLength <= 31) {
			$TXT_pmsitype = "TSP";
            // recuperation du mois et de l'annee dans le nom du FICHSUP transports
            $TXT_fileparts = explode('.', $TXT_filename);
            if (count($TXT_fileparts) > 1) {
                $TXT_annee = $TXT_fileparts[1];
                $TXT_mois = $TXT_annee . str_pad($TXT_fileparts[2], 2, '0', STR_PAD_LEFT);
            }
		}
        
		if ($maxCol == 2) {
			$TXT_pmsitype = "RSM";
		}
		// Pour Baclesse, les nombres de colonnes sont différents pour les fichiers de rss-noms
		// by CLA 04-03-2013
		if ($finess == '140000639') {
			if ($maxCol == 4) {
				$TXT_pmsitype = "RSI";
			}
			else if ($maxCol == 5) {
				$TXT_pmsitype = "MED";
			}
		}
		else {
			if ($maxCol == 3) {
				$TXT_pmsitype = "RSI";
			}
			if ($maxCol > 3 && $maxCol < 6) {
				$TXT_pmsitype = "MED";
			}
		}
		if ($maxCol > 6 && $maxCol < 30) {
			$TXT_pmsitype = "ACM";
		}
		if ($maxCol > 30) {
            if (stripos($TXT_filename, '.valo.') !== false) {
                $TXT_pmsitype = "VSJ";
            }
            if (stripos($TXT_filename, '.valo.ace') !== false || stripos($TXT_filename, '.valo_ace') !== false) {
                $TXT_pmsitype = "VSE";
            }
            // recuperation du mois et de l'annee dans le nom du fichier de valo
            $TXT_fileparts = explode('.', $TXT_filename);
            if (count($TXT_fileparts) > 1) {
                $TXT_annee = $TXT_fileparts[1];
                $TXT_mois = $TXT_annee . str_pad($TXT_fileparts[2], 2, '0', STR_PAD_LEFT);
            }
		}
		if ($TXT_pmsitype != "") {
			$TXT_finess = $finess;
			$TXT_annee = ($TXT_annee == "") ? "0000" : $TXT_annee;
			$TXT_mois = ($TXT_mois == "") ? "000000" : $TXT_mois;
		}
	}
	
	
	
	if ($TXT_error == "") {
		if ($TXT_pmsitype == "") {
			$TXT_error = "Données non PMSI (ni RSS, ni RSF, ni RSA)";
		}
	}
	
	if ($TXT_error == "") {
		if ($TXT_pmsitype == "RSS" && !($typeEts != "2" && $typeEts != "3")) {
			$TXT_error = "Format RSS.TXT incompatible pour exDG";
		}
	}
	
	if ($TXT_error == "") {
		if ($TXT_pmsitype == "RSF" && !($typeEts != "2" && $typeEts != "3")) {
			$TXT_error = "Format RSF.TXT incompatible pour exDG";
		}
	}
	
	if ($TXT_error == "") {
		if ($TXT_pmsitype == "RSS" || $TXT_pmsitype == "RSF") {
		if ($TXT_finess != $finess) {
			$TXT_error = "Finess différent $TXT_finess de $finess";
		}
		}
	}
	
	if ($TXT_error == "") {
		if ($TXT_pmsitype == "RSS" || $TXT_pmsitype == "RSF") {
		if (alreadyZIP()) {
			$TXT_error = "Fichier TXT incompatible avec RSS ou RSF ZIP déjà chargé";
		}
		}
	}
	
	
	if ($TXT_error != "") {
		@unlink($TXT_filepath);
	}
	else {
		valide_file($TXT_filepath, $TXT_pmsitype, $TXT_finess, $TXT_mois, $TXT_filedate);
	}

}


function valide_file($ZIP_filepath, $ZIP_pmsitype, $ZIP_finess, $ZIP_mois, $ZIP_filedate) {

	$path = dirname($ZIP_filepath);
	$name = basename($ZIP_filepath);
	$prefix = "PMSIMPORT." . $ZIP_pmsitype . ".";
	$prefixComp = "PMSIMPORT." . $ZIP_pmsitype . "." . $ZIP_finess . "." . $ZIP_mois . "." . $ZIP_filedate . ".";

	$rep=@opendir($path);
	if ($rep > 0) {
		while ($file = readdir($rep)){
			if($file != '..' && $file !='.' && $file !=''  ){
				$longFile = $path . '/' . $file;
			
				$fileType = "";
				$path_parts = pathinfo($longFile);

				$fileType =  strtoupper($path_parts['extension']);
				if (is_dir($longFile)) {
					$fileType = "DIR";
				}
				
				if (substr($file,0,strlen($prefix)) == $prefix) {
					@unlink($longFile);
				}
			}
		}
	}
	@closedir($rep);

	
	rename("$ZIP_filepath", "$path/$prefixComp$name");
	
	// Pour Druide, il faut convertir
	if ($ZIP_pmsitype == "DRUIDE_SEJ" || $ZIP_pmsitype == "DRUIDE_ACE" || $ZIP_pmsitype == "DRUIDE_OQN") {
		$submitCmd = realpath(dirname(__FILE__) . "/../../pmsi/import_rss_rsf/iCTI_convert_druide.exe") . " -fs \"$path/$prefixComp$name\" ";
		$return = exec($submitCmd);
	}

}





// test si un fichier TXT RSS ou RSF
function alreadyTXT() {

	global $tmp_path;


	
	$path = $tmp_path;
	$rep=@opendir($path);
	if ($rep > 0) {
		while ($FILE_fullname = readdir($rep)){
			if($FILE_fullname != '..' && $FILE_fullname !='.' && $FILE_fullname !='' && substr($FILE_fullname,0,10) == "PMSIMPORT."  ){
				if(substr($FILE_fullname,0,14) == "PMSIMPORT.RSS." || substr($FILE_fullname,0,14) == "PMSIMPORT.RSF." ){
					return TRUE;
				}
			}
		}
	}
	@closedir($rep);

	
	return FALSE;

}



// test si un fichier TXT RSS ou RSF
function alreadyZIP() {

	global $tmp_path;


	
	$path = $tmp_path;
	$rep=@opendir($path);
	if ($rep > 0) {
		while ($FILE_fullname = readdir($rep)){
			if($FILE_fullname != '..' && $FILE_fullname !='.' && $FILE_fullname !='' && substr($FILE_fullname,0,10) == "PMSIMPORT."  ){
				if(substr($FILE_fullname,0,14) == "PMSIMPORT.ZIN." || substr($FILE_fullname,0,14) == "PMSIMPORT.ZOU." || substr($FILE_fullname,0,14) == "PMSIMPORT.ZIF." ){
					return TRUE;
				}
			}
		}
	}
	@closedir($rep);

	
	return FALSE;

}


function vitalia_convertDc($dcfile) {

	global $tmp_path;
	
	$xml = @simplexml_load_file($dcfile);

		
	$medFile = "$tmp_path/MED.TXT";
	$outputHandle = fopen($medFile, "w");
	if ($xml->MEDS) {
	foreach ($xml->MEDS as $headerNode) {
		foreach ($headerNode->MED as $node) {
			$cod = trim($node["cod"]);
			$nom = trim($node["nom"]);
			$pre = trim($node["pre"]);
			$spe = trim($node["spe"]);
			$ade = trim($node["ade"]);
			fwrite($outputHandle, "$cod\t$nom\t$pre\t$spe\t$ade\r\n");
		}
	}
	}
	fclose($outputHandle);
	control_txtfile($medFile, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype, $TXT_filesize, $TXT_filedate, $TXT_error);
		
	$rssnomFile = "$tmp_path/RSSNOM.TXT";
	$outputHandle = fopen($rssnomFile, "w");
	if ($xml->RSIS) {
	foreach ($xml->RSIS as $headerNode) {
		foreach ($headerNode->RSI as $node) {
			$rss = trim($node["rss"]);
			$nom = trim($node["nom"]);
			$pre = trim($node["pre"]);
			fwrite($outputHandle, "$rss\t$nom\t$pre\r\n");
		}
	}
	}
	fclose($outputHandle);
	control_txtfile($rssnomFile, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype, $TXT_filesize, $TXT_filedate, $TXT_error);
		
	$rssmedFile = "$tmp_path/RSSMED.TXT";
	$outputHandle = fopen($rssmedFile, "w");
	if ($xml->RSMS) {
	foreach ($xml->RSMS as $headerNode) {
		foreach ($headerNode->RSM as $node) {
			$rss = trim($node["rss"]);
			$med = trim($node["med"]);
			fwrite($outputHandle, "$rss\t$med\r\n");
		}
	}
	}
	fclose($outputHandle);
	control_txtfile($rssmedFile, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype, $TXT_filesize, $TXT_filedate, $TXT_error);
		
		
	$actmedFile = "$tmp_path/ACTMED.TXT";
	$outputHandle = fopen($actmedFile, "w");
	if ($xml->ACMS) {
	foreach ($xml->ACMS as $headerNode) {
		foreach ($headerNode->ACM as $node) {
			$rss = trim($node["rss"]);
			$med = trim($node["med"]);
			$act = trim($node["act"]);
			$cca = trim($node["cca"]);
			$ccp = trim($node["ccp"]);
			$umc = trim($node["umc"]);
			$dat = trim($node["dat"]);

			fwrite($outputHandle, "$rss\t$med\t$act\t$cca\t$ccp\t \t$dat\t1\t1\r\n");

		}
	}
	}
	fclose($outputHandle);
	control_txtfile($actmedFile, $TXT_finess, $TXT_annee, $TXT_mois, $TXT_pmsitype, $TXT_filesize, $TXT_filedate, $TXT_error);
	
	
	@unlink($dcfile);
	
}




function initializeDir() {
	
	if (! file_exists("../../../temp")) {
		@mkdir("../../../temp");
	}

}





?> 