/**
 * Calls servlet to evaluate the program in order to obtain the variables of the question.
 */
function wrsqz_getInfo($questionType, $questionId, $data) {

	$varArray = wrsqz_getVars($data['text']);
	$vars = implode(',', $varArray);

	if (empty($vars)) {
		return array('' => '');
	}

	if (array_key_exists('function',$data)) {
		$function=$data['function'];
	} else {
		$function='var';
	}

	$postdata = array(
		'mode' => 'id',
		'function' => $function,
		'id' => $data['wiris']->idcache,
		'md5' => $data['wiris']->md5,
		'seed' => $data['seed'],
		'var' => $vars
	);

	// We do a first attempt to get the variables without sending the whole program because it might be cached.
	$msg = wrsqz_openServlet($postdata);
	$params = explode(';', $msg);

	if (trim($params[0]) == 'false') {
		
		if (array_key_exists('problem',$data)) {
			// Get the program from the parameter
			$problem=$data['problem'];
		}
		if (!isset($problem)) {
			// Get the program from the database
			$problem = wrsqz_getProgram($questionType, $questionId);
			if ($problem===false) {
				unset($problem);
			}
		}
		if (!isset($problem)) {
			// if it is not set, exit with error
			return false;
		}

		$postdata = array(
			'mode' => 'problem',
			'function' => $function,
			'md5' => $data['wiris']->md5,
			'seed' => $data['seed'],
			'var' => $vars,
			'problem' => $problem
		);
		
		$msg = wrsqz_openServlet($postdata);
		$params = explode(';', $msg);
	}
	
	$params_length = count($params);
	
	if ($params_length < 2) {
		return array();
	}
	
	if ($params_length < 3) {
		return array('id' => $params[1]);
	}
	
	$newVarArray = explode(':', $params[2]);
	$result = array();
	$i = 0;
	
	foreach ($varArray as $key => $value) {
		$varContent = explode('&', trim($newVarArray[$i]));
		
		if (count($varContent) >= 2) {
			$varContent[1] = wrsqz_trimQuotes($varContent[1], '"');
			$result[$key] = urldecode($varContent[1]);
			++$i;
		}
	}
	
	wrsqz_filterImages($result);
	
	return array(
		'vars' => $result,
		'id' => $params[1]
	);
}
function wrsqz_set_data($questionType, $dbType, &$mform, &$question) {
	$default_values = array();
	//common options
  if(isset($question->options->wiris->options)){
    $options = $question->options->wiris->options;
    if(isset($options['wirisCASForComputations'])){
      $default_values['wirisCASForComputations'] = $options['wirisCASForComputations'];
    }
    if(isset($options['hiddenInitialCASValue'])){
      $default_values['hiddenInitialCASValue'] = $options['hiddenInitialCASValue'];
    }
  }

  //question-type specific options
	if ($questionType == 'shortanswer' && isset($question) && isset($question->options) && isset($question->options->wiris) && isset($question->options->wiris->eqoption)) {
		$default_values['wirisEditor'] = '';
		mb_parse_str($question->options->wiris->eqoption, $eqoptionArray);

		if (isset($eqoptionArray['editor']) && $eqoptionArray['editor'] == 'true') {
			$default_values['wirisEditor'] = '1';
		}
		if (isset($eqoptionArray['multipleAnswers']) && $eqoptionArray['multipleAnswers'] == 'true') {
			$default_values['multipleAnswers'] = '1';
		}
		/*if (isset($eqoptionArray['wirisCASForComputations']) && $eqoptionArray['wirisCASForComputations'] == 'true') {
			$default_values['wirisCASForComputations'] = '1';
		}*/

		if (isset($eqoptionArray['testFunction'])){
      //set testFunctionNames where their associated answers are
      $index = 0;
      
      foreach ($question->options->answers as $answer){
        if (isset($eqoptionArray['testFunction'][$answer->id])){
          $testFunctionNameIndex = $eqoptionArray['testFunction'][$answer->id];
          $default_values['testFunctionName['.$index.']'] = $eqoptionArray['testFunctionName'][$testFunctionNameIndex];
          unset($eqoptionArray['testFunctionName'][$testFunctionNameIndex]);
        }
        $index++;
      }
      //set test functions with no associated answer.
      foreach($eqoptionArray['testFunctionName'] as $key => $value){
        $default_values['testFunctionName['.$index.']'] = $value;
        $index++;
      }
    }else if (isset($eqoptionArray['testFunctionName'])){
      //Backwards compatibility for old WIRIS quizzes (didn't have testFunction attribute).
      foreach ($eqoptionArray['testFunctionName'] as $index => $value){
        $default_values['testFunctionName['.$index.']'] = $eqoptionArray['testFunctionName'][$index];
      }
    }

	}else if($questionType == 'multianswer' && isset($question) 
    && isset($question->options) && isset($question->options->wiris)
    && isset($question->options->wiris->eqoption)){

    mb_parse_str($question->options->wiris->eqoption, $eqoptionArray);
    if (isset($eqoptionArray['editor']) && $eqoptionArray['editor'] == 'true') {
			$default_values['wirisEditor'] = '1';
		} else {
      $default_values['wirisEditor'] = '';
    }
  }

	if (isset($question) && isset($question->options) && isset($question->options->wiris) && !empty($question->options->wiris->override)) {
		if ($questionType == 'multichoice') {
			$overrideList = explode(';', $question->options->wiris->override);
			
			foreach ($overrideList as $key => $value) {
				$default_values['gradeOverride[' . $key . ']'] = $value;
			}
		}else if ($questionType == 'truefalse') {
			$overrideList = explode(';', $question->options->wiris->override);
			$default_values['wirisAnswer'] = $overrideList[0];
		}
	}

	global $CFG;
	
	$pos = ($mform->_elementIndex['hiddenCASValue']);
	$value = trim($mform->_elements[$pos]->_attributes['value']);

  $selectedLang = optional_param('WIRISCASLang','',PARAM_ALPHA);
  $availableLangs = wrsqz_getAvailableCASLangs();

	if (!empty($value)) {
		$program = $value;
    $sessionLang = wrsqz_CASLanguageFromSession($program);
    if(in_array($selectedLang, $availableLangs) && $selectedLang != $sessionLang){
      //We have to translate the WIRIS session
      $translation = wrsqz_translateCASSession($program,$selectedLang);
      if($translation !==false){
        $program = $translation[0];
        $CASLang = $selectedLang;
        //Rearrange all form fields with the new named variables (at the end of the function).
      }else{
        //We couldn't translate the program. Do nothing
        $CASLang = $sessionLang;
      }
    }else{
      $CASLang = $sessionLang;
    }
	}else{
        if (isset($question) && isset($question->id)
        && ($program = wrsqz_getProgram($questionType, $question->id)) !== false
        && !empty($program)) {
            $CASLang = wrsqz_CASLanguageFromSession($program);
        }else {
            $CASLang = wrsqz_currentCASLanguage();
            $program = wrsqz_getDefaultCASCode($CASLang);
        }
    }

  $default_values['htmlWirisEditor']  = '<applet  name="WirisCASApplet" code="' . wrsqz_getCASClass($CASLang) . '" codebase="' . $CFG->wiriscascodebase . '" archive="' . wrsqz_getCASArchive($CASLang) . '" height="450" WIDTH="100%">';
	$default_values['htmlWirisEditor'] .= '<param name="version" value="2.0"/>';
	$default_values['htmlWirisEditor'] .= '<param name="command" value="false"/>';
	$default_values['htmlWirisEditor'] .= '<param name="commands" value="false"/>';
	$default_values['htmlWirisEditor'] .= '<param name="interface" value="false"/>';
	$default_values['htmlWirisEditor'] .= '<param name="XMLinitialText" value="' . htmlentities($program, ENT_QUOTES, 'UTF-8') . '"/>';
	$default_values['htmlWirisEditor'] .= '</applet>';
  $default_values['WIRISCASLang'] = $CASLang;
    
	// defined only because we call wrsqz_wirisQuizzesUsed
  $default_values['hiddenCASValue'] = $program;

  $question = (object)(array_merge((array)$question, $default_values));

  if(isset($translation) && ! empty($translation[1])){
        //If WIRIS CAS program had to be translated, there may be references (#a) to
        //old variable names, so replace them.
    wrsqz_replaceVarReferencesInFlatQuestion($questionType, $question, $translation[1]);
    wrsqz_replaceVarReferencesInForm($questionType, $mform, $translation[1]);
  }

  // If uses wiris quizzes, display advanced otherwise the program
  // is lost if the advanced button is never clicked
  if (wrsqz_wirisQuizzesUsed($question)) {
     $mform->setShowAdvanced(1);
  }

}