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

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

include_once(PATH_TO_ROOT.'_class/createQuestion/Question.php');
include (PATH_TO_ROOT."_class/class.ConvertCodepage.php");
include (PATH_TO_ROOT."webcati/_class/class.QuestionExport.php");


class ExImportManipulator extends GridDataManipulator
{
	function StoreToBinary($array, $tmp_path_on_disk, $id_user) {

		if (!$fhandle=fopen($tmp_path_on_disk."/binary_export_file".$id_user,"a")) {
			return 0;
		}

		for ($i=0; $i<80; $i++) {
			$len=strlen($array[$i]);
			$byte1=0;
			$byte2=0;
			for ($z=0; $z<$len; $z++) {
				switch($array[$i]{$z}) {
					case "1":
						$byte1+=1;
						break;
					case "2":
						$byte2+=128;
						break;
					case "3":
						$byte2+=64;
						break;
					case "4":
						$byte2+=32;
						break;
					case "5":
						$byte2+=16;
						break;
					case "6":
						$byte2+=8;
						break;
					case "7":
						$byte2+=4;
						break;
					case "8":
						$byte2+=2;
						break;
					case "9":
						$byte2+=1;
						break;
					case "0":
						$byte1+=2;
						break;
					case "X":
						$byte1+=4;
						break;
					case "Y":
						$byte1+=8;
						break;
					case " ":
						$byte1+=0;
						break;
				}
			}

// 			echo "$i: byte1: $byte1<br/>byte2: $byte2<br/>";
			$bstring=pack("v",$byte1);
			if (fwrite($fhandle,$bstring,1)==false) {
				return 0;
			}
			$bstring=pack("v",$byte2);
			if (fwrite($fhandle,$bstring,1)==false) {
				return 0;
			}
		}
		fclose($fhandle);
		return 1;
	}

	function create_max_lenght_str($cheking_str, $needed_str_num) {
		$max_var_lenght = strlen($cheking_str);
		if ($max_var_lenght > $needed_str_num) {
			$return_str = substr($cheking_str,0,$needed_str_num);
		} else {
			unset($add_space);
			for ($n=0;$n<($needed_str_num-$max_var_lenght);$n++) {
				$add_space .= " ";
			}
			$return_str = $add_space.$cheking_str;
		}
		return $return_str;
	}

	function create_spaces($cur_column, $needed_column) {
		unset($return_spaces);
		for ($n=0;$n<($needed_column-$cur_column);$n++) {
			$return_spaces .= " ";
		}
		return $return_spaces;
	}
	public function exportAction()
	{
		$cc = new ConvertCodepage();

		$id_project = $_POST['projectId'];
		if($_POST['ids'])
		{
			$sqlWhere = "WHERE b.id IN (".$_POST['ids']. ")";
		}

		$export_select = $_POST['exportSelect'];
		$export_file_type = $_POST['exportFileType'];
		$SS10_type = $_POST['SS10exportFileType'];
		$data_export_separator = $_POST['dataSeparator'];
		$validonly = $_POST['validOnly'];
		$enc = $_POST['encoding'];
		$removeLine = $_POST['removeNewline'];
		if ($export_select == 6 OR ($export_select == 8 AND $export_file_type == 1) OR ($export_select== 5 && $SS10_type > 1)) {
				$koncnica = ".sps";
			} elseif ($export_select == 4) {
				$koncnica = ".txt";
			} elseif ($export_select == 3) {
				$koncnica = ".csv";
			} else {
				$koncnica = ".dat";
			}

			if ($export_into_screen == 1) {
				$lineBreak = "<BR>";
				$spaceChar = "&nbsp;";
				echo "<HTML>";
					echo "<head>";
						echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=$default_char_code_page\">";
					echo "</head>";
					echo "<BODY topmargin=2 BACKGROUND=\"\" BGCOLOR=\"#ffffff\" TEXT=\"#004aa0\"><PRE>";
			} elseif($export_select != 9) {
				$lineBreak = "\r\n";
				$spaceChar = " ";
  			header('Content-Type: application/octetstream');
				if ($export_select == 8 AND $export_file_type == 1) {
  				header('Content-Disposition: Attachment; filename="Read_ascii_'.$this->table.$koncnica.'"');
				} else {
  				header('Content-Disposition: Attachment; filename="Data_'.$this->table.$koncnica.'"');
				}
  			header('Expires: 0');
  			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  			header('Pragma: public');
			}



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

			$id_language = $_POST['id_language'];
			 	$id_lngDef = $_POST['id_lngDef'];
				//lets get the language data
			   	$sql = "SELECT * FROM $this->table"."_language INNER JOIN _LanguageText ON id_text_type = id_text WHERE id_language = $id_language OR id_language=$id_lngDef";
				$resLng = $this->db->SQLexecute($sql);
				while ($rowLng = $this->db->fetchAssoc($resLng))
				{
					if($rowLng['id_language'] == $id_language || !$lngArray[ $rowLng['id_question'] ][ $rowLng['variable'] ])
						$lngArray[ $rowLng['id_question'] ][ $rowLng['variable'] ] = $rowLng['id_text_type'] == 2 ? addslashes( $rowLng['lngText']) : $rowLng['lngText'] ;
				}

			$sql = "SELECT a.* FROM $this->table a INNER JOIN ".$this->table."_tree b ON a.id = b.id_question $sqlWhere ORDER by q_pos";
			if(!$res = $this->db->SQLexecute($sql)) { echo $this->db->JsonError(); exit; }

			if($_POST['sysChecked'] || $_POST['systemIds'])
			{
				if($_POST['systemIds'])
					$izbrane_kolone = $_POST['systemIds'];
				else {

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

                    //20152403 Tanis Added backslash after TP and EV beacouse oterwise you will get duplicate fields in export when there is field named tp or ev
					$telSql = "SHOW COLUMNS FROM `{$this->table}_structure` WHERE Field LIKE 'TP\_%' OR Field LIKE 'EV\_%'";

					$telRes = $this->db->SQLexecute($telSql);
					// Add by Borut 2015.01.26
					// in case of merged projects, sp_man column must be also exported
					$izbrane_kolone = "a.id, id_clien, flag_cli, user_id, user_type, id_device, id_loginSID, id_language, sp_man, id_site,a.status, a.status_rec, flag_bad, t_start, t_stop, d_start AS start_time, d_stop AS end_time, t_pause, t_diffs";

					while ($telRow = $this->db->fetchAssoc($telRes))
					{
						 $izbrane_kolone .= ",".$telRow['Field'];

					}


				}

			}

			//export of SPSS labels and frequencies
			if($export_select== 5 && $SS10_type > 1)
			{

				function remove_variables_str($str_var) {
					$str_var = " ".$str_var;
					while ($dolar_position = strpos($str_var,"$",$dolar_position)) {
						$space_position = strpos($str_var," ",$dolar_position);
						$str_var = substr($str_var,0,$dolar_position)."...".substr($str_var,$space_position);
					}
					return(substr($str_var,1));
				}


				while ($row = $this->db->fetchAssoc($res) )
				{
					if($lngArray[$row['id']])
					{
						foreach ($lngArray[$row['id']] as $lngVar => $lngText) {
							$row[$lngVar] = $lngText;
						}

					}
					$VAR = $row['q_name'];
                    //Tanis changed becouse of the problem with datetime export in csv
					$q = ExportQuestion::createQuestion($row['tip_sql'],$this->db,$row);
					$disable_question = $row['disable_question'];
					$tip = $row['tip_sql'];
					$scale_typ = $row['les_sql'];
					$vprasanje = addslashes( strip_tags( $row['vpr_sql'] ) );
					$odgovori = $q->cleanAnswerString($row['odg_sql']);
					$legenda = $q->cleanAnswerString($row['leg_sql']);

					//echo "tip: $tip\r\n";
					//echo "scale type: $scale_typ\r\n";
					//echo "answer num:  $answer_num\r\n";

					if($SS10_type == 2)
						include (PATH_TO_ROOT.'webcati/_ajax/ExImportData/make_labels.php');
					else if($SS10_type == 3)
						include (PATH_TO_ROOT.'webcati/_ajax/ExImportData/make_frequencies.php');

				}
				if($_POST['exportRecode'])
				{
					try {
						$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);
						$sql = "SELECT * FROM $this->table"."_var_lab";
						$res = $this->db->SQLexecute($sql);
						while ($row = $this->db->fetchAssoc($res))
						{
							$varmame = implode('_', explode('_',$row['varname'],-1) );
							if(!$done[$varmame])
							{
								$lab = strip_tags($row['lab']);
								$lab = str_replace(array('\n','\r','\t'),array(", ",""," "),$lab);
								$done[$varmame] = true;
								echo "VAR LABEL$lineBreak".$varmame."_1";
	  							echo " '".$lab."'.$lineBreak";
	  							$resLab = $this->db->SQLexecute("SELECT * FROM $this->table"."_labels WHERE var_name = '$varmame'");
	  							$write = true;
	  							while ($rowLab = $this->db->fetchAssoc($resLab))
	  							{
	  								if($write)
	  								echo "VAL LABEL ".$row['varname'];
	  								$write = false;

	  								$lab = strip_tags($rowLab['label']);
									$lab = str_replace(array('\n','\r','\t'),array(", ",""," "),$lab);
	  								echo "$lineBreak".$rowLab['id_var']." '".$lab."'";
	  							}
	  							if(!$write)
	  							echo ".$lineBreak";
						  		echo "$lineBreak";
						  		echo "$lineBreak";
							}
						}
					}
					catch (Exception $e)
					{

					}
					$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				}


				return ;
			}


			if($_POST['qFieldsIds'])
			{
				if($izbrane_kolone)
						$izbrane_kolone .= ',';
					$izbrane_kolone .=$_POST['qFieldsIds'];
			}
			else
			while ($row = $this->db->fetchAssoc($res) )
			{
				if($lngArray[$row['id']])
				{
					foreach ($lngArray[$row['id']] as $lngVar => $lngText) {
						$row[$lngVar] = $lngText;
					}

				}
                  //Tanis changed becouse of the problem with datetime export in csv
				$q = ExportQuestion::createQuestion($row['tip_sql'],$this->db,$row);
				$flds =  $q->getStructureFields();
				if(is_array($flds) && count($flds) > 0)
				{
					if($izbrane_kolone)
						$izbrane_kolone .= ',';
					$izbrane_kolone .='a.'.implode(',a.',$flds);
				}
				if($q->use_for_quotas)
				{
					$izbrane_kolone .= ',a.QT_'.$q->q_name;
				}
			}
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		//let's add the quota variables if they exist!
//			if($_POST['exportQuotas'] || true)
//			{
//				$telSql = "SHOW COLUMNS FROM `{$this->table}_structure` WHERE Field LIKE 'QT_%' AND Field != 'QT_user_id'";
//				$telRes = $this->db->SQLexecute($telSql);
//				while ($telRow = $this->db->fetchAssoc($telRes))
//				{
//					$izbrane_kolone .= ','.$telRow['Field'];
//				}
//			}
			if($_POST['exportRecode'])
			{
				$this->db->ChangeDatabase(DB_WARPIT_WEBRECODE);
				$telSql = "SHOW COLUMNS FROM `$this->table` WHERE Field != 'id'";
				$telRes = $this->db->SQLexecute($telSql);
				while ($telRow = $this->db->fetchAssoc($telRes))
				{
					$izbrane_kolone .= ',b.'.$telRow['Field']." AS REC_".$telRow['Field'];
				}
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

			}
			//let's add the telephone variables if they exist!
			//they will now be in the tree to select!
//			$telSql = "SHOW COLUMNS FROM `{$this->table}_structure` WHERE Field LIKE 'TP_%'";
//			$telRes = $this->db->SQLexecute($telSql);
//			while ($telRow = $this->db->fetchAssoc($telRes))
//			{
//				$izbrane_kolone .= ','.$telRow['Field'];
//			}


			$dateFrom = $_POST['dateFrom'];
			$dateTo = $_POST['dateTo'];
			$dataFilter = $_POST['dataFilter'];

			if($dateFrom)
				$where[] = "t_start >= $dateFrom";
			if($dateTo)
				$where[] = "t_start <= $dateTo";
			if($dataFilter)
				$where[] = '('.$dataFilter.')';


			if($_POST['telIds'] || $_POST['telFolder'])
			{
				$sql = "SELECT name,id_telname FROM _Projects INNER JOIN _TelephoneTables ON _TelephoneTables.id = id_telname  WHERE _Projects.id = $id_project";
				$telTable = $this->db->fetchRow($this->db->SQLexecute($sql));
				$telId = $telTable[1];
				$telTable = 'tel___'.$telTable[0];
				if($_POST['telIds'])
				{
				    
					//20151027 Tanis I trimed out all comas from inserted strings
                    $telFields = trim($_POST['telIds'], ",");
					//$telFields = 'c.'.implode(',c.',$telFields);
				}
				else {
					$telFields = '*';
				}

					//here we can have duplicates...we don't give a fuck
					$dataSQL = "SELECT $telFields,$izbrane_kolone FROM $telTable c ";
					$dataSQL .= " LEFT JOIN $this->table"."___telIndex d ON d.id_tel = c.id ";
					$dataSQL .= " LEFT JOIN $this->table"."_structure a ON a.id_tel = c.id"; //this last line is to prevent duplicates!
					if($validonly) $dataSQL .= " AND a.id IN (SELECT id FROM $this->table"."_structure WHERE  status=1 AND status_rec=1  group by id_tel)";
					$where[] = 'proj_reserved = '.$id_project;


			}
			else
			{
				if ($validonly) $where[] = "a.status=1 AND a.status_rec=1";

				$dataSQL  = "SELECT $izbrane_kolone FROM $this->table"."_structure a";
			}
			if($_POST['exportRecode'])
			{
				$dataSQL .= " INNER JOIN ".DB_WARPIT_WEBRECODE.".$this->table b ON a.id = b.id";
			}
			if($where)
				$dataSQL .= " WHERE ".implode(" AND ",$where);
			if(!$res = $this->db->SQLexecute($dataSQL)) { echo $this->db->JsonError(); exit; }


			$dispayColumns = true;
			$dispayData = true;
			switch ($export_select) {
				case 4:
					$separator = "\t";
				break;
				case 3:
					$encloser = '"';
					$separator = ";";
				break;
				//SPSS 8
				case 2:
				//SPSS 9
				case 7:
				//SPSS 10,11
				case 5:
				//SPSS datalist
				case 6:

						if($export_select == 5 && $SS10_type > 1)
						{




							break;
						}

						$dispayColumns = false;
						$number_of_fields = mysql_num_fields($res);

							if($export_select == 5)
								$txt_export_data = "GET DATA  /TYPE = TXT{$lineBreak} /FILE = 'd:\\test.dat'{$lineBreak} /DELCASE = LINE{$lineBreak} /DELIMITERS = \"$data_export_separator\"{$lineBreak} /ARRANGEMENT = DELIMITED{$lineBreak} /FIRSTCASE = 1{$lineBreak} /IMPORTCASE = ALL{$lineBreak} /VARIABLES = ";
  							else if($export_select == 6)
								$txt_export_data = "DATA LIST FREE{$lineBreak}";
							else
								$txt_export_data = "SET UNDEFINED = WARN.{$lineBreak}DATA LIST FILE='d:\\test.dat' FREE('$data_export_separator'){$lineBreak}/ ";

							for ($k=0; $k<$number_of_fields; $k++) {
								$name_of_field = mysql_field_name($res, $k);
								$type_of_field = mysql_field_type($res, $k);
								if ($type_of_field == "int") {
									$type_of_field = "F";
								}
								elseif ($type_of_field == "string" OR $type_of_field == "blob") {
									$type_of_field = "A";
								}
								elseif ($type_of_field == "time" || $type_of_field=='datetime') {
									$type_of_field = "A";
								}
								else {
									$type_of_field = "F";
								}
								$lenght_of_field = mysql_field_len($res, $k);
								if ($lenght_of_field>250) $lenght_of_field = 250;
								if($export_select == 5)
								$txt_export_data = $txt_export_data.$name_of_field." ".$type_of_field.$lenght_of_field." ";
								else
								$txt_export_data = $txt_export_data.$name_of_field."(".$type_of_field.$lenght_of_field.") ";
							}
								if($export_select == 7)
								{
									$rowAddition = $data_export_separator.'0';
									$txt_export_data = $txt_export_data."spss9fix(F1)";
								}

								if($export_select == 6)
								{
									$txt_export_data = $txt_export_data.".{$lineBreak}BEGIN DATA.{$lineBreak}";
									echo $txt_export_data;
									$separator = ' ';
									$encloser = "'";
								}
								else
								{
									$txt_export_data = $txt_export_data.".{$lineBreak}EXECUTE.{$lineBreak}";
									echo $txt_export_data;
									echo "{$lineBreak}{$lineBreak}{$lineBreak}";
								//in case 5, must be different ??????????? ask borut (data_export.php3 line 775
									echo "ASCII data to read into SPSS:{$lineBreak}Save to D disk as test.dat{$lineBreak}{$lineBreak}";
							  		$separator = $data_export_separator;
								}
				break;
				case 1:
				//fixed SPSS 7
					$dispayColumns = false;
					$number_of_fields = mysql_num_fields($res);

						$column_counter = 1;
			  		if ($export_into_screen == 1) {
							echo "<PRE>SPSS program for load database:<br><br>";
							$txt_export_data = "DATA LIST FILE=\"d:\\test.dat\" FIXED<br> / ";
				 		} else {
							echo "SPSS program for load database:\r\n\r\n";
							$txt_export_data = "DATA LIST FILE=\"d:\\test.dat\" FIXED\r\n / ";
			  		}
						for ($k=0; $k<$number_of_fields; $k++) {
							$name_of_field = mysql_field_name($res, $k);
							$type_of_field = mysql_field_type($res, $k);
							if ($type_of_field == "string" OR $type_of_field == "blob") {
								$type_of_field = "(A)";
								$column_counter_end = $column_counter + 59;
								$txt_export_data = $txt_export_data.$name_of_field." ".$column_counter."-".$column_counter_end." ".$type_of_field." ";
							}
							else {
								$lenght_of_field = mysql_field_len($res, $k);
								$column_counter_end = $column_counter + $lenght_of_field;
								$txt_export_data = $txt_export_data.$name_of_field." ".$column_counter."-".$column_counter_end." ";
							}
							$column_counter = $column_counter_end + 1;
						}
						$txt_export_data = $txt_export_data.".";
			  		if ($export_into_screen == 1) {
							echo $txt_export_data."<br>EXECUTE.<br><br>";
				 		} else {
							echo $txt_export_data."\r\nEXECUTE.\r\n \r\n";
			  		}

						while ($myrow = mysql_fetch_array($res)) {
							$column_counter = 1;
							for ($j=0; $j<$number_of_fields; $j++) {
								$name_of_field = mysql_field_name($res, $j);
			// samo da scistim enterje
								$clean_str = str_replace("\r\n", " ", $myrow[$name_of_field]);
								$clean_str = str_replace("\r", " ", $clean_str);
								$name_of_field = str_replace("\n", " ", $clean_str);

								$type_of_field = mysql_field_type($res, $j);
								if ( $type_of_field == "string" OR $type_of_field == "blob") {
									$column_counter_end = $column_counter + 59;
									$variable_data = $name_of_field;
									$variable_data = trim($variable_data);
									$variable_data = substr($variable_data,0,59);
									$variable_data_len = strlen($variable_data);
									echo $variable_data;
									for ($i=$variable_data_len;$i<60;$i++) {
										echo " ";
									}
								} else {
									$lenght_of_field = mysql_field_len($res, $j);
									$column_counter_end = $column_counter + $lenght_of_field;
									$variable_data = $name_of_field;
									$variable_data_len = strlen($variable_data);
									for ($i=$variable_data_len;$i<($lenght_of_field+1);$i++) {
										echo " ";
									}
									echo $variable_data;
								}
								$column_counter = $column_counter_end + 1;
							}
			    		if ($export_into_screen == 1) {
								echo "<br>";
			  	 		} else {
								echo "\r\n";
			    		}
						}
			  		if ($export_into_screen == 1) {
							echo "<br><br>";
				 		} else {
							echo "\r\n \r\n";
				 		}
				break;
				case 8:
				//Fixed (ASCII)
				$dispayData = false;
				$dispayColumns = false;
				$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
				if ($export_file_type == 1) {

					unset($export_vars_file);
	 				$export_vars_file = "DATA LIST FILE=\"c:\\tmp\\test.dat\" FIXED\r\n / ";
		     	  $select_ascii_datamap = "SELECT var_name, var_type, start_col, length_col FROM _DatamapAscii WHERE id_project=$id_project ORDER BY start_col";
		//				echo $select_ascii_datamap."<br>";

					if(!$result_ascii_datamap =  $this->db->SQLexecute($select_ascii_datamap)) { echo $this->db->JsonError(); exit; }
						while($row_ascii_datamap = mysql_fetch_array($result_ascii_datamap)) {
							$export_vars_file .= $row_ascii_datamap[var_name]." ".$row_ascii_datamap['start_col']."-".($row_ascii_datamap['start_col']+$row_ascii_datamap['length_col']-1)." ";
							if ($row_ascii_datamap[var_type] == "A") $export_vars_file .= "(A) ";
							$export_vars_file .= "\r\n";
						}
						$export_vars_file .= ".\r\nEXECUTE.";
						echo $export_vars_file;
					} else {
		// precitam vse podatke v structure
						if ($validonly) $only_valid = "WHERE status=1 AND status_rec=1";

                        //20.1.2015 Tanis je dodal as a v tabelo ker je bil error pri exportu
						$SQLselect_all_data = "SELECT $izbrane_kolone FROM ".$this->table."_structure a $only_valid $str_uts ORDER by id";
						//echo $SQLselect_all_data."<br>";
						$result_all_ascii =$this->db->SQLexecute($SQLselect_all_data);

		// precitam variable ki jih moram exportirat in za katere imam narejeno strukturo
		     	  $select_ascii_datamap = "SELECT var_name, var_type, start_col, length_col FROM _DatamapAscii WHERE id_project=$id_project ORDER BY start_col";
		//				echo $select_ascii_datamap."<br>";
		     		if(!$result_ascii_datamap =  $this->db->SQLexecute($select_ascii_datamap)) { echo $this->db->JsonError(); exit; }
						unset($all_export_vars);
						while($row_ascii_datamap = mysql_fetch_array($result_ascii_datamap)) {
							$all_export_vars['var_name'][] = $row_ascii_datamap['var_name'];
							$all_export_vars['var_type'][$row_ascii_datamap['var_name']] = $row_ascii_datamap['var_type'];
							$all_export_vars['start_col'][$row_ascii_datamap['var_name']] = $row_ascii_datamap['start_col'];
							$all_export_vars['length_col'][$row_ascii_datamap['var_name']] = $row_ascii_datamap['length_col'];
						}

		// za vsako vrsto podatkov nardim export fixed ascii
						while($row_all_ascii = mysql_fetch_array($result_all_ascii)) {
							$cur_column = 1;
							if($all_export_vars['var_name'])
							foreach($all_export_vars['var_name'] as $varname_item) {
								echo $this->create_spaces($cur_column, $all_export_vars['start_col'][$varname_item]);
								echo $this->create_max_lenght_str($row_all_ascii[$varname_item], $all_export_vars['length_col'][$varname_item]);
								$cur_column += ($all_export_vars['start_col'][$varname_item] - $cur_column) + $all_export_vars['length_col'][$varname_item];
							}
							echo "\r\n";
						}
					}
				break;
				case 9:
					$dispayData = false;
					$dispayColumns = false;
					include (PATH_TO_ROOT.'_support/class.SystemVariables.php');
					$definitionVar = new SystemVariables($this->db);
					$definitionVar->LoadVariables('1');
					$tmp_path_on_disk = TMP_PATH_ON_DISK;

					      $filename = $tmp_path_on_disk."/binary_export_file".$id_user;
					      if (file_exists($filename)) {
					        unlink($filename);
					      }
					// precitam vse podatke v structure
								if ($validonly) $only_valid = "WHERE status=1 AND status_rec=1";
                                //20.1.2015 Tanis je dodal as a v tabelo ker je bil error pri exportu
								$SQLselect_all_data = "SELECT $izbrane_kolone FROM ".$this->table."_structure as a $only_valid $str_uts ORDER by id";
					//			echo $SQLselect_all_data."<br>";
								$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
								if(!$result_all_binary = $this->db->SQLexecute($SQLselect_all_data))  { echo $this->db->JsonError(); exit; }

					// najprej rabim max stevilo kartic
					      $select_binary_numcard = "SELECT max(bin_card) FROM _DatamapBinary WHERE id_project=$id_project";
					//			echo $select_binary_numcard."<br>";
							if(!$result_binary_numcard = $this->db->SQLexecute($select_binary_numcard))  { echo $this->db->JsonError(); exit; }
								$row_binary_numcard = mysql_fetch_row($result_binary_numcard);
								$max_bincard = $row_binary_numcard[0];

					// precitam variable ki jih moram exportirat in za katere imam narejeno strukturo
					//20150511 Tanis odstrani field_cnt, ker tega ne potrebujemo pri exportu
					        $select_binary_datamap = "SELECT var_name,bin_card, bin_column, var_value, var_rec_value, bin_length FROM _DatamapBinary WHERE id_project=$id_project ORDER BY bin_card, bin_column, var_value";
				  // 			echo $select_binary_datamap."<br>";
				//exit;
                		if(!$result_binary_datamap = $this->db->SQLexecute($select_binary_datamap))  { echo $this->db->JsonError(); exit; }
									if (mysql_num_rows($result_binary_datamap)) {
									$fCnt = 1;
					  				while($row_binary_datamap = mysql_fetch_array($result_binary_datamap)) {
					  					/*//$all_export_vars['field_cnt'][] = $row_binary_datamap['field_cnt'];
					  					$all_export_vars['var_name'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_name'];
					  					$all_export_vars['bin_column'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_column'];
					  					$all_export_vars['bin_length'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_length'];
					  					$all_export_vars['var_value'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_value'];
					  					$all_export_vars['var_rec_value'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_rec_value'];
					  					$all_export_vars['bin_card'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_card'];
                                       */
                                        $all_export_vars['field_cnt'][] = $fCnt;
                                        $all_export_vars['var_name'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_name'];
                                        $all_export_vars['bin_column'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_column'];
                                        $all_export_vars['bin_length'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_length'];
                                        $all_export_vars['var_value'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_value'];
                                        $all_export_vars['var_rec_value'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['var_rec_value'];
                                        $all_export_vars['bin_card'][$row_binary_datamap['field_cnt']] = $row_binary_datamap['bin_card'];
					  				    $fCnt++;
                                    }

					// zdaj pa shranim vse rekorde, rekord po prekord, za vse kartice eno za drugo
						 				mysql_data_seek($result_all_binary,0);
					  				$cur_col_num = 0;
					  				while($row_all_binary = mysql_fetch_array($result_all_binary)) {
					  					foreach($all_export_vars[field_cnt] as $fieldcnt_item) {
					  						if (($row_all_binary[$all_export_vars['var_name'][$fieldcnt_item]] == $all_export_vars['var_value'][$fieldcnt_item] OR ($row_all_binary[$all_export_vars[var_name][$fieldcnt_item]] != $all_export_vars[var_value][$fieldcnt_item] AND !$all_export_vars[var_value][$fieldcnt_item])) AND $pre_realvar != $all_export_vars[var_name][$fieldcnt_item]) {
					//							echo "bin_card: ".$all_export_vars[bin_card][$fieldcnt_item]." | ".$row_all_binary[$all_export_vars[var_name][$fieldcnt_item]]." | ".$all_export_vars[var_name][$fieldcnt_item]." | ".$fieldcnt_item." | ".$all_export_vars[var_value][$fieldcnt_item]." - cur_col_num: $cur_col_num<br>";
					  							$pre_realvar = $all_export_vars['var_name'][$fieldcnt_item];
					// ce obstaja rekodirana vrednost potem vzamem tisto
					  							if ($all_export_vars['var_rec_value'][$fieldcnt_item] OR $all_export_vars['var_rec_value'][$fieldcnt_item]==="0") {
					  								$obdelovana_stevilka = $all_export_vars['var_rec_value'][$fieldcnt_item];
					  								$dolzina_stevilke = strlen($obdelovana_stevilka);
					//								echo "vzamem rekodirano<br>";
					  							} else {
					  								$obdelovana_stevilka = $row_all_binary[$all_export_vars['var_name'][$fieldcnt_item]];
					  								$dolzina_stevilke = strlen($obdelovana_stevilka);
					  							}
					  							$pricakovana_dolzina = $all_export_vars['bin_length'][$fieldcnt_item];
					//								echo "pricakovana_dolzina: $pricakovana_dolzina | dolzina_stevilke: $dolzina_stevilke<br>";
					  							if ($pricakovana_dolzina - $dolzina_stevilke < 0 ) {
					  								echo "<font color=red>You are exceed number of free columns!</font><br>";
														echo "bin_card: ".$all_export_vars['bin_card'][$fieldcnt_item]."<br>";
														echo "variable name: ".$all_export_vars['var_name'][$fieldcnt_item]."<br>";
														echo "variable value: ".$row_all_binary[$all_export_vars['var_name'][$fieldcnt_item]]."<br>";
														echo "curent column: ".$cur_col_num."<br>";
					  								exit();
					  							}
					  							$cur_col_num = ($all_export_vars['bin_column'][$fieldcnt_item] - 1) + ($pricakovana_dolzina - $dolzina_stevilke);
					  							for ($z=0; $z<$dolzina_stevilke; $z++) {
					  								$array_binary_store[$all_export_vars['bin_card'][$fieldcnt_item]][($cur_col_num+$z)] .= $obdelovana_stevilka[$z];
					  							}
					  						}
					  					}

					// tule se konca en rekord imam array po vseh karticah, grem ga izpisat v file
					// grem skozi vse bin kartice in exportiram podatke
											for ($cnt_bincar=1;$cnt_bincar<=$max_bincard;$cnt_bincar++) {
												if ($array_binary_store[$cnt_bincar]) {
													$binary_data_to_file = $array_binary_store[$cnt_bincar];
												} else {
					      					$binary_data_to_file = array(
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','',
					      					'','','','','','','','','','');
												}
						        		$this->StoreToBinary($binary_data_to_file, $tmp_path_on_disk, $id_user);
						            if (!file_exists($filename)) {
					  	            die("NO FILE HERE, $filename");
					    	        }
											}
					  					unset($array_binary_store);

					  				}
					  				unset($obdelovana_stevilka);
					  				unset($row_all_binary);
					  				unset($all_export_vars);
									} else {
										echo "Datamap is not define!";
										exit();
									}


					      header("Pragma: public");
					      header("Expires: 0");
					      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
					      header("Cache-Control: private",false);
					      header("Content-Type: application/force-download");
					      header("Content-Disposition: attachment; filename=\"Data_".$this->table.".rd\";");
					      header("Content-Transfer-Encoding: binary");
					      header("Content-Length: ".@filesize($filename));
					      set_time_limit(0);
					      @readfile("$filename") or die("File not found.");
				break;
				default:
					$separator = ',';
				break;
			}
			if($dispayColumns)
			{
				$row = $this->db->fetchAssoc($res);
				if($row)
				{
					$koloneArr = array_keys($row);
					echo implode($separator,$koloneArr).$lineBreak;

					echo $encloser.implode($encloser.$separator.$encloser,$row).$encloser.$rowAddition.$lineBreak;
				}

			}
			if($dispayData)
				while ($row = $this->db->fetchAssoc($res))
				{
					if($removeLine)
					{
						foreach ($row as &$rowData) {
							$rowData = str_replace(array("\n","\r"),' ',$rowData);
						}

					}
					//echo $encloser.implode($encloser.$separator.$encloser,$row).$encloser.$rowAddition.$lineBreak;
					echo $cc->convert_string('utf-8',$enc, $encloser.implode($encloser.$separator.$encloser,$row).$encloser.$rowAddition.$lineBreak);
				}
	}
	public function getFieldsAction()
	{
		//$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		//Tanis changed becouse of the problem with datetime export in csv
		$q = ExportQuestion::createQuestionFromTable($this->db,$this->table,$_POST['qId']);
		$p = $q->getStructureFields();
		return "{success:true,fields: '". implode(',', $p)."' }";

	}
	//with the template grids select we add a querry to translate the ids into question names
	public function selectAction()
	{

		if($_POST['RMcomp'] == 'tree')
		{
				$idProject = $_POST['id_project'];
				$sql = "SELECT name,id_telname FROM _Projects INNER JOIN _TelephoneTables ON _TelephoneTables.id = id_telname  WHERE _Projects.id = $idProject";
				$telTable = $this->db->fetchRow($this->db->SQLexecute($sql));
				$telId = $telTable[1];
				$telTable = $telTable[0];
				$node = $_POST['node'];
				if($node == '0')
				{


					if($telTable)
					{
						$tel['text'] = 'Telephone';
						$tel['id'] = 'telephoneFolder';
						$tel['leaf'] = false;
						$tel['checked'] = false;

						$data[] = $tel;
					}


					$sys['text'] = 'System';
					$sys['id'] = 'system';
					$sys['leaf'] = false;
					$sys['checked'] = true;

					$que['text'] = 'Questions';
					$que['id'] = 'question';
					$que['leaf'] = false;
					$que['checked'] = true;

					$data[] = $sys;
					$data[] = $que;

				}

				else if($node == 'telephoneFolder')
				{
					$telF['text'] = 'id_tel';
					$telF['id'] = 'id_tel';
					$telF['leaf'] = true;
					$telF['checked'] = false;
					$telF['dataType'] = 'tel_index';
					$data[] = $telF;

					$telField = array('oms','telephone','region','town','zip','name','address','status','status_rec','id_import');
					$ids = explode(',',$_POST['telIds']);
					foreach ($telField as $fieldKey => $fieldName) {
						$telF['text'] = $fieldName;
						$telF['id'] = $fieldName;
						$telF['leaf'] = true;
						$telF['checked'] = in_array('c.'.$fieldName,$ids);;
						$telF['dataType'] = 'telephone';
						$data[] = $telF;
					}



					$indexField = array('last_call','call_num','call_time','id_ank','ank_user_type','app_time','app_koment','status_comment','app_middle','app_call_this_num');
					foreach ($indexField as $fieldKey => $fieldName) {
							$telF['text'] = $fieldName;
							$telF['id'] = $fieldName;
							$telF['leaf'] = true;
							$telF['checked'] = in_array('d.'.$fieldName,$ids);;;
							$telF['dataType'] = 'tel_index';
							$data[] = $telF;
						}

					$tfRes = $this->db->SQLexecute("SELECT name FROM _TelephoneTablesAddon WHERE id_telbaza = $telId ORDER by orderBy");
					while ($tfRow = $this->db->fetchRow($tfRes))
					{
						$telF['text'] = 'tel_'.$tfRow[0];
						$telF['id'] = 'tel_'.$tfRow[0];
						$telF['leaf'] = true;
						$telF['checked'] = false;
						$telF['dataType'] = 'telephone';
						$data[] = $telF;
					}

				}
				else if ($node == 'system')
				{
					$sysField = array('id','id_clien','flag_cli','user_id','id_site','status','status_rec','t_start','t_stop','d_start','d_stop','t_pause');
					$ids = explode(',',$_POST['systemIds']);

					foreach ($sysField as $fieldKey => $fieldName) {
						$sysF['text'] = $fieldName;
						$sysF['id'] = $fieldName;
						$sysF['leaf'] = true;
						$sysF['checked'] = in_array('a.'.$fieldName,$ids);
						$sysF['dataType'] = 'system';
						$data[] = $sysF;
					}

					$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
                    //20152403 Tanis Added backslash after TP and EV beacouse oterwise you will get duplicate fields in export when there is field named tp or ev
					$telSql = "SHOW COLUMNS FROM `{$this->table}_structure` WHERE Field LIKE 'TP\_%' OR Field LIKE 'EV\_%'";
					$telRes = $this->db->SQLexecute($telSql);
					while ($telRow = $this->db->fetchAssoc($telRes))
					{
						$sysF['text'] = $telRow['Field'];
						$sysF['id'] = $telRow['Field'];
						$sysF['leaf'] = true;
						$sysF['checked'] = in_array('a.'.$telRow['Field'],$ids);
						$sysF['dataType'] = 'system';
						$data[] = $sysF;
					}
				}
				else if($node == 'question')
				{
					$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
					$ids = explode(',',$_POST['ids']);
					$sql = "SELECT a.*,b.tip_sql FROM $this->table"."_tree a LEFT JOIN $this->table b ON a.id=b.id WHERE is_leaf=true ORDER BY orderBy";
					$res = $this->db->SQLexecute($sql);
					while ($row = $this->db->fetchAssoc($res))
					{
						$queF['text'] = $row['idLab'];
						$queF['id'] = $row['id'];
						$queF['leaf'] = false;
						$queF['checked'] = in_array($row['id'],$ids);
						$queF['dataType'] = 'question';
						//Tanis changed becouse of the problem with datetime export in csv
						$q = ExportQuestion::createQuestion($row['tip_sql']);
						$queF['iconCls'] = $q->getIconCls();
						$data[] = $queF;
					}


				}
				else if(is_numeric($node))
				{
					$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
                    //Tanis changed becouse of the problem with datetime export in csv
					$q = ExportQuestion::createQuestionFromTable($this->db,$this->table,$node);
					$p = $q->getStructureFields();
					$ids = explode(',',$_POST['qFieldsIds']);
					//print_r($p);
					foreach ($p as $field) {
						$sysF['text'] = $field;
						$sysF['id'] = $field;
						$sysF['leaf'] = true;
						$sysF['checked'] = in_array($field,$ids);;
						$sysF['dataType'] = 'qFields';
						$data[] = $sysF;
					}

					if($q->use_for_quotas)
					{
						$sysF['text'] = 'QT_'.$q->q_name;
						$sysF['id'] = 'QT_'.$q->q_name;
						$sysF['leaf'] = true;
						$sysF['checked'] = false;
						$sysF['dataType'] = 'qFields';
						$data[] = $sysF;
					}


				}


			return json_encode($data);
		}
		$this->addWhere('id_project = '.$_POST['projectId']);
		$this->addWhere('templateType = '.$_POST['templateType']);
		$this->fetchSelect();
		foreach ($this->arr as &$row)
		{
			if($row['variables'])
			{
				$loadData = explode('|',$row['variables']);
				$qIds = $loadData[0];
				if($qIds)
				{
					$sql = "SELECT idLab FROM ".DB_WARPIT_WEBCATI.'.'.$_POST['tableName']."_tree WHERE id IN (".$qIds.')';
					If (!$rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
					unset($bla);
					while ($qR = $this->db->fetchArray($rs))
					{
						$bla[] = $qR[0];
					}
					if($bla)
						$row['varNames'] = implode(',',$bla);
				}
				//we need only questions to display the question line in selected fields
				$row['questionsOnly'] = $row['varNames'];

				$sys = explode(',',$loadData[1]);
				for($i=1;$i<count($sys);$i++ )
				{
					$tmp = explode('.',$sys[$i]); //removing the a.
					$sys[$i] = $tmp[1];
				}
				array_shift($sys);
				$sys = implode(',',$sys);
				$tel = explode(',',$loadData[2]);
				for($i=1;$i<count($tel);$i++ )
				{
					$tmp = explode('.',$tel[$i]); //removing the a.
					$tel[$i] = $tmp[1];
				}
				array_shift($tel);
				$tel = implode(',',$tel);
				if($sys[1])
					$row['varNames'] .= ','.$sys;
				if($tel[1])
					$row['varNames'] .= ','.$tel;
				$row['varNames'] .= ','.$loadData[3];
			}
		}
		return parent::selectAction();
	}

	public function saveTemplateAction()
	{
		$name = $_POST['name'];
		$ids = $_POST['ids'].'|'.$_POST['sysChecked'].','.$_POST['systemIds'].'|'.$_POST['telFolder'].','.$_POST['telIds'].'|'.$_POST['qFieldsIds'];
		$projectId = $_POST['projectId'];
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "INSERT INTO _ExportTemplate (id_project,templateName,variables,templateType) VALUES ($projectId,'$name','$ids',".$_POST['templateType'].")";
		If (!$rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
		return '{success:true}';
	}
}

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
$manipulator = new ExImportManipulator($db,$_POST['RMtable']);


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

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

}



?>