<?php

	/**
	 * Function for fetching variables from structure table!
	 *
	 * @param string $vars comma seperated variables to be retrieved
	 * @return unknown
	 */
	function getVar($vars)
	{
		global $db;
		$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT $vars FROM ".$_SESSION['projname']."_structure WHERE id = ".$_SESSION['id_record'];
		$res = $db->SQLexecute($sql);
		$row = $db->fetchAssoc($res);
		/*foreach ($row as $key => $val) {
			echo $key;
			$GLOBALS[$key] = $val;
			echo $GLOBALS[$key];
		}*/
		return $row;
	}

	function getVarFromTable($aTable,$aSelectField,$aCondition) {
		global $db;
		$sql = "SELECT ".$aSelectField." FROM ".$aTable." ".$aCondition;
		//echo $sql;
		$res = $db->SQLexecute($sql);
		while ($row = $db->fetchAssoc($res)) {
			$r[] = $row;
		}
		return $r;
	}
	/**
	 * Function for storing variables into structure table!
	 *
	 * @param string $vars coma seprated, ie. q1=2,q2=6
	 * @return unknown
	 */
	function saveVar($vars)
	{
		global $db;
		$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "UPDATE ".$_SESSION['projname']."_structure SET $vars WHERE id = ".$_SESSION['id_record'];
		return $db->SQLexecute($sql);
	}


	/**
	 * Function for manualy seting answer rotation
	 *
	 * @param unknown_type $answers - can be either array with answers, where key is number and value is text
	 * 								or string as defined in the answer field
	 */
	function setAnswers($answers, $q_name = null)
	{
		global $qInfo,$questionnaire,$db;
		$d = new Display($db,$questionnaire);
		if(is_array($answers))
		{

		//	foreach ($answers as $val => $ans) {
		//		$finArr[]=array($val,$d->readRequiredQuestionVariables( $ans ) );
		//	}
		//20150330 Tanis added $q_name paramter becouse sometimes we call this function outside of script and $qInfo is not set yet.
		    if(!is_null($q_name)) $_SESSION['ansRotation'][$q_name] = $answers;
			$_SESSION['ansRotation'][ $qInfo['q_name']  ] = $answers;
         //   var_dump($_SESSION['ansRotation'][ $qInfo['q_name']  ] );


		}
		else if(is_string($answers))
		{
			include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
			$q = new Question();
			//we create a fake display so that we can use te reading!

			$_SESSION['ansRotation'][ $qInfo['q_name']  ] = $q->answerToArray( $d->readRequiredQuestionVariables( $answers )  );

		}
	}



	/**
	 * Function for manualy seting legend rotation
	 *
	 * @param unknown_type $legend - can be either array with legend answers, where key is number and value is text
	 * 								or string as defined in the legend answer field
	 */
	function setLegend($legend)
	{
		global $qInfo,$questionnaire,$db;
			$d = new Display($db,$questionnaire);
		if(is_array($answers))
		{

			foreach ($legend as $val => $ans) {
				$finArr[]=array($val,$d->readRequiredQuestionVariables( $ans ) );
			}
			$_SESSION['legRotation'][ $qInfo['q_name']  ] = $finArr;


		}
		else if(is_string($answers))
		{
			include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
			$q = new Question();
			//we create a fake display so that we can use te reading!
			$_SESSION['legRotation'][ $qInfo['q_name']  ] = $q->answerToArray( $d->readRequiredQuestionVariables( $legend )  );

		}
	}


	/**
	 * Function for setting question properties - Instruction
	 *
	 * @param string $text
	 */
	function setInstruction($text)
	{
		$GLOBALS['userSetInstruction'] = $text;
	}


	/**
	 * Function for setting question properties - Question
	 *
	 * @param string $text
	 */
	function setQuestion($text)
	{
		$GLOBALS['userSetQuestion'] = $text;
	}


	/**
	 * Function for setting question properties - Filter
	 *
	 * @param string $text
	 */
	function setFilter($text)
	{
		global $qInfo;
		$qInfo['fil_sql'] = $text;
	}


	/**
	 * Check how many columns are filled
	 *
	 * @param array $varArray
	 * @return int $maxAnswers (count of not null variables)
	 */
	function max_answers($varArray)
	{
		if(is_array($varArray))
		{
			$maxAnswers = 0;
			foreach ($varArray as $val) {
				//if( $val || $val === 0 || $val === '0' ) $maxAnswers++;
				// tole sem moral umakniti in zdaj 0 ni vec validen odgovor
				if( $val ) $maxAnswers++;
			}
		}
		return $maxAnswers;
	}


	/**
	 * Convert question name(s) to question id(s)
	 *
	 * @param unknown_type $questions
	 * question names, can be string, separated with coma or array
	 *
	 * @return array $ret (array of question name id(s))
	 */
	function nameToId($questions)
	{
		if(!is_array($questions))
			$questions = explode(',',$questions);
		global $db;
		$res = $db->get($_SESSION['proj_name'], "q_name IN ('".implode("','",$questions)."')",'id,q_name',DB_WARPIT_WEBCATI );
		$n2id = array();
		foreach ($res as $q) {
			$n2id[$q['q_name']] = $q['id'];
		}
		foreach ($questions as $q) {
			$ret[] = $n2id[$q];
		}

		return $ret;
	}


	/**
	 * Set questionnaire custom rotation string
	 *
	 * @param unknown_type $rot (can be string, separated with coma or array)
	 */
	function setRotationString($rot)
	{
		$e = $GLOBALS['engine'];
		$tmpRot = explode('/',$e->rotationString);
		$ids = nameToId($rot);
		//delete all questions in between and enter the passed string
		$start = $_SESSION['rotationStrStart']+1;
		$lng = $_SESSION['rotationStrLength'];
		for($i = $start;$i < $start+$lng; $i++ )
		{
			 unset( $tmpRot[$i] );
		}
		$i = $start+1;
		foreach ($ids as $id) {
			$tmpRot[$i] = $id;
			$i++;
		}

		ksort($tmpRot);
		// add also _End at the end of string (2/)
		$_SESSION['rotationString'] = $e->rotationString = implode('/',$tmpRot)."2/";
	}


	function unique_item_answer($all_answers) {
	$sum1 = array_sum($all_answers);
	$unique_all_answers = array_unique($all_answers, SORT_NUMERIC);
	$sum2 = array_sum($unique_all_answers);
	if ($sum1 == $sum2)
	return true;
	else
	return false;
	}

	function count_arr_values($all_answers,$cnt_number) {
	$tmp_cnt_arr = array_count_values($all_answers);
	return $tmp_cnt_arr[$cnt_number];
	}

	function structureCount($var,$cnd=false)
	{
		global $db;
		if($cnd) $cnd = 'WHERE '.$cnd;
		$sql = "SELECT count(*),$var FROM ".$_SESSION['projname']."_structure $cnd GROUP BY $var";
		$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

		$res = $db->SQLexecute($sql);
		$ret = array();
		while($row = $db->fetchRow($res))
				$ret[ $row[1] ] = $row[0];

		return $ret;
	}


	/**
	 * Enter description here...
	 *
	 * @param unknown_type $sql
	 * @return unknown
	 */
	function exeSql($sql) {
		global $db;
		$res = $db->SQLexecute($sql);
		return $res;
	}


	/**
	 * Function which comunicates with warpit API to make some actions more easy
	 *
	 * @param xml string $XMLstring
	 * @return returns curl result
	 */
	function xmlAPI($XMLstring) {

 		$url = WARPIT_WWW.'API/index.php';

		$fields = array(
			            'XML'=>urlencode($XMLstring),
			            'appID'=>urlencode("SoulskinerHardCodedAndVerySecure")
			        );

			//url-ify the data for the POST
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
		rtrim($fields_string,'&');

		//open connection
		$ch = curl_init();

		//set the url, number of POST vars, POST data
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch,CURLOPT_POST,count($fields));
		curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		//execute post
		$response = curl_exec($ch);
		$status = curl_getinfo($ch);

		/*echo "<pre>";
		print_r($response);
		echo "</pre>";
		*/
		return $response;
		//close connection
		curl_close($ch);
 	}

 	/**
 	 * Function which checks if email sytnax is correct. This function does not return if email is available or exists.
 	 *
 	 * @param string_type $email
 	 * @return bool
 	 * if return is true email is ok otherwise it is not ok...
 	 */

 	function check_email_address($email) {
	  // First, we check that there's one @ symbol,
	  // and that the lengths are right.
	  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
	    // Email invalid because wrong number of characters
	    // in one section or wrong number of @ symbols.
	    return false;
	  }
	  // Split it into sections to make life easier
	  $email_array = explode("@", $email);
	  $local_array = explode(".", $email_array[0]);
	  for ($i = 0; $i < sizeof($local_array); $i++) {
	    if
		(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
			$local_array[$i])) {
	      return false;
	    }
	  }
	  // Check if domain is IP. If not,
	  // it should be valid domain name
	  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
	    $domain_array = explode(".", $email_array[1]);
	    if (sizeof($domain_array) < 2) {
	        return false; // Not enough parts to domain
	    }
	    for ($i = 0; $i < sizeof($domain_array); $i++) {
	      if
			(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",
			$domain_array[$i])) {
	        return false;
	      }
	    }
	  }
	  return true;
	}

	/**
	 * check if number is real integer, english format
	 * if $cnt > 0 check also number of digits, must not be higher then $cnt
	 *
	 * @param unknown_type $number
	 * @return unknown
	 */
	function is_numeric_format($number,$cnt=0) {
		$clearNumber = str_replace(array(","), "", $number);
		if (ctype_digit($clearNumber))
			if ($cnt) {
				if (strlen($clearNumber) <= $cnt)
					return true;
				else
					return false;
			}
			else
				return true;
		else
			return false;
	}
	/**
     * @aConvert array key = fieldn name v cati structure val = field_name v poolu
     */
	function CopyWebuserspool($aConvert) {
		//return;
		global $db;
		foreach ($aConvert as $poolKey => $catiKey ) $tmp[] =  "a.".$catiKey." = b.".$poolKey;
		if ($tmp) {
		$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE.".".$_SESSION['projname']."_structure as a ,
					   ".DB_WARPIT_USERSPOOL."._Interviewer as b SET ".implode(", ",$tmp)." WHERE a.user_id = b.id AND a.id = ".$_SESSION['id_record'];
		$db->SQLexecute($sql);
		}
	}


    /**
     * Function copy value of all fields for selected question. This function works only with marged projects. Both questions need to be a same type and need to have equal number of fields
     *
     * @param string $projectFrom name of project you want to copy from
     * @param string $projectTo name of project you want to copy to
     * @param string $questionFrom name of question you want to copy fields from
     * @param string $questionTo name of question you want to copy fields to
     * @param array $fieldsArray array for mapping fields. Key is field in first project value is field in second project
     * @return none
     */
    function copyQuestion($projectFrom, $projectTo, $questionFrom, $questionTo, $fieldsArray = null)
    {
        global $db;
        include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');


        if(is_array($fieldsArray))
        {
            foreach($fieldsArray as $from => $to)
            {
                $tmpSql[] = "b." . $to . " = a." . $from;
             }
        }
        else
        {
            $row = $db->get($projectFrom, " q_name =  '". $questionFrom . "'" ,null, DB_WARPIT_WEBCATI);
            $questionIdFrom = $row[0]['id'];
            $qFrom = Question::createQuestionFromTable($db, $projectFrom, $questionIdFrom);
            $fieldsFrom = $qFrom->getStructureFields();

            $row = $db->get($projectTo, " q_name =  '". $questionTo . "'" ,null, DB_WARPIT_WEBCATI);
            $questionIdTo = $row[0]['id'];


            $qTo = Question::createQuestionFromTable($db, $projectTo, $questionIdTo);
            $fieldsTo = $qTo->getStructureFields();

            $tmpSql = array();
            if(count($fieldsTo) == count($fieldsFrom))
            {
                foreach($fieldsFrom as $field)
                {
                     $tmpSql[] = "b." . current($fieldsTo) . " = " . "a." . $field;
                    next($fieldsTo);
                }
            }
            else
            {
                print "Questions has diferent number of fields";
                return;
            }
        }


        $sql = "UPDATE " . DB_WARPIT_WEBCATI_BASE . "." . $projectFrom . "_structure AS a, " .
                DB_WARPIT_WEBCATI_BASE . "." . $projectTo . "_structure AS b
                SET " . implode(',', $tmpSql) . "
                WHERE a.sp_man = b.sp_man AND b.id = " . $_SESSION['id_record'];
        $db->SQLexecute($sql);

        $db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
    }

	// function which returns duration of previus question
	// You can use this function to filterout condition when do you want that someone needs to be on the question
	// for some time. Return of function is in seconds.
	// Added by Soulskiner, 14.3.2014 at 23.59
	function GetQuestionDuration() {
		if ( $_POST['RMquestionDuration'] ) return $_POST['RMquestionDuration'];
		else return false;
	}


	/**
	 * sum all fields inside multiresponse, if there is no question name, it return sum of current question
	 *
	 */
	function sum_mr($q_name = null, $exclude_col = null) {
		global $qInfo,$questionnaire,$db;
		$d = new Display($db,$questionnaire);
		include_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		$q = new Question();

		echo "<pre>";
		echo "<br><br><br>qInfo:<br>";
		var_dump($qInfo);
		echo "<br><br><br>display:<br>";
		var_dump($d);
		echo "<br><br><br>question:<br>";
		var_dump($q);
		echo "</pre>";
	}

  function CopyToUserPool($aConvert, $id_group = null)
  {
        global $db;

        $questionFieldsList = implode(",", $aConvert);
        $catiValues = getVar($questionFieldsList);

        $emailField = "";
        $otherFields = array();
        foreach($aConvert as $poolKey => $catiKey)
        {
            if(trim($poolKey) == "email" && strlen($poolKey) > 0)
                $emailField = "email = '" . mysql_real_escape_string($catiValues[$catiKey]) . "'";
            else
                $otherFields[] = $poolKey . " = '" . mysql_real_escape_string($catiValues[$catiKey]) . "'";
        }

        // DB_WARPIT_USERSPOOL DB_WARPIT_WEBCATI_BASE
        if(strlen($emailField) > 10)
        {
            $sql =  "INSERT INTO " . DB_WARPIT_USERSPOOL . "._Interviewer ";
            $sql .= " SET " . $emailField;
						if(count($otherFields) > 0)
						{
							$sql .= ","  . implode(',', $otherFields);
            	$sql .= " ON DUPLICATE KEY UPDATE "  . implode(',', $otherFields);
						}
            $db->SQLexecute($sql);
            $id = $db->GetLastInsertId();

            if($id_group && $id > 0)
            {
                $sql = "INSERT INTO " . DB_WARPIT_USERSPOOL . "._group_link SET id_group = " . $id_group . ", id = " . $id;
                $db->SQLexecute($sql);
            }
        }
    }

?>
