<?php

class FormDataManipulator
{

	function __construct($db,$table)
	{
		$this->db = $db;
		$this->table = $table;
        //7.1.2015 sqlinjection
        if(class_exists('convert'))
        {
            if(isset($_POST['RMtable'])) $_POST['RMtable'] = convert::toString($_POST['RMtable']);
            if(isset($_POST['SQL'])) $_POST['SQL'] = convert::toString($_POST['SQL']);
            if(isset($_POST['id'])) $_POST['id'] = convert::toInt($_POST['id']);
        }
	}

	function loadAction()
	{
		if($_POST['SQL'])
		{
			$sql = $_POST['SQL']." WHERE a.id = ".$_REQUEST['id'];
		}
		else
			$sql = "SELECT * FROM $this->table WHERE $this->table.id = ".$_REQUEST['id'];

		If (!$res = $this->db->SQLexecute($sql)) {

			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';

		}else{

		    If ($row = $this->db->fetchAssoc($res)) {

		    	foreach ($row as $key => $val) {
		    		$this->data['podatki['.$key.']']=$val;
		    	}



		    	return '{success: true, data:'.json_encode($this->data).'}';
		    }else{
		    	return '{success: false,error:"no data!"}';
		    }

		}
	}
	function submitAction()
	{
		$sqlData = array();
		if($_POST['insertTree']) //the form was used with for a insertion in a tree!!! we add the item
		{
			if(!$_POST['podatki']['idLab'])
				return "{success:false, error:'No name entered!' }";
			include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");
			$tmpTree = new TreeDataManipulator($this->db,$this->table);
			$tmpTree->insertItemAction();
			$_POST['id'] = $tmpTree->insertId;
		}

		$podatki = $_POST['podatki'];
		foreach ($podatki as $key=>$pod)
		{
			if (is_array($pod))
			{
				foreach ($pod as $key1=>$pod1) {
					$sqlData[$key1][$key]= $key." = '".mysql_escape_string($pod1)."'";
				}

			}
			else
			{
				$sqlData[$this->table][$key] = $key. " = '".mysql_escape_string($pod)."'";
			}
		}
		foreach ($sqlData as $tabela => $polja) {
			$sql = 'UPDATE '.$tabela.' SET ' . implode(',',$polja).' WHERE id = '.$_POST['id'];
			If (!$res = $this->db->SQLexecute($sql)) {

			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';

			}
		}
		return "{success:true}";



	}
	function updateAction()
	{
		$_POST['value'] = addslashes($_POST['value']);
		//Marko 17.4.2015
		if($_POST['syntexCheck']){

			$value = $_POST['value'];
			$lines = explode("\n", $value);

			$syntexErrors = array();

			$tableName = $_POST['RMtable']."_structure";

			$sql = "DESCRIBE ".DB_WARPIT_WEBCATI_BASE.".".$tableName;
			if(!$res = $this->db->SQLexecute($sql)) die($this->db->JsonError());

			$fields = array();
			while($row = $this->db->fetchAssoc($res)){
				$fields[] = $row['Field'];
			}

			$cantEndWith = array("==", "!=", "!", "=", "AND", "OR", "NOT", "<", ">", "(", "+", "-", "/", "*", ".", ",");
			$brakets = array();

			foreach ($lines as $lineNum => $line) {
				$parts = explode(" ", $line);
				$last = "";
				$char = 0;
				foreach ($parts as $key => $value) {
					$char += strlen($value);
					if($value[0] == '$'){ //Variable
						if(!in_array(ltrim($value, '$'), $fields)){ //varibale not in structure
							$syntexErrors[] = "Varibale <b>{$value}</b> does not exists in {$tableName} (Line: ".($lineNum + 1).", Column: {$char})";
						}
					}
					if($value == '='){
						$syntexErrors[] = "Please use <b>==</b> or <b>!=</b> insted of <b>=</b> (Line: ".($lineNum + 1).", Column: {$char})";
					}

					for ($i=0; $i < strlen($value); $i++) {
						if($value[$i] == "("){
							if($starBrakets == null)
								$starBrakets = array("count" => 1, "line" => $lineNum + 1, "char" => $char);
							else{
								$c = $starBrakets['count']+1;
								$starBrakets = array("count" => $c, "line" => $lineNum + 1, "char" => $char);
							}
						}
						if($value[$i] == ")"){
							if($endBrakets == null)
								$endBrakets = array("count" => 1, "line" => $lineNum + 1, "char" => $char);
							else{
								$c = $endBrakets['count']+1;
								$endBrakets = array("count" => $c, "line" => $lineNum + 1, "char" => $char);
							}
						}
					}

					if($lineNum == count($lines) -1){
						if(count($parts) > 2){
							if($key == count($parts) -2) $last = $value;
						}
						if($key == count($parts) -1){
							//last
							$output = preg_replace('!\s+!', ' ', $value);
							if($output == " " || $output == "") $value = $last;
							if(in_array($value, $cantEndWith))
								$syntexErrors[] = "End of line error <b>{$value}</b> (Line: ".($lineNum + 1).", Column: {$char})";
						}
					}
				}
			}

			if($starBrakets != null || $endBrakets != null){
				if($starBrakets['count'] != $endBrakets['count']){
					if($starBrakets['count'] > $endBrakets['count'])
						$syntexErrors[] = "Missing a <b>)</b> (Line: ".($endBrakets['line']).", Column: {$endBrakets['char']})";
					else
						$syntexErrors[] = "Missing a <b>(</b> (Line: ".($starBrakets['line']).", Column: {$endBrakets['char']})";
				}
			}

		}
		//echo "NOp";
		if(sizeof($syntexErrors) == 0){
			$idField = $_POST['idField'];
			if(!$idField) $idField = 'id';
			if($_POST['SQLwhere']) $where = " AND ".$_POST['SQLwhere'];

			$sql = 'UPDATE '.$_POST['RMtable']." SET ".$_POST['field']." = '".( ($_POST['RMtrim']) ? trim($_POST['value']) : $_POST['value'] )."' WHERE $idField = ".$_REQUEST['id'].$where;
			If (!$rs = $this->db->SQLexecute($sql)) {

					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';

				}else{



				return '{success:true}';
			}
		}else{
			return '{success:true, syntexErrors: '.json_encode($syntexErrors).'}';
		}
		//!Marko 17.4.2015
	}
}


?>