/**
 * Replace variable names using $nameMap in the tables of $questionId.
 */
function wrsqz_replaceVarReferencesInDatabase($questionType, $questionId, $nameMap){
    $extradbfields = array(
        'essay'       => array(),
        'match'       => array(
                         'question_match_sub'=>array('questiontext','answertext')
                         ),
        'multianswer' => array(),
        'multichoice' => array(
                         'question_multichoice'=>array('correctfeedback','partiallycorrectfeedback','incorrectfeedback'),
                         'question_answers'=>array('answer','feedback')
                         ),
        'shortanswer' => array(
                         'question_answers'=>array('answer','feedback')
                         ),
        'truefalse'   => array(
                         'question_answers'=>array('answer','feedback')
                         )
        );
    //update common text fields
    $question = get_record('question','id',$questionId);
    $question->questiontext = wrsqz_replaceVars($nameMap,$question->questiontext);
    $question->generalfeedback = wrsqz_replaceVars($nameMap,$question->generalfeedback);
    update_record('question', $question);

    //update type specific text fields
    $textfields = $extradbfields[$questionType];
    foreach($textfields as $table=>$fields){
        $values = get_records($table,'question',$questionId);
        foreach($values as $value){
            foreach($fields as $field){
                $value->$field = wrsqz_replaceVars($nameMap,$value->$field);
            }
            update_record($table, $value);
        }
    }
    //update special-encoded fields
    if($questionType == 'shortanswer' || $questionType=='multianswer'){
        $table = 'question_'.$questionType.'wiris';
        $wirisrecord = get_record($table,'question',$questionId);
        mb_parse_str($wirisrecord->eqoption, $eqoptionArray);
        if(isset($eqoptionArray['testFunctionName'])){
            foreach($eqoptionArray['testFunctionName'] as $index=>$value){
                $eqoptionArray['testFunctionName'][$index] = wrsqz_replaceVars($nameMap,$value, false);
            }
        }
        if(function_exists('http_build_query')){
            $wirisrecord->eqoption = http_build_query($eqoptionArray,null,'&');
        }else{
            $wirisrecord->eqoption = wrsqz_http_build_query($eqoptionArray);
        }
        if(!isset($wirisrecord->eqoption) || $wirisrecord->eqoption == null){
            $wirisrecord->eqoption = '';
        }
        update_record($table, $wirisrecord);
    }

    //recursive calls for multianswer question
    if($questionType == 'multianswer'){
        $subquestions = get_records('question','parent',$questionId,'id,qtype');
        foreach($subquestions as $id=>$subquestion){
            $qtype = $subquestion->qtype;
            if(substr($qtype,-5)=='wiris'){
                $qtype = substr($qtype,0,-5);
            }
            wrsqz_replaceVarReferencesInDatabase($qtype, $id, $nameMap);
        }
    }
    
}
function wrsqz_save_question_options($questionType, $dbType, &$question) {

    /*Delete old tables*/
  if (($oldproblem = get_records('question_' . $questionType . 'wiris', 'question', $question->id, 'id ASC')) === false) {
		$oldproblem = array();
	}
	
	foreach ($oldproblem as $op) {
		delete_records('question_' . $questionType . 'wiris', 'id', $op->id);
	}
	
	if(($oldproblem = get_records('question_' . $dbType, 'question', $question->id, 'id ASC')) === false) {
		$oldproblem = array();
	}
	
	foreach ($oldproblem as $op) {
		delete_records('question_' . $dbType, 'id', $op->id);
	}

  /*Store new values*/
	if (wrsqz_wirisQuizzesUsed($question)) {
		//common fields
    $problem->id = $problem->idcache = 0;
		$problem->question = $question->id;
    $program = $question->hiddenCASValue;
		$problem->md5 = md5($program);
    //options field

    //1. General options
    $options = array();
    if(!empty($question->wirisCASForComputations)){
      $options['wirisCASForComputations'] = $question->wirisCASForComputations;
    }
    if(!empty($question->hiddenInitialCASValue)){
      $options['hiddenInitialCASValue'] = stripslashes_safe($question->hiddenInitialCASValue);
    }
		
    //2. Question-type specific options
		if ($questionType == 'shortanswer') {
      $eqoptionArray=array();
      if(!empty($question->wirisEditor))
        $eqoptionArray['editor'] = 'true';
      if(!empty($question->multipleAnswers))
        $eqoptionArray['multipleAnswers'] = 'true';
      /*if(!empty($question->wirisCASForComputations))
        $eqoptionArray['wirisCASForComputations']='true';*/
      if(isset($question->testFunctionName)){
        $eqoptionArray['testFunctionName']=array();
        $eqoptionArray['testFunction'] = array();
        //get an indexed answer id array. this is done because answers are reordered
        //when are saved, skipping blank ones.
        if(isset($question->answers)){
          $answersList = explode(',',$question->answers);
        }else{
          $answersList = explode(',',wrsqz_deprecated_answersList($question));
        }
        $k=0;
        $answersId=array();
        foreach ($question->answer as $key => $dataanswer) {
          if (!(trim($dataanswer) == '' && $question->fraction[$key] == 0 && wrsqz_html_is_blank($question->feedback[$key]))) {
            $answersId[$key]=$answersList[$k];
            $k++;
          }
        }

        foreach($question->testFunctionName as $index => $value){
          if(!empty($value) && trim($value)!=''){
            $eqoptionArray['testFunctionName'][$index] = $value;
            if(isset($answersId[$index])){
              $eqoptionArray['testFunction'][$answersId[$index]]=$index;
            }
          }
        }
      }
      if(function_exists('http_build_query')){
        $problem->eqoption = http_build_query($eqoptionArray,null,'&');
      }else{
        $problem->eqoption = wrsqz_http_build_query($eqoptionArray);
      }
            
      if(!isset($problem->eqoption) || $problem->eqoption == null){
        $problem->eqoption='';
      }
            
		}else if ($questionType == 'truefalse') {
			$wirisAnswer = trim($question->wirisAnswer);
			$problem->override = (!empty($wirisAnswer)) ? $wirisAnswer : '';
		}else if ($questionType == 'multichoice') {
			$problem->override = implode(';', $question->gradeOverride);
		}else if ($questionType == 'multianswer'){
      $problem->eqoption = (empty($question->wirisEditor)) ? '' : 'editor=true&';
    }

    //serialize & save options field
    $problem->options = serialize($options);

		if (insert_record('question_' . $questionType . 'wiris', $problem) !== false) {
			unset($problem);
			
			$problem->id = 0;
			$problem->question = $question->id;
			$problem->program = $question->hiddenCASValue;

			if (insert_record('question_' . $dbType, $problem) !== false) {
				return true;
			}

			$result->error = 'Could not insert quiz WIRIS exercice!'; 
			return $result;
		}

		$result->error = 'Could not insert quiz ' . $questionType . 'wiris options!';
		return $result;
	}
	
	$question->qtype = $questionType;
	return update_record('question', $question);
}