<?php
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");

//ini_set("display_errors","1");
class liveUpdateManipulator extends TreeDataManipulator
{
	public $newLine = "\r\n";

	function UpdateSQLManualAction() {
		$checkSlashes = strpos($pod['st'], "\\");
		if (!$checkSlashes)  $_POST['podatki']['sql_statments'] = addslashes($_POST['podatki']['sql_statments']);

		$sql = "UPDATE _LiveUpdateSql SET sql_statments = '".$_POST['podatki']['sql_statments']."' WHERE id = ".$_POST['id'];
		$this->db->SQLexecute($sql);
		echo "{success:true}";
	}

	function selectAction()
	{
		$id = $_POST['id'];
		$showType = $_POST['type'];
		if($id == '')
		{ //we opened the root or older node node.
			//if root we show 5 last versions and an 'older' folder!
			$rowLimit = 5;

			$tableVersions = '_LiveUpdateVersion';
			$sql = 'SELECT * FROM '.$tableVersions.' ORDER BY file_program_ver';

			//we check if 'older' folder is neccesery
			$rs  = $this->db->SQLexecute("SELECT COUNT(*) FROM ".$tableVersions );
			$row = $this->db->fetchArray($rs);
			$rowNum = $row[0];
			if($showType == 'older')
			{//if older was opened we show all but last 5 versions
				$sql .= ' LIMIT 0,'.($rowNum - $rowLimit);
			}

			else if($rowNum > $rowLimit )
			{//if root was opened we limit to the last five records
				//we add the older folder (type is 'older')
				$path['file_name'] = 'Older';
				$path['id'] = 'older';
				$path['RMtype'] = 'older';

				$nodes[] = $path;

				$sql .= ' LIMIT '.( $rowNum - $rowLimit).",$rowNum";
			}

			$lab = 'file_program_ver';
			$idLab = $lab;
			$type = 'version';

			$is_leaf = false;
		}
		else if($showType == 'version')
		{ //a version folder was opened
		  //we operati 2 trees! one shows files the other shows sql statements. we check which send a request and set up apropriate SQL
			$LUtype = $_POST['LUtree'];
			if($_POST['LUtree'] == 'files')
			{
				$table = '_LiveUpdateFiles';
				$sql = "SELECT * FROM $table WHERE version = $id ORDER BY file_type,relative_path,file_name";
				$lab = 'file_name';

			}
			else if ($LUtype == 'statments')
			{
				$table = '_LiveUpdateSql';
				$sql = "SELECT * FROM $table WHERE version = $id ORDER BY project_id,statement_id";
				$lab = 'liveupdate_comment';
			}
			$idLab = 'id';
			$type = 'file';
			$is_leaf = true;
		}
		//we execute the setup sql
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}

		// display each child
		while ($row = $this->db->fetchAssoc($res)) {
			// Response parameters.
			$path = array();
			//we set up which label to use as name depending on type (version, other) and tree (files, sql)
			$path['file_name']		=html_entity_decode( $row[ $lab ] );
			$path['leaf'] = $is_leaf;
			//we must use random id, to not mess up the tree
			$path['id']			= $type.'_'.$row['id'];
			//we store the original id in a different variable
			$path['origId']	=$row[ $idLab ];
			$path['RMtype'] = $type;
			if($LUtype == 'files')
			{
				$path['relative_path'] = $row['relative_path'];

				if($row['file_type'] == 1)
				{
					$filePath = WARPIT_ABSOLUTE.$row['relative_path'].'/'.$row['file_name'];
					$path['file_type'] = 'Warpit';
				}
				else if($row['file_type'] == 2)
				{
					$filePath = WARPIT_WEBPROJECTS.$row['relative_path'].'/'.$row['file_name'];
					$path['file_type'] = 'Webprojects';
				}
				else
				{
					$filePath = WARPIT_LIVEUPDATE_SQLVERSION.$row['file_name'];
					$path['file_type'] = 'SQL file';
				}
				if($fInfo = pathinfo($filePath,PATHINFO_EXTENSION))
					$path['iconCls'] = 'file-'.$fInfo;
				$path['checked'] = false;
			}
			else if ($LUtype == 'statments')
			{
				$path['database'] = $row['sql_database'];
				$path['dateTime'] = $row['insertTime'];
			}
			else if($type = 'version')
			{//for version we check if there are disabled
				if($row['active']==0)
					$path['iconCls'] = 'icon_delete_folder';
			}

			$nodes[] = $path;
		}

		//return $nodes;


		return json_encode($nodes);

	}

	function getLastVersion()
	{
		$sql = "SELECT MAX(file_program_ver) FROM _LiveUpdateVersion";
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		$row = $this->db->fetchArray($res);
		return $row[0];
	}

	function insertFilesAction()
	{

		$files = json_decode( stripslashes($_POST['files'] ) ,true);

		if($_POST['folder'])
		{
			$folder = json_decode( stripslashes($_POST['folder'] ) ,true);
			$path = $folder['path'];
			$type = $folder['fileType'];
				if($folder['fileType'] == 1)
				{
					//values read from configfile !!!!
					//$path = "/var/www/warpit/".$path;
					$prepath = WARPIT_ABSOLUTE;
				}
				else {
					//$path = "/var/".$path;
					$prepath = WARPIT_WEBPROJECTS;
				}
						$file_list = '';
					  	$stack[] = $path;
					    while ($stack) {
					      $current_dir = array_pop($stack);
					      if ($dh = opendir( $prepath.$current_dir)  ) {
					        while (($file = readdir($dh)) !== false) {
					          if ($file !== '.' AND $file !== '..') {
					            $current_file = "{$current_dir}{$file}";
					            if (is_file($prepath.$current_file)) {
					              	$newFile['name'] = $file;
					              	$newFile['path'] = $current_dir;
					              	$newFile['fileType'] = $type;
					            	$files[] = $newFile;
					            } elseif (is_dir($prepath.$current_file)) {
					  				   $stack[] = $current_file.'/';
					            }
					          }
					        }
					      }
					    }
		}


		$this->db->ChangeDatabase(DB_WARPIT_LIVEUPDATE);


		$ver = $this->getLastVersion();

		foreach ($files as $fl) {

			$sql = "SELECT id FROM _LiveUpdateFiles WHERE file_name = '".$fl['name']."' AND relative_path = '".$fl['path']."'
			AND file_type = ".$fl['fileType']." AND version = ".$ver;
			If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
			$row = $this->db->fetchArray($res);
			if(!$row)
				$values[] = '(\''.implode("','",$fl)."',$ver)";
		}

		if( !is_array($values)  )
		{
			return "{ success:false,error:'No files added!' }";
		}

		$sql = "INSERT IGNORE INTO _LiveUpdateFiles (file_name,relative_path,file_type,version  ) VALUES";

		$sql .= implode(',',$values);
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}

		return "{ success:true }";
	}

	function removeFilesAction()
	{
		$ids = json_decode( stripslashes( $_POST['files'] ));

		$sql = "DELETE FROM  ".$this->table." WHERE id IN (".implode(',',$ids).')' ;
		//echo $sql;

		if($this->db->SQLexecute($sql))
		{
			echo " { success: true  }";
		}
		else
		{
			echo "{success:false,STATEMENT:'$sql'}";
		}
	}
	function deactivateVersionAction()
	{
		$ids = json_decode( stripslashes( $_POST['versions'] ));

		$sql = "UPDATE _LiveUpdateVersion SET active = abs(active - 1) WHERE file_program_ver IN (".implode(',',$ids).')' ;
		//echo $sql;

		if($this->db->SQLexecute($sql))
		{
			echo " { success: true  }";
		}
		else
		{
			echo "{success:false,STATEMENT:'$sql'}";
		}
	}

	function removeStatementsAction()
	{
		$ids = json_decode( stripslashes( $_POST['files'] ));

		$sql = "DELETE FROM  _LiveUpdateSql WHERE id IN (".implode(',',$ids).')' ;
		//echo $sql;

		if($this->db->SQLexecute($sql))
		{
			echo " { success: true  }";
		}
		else
		{
			echo "{success:false,STATEMENT:'$sql'}";
		}
	}


	function resultForEach($ar = array()) {
		foreach ($ar as $key=>$val) $tmp[] = $key." = '".addslashes($val)."'";
		return ($tmp);
	}


	function SQLgenerator($sql,$insertParams = array()) {

		//$this->db->ChangeDatabase($database);
		$res = $this->db->SQLexecute($sql);
		while ($zad = $this->db->fetchAssoc($res)) {

			if ( $insertParams['action'] == "insert" ) {
				$rec = $this->resultForEach($zad);
				if ($insertParams['QT_user_type']) {
					$_sql[]  = str_replace("QT_user_type = '0'","QT_user_type = '".$insertParams['QT_user_type']."'", "INSERT INTO ".$insertParams['tableName']." SET ".implode(",",$rec).";");
				}
				else {
					$_sql[] = "INSERT INTO ".$insertParams['tableName']." SET ".implode(",",$rec).";";
				}
			} elseif ( $insertParams['action'] == "replace" ) {
				$rec = $this->resultForEach($zad);
				$_sql[] = "REPLACE INTO ".$insertParams['tableName']." SET ".implode(",",$rec).";";
			}
		}
		return $_sql;
	}

	function SQLstructureGenerator($table,$database) {

		$this->db->ChangeDatabase($database);
		$res = $this->db->SQLexecute("SHOW CREATE TABLE ".$table);
		$zad = $this->db->fetchArray($res);
		return $zad[1];
	}

	function SQLaproovedUsersGenerator($sql) {

		$res = $this->db->SQLexecute($sql);
		while ($zad = $this->db->fetchAssoc($res)) {
			$tmp = explode("-",$zad['loginSID']);
			$myProject = $zad['id_project'];
			$_sql[] =  "INSERT IGNORE INTO `_www_ids` (`id`, `id_user`, `user_type`, `id_project`, `id_site`, `loginSID`, `idGenStruc`) VALUES (null, ".$zad['id_user'].", ".$zad['user_type'].", ".($zad['id_project'] * -1).", 0, '".$tmp[0]."', 0);";
		}

		if ($myProject > 0) {
			$_sql[] =  "DELETE FROM _www_ids WHERE id_user>0 AND user_type=0 AND id_project=".$myProject." AND id_site=0 AND id_user NOT IN (SELECT * FROM (SELECT id_user FROM `_www_ids` WHERE id_user>0 AND user_type=0 AND id_site=0 AND id_project=".($myProject * -1).") AS p );";
			$_sql[] =  "UPDATE IGNORE `_www_ids` SET `id_project`=ABS(`id_project`), `loginSID` = CONCAT(`loginSID`,'-',`id`) WHERE `id_project`<0;";
		}
		$_sql[] =  "DELETE FROM `_www_ids` WHERE `id_project`<0;";

		return $_sql;
	}

	function prepareSQLAction()
	{

		$table = '_LiveUpdateSql';
		$checked = json_decode( stripslashes($_POST['checks'] ) ,true);
		$projects = json_decode( stripslashes($_POST['projects']),true  );
		$version = $this->getLastVersion();
		//temp a fixed project testIg

		foreach ($projects as $projObj)
		{
			$id_project = $projObj['id'];
			$tren_tabl =  $projObj['name'];

	  		foreach($checked AS $key => $item_liveupdate) {
	  			   unset($live_build,$questionnaire_structure,$data);
					  			switch($item_liveupdate) {

// --------------------------------------------------------------------------
// 	Questionnaire: _projects, questionnaire, language, script, tree tables
// --------------------------------------------------------------------------
					  				case 1:

					  					$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._Projects WHERE id = ".$id_project;

					  					$data = $this->SQLgenerator($sql,array("action" => "replace","tableName" => "_Projects"));
										//var_dump($data);
										$live_build = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));


										// here we find out tree structure where is project and copy all parts of tree
										// here we have fix deep of tree defined to 6

										$sql = "SELECT a.id as id1, b.id as id2, c.id  as id3, d.id  as id4, e.id  as id5, f.id  as id6
													FROM ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS a
														LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS b ON a.id_sup = b.id
														LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS c ON b.id_sup = c.id
														LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS d ON c.id_sup = d.id
														LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS e ON d.id_sup = e.id
														LEFT JOIN ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree AS f ON e.id_sup = f.id
													WHERE a.id = ".$id_project;
										/*echo $sql;
										exit;*/
										$res = $this->db->SQLexecute($sql);
										$zad = $this->db->fetchAssoc($res);
										foreach ($zad as $val) {
											if (is_null($val)) break;
											$projTreeId[] = $val;
										}

										if ($projTreeId) {
											// now we get all records of projects trtee and prepare replace statements
											$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._ProjectsTree WHERE id IN (".implode(",",$projTreeId)." )";

						  					$data = $this->SQLgenerator($sql,array("action" => "replace","tableName" => "_ProjectsTree"));
											if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));
										}


										$live_build .= $this->newLine."<stat>DELETE FROM  _LanguageProjects WHERE id_project = ".$id_project.";";
										$live_build .= $this->newLine."<stat>DELETE FROM  _LanguageUserInterface WHERE id_project IN (0, ".$id_project.");";
										$live_build .= $this->newLine."<stat>DELETE FROM  _QuestionRotation WHERE id_project = ".$id_project.";";
										$live_build .= $this->newLine."<stat>DELETE FROM  _ProjectExtraVariables  WHERE id_project = ".$id_project.";";


										// load data for project languages
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._ProjectExtraVariables  WHERE id_project = ".$id_project.";";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_ProjectExtraVariables "));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data for project languages
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._LanguageProjects WHERE id_project = ".$id_project.";";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_LanguageProjects "));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data for project languages interface
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._LanguageUserInterface  WHERE id_project IN (0, ".$id_project.");";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_LanguageUserInterface"));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data for project languages interface
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._QuestionRotation  WHERE id_project IN (".$id_project.");";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_QuestionRotation"));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));




					  					$sql_comment = "UPDATE _Projects table for: ".$tren_tabl;
										// zapis v liveupdate tabelo
					  		  			$sql_add_build = "REPLACE INTO ".DB_WARPIT_LIVEUPDATE.".".$table."
					  		  									SET statement_id = 11,
					  		  										project_id = $id_project,
					  		  										version='".$version."',
					  		  										sql_database = 'table_warpit_webcati_base',
					  		  										sql_statments = '$live_build',
					  		  										liveupdate_comment = '$sql_comment' ";

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

										$questionnaire_structure = array();

										// delete questionnaire table if allready exists
										$questionnaire_structure[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl.";";
										$questionnaire_structure[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."_language;";
										$questionnaire_structure[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."_script;";
										$questionnaire_structure[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."_tree;";

										// create new structure of questionnaire table
										$questionnaire_structure[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl,DB_WARPIT_WEBCATI)).';';

										// create new structure of questionnaire table for language
										$questionnaire_structure[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."_language",DB_WARPIT_WEBCATI)).';';
										// create new structure of questionnaire table for script
										$questionnaire_structure[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."_script",DB_WARPIT_WEBCATI)).';';
										// create new structure of questionnaire table for tree
										$questionnaire_structure[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."_tree",DB_WARPIT_WEBCATI)).';';


										// load data of all questions in this questionnaire
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI.".".$tren_tabl;
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl));
										if ($data) $live_build = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data of all questions in this questionnaire language
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI.".".$tren_tabl."_language";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."_language"));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data of all questions in this questionnaire script
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI.".".$tren_tabl."_script";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."_script"));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// load data of all questions in this questionnaire script
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI.".".$tren_tabl."_tree";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."_tree"));
										if ($data) $live_build .= addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));





									    // zapis v liveupdate tabelo
					  		  		    $sql_add_build = "REPLACE INTO ".DB_WARPIT_LIVEUPDATE.".".$table."  SET
					  		  								statement_id = 12,
					  		  								project_id = $id_project,
					  		  								version='".$version."',
					  		  								sql_database = 'table_warpit_webcati',
					  		  								sql_statments='".implode(" ",$questionnaire_structure).$live_build."',
					  		  								liveupdate_comment='CREATE questionnaire: ".$tren_tabl."'";


					    				If (!$this->db->SQLexecute($sql_add_build)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql_add_build.'"}';	}
					  					break;
// -------------------------------------
// 	Questionnaire structure data file && Delete structure table on notebook:
// -------------------------------------
					  			case 2:

					  				$sql_comment = "CREATE structure table: ".$tren_tabl;

									// Delete structure table on notebook:
									if ( in_array(3,$checked) )  {
										$live_build[] = $this->newLine."<stat>#BACKUP ".$tren_tabl."_structure ;";
										$live_build[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."_structure;";
										$live_build[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."___EngineLog;";
										$live_build[] = $this->newLine."<stat>DELETE FROM  _www_interviewer_statistics WHERE id_project = ".$id_project.";";
									}

									// Questionnaire structure data file
									$live_build[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."_structure",DB_WARPIT_WEBCATI_BASE)).';';
									$live_build[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."___EngineLog",DB_WARPIT_WEBCATI_BASE)).';';


					  		  		$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 3,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";


					    			If (!$this->db->SQLexecute($sql_add_build)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql_add_build.'"}';	}
					    			break;
// -------------------------------------
//	  Quota definitions:
// -------------------------------------

					  				case 4:
							    		$sql_comment = "UPDATE quota definitions: ".$tren_tabl;

							    		$live_build[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."___quotaLock;";
							    		$live_build[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."___quotaCalc;";
							    		$live_build[] = $this->newLine."<stat>DROP TABLE IF EXISTS ".$tren_tabl."___quotaLimits;";

							    		$quotaLockExist = $this->db->TableExists($tren_tabl."___quotaLock",DB_WARPIT_WEBCATI_BASE);
							    		$quotaCalcExist = $this->db->TableExists($tren_tabl."___quotaCalc",DB_WARPIT_WEBCATI_BASE);
							    		$quotaLimitsExist = $this->db->TableExists($tren_tabl."___quotaLimits",DB_WARPIT_WEBCATI_BASE);

							    		if ( $quotaLockExist ) $live_build[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."___quotaLock",DB_WARPIT_WEBCATI_BASE)).';';
										if ( $quotaCalcExist ) $live_build[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."___quotaCalc",DB_WARPIT_WEBCATI_BASE)).';';
										if ( $quotaLimitsExist ) $live_build[] = $this->newLine."<stat>".addslashes($this->SQLstructureGenerator($tren_tabl."___quotaLimits",DB_WARPIT_WEBCATI_BASE)).';';

										if ($quotaLockExist) {
											// data for QUOTA LOCK
											$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$tren_tabl."___quotaLock";
											$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."___quotaLock"));
											if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));
										}
										if ( $quotaLimitsExist ) {
											// data for QUOTA LIMITS
											$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$tren_tabl."___quotaLimits";
											$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."___quotaLimits", "QT_user_type"=>4));
										}

										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

									//	$live_build[] = $this->newLine."<stat>UPDATE IGNORE".DB_WARPIT_WEBCATI_BASE.".".$tren_tabl."___quotaLimits SET QT_user_type = 4;";

					    				//quota definitions

					    				// first we delete existing quota definitions on capi system
					    				$live_build[] = $this->newLine."<stat>DELETE FROM quota_layer_addon WHERE id IN (SELECT layer FROM quota_layer WHERE id_project = ".$id_project.");";
					    				$live_build[] = $this->newLine."<stat>DELETE FROM quota_layer WHERE id_project = ".$id_project.";";
					    				$live_build[] = $this->newLine."<stat>DELETE FROM recode WHERE id_project = ".$id_project.";";
					    				$live_build[] = $this->newLine."<stat>DELETE FROM recolabel WHERE id_project = ".$id_project.";";

					    				// we fill quota labels and recode values
					    				$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".recode WHERE id_project = ".$id_project;
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "recode"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".recolabel WHERE id_project = ".$id_project;
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "recolabel"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

					    				// we fill quota layer
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".quota_layer WHERE id_project = ".$id_project;
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "quota_layer"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// we fill quota_layer_addon
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".quota_layer_addon WHERE id IN (SELECT layer FROM quota_layer WHERE id_project = ".$id_project.");";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "quota_layer_addon"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 4,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";


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

					  					break;
// -------------------------------------
//	  Questionnaire aprooved users:
// -------------------------------------
					  				case 5:

					  					$sql_comment = "UPDATE Questionnaire aprooved users: ".$tren_tabl;

							    		// Questionnaire aprooved users - done by Soulskiner, big BUG destroy prepared sessions
										//$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids WHERE id_project = ".$id_project;
										//$data = $this->SQLgenerator($sql,array("action" => "replace","tableName" => "_www_ids"));

										// new Questionnaire aprooved users - done by Borut, 20151202
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids WHERE (user_type = 0 OR user_type=3) AND id_project = ".$id_project;
										//echo "/*new Questionnaire aprooved users - $sql*/";
										$data = $this->SQLaproovedUsersGenerator($sql);
					    				if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 5,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";


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

					  					break;

// -------------------------------------
//	WEB questionnaire styles:
// -------------------------------------
					  				case 6:

					  					$sql_comment = "UPDATE WEB questionnaire styles: ".$tren_tabl;

					  					$live_build[] = $this->newLine."<stat>TRUNCATE TABLE _DesignerTemplates;";
					    				$live_build[] = $this->newLine."<stat>TRUNCATE TABLE _DesignerCss;";
					  					$live_build[] = $this->newLine."<stat>TRUNCATE TABLE _DesignerClsPropLink;";
					  					$live_build[] = $this->newLine."<stat>DELETE FROM _DesignerManager WHERE id_project = ".$id_project.";";

					  					// _DesignerTemplates
							    		$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._DesignerManager WHERE id_project = ".$id_project.";";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_DesignerManager"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

							    		// _DesignerTemplates
							    		$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._DesignerTemplates ";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_DesignerTemplates"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// _DesignerCss
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._DesignerCss ";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_DesignerCss"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										// _DesignerClsPropLink
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._DesignerClsPropLink";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "_DesignerClsPropLink"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));
										/*
											// _DesignerClsPropLink
										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._DesignerClsPropLink ";
										$data = $this->SQLgenerator($sql,array("action" => "replace","tableName" => "_DesignerClsPropLink"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));
					    				*/
										$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 7,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";


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

					  					break;


// -------------------------------------
//	  CAPI interviewers:
// -------------------------------------
					  				case 7:

					  					$sql_comment = "UPDATE CAPI interviewers: ".$tren_tabl;


										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._Interviewer WHERE id IN (SELECT id_user FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids WHERE id_project = ".$id_project.")";
										$data = $this->SQLgenerator($sql,array("action" => "replace","tableName" => "_Interviewer"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));


					    				if ($live_build) {
											$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 8,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";
												//20151216 Tanis Premaknil sem ta SQL znotraj zavitih oklepajev, ker se je pojavil error ce na anketi ni bilo anketrajev in si jih vseeno poskusal dodati v verzijo
												If (!$this->db->SQLexecute($sql_add_build)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql_add_build.'"}';	}
					    				}


					  					break;
// -------------------------------------
//	  CAPI sample:
// -------------------------------------
					  				case 8:

					  					$sql_comment = "UPDATE CAPI sample: ".$tren_tabl;
							    		$sql1 = "SHOW CREATE TABLE `".DB_WARPIT_WEBCATI_BASE."`.`".$tren_tabl."___sample`";
							    		$res1 = $this->db->SQLexecute($sql1);
							    		$zad1 = $this->db->fetchArray($res1);

							    		$data[] = str_replace("CREATE TABLE","CREATE TABLE IF NOT EXISTS",$zad1[1]);

							    		$data[] = "DELETE FROM _CapiProperties WHERE id_project = ".$id_project;


							    		$sql = "SELECT * FROM `".DB_WARPIT_WEBCATI_BASE."`._CapiProperties WHERE id_project = ".$id_project;
										$res = $this->db->SQLexecute($sql);
										while ($zad = $this->db->fetchAssoc($res)) {
											$sqltmp = array();
											foreach ($zad as $k=>$v) $sqltmp[] = $k." = '".$v."'";
											$data[] = "INSERT INTO _CapiProperties SET ".implode(",",$sqltmp).";";
										}


										$data[] = "DELETE FROM `".$tren_tabl."___sample`";

										$sql = "SELECT b.* FROM `".DB_WARPIT_WEBCATI_BASE."`._Projects as a
													LEFT JOIN `".DB_WARPIT_WEBCATI_BASE."`._CapiTables as b ON a.id_capiTable = b.id WHERE a.id = ".$id_project;
										$res = $this->db->SQLexecute($sql);
										$zad = $this->db->fetchAssoc($res);

										$sqltmp = array();
										foreach ($zad as $k=>$v) $sqltmp[] = $k." = '".$v."'";
										$data[] = "DELETE FROM _CapiTables WHERE id = ".$zad['id'];
										$data[] = "INSERT INTO _CapiTables SET ".implode(",",$sqltmp);

										$data[] = "DROP TABLE IF EXISTS capi___".$zad['name'];

										$sql1 = "SHOW CREATE TABLE `".DB_WARPIT_WEBCATI_BASE."`.`capi___".$zad['name']."`";
							    		$res1 = $this->db->SQLexecute($sql1);
							    		$zad1 = $this->db->fetchArray($res1);

							    		$data[] = str_replace("CREATE TABLE","CREATE TABLE IF NOT EXISTS",$zad1[1]);

										$live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".capi___".$zad['name'];
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => "capi___".$zad['name']));



										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));


										$sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE.".".$tren_tabl."___sample";
										$data = $this->SQLgenerator($sql,array("action" => "insert","tableName" => $tren_tabl."___sample"));
										if ($data) $live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

										if ($live_build) {
											$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 9,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";
					    				}
					    				If (!$this->db->SQLexecute($sql_add_build)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql_add_build.'"}';	}

					  					break;

// -------------------------------------
//	  PLUGINS:
// -------------------------------------
					  				case 9:

					  					$sql_comment = "Prepare data for plugins: ".$tren_tabl;

							    		$sql = "SELECT * FROM `".DB_WARPIT_WEBCATI_BASE."`.`_Plugin`
													WHERE `id_plugin` IN ( SELECT id_plugin FROM  ".DB_WARPIT_WEBCATI.".`".$tren_tabl."`
																				WHERE `id_plugin` > 0 GROUP BY id_plugin )";
							    		$res = $this->db->SQLexecute($sql);
							    		while ($zad = $this->db->fetchAssoc($res)) {
							    			$data[] = "INSERT IGNORE INTO `_Plugin` SET id_plugin 	= '".$zad['id_plugin']."', plugin_name = '".$zad['plugin_name']."',	plugin_path	= '".$zad['plugin_path']."'";

							    			// I prepare sql for create a table with plugin... I don't know if it is first time so
							    			// run sql every liveupdate with syntax if not exists
							    			$sql1 = "SHOW CREATE TABLE `".DB_WARPIT_WEBCATI_BASE."`.`_plugin_".$zad['plugin_path']."`  ";
							    			$res1 = $this->db->SQLexecute($sql1);
							    			$zad1 = $this->db->fetchArray($res1);
							    			$data[] = str_replace("CREATE TABLE","CREATE TABLE IF NOT EXISTS",$zad1[1]);

							    			// clean data on existing project
							    			$data[] = "DELETE FROM `_plugin_".$zad['plugin_path']."` WHERE id_project = ".$id_project;

							    			$sql1 = "SELECT * FROM `".DB_WARPIT_WEBCATI_BASE."`.`_plugin_".$zad['plugin_path']."` WHERE id_project = ".$id_project;
							    			$res1 = $this->db->SQLexecute($sql1);
							    			while ($zad1 = $this->db->fetchAssoc($res1)) {
							    				unset($zad1['id'],$tmp);
							    				foreach ($zad1 as $key=>$val) $tmp[] = $key." = '".$val."'";
							    				$data[] = "INSERT INTO `_plugin_".$zad['plugin_path']."` SET ".implode(",",$tmp);
							    			}



							    		}


										$live_build[] = addslashes($this->newLine."<stat>".implode($this->newLine."<stat>",$data));

					    				if ($live_build) {
											$sql_add_build = "REPLACE INTO  ".DB_WARPIT_LIVEUPDATE.".".$table." SET
									  		  				statement_id = 10,
									  		  				project_id = $id_project,
									  		  				version='$version',
									  		  				sql_database = 'table_warpit_webcati_base',
									  		  				liveupdate_comment = '$sql_comment',
									  		  				sql_statments='".implode("",$live_build)."'";
					    				}

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

					  					break;

					  			}
					  		}
		}
		 return "{ success:true }";
	}

	function sqlCopyVersionAction()
	{
		$version = $_POST['version'];
		$lastV = $this->getLastVersion();
		$table = '_LiveUpdateSql';

		$sql = "INSERT IGNORE INTO $table (version,project_id,statement_id,sql_database,sql_statments,liveupdate_comment,users_id) SELECT $lastV,project_id,statement_id,sql_database,sql_statments,liveupdate_comment,users_id FROM $table WHERE version = $version";
		If (!$this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		return "{ success:true }";

	}

	function createVersionAction()
	{
		//include_once (PATH_TO_ROOT."webcati/_ajax/liveUpdate/createZip/srvzip.php" );
		include_once (PATH_TO_ROOT."webcati/_ajax/liveUpdate/createZip.class.php");

		$this->createSqlFileAction();

		$version = $_POST['version'];
		$zip = new CreateZip($_POST['version'], $this->db);

		$zip->SQLgeneratedFiles = $this->SQLgeneratedFiles;

		$zip->create();
		//createZIP($_POST['version'],$this->db);
		if($zip->IsError())
		{
			return "{ success:false,error:'{$zip->GetError()}' }";
		}
		$newVer = $_POST['version']+1;

		$sql = "UPDATE _LiveUpdateVersion SET active = 1 WHERE file_program_ver = $version";
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}

		$sql  = "INSERT INTO _LiveUpdateVersion(active,file_program_ver,support_program_ver,id_user) VALUES (0,$newVer,0,".$_SESSION['UserInfo']['id']." ) ";
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		return "{ success:true }";
	}

	function customStatementAction()
	{
		$pod = $_POST['podatki'];

		$checkSlashes = strpos($pod['st'], "\\");
		if (!$checkSlashes)  $pod['st'] = addslashes($pod['st']);

		$live_build = '<stat>'.$pod['st'];
		$sql_comment = $pod['com'];
		$version = $this->getLastVersion();
		$db = $_POST['db'];
		$table = '_LiveUpdateSql';

		$sql_add_build = "REPLACE INTO $table SET statement_id = 99, project_id = -1, version='".$version."',sql_database = '".$db."', sql_statments='".$live_build."',liveupdate_comment='$sql_comment' ";
		$this->db->ChangeDatabase(DB_WARPIT_LIVEUPDATE);
		If (!$this->db->SQLexecute($sql_add_build)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql_add_build.'"}';	}
		$autoId = $this->db->GetLastInsertId();
		$sql = "UPDATE $table SET project_id = $autoId WHERE id = $autoId";
		If (!$this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}


		return "{ success:true }";
	}

function createSqlFileAction()
	{

		unset($this->SQLgeneratedFiles);

		$version = $_POST['version'];
		$table = '_LiveUpdateSql';
		$sql = "SELECT * FROM $table WHERE version = $version ORDER BY sql_database,project_id,statement_id";
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}

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

			if ($row['sql_database'] != $trenDatabase) {

				$trenDatabase = $row['sql_database'];
				$fileName = 'SQL-'.$trenDatabase.'-'.$version.'.sql';
				if ($file) fclose($file);

				if (!file_exists(WARPIT_LIVEUPDATE_ZIPVERSION."tmp")) {
					mkdir(WARPIT_LIVEUPDATE_ZIPVERSION."tmp",0755,1);
				}

				$file = fopen(WARPIT_LIVEUPDATE_ZIPVERSION."tmp/".$fileName,'w');
				$this->SQLgeneratedFiles[$trenDatabase] = $fileName;
			}
			fwrite($file,$row['sql_statments']);
		}
		if ($file) fclose($file);
	}
}

//$tableName = $_POST['RMtable'];
$db->ChangeDatabase(DB_WARPIT_LIVEUPDATE);

$tableName = '_LiveUpdateFiles';


$manipulator = new liveUpdateManipulator($db,$tableName);


$comm = $_REQUEST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else
{

	echo '{success:false,error:"Unknown action!"}';

}


?>
