<?php
  global $_FILES;
  
	class cTestImportPage extends cTeacherPage
	{
    	 
    private static function ValidateXml($xml, &$message)
    {
      libxml_use_internal_errors(true);
      
      $doc = new DOMDocument('1.0', 'utf-8');
      $doc->loadXML($xml);
      
      $errors = libxml_get_errors();
      if (empty($errors))
      {	
    		if ( !$doc->validate() )
    		{
    			$message = "Neplatný xml súbor.";
    			return false;
    		}
   			return true;
      }

      $error = $errors[ 0 ];
      if ($error->level < 3)
      {
        return true;
      }

      $lines = explode("r", $xml);
      $line = $lines[($error->line)-1];

      $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

      return false;
    }
    
    function EvaluateTest($testID,$studentID)
    {
      $query = "SELECT *
								FROM tTest 
							 	WHERE id='".$testID."' AND mark IS NOT NULL;";
			$result = $this->db->QueryToRow($query);
      // ak test este nebol vyhodnoteny...
			if ( $result == 0 ) 
			{
				// vyhodnotenie testu
				// napln pole skalou
				$query = "SELECT tS.*, tC.name, tC.id AS id_course
									FROM tCourse AS tC
									INNER JOIN tScale AS tS ON tS.id = tC.id_scale
									INNER JOIN tTestTemplate AS tTT ON tTT.id_course = tC.id
									INNER JOIN tTest AS tT ON tT.id_testTemplate = tTT.id
									WHERE tT.id = '".$testID."';";
				$scale = $this->db->QueryToRow($query);

				$this->smarty->assign("courseId", $scale['id_course']);
				$this->smarty->assign("courseName", $scale['name']);

				// napln pole odpovedami
	      $query = "SELECT tQ.id AS id_question, tQ.question, tA.text, tTATA.value, tA.correct, ".
	               "tTA.comment, tTA.points, tTA.id AS id_testAnswer ".
	               "FROM tTest AS tT, tTestTemplate AS tTT, tTestItems as tTI, tAnswerSet AS tAS, ".
	               "tQuestion AS tQ, tAnswer AS tA, tTestAnswerToAnswer AS tTATA, tTestAnswer AS tTA ".
	               "WHERE tT.id=".$testID." AND tT.id_user=".$studentID." AND ".
	               "tT.id_testTemplate=tTT.id AND tTI.id_testTemplate=tTT.id AND ".
	               "tTI.id_answerSet=tAS.id AND tAS.id_question=tQ.id AND ".
	               "tA.id_answerSet=tAS.id AND tTATA.id_answer=tA.id AND ".
	               "tTATA.id_testAnswer=tTA.id AND tTA.id_test=tT.id ".
	               "ORDER BY tQ.id;";
	      $answers = $this->db->QueryToArray($query);
	      $questionId = 0;
	      $totalPoints = 0;
	      $points = 0;
				foreach ($answers as $answer) 
				{
					// zistit typ odpovede: full, missing, partial, bad
					
					if ($questionId == 0 || $questionId != $answer['id_question']) // ak som narazil na novu otazku
					{
																		
						if ($questionId != 0) 
						{
							if ($bad) // odpoved je zla
							{
								$answerType = 'bad';
								$points = $scale['ptsBad'];
							}
							elseif (!$answered) // odpoved nie je zodpovedana
							{
								$answerType = 'missing';
								$points = $scale['ptsEmpty'];
							}
							elseif ($partial) // odpoved je ciastocna
							{
								$answerType = 'partial';
								$points = $scale['ptsPartial'];
							}
							else // odpoved je spravna
							{
								$answerType = 'full';
								$points = $scale['ptsFull'];
							}

							// nastav spravne hodnoty v tTestAnswer
							$query = "UPDATE tTestAnswer SET points='$points', answerType='$answerType' WHERE id='$testAnswerId';";
							$result = $this->db->Query($query);
							$totalPoints += $points;
						}

						$questionId = $answer['id_question'];
						$testAnswerId = $answer['id_testAnswer'];
						$answered = false;
						$partial = false;
						$bad = false;
					}
					
					if ($answer['value'] === '1') $answered = true; // na otazku bolo odpovedane
					
					if ($answer['correct'] !== '1' && $answer['value'] === '1') // ak odpoved nie je spravna a aj napriek tomu je oznacena
					{
						$bad = true;
					}
					elseif ($answer['correct'] === '1' && $answer['value'] !== '1') // ak odpoved nie je oznacena ale je spravna
					{
						$partial = true;
					}
				}

				// treba spracovat este poslednu otazku
				if ($bad) // odpoved je zla
				{
					$answerType = 'bad';
					$points = $scale['ptsBad'];
				}
				elseif (!$answered) // odpoved nie je zodpovedana
				{
					$answerType = 'missing';
					$points = $scale['ptsEmpty'];
				}
				elseif ($partial) // odpoved je ciastocna
				{
					$answerType = 'partial';
					$points = $scale['ptsPartial'];
				}
				else // odpoved je spravna
				{
					$answerType = 'full';
					$points = $scale['ptsFull'];
				}

				// nastav spravne hodnoty v tTestAnswer
				$query = "UPDATE tTestAnswer SET points='$points', answerType='$answerType' WHERE id='$testAnswerId';";
				$result = $this->db->Query($query);
				$totalPoints += $points;

				// nastav spravne hodnoty v tTest
				// zisti aka je pridelena znamka na zaklade poctu bodov
				if ($totalPoints < $scale['E'])
				{
					$mark = 'Fx';
				}
				elseif ($totalPoints < $scale['D'])
				{
					$mark = 'E';
				}
				elseif ($totalPoints < $scale['C'])
				{
					$mark = 'D';
				}
				elseif ($totalPoints < $scale['B'])
				{
					$mark = 'C';
				}
				elseif ($totalPoints < $scale['A'])
				{
					$mark = 'B';
				}
				else
				{
					$mark = 'A';
				}
				$query = "UPDATE tTest SET points='$totalPoints', mark='$mark', totalTime=totalTime-NOW() WHERE id='".$testID."';";
				$result = $this->db->Query($query);
      }
    }
    
    function SaveTest($test, $examID)
    {
      if (isset($test["id"]) && isset($test["ISIC"]) && isset($test["questions"]) && (count($test["questions"])>0))
      {
        $query = "SELECT tT.id FROM tTest AS tT, tTestTemplate AS tTT WHERE tT.id_testTemplate=tTT.id AND ".
                 "tTT.printed=1 AND tT.id_exam=0 AND tT.id_user=0 AND tT.id=".$test["id"].";";
        $result = $this->db->QueryToRow($query);
        //test je nevyplneny a vytlaceny
        if ( $result != 0 )
        {
          $query = "SELECT tU.id FROM tUser AS tU, tStudents AS tS, tCourseToUser AS tCTU ".
                   "WHERE tS.id=tU.id AND tCTU.id_user=tU.id AND ".
                   "tCTU.id_course=".$this->getParams["courseID"]." AND tU.ISIC='".$test["ISIC"]."';";
          $result = $this->db->QueryToRow($query);
          //student patri predmetu
          if ( $result != 0 )
          {
            $studentID=$result["id"];
            foreach ($test["questions"] as $keyQ=>$valueQ)
            {
              $valueQ["order"]=mysql_real_escape_string($valueQ["order"]);
              foreach ($valueQ["answers"] as $keyA=>$valueA)
              {
                $valueA["order"]=mysql_real_escape_string($valueA["order"]);
                $valueA["value"]=mysql_real_escape_string($valueA["value"]);
                $query = "SELECT tTATA.id_answer, tTATA.id_testAnswer FROM tTestAnswerToAnswer AS tTATA, tTestAnswer AS tTA ".
                         "WHERE tTATA.id_testAnswer=tTA.id AND tTA.id_test=".$test["id"]." AND ".
                         "tTA.index=".$valueQ["order"]." AND tTATA.index=".$valueA["order"].";";
                $result = $this->db->QueryToRow($query);
                //student patri predmetu
                if ( $result != 0 )
                {
                  $answerID=$result["id_answer"];
                  $testAnswerID=$result["id_testAnswer"];
                  $query = "UPDATE tTestAnswerToAnswer SET value=".$valueA["value"]." ".
                           "WHERE id_answer=".$answerID." AND id_testAnswer=".$testAnswerID.";";
                  $result = $this->db->Query($query);
                }
              }
            }
            $query = "UPDATE tTest SET id_exam=".$examID.", id_user=".$studentID." WHERE ".
                     "id=".$test["id"].";";
            $result = $this->db->Query($query);
            $this->EvaluateTest($test["id"],$studentID);
          }
        }
        /*echo "Test: ".$test["id"]."<br />";
        echo $test["ISIC"]."<br />";
        echo "Otazky:<br />";
        foreach ($test["questions"] as $keyQ=>$valueQ)
        {
          echo $valueQ["order"]."<br />";
          echo "Odpovede: <br />";
          foreach ($valueQ["answers"] as $keyA=>$valueA)
          {
            echo $valueA["order"]."-".$valueA["value"]."<br />";
          }
        }
        echo "<br /><br />";
        */
      }
    }
    
    function __construct( $smarty, $db, $action, $postParams, $getParams )
    {
      parent::__construct( $smarty, $db, $action, $postParams, $getParams );
      $this->menu=new cCourseTeacherMenu;
      if (isset($this->getParams["courseID"]) && ($this->getParams["courseID"]!=="")) 
      {
        $this->menu->GenerateMenu("&amp;courseID=".$this->getParams["courseID"]);
      }
      else
      {
        $this->menu->GenerateMenu("");
      }
      $menuItem=$this->menu->GetItemByLabel("testy");
      $menuItem->bExpanded=true;
      $menuItem=$menuItem->GetItemByLabel("importovanie");
      $menuItem->bSelected=true;
    }
		
    function Process()
    {
      if ($this->bLoggedInAsTeacher && $this->IsTeacherToCourse())
      {
        if ($this->action==="import") 
        {
          $this->getParams["examID"]=$this->postParams["examID"];
          if (isset($_FILES["xml"]) && $this->IsCourseToExam())
          {
            $fp = fopen ($_FILES["xml"]["tmp_name"], "r");
            $content = fread ($fp, $_FILES["xml"]["size"]);
            fclose ($fp);
            
            $xmlParser = xml_parser_create('UTF-8');
          	xml_parser_set_option( $xmlParser, XML_OPTION_CASE_FOLDING, 0 );
      			xml_parser_set_option( $xmlParser, XML_OPTION_SKIP_WHITE, 1 );
      			if ( $this->ValidateXml($content, $error) )
      			{
      				xml_parse_into_struct( $xmlParser, $content, $values, $indexes );
      				$test=array();
      				foreach ($values as $key=>$value)
      				{
                if (($value["tag"]==="test") && ($value["type"]==="open"))
                {
                  $test=array();
                  $test["questions"]=array();
                }
                if (($value["tag"]==="test") && ($value["type"]==="close"))
                {
                  $this->SaveTest($test,$this->getParams["examID"]);
                }
                if (($value["tag"]==="ISIC") && ($value["type"]==="complete"))
                {
                  $test["ISIC"]=$value["value"];
                }
                if (($value["tag"]==="id") && ($value["type"]==="complete"))
                {
                  $test["id"]=$value["value"];
                }
                if (($value["tag"]==="question") && ($value["type"]==="open"))
                {
                  $test["questions"][count($test["questions"])]["answers"]=array();
                }
                if (($value["tag"]==="order") && ($value["type"]==="complete") && ($value["level"]==4))
                {
                  $test["questions"][count($test["questions"])-1]["order"]=$value["value"];
                }
                if (($value["tag"]==="answer") && ($value["type"]==="open"))
                {
                  $test["questions"][count($test["questions"])-1]["answers"][count($test["questions"][count($test["questions"])-1]["answers"])]["order"]=0;
                }
                if (($value["tag"]==="order") && ($value["type"]==="complete") && ($value["level"]==5))
                {
                  $test["questions"][count($test["questions"])-1]["answers"][count($test["questions"][count($test["questions"])-1]["answers"])-1]["order"]=$value["value"];
                }
                if (($value["tag"]==="value") && ($value["type"]==="complete"))
                {
                  $test["questions"][count($test["questions"])-1]["answers"][count($test["questions"][count($test["questions"])-1]["answers"])-1]["value"]=$value["value"];
                }
              }
              $this->smarty->assign("informationText", "Importovanie prebehlo úspešne.");
      			}
      			else
      			{
             $this->smarty->assign("informationText", $error);
            }
      			xml_parser_free( $xmlParser );
          }
          else
          {
            $this->smarty->assign("informationText", "Nedovolený upload xml súboru.");
          }
          $this->action="";
        }
      }
      return true;
    }
    
    function Draw()
    {
      if ($this->bLoggedInAsTeacher && ($this->IsTeacherToCourse())) 
      {
        if ($this->action==="")
        {
          $query = "SELECT tE.date, tE.id FROM tExam AS tE WHERE tE.id_course=".
                   $this->getParams["courseID"]." ORDER BY tE.date DESC;";
          $result = $this->db->QueryToArray($query);
          if ( $result != 0 )
          {
            foreach($result as $key=>$value)
            {
              $result[$key]["date"]=substr($result[$key]["date"],0,16);
            }
            $this->smarty->assign("examList", $result);
          }
        }
      }
      else
      {
        $this->bAccessDenied=true;
      }
      $this->smarty->assign("action", $this->action);
      $this->smarty->assign("course", $this->CourseName());
      $this->smarty->assign("courseID", $this->getParams["courseID"]);
      $this->smarty->assign("content","testImport.tpl");
      parent::Draw();
    }
	}
?>
