<?php

require_once("../../../modules/base/php/lib/cti/Batch/Log.functions.php");

class CTI_SqlStatements_class {

	var $sqlStatements_XML;
	var $iCTI_connexion;
	var $environmentVars;
	var $sqlOptions;
	
	var $affectedRows;
	
	var $sqlOption_debug;
	
	function CTI_SqlStatements_class($_XMLfile, $_iCTI_connexion, $_environmentVars=array(), $_sqlOptions=array()) {
		if (get_class($_XMLfile) == "CTI_SimpleXMLElement") {
			$this->sqlStatements_XML = $_XMLfile;
		}	
		else {
			$this->sqlStatements_XML = simplexml_load_file($_XMLfile, 'CTI_SimpleXMLElement', LIBXML_NOCDATA);
		}
		$this->iCTI_connexion = $_iCTI_connexion;
		$this->environmentVars = $_environmentVars;
		$this->sqlOptions = $_sqlOptions;
		
		$this->sqlOption_debug = false;
		foreach ($this->sqlOptions as $sqlOption) {
			if ($sqlOption == "-debugsql") {
				$this->sqlOption_debug = true;
			}
		}
    }
	
	
	function executeStatementsNode($nodeName="", $mainNode=NULL, &$nbE=0, &$nbW=0) {

		global $DB_pmsischema;
		global $DB_comptaschema;
		global $DB_activiteschema;
		
		
		$qmain = FALSE;
		
		if ($mainNode == NULL) {
			$mainNode = $this->sqlStatements_XML;
			$qmain = TRUE;
			$nbE=0;
			$nbW=0;
			$this->affectedRows = 0;
		}
		
		foreach ($mainNode->NODE as $queryNode) {
			$name = trim($queryNode->getAttribute('name'));
			$label = trim($queryNode->getAttribute('label'));
			$traceEcho = trim($queryNode->getAttribute('traceEcho'));
			$traceLabel = trim($queryNode->getAttribute('traceLabel'));
			$traceIndex = trim($queryNode->getAttribute('traceIndex'));
			$traceEnd = trim($queryNode->getAttribute('traceEnd'));
			if ($traceLabel== "false") {
				$traceIndex = "false";
			}
			foreach (array_keys($this->environmentVars) as $environmentVarKey ) {
				$environmentVarValue = $this->environmentVars[$environmentVarKey];
				$sqlkey = strtoupper("[$environmentVarKey]");
				$label = str_ireplace($sqlkey, $environmentVarValue, $label);
			}
			if ($queryNode->getAttribute('name') == $nodeName || $nodeName == "") {

				$sqlcmd = trim($queryNode->getAttribute('sqlcmd'));
				$condition = trim($queryNode->getAttribute('condition'));
				
				$condition_OK = TRUE;
					
				if ($condition != "") {
					$condition = preg_replace('!/\*.*?\*/!s', '', $condition);
					$condition = preg_replace('!--.*!', '', $condition);
					$condition = preg_replace('/\n\s*\n/', "\n", $condition);
					foreach (array_keys($this->environmentVars) as $environmentVarKey ) {
						$environmentVarValue = $this->environmentVars[$environmentVarKey];
						$sqlkey = strtoupper("[$environmentVarKey]");
						$condition = str_ireplace($sqlkey, $environmentVarValue, $condition);
					}
					
					$condition = "if ($condition) {return '1';} else {return '0';}";
					$condition_val = eval($condition);
					if ($condition_val == '0') {
						$condition_OK = FALSE;
					}

				}
				
				if ($condition_OK == TRUE) {
				
					if ($traceLabel != "false") {
						if ($qmain == TRUE) {
							logInfoMsg($label);
						}
						else {
							logInfoMsg($label." ");
						}
					}
				
					if ($sqlcmd != "") {

						// Suppression des commentaires SQL ('/* */', '--' et des lignes vides)
						$sqlcmd = preg_replace('!/\*.*?\*/!s', '', $sqlcmd);
						$sqlcmd = preg_replace('!--.*!', '', $sqlcmd);
						$sqlcmd = preg_replace('/\n\s*\n/', "\n", $sqlcmd);
						
						$sqlcmd_array = explode(";", $sqlcmd);
						
						$nbC = 0;
						
						foreach ($sqlcmd_array as $sqlcmd) {
							$sqlcmd = trim($sqlcmd);
							$sqlcmd = str_ireplace(".,", ";", $sqlcmd);
		
							foreach (array_keys($this->environmentVars) as $environmentVarKey ) {
								$environmentVarValue = $this->environmentVars[$environmentVarKey];
								$sqlkey = strtoupper("[$environmentVarKey]");
								$sqlcmd = str_ireplace($sqlkey, $environmentVarValue, $sqlcmd);
							}
							
							if (substr($sqlcmd,0,5) == "echo ") {
								$sqlcmd = str_ireplace("[CTI_STMT_LASTaffectedRows]", $nbW, $sqlcmd);
								if ($traceEcho != "false") {
									logInfoMsg(trim(substr($sqlcmd,5)));
								}
								$sqlcmd = "";
							}

							if ($sqlcmd != "") {
								$nbC++;
								if ($nbC > 9) {
									$nbC = 0;
								}
								if ($this->sqlOption_debug == true) {
									logInfoMsg("DEBUG SQL ");
								}
								if ($traceIndex != "false") {
									echo "$nbC";
								}
								if ($this->sqlOption_debug == true) {
									echo "\r\n$sqlcmd ";
								}
								$nbW = 0;
								$this->executeStatement($sqlcmd, $nbE, $nbW);
								
								$this->affectedRows = $this->affectedRows + $nbW;
							}
						}
						
					}
					
					$this->executeStatementsNode("",$queryNode, $nbE, $nbW);
					
					if ($qmain == TRUE && $traceEnd != "false") {
						logInfoMsg("FIN $label, $nbE erreurs");
					}
				}
			}
		}
		
	}



	function executeStatement($sqlcmd, &$nbE=0, &$nbW=0) {
	
		$special_CTISELECT_PROPERTY_READ = FALSE;
		if (substr($sqlcmd, 0, 24) == "CTISELECT_PROPERTY_READ ") {
			$sqlcmd = "SELECT " . trim(substr($sqlcmd, 24));
			$special_CTISELECT_PROPERTY_READ = TRUE;
		}

		$toResult = @pg_query($this->iCTI_connexion , $sqlcmd);

		
		if ($toResult == FALSE) {
			$error = pg_last_error($this->iCTI_connexion);
			logErrorMsg("Erreur $error pour $sqlcmd");

			$nbE++;
			
			$toResult = "ERROR";
		}
		else {
			if ($special_CTISELECT_PROPERTY_READ == TRUE) {
				$toRecord = pg_fetch_array($toResult);
				if ($toRecord !== FALSE) {
					$this->environmentVars[trim($toRecord[0])] = trim($toRecord[1]);
				}
		
			}
		}
		
		$nbW = $nbW + @pg_affected_rows($toResult);


		return $toResult;
		
		
	}
	
	
	
}

class CTI_Args_class {

	
	var $args;
	
	function CTI_Args_class() {
		global $argv;
		$args = array();
		$currentOption = "";
		
		for ($i = 1; $i <= 1000; $i++) {
			$arg = trim($argv[$i]);

			if ($arg == "") {
				break;
			}
			
			if (substr($arg,0,1) == "-") {
				$currentOption = $arg;
				$this->args[$currentOption] = "ONLYKEY";
			}
			else {
				if ($this->args[$currentOption] == "ONLYKEY") {
					$this->args[$currentOption] = "";
				}
				if ($this->args[$currentOption] != "") {
					$this->args[$currentOption] = $this->args[$currentOption] . " ";
				}
				$this->args[$currentOption] = $this->args[$currentOption] . $arg;
			}
		}
    }
	
}





?>