<?php
$max_unit_length = 50;

    if (isset($_GET['delete_test']) && eF_checkParameter($_GET['delete_test'], 'id')) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        try {
            $currentTest = new EfrontTest($_GET['delete_test']);
            $currentTest -> delete();
            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&message=".urlencode(_SUCESSFULLYDELETEDTEST)."&message_type=success");
        } catch (Exception $e) {
            $message      = _SOMEPROBLEMEMERGED.': '.$e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['add_test']) || (isset($_GET['edit_test']) && eF_checkParameter($_GET['edit_test'], 'id')) || (isset($_GET['edit_unit']) && eF_checkParameter($_GET['edit_unit'], 'id'))) {
        if (isset($_GET['edit_unit'])) {
            $currentTest        = new EfrontTest($_GET['edit_unit'], true);
            $_GET['edit_test'] = $currentTest -> test['id'];
        }

        try {
            $optionsArray = $currentContent -> toHTMLSelectOptions();    //Get the units as an array of formated strings, that can be used to form an HTML select list
            isset($_GET['edit_test']) ? $postTarget = basename($_SERVER['PHP_SELF'])."?ctg=tests&edit_test=".$_GET['edit_test'] : $postTarget = basename($_SERVER['PHP_SELF'])."?ctg=tests&add_test=1&from_unit=".$_GET['from_unit'];
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }

        $load_editor = true;

        $form = new HTML_QuickForm("question_form", "post", $postTarget, "", null, true);
        $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter');                   //Register this rule for checking user input with our function, eF_checkParameter

        $select_units = & HTML_QuickForm :: createElement('select', 'parent_content', _UNITPARENT, null, 'class = "inputSelect"');

        //Check if the test's parent unit exists or is inactive 
        if (isset($_GET['edit_test'])) {
            $currentTest = new EfrontTest($_GET['edit_test']);
            $testUnit    = $currentTest -> getUnit();
            if (!in_array($testUnit['parent_content_ID'], array_keys($optionsArray))) {
                $result = eF_getTableData("content", "name", "id=".$testUnit['parent_content_ID']);
                //If it doesn't exist, update the parent unit to root
                if (sizeof($result) == 0) {
                    $testUnit['parent_content_ID'] = 0;
                    $testUnit -> persist();
                } else {
                    $optionsArray[$testUnit['parent_content_ID']] = $result[0]['name'];            //Append the inactive unit's name to the select box (which will be freezed below)
                }
            }
        }
        $select_units -> addOption(_ROOTUNIT, 0);
        $select_units -> loadArray($optionsArray);
        $form -> addElement($select_units);

        $form -> addRule('parent_content', _THEFIELD.' '._UNITPARENT.' '._ISMANDATORY, 'required', null, 'client');
        $form -> addRule('parent_content', _INVALIDID, 'numeric');

        $form -> addElement('text', 'name', null, 'class = "inputText"');
        $form -> addRule('name', _THEFIELD.' "'._NAME.'" '._ISMANDATORY, 'required', null, 'client');
        $form -> addRule('name', _INVALIDFIELDDATAFORFIELD.' "'._NAME.'"', 'checkParameter', 'text');

        $form -> addElement('text', 'duration', null, 'class = "inputText"');
        $form -> addRule('duration', _THEFIELD.' "'._DURATIONINMINUTES.'" '._ISMANDATORY, 'required', null, 'client');
        $form -> addRule('duration', _THEFIELD.' "'._DURATIONINMINUTES.'" '._MUSTBENUMERIC, 'numeric', null, client);

        $form -> addElement('text', 'redoable', null, 'class = "inputText"');
        $form -> addRule('redoable', _THEFIELD.' "'._REDOABLE.'" '._MUSTBENUMERIC, 'numeric', null, client);

        $form -> addElement('advcheckbox', 'onebyone',          null, null, null, array(0, 1));
        $form -> addElement('advcheckbox', 'given_answers',     null, null, null, array(0, 1));
        $form -> addElement('advcheckbox', 'answers',           null, null, null, array(0, 1));
        $form -> addElement('advcheckbox', 'shuffle_answers',   null, null, null, array(0, 1));
        $form -> addElement('advcheckbox', 'shuffle_questions', null, null, null, array(0, 1));
        $form -> addElement('textarea',    'description',       null, 'class = "mceEditor" style = "width:100%;height:16em;"');

        isset($_GET['from_unit']) && eF_checkParameter($_GET['from_unit'], 'id') ? $selectedUnit = $_GET['from_unit'] : $selectedUnit = 0;
        $selectedUnit ? $units = $currentContent -> getNodeChildren($selectedUnit) : $units = $currentContent -> tree;
        foreach ($iterator = new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($units)), array('id', 'name')) as $key => $value) {
            $key == 'id' ? $ids[] = $value : $names[] = $value;
        }
        $unitNames      = array_combine($ids, $names);
        $questions_list = eF_getTableData("questions", "*", "content_ID IN (".implode(",", $ids).")", "content_ID ASC,  timestamp DESC");     //Retrieve all questions that belong to this unit or its subunits

        $done_questions = eF_getTableData("done_questions", "*");                                       //Get all the done questions
        foreach ($done_questions as $done_question) {
            $done_question_ids[$done_question['questions_ID']][] = $done_question['score'];             //Group done questions per question, and get the score
        }

        $difficulties = array('low' => array(), 'medium' => array(), 'high' => array());
        for ($i = 0; $i < sizeof($questions_list); $i++) {
            $form -> addElement("checkbox", "questions[".$questions_list[$i]['id']."]");
            $form -> addElement('select', 'question_weight['.$questions_list[$i]['id'].']', null, array(1 => '1', 2, 3, 4, 5, 6, 7, 8, 9, 10));

            if ($done_question_ids[$questions_list[$i]['id']]) {
                $questions_list[$i]['done_times']    = sizeof($done_question_ids[$questions_list[$i]['id']]);
                $questions_list[$i]['average_score'] = round(array_sum($done_question_ids[$questions_list[$i]['id']]) / sizeof($done_question_ids[$questions_list[$i]['id']]) * 100, 2) ;
            } else {
                $questions_list[$i]['done_times']    = 0;
                $questions_list[$i]['average_score'] = '';
            }

            $questions_list[$i]['text']           = strip_tags($questions_list[$i]['text']);        //If we ommit this line, then the questions list is html formatted, images are displayed etc, which is *not* the intended behaviour
            $questions_list[$i]['parent_name']    = $unitNames[$questions_list[$i]['content_ID']];
            $questions[$questions_list[$i]['id']] = $questions_list[$i];

            $difficulties[$questions_list[$i]['difficulty']][] = $questions_list[$i]['id'];         //Gather the number of questions per difficulty
        }

        $form -> addElement('advcheckbox', 'random_test', null, null, 'onclick = "if (this.checked) document.getElementById(\'random_questions\').style.display = \'\'; else document.getElementById(\'random_questions\').style.display = \'none\';"', array(0, 1));
        $form -> addElement('select', 'low',    _EASY,   range(0, sizeof($difficulties['low'])));
        $form -> addElement('select', 'medium', _MEDIUM, range(0, sizeof($difficulties['medium'])));
        $form -> addElement('select', 'high',   _HARD,   range(0, sizeof($difficulties['high'])));
        $form -> setDefaults(array('random_test' => 0,
                                   'low'         => sizeof($difficulties['low']),
                                   'medium'      => sizeof($difficulties['medium']),
                                   'high'        => sizeof($difficulties['high'])));
        $form -> addElement('submit', 'submit_random_test', _CREATE, 'class = "flatButton"');

        if (isset($_GET['edit_test'])) {

            $form -> freeze('parent_content');
            $form -> setDefaults(array('parent_content'    => $testUnit['parent_content_ID'],
                                       'name'              => $testUnit['name'],
                                       'duration'          => round($currentTest -> test['duration'] / 60),   //Duration is displayed in minutes, but is stored in seconds
                                       'redoable'          => $currentTest -> test['redoable'],
                                       'onebyone'          => $currentTest -> test['onebyone'],
                                       'given_answers'     => $currentTest -> test['given_answers'],
                                       'answers'           => $currentTest -> test['answers'],
                                       'description'       => $currentTest -> test['description'],
                                       'shuffle_answers'   => $currentTest -> test['shuffle_answers'],
                                       'shuffle_questions' => $currentTest -> test['shuffle_questions']));

            foreach ($currentTest -> getQuestions() as $testQuestion) {                                     //Set to selected the questions that the test includes, along with their weights
                $form -> setDefaults(array('questions['.$testQuestion['id'].']'       => 1,
                                           'question_weight['.$testQuestion['id'].']' => $testQuestion['weight']));
            }
            $smarty -> assign("T_CURRENT_TEST", $currentTest -> test);
        }

        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            $form -> freeze();            
        } else {
            $form -> addElement('submit', 'submit_test', _SAVETEST, 'class = "flatButton"');
            if (isset($_GET['edit_test'])) {
                $form -> addElement('submit', 'submit_test_new', _SAVEASNEWTEST, 'class = "flatButton"');
            }
            
            if ($form -> isSubmitted() && $form -> validate()) {
                $values = $form -> exportValues();
                if (isset($_GET['edit_test']) && !isset($values['submit_test_new'])) {                                                            //This means we are updating an existing test; Assign existing values to form elements
                    try {
                        $testUnit['name']              = $values['name'];
                        $testUnit['parent_content_ID'] = $values['parent_content'];
                        $testUnit -> persist();

                        $testFields = array('duration'          => ($values['duration'] * 60),              //Duration is displayed in minutes, but is stored in seconds
                                            'redoable'          => $values['redoable'] ? $values['redoable'] : 0,
                                            'onebyone'          => $values['onebyone'],
                                            'given_answers'     => $values['given_answers'],
                                            'answers'           => $values['answers'],
                                            'description'       => $values['description'],
                                            'shuffle_answers'   => $values['shuffle_answers'],
                                            'shuffle_questions' => $values['shuffle_questions']);
                        $currentTest -> test = array_merge($currentTest -> test, $testFields);
                        $currentTest -> persist();
                        $currentTest -> removeQuestions();

                        if (isset($values['submit_random_test'])) {
                            $values['questions'] = array();
                            foreach ($difficulties as $key => $difficulty) {
                                if (sizeof($difficulty) > 0 && $values[$key] <= sizeof($difficulty)) {
                                    shuffle($difficulty);
                                    $temp = array_slice($difficulty, 0, $values[$key]);
                                    $values['questions'] = array_merge($temp, $values['questions']);
                                }
                            }
                            $values['questions'] = array_flip($values['questions']);
                        }

                        foreach ($values['questions'] as $key => $question) {                        //Assign corresponding weights to submitted questions
                            $values['questions'][$key] = $values['question_weight'][$key];
                        }
                        $currentTest -> addQuestions($values['questions']);
                        header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&message=".urlencode(_SUCCESFULLYMODIFIEDTEST)."&message_type=success");
                    } catch (Exception $e) {
                        $message      = _SOMEPROBLEMEMERGED.': '.$e -> getMessage().' ('.$e -> getCode().')';
                        $message_type = 'failure';
                    }
                } else {
                    $contentFields = array('data'              => '',
                                           'name'              => $values['name'],
                                           'lessons_ID'        => $currentLesson -> lesson['id'],
                                           'ctg_type'          => "tests",
                                           'active'            => 1,
                                           'timestamp'         => time(),
                                           'parent_content_ID' => $values['parent_content']);

                    $testFields = array('active'            => 1,
                                        'content_ID'        => $test_content_ID,
                                        'duration'          => ($values['duration'] * 60),  //Duration is displayed in minutes, but is stored in seconds
                                        'redoable'          => $values['redoable'] ? $values['redoable'] : 0,
                                        'onebyone'          => $values['onebyone'],
                                        'given_answers'     => $values['given_answers'],
                                        'answers'           => $values['answers'],
                                        'description'       => $values['description'],
                                        'shuffle_answers'   => $values['shuffle_answers'],
                                        'shuffle_questions' => $values['shuffle_questions']);

                    try {
                        $newUnit = $currentContent -> insertNode($contentFields);
                        $newTest = EfrontTest :: createTest($newUnit, $testFields);

                        foreach ($values['questions'] as $key => $question) {                        //Assign corresponding weights to submitted questions
                            $values['questions'][$key] = $values['question_weight'][$key];
                        }
                        $newTest -> addQuestions($values['questions']);
                        header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&message=".urlencode(_SUCCESFULLYADDEDTEST)."&message_type=success");
                    } catch (Exception $e) {
                        $message      = _SOMEPROBLEMEMERGED.': '.$e -> getMessage().' ('.$e -> getCode().')';
                        $message_type = 'failure';
                    }
                }
            }
        }
        $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);


        $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
        $form -> setRequiredNote(_REQUIREDNOTE);
        $form -> accept($renderer);

        $smarty -> assign('T_TEST_FORM', $renderer -> toArray());
        $smarty -> assign('T_UNIT_QUESTIONS', $questions);
        $smarty -> assign("T_QUESTIONTYPESTRANSLATIONS", Question :: $questionTypes);//pr($question_types_translations);
        $smarty -> assign("T_QUESTIONDIFFICULTYTRANSLATIONS", array('low' => _LOW, 'medium' => _MEDIUM, 'high' => _HIGH));//pr($question_types_translations);

    } elseif (isset($_GET['show_test']) && eF_checkParameter($_GET['show_test'], 'id') || isset($currentUnit)) {
        try {
            if (isset($currentUnit)) {                //Preview the test like you normally view the ontent
                $showTest = new EfrontTest($currentUnit['id'], true);
                $iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1));
                $smarty -> assign("T_UNIT",          $currentUnit);
                $smarty -> assign("T_NEXT_UNIT",     $currentContent -> getNextNode($currentUnit, $iterator));
                $smarty -> assign("T_PREVIOUS_UNIT", $currentContent -> getPreviousNode($currentUnit, $iterator));        //Next and previous units are needed for navigation buttons
                $smarty -> assign("T_PARENT_LIST",   $currentContent -> getNodeAncestors($currentUnit));       //Parents are needed for printing the title
                $smarty -> assign("T_SHOW_TOOLS",    true);                                                    //Tools is the right upper corner table box, that lists tools such as 'upload files', 'copy content' etc

                $iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1));
                $smarty  -> assign("T_CONTENT_TREE", $currentContent -> toHTML($iterator, 'dhtmlContentTree', array('truncateNames' => 20, 'edit' => true, 'selectedNode' => $currentUnit['id'])));

            } else {                                //Preview the test without all the navigation info
                // Check if the test id is a content ID or a test ID
                if (isset($_GET['isContentId'])) {
                    $test_id = eF_getTableData("tests","id","content_ID = '".$_GET['show_test']."'");
                    $showTest = new EfrontTest($test_id[0]['id']);
                } else {
                    $showTest = new EfrontTest($_GET['show_test']);
                }
            }
            $smarty -> assign ("T_CURRENT_TEST", $showTest -> test);
            $smarty -> assign ("T_TEST_UNSOLVED", $showTest -> toHTMLQuickForm($form));
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['show_solved_test']) && eF_checkParameter($_GET['show_solved_test'], 'id')) {
        try {
            $result   = eF_getTableData("done_tests", "tests_ID, users_LOGIN", "id=".$_GET['show_solved_test']);
            $showTest = new EfrontTest($result[0]['tests_ID']);
            //Set "show answers" and "show given answers" to true, since it is the professor that sees the test
            $showTest -> test['answers']       = 1;
            $showTest -> test['given_answers'] = 1;

            $showTest -> setDone($result[0]['users_LOGIN']);
            $smarty   -> assign("T_CURRENT_TEST", $showTest -> test);
            $smarty   -> assign("T_SOLVED_TEST_DATA", $showTest -> doneInfo);
            $smarty   -> assign("T_TEST_SOLVED", $showTest -> toHTMLQuickForm(new HTML_Quickform(), false, true));
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['redo_test']) && eF_checkParameter($_GET['redo_test'], 'id')) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        try {
            $result   = eF_getTableData("done_tests", "tests_ID, users_LOGIN", "id=".$_GET['redo_test']);
            $showTest = new EfrontTest($result[0]['tests_ID']);
            $showTest -> reset($result[0]['users_LOGIN']);
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['correct_question']) && eF_checkParameter($_GET['correct_question'], 'id')) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        $form = new HTML_QuickForm("correct_question_form", "post", basename($_SERVER['PHP_SELF'])."?ctg=tests&correct_question=".$_GET['correct_question'], "", null, true);
        $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter');                   //Register this rule for checking user input with our function, eF_checkParameter

        $form -> addElement('text', 'score', _SCORE, 'class = "inputText" style = "width:3em"');                                                        //The user lesson score
        $form -> addRule('score', _THEFIELD.' "'._SCORE.'" '._ISMANDATORY, 'required', null, 'client');                            //The score must be numeric
        $form -> addRule('score', _THEFIELD.' "'._SCORE.'" '._MUSTBENUMERIC, 'numeric', null, 'client');                            //The score must be numeric
        $form -> addRule('score', _RATEMUSTBEBETWEEN0100, 'callback', create_function('&$a', 'return ($a >= 0 && $a <= 100);'));    //The score must be between 0 and 100
        $form -> setDefaults(array('score' => 0));
        $form -> addElement('submit', 'submit_score', _SUBMIT, 'class = "flatButton"');

        $question = eF_getTableData("done_tests dt, done_questions dq, questions q", "dt.*, dt.score as test_score, dq.*, q.answer as example_answer, q.text", "q.id=dq.questions_ID and dq.done_tests_ID=dt.id and dq.id=".$_GET['correct_question']);
        isset($question[0]['answer']) && unserialize($question[0]['answer']) !== false ? $question[0]['answer'] = unserialize($question[0]['answer']) : $question[0]['answer'] = '';
        try {
            $currentTest = new EfrontTest($question[0]['tests_ID']);
            $currentTest -> setDone($question[0]['users_LOGIN']);
            $currentTest -> doneInfo['score'] = round($currentTest -> doneInfo['score'] * 100, 2);
            $smarty -> assign("T_CURRENT_TEST", $currentTest -> test);
            $smarty -> assign("T_DONE_TEST_INFO", $currentTest -> doneInfo);
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }

        preg_match("/<file id = \"(.*)\">/", $question[0]['answer'], $uploadedFiles);
        if ($uploadedFiles) {
            $question[0]['answer'] = preg_replace("/<file id = \"(.*)\">/", "", $question[0]['answer']);
            try {
                $uploadedFile = new EfrontFile($uploadedFiles[1]);
                $question[0]['uploaded_file']['id']   = $uploadedFile['id'];
                $question[0]['uploaded_file']['name'] = $uploadedFile['name'];
            } catch (Exception $e) {
                $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                $message = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            }
        }

        $smarty -> assign("T_DONE_QUESTION", $question[0]);

        if ($form -> isSubmitted() && $form -> validate() && $question[0]['score'] == -1) {
            $questionWeight = $currentTest -> getQuestionWeight($question[0]['questions_ID']);
            $questionScore  = ($form -> exportValue('score') / 100) * $questionWeight;
            eF_updateTableData("done_questions", array("score" => $form -> exportValue('score') / 100), "id=".$_GET['correct_question']);
            eF_updateTableData("done_tests",     array("score" => $question[0]['test_score'] + $questionScore), "id=".$question[0]['done_tests_ID']);
            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&tab=correct_question&message="._SUCCESFULLYADDEDRATE."&message_type=success");
        } elseif ($question[0]['score'] != -1) {
            $message = _YOUHAVEALREADYCORRECTEDTHISQUESTION;
            $message_type = 'failure';
        }

        $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);


        $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
        $form -> setRequiredNote(_REQUIREDNOTE);
        $form -> accept($renderer);

        $smarty -> assign('T_CORRECT_QUESTION_FORM', $renderer -> toArray());

    } elseif (isset($_GET['questions_order']) && eF_checkParameter($_GET['questions_order'], 'id')) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        $currentTest = new EfrontTest($_GET['questions_order']);
        $questions   = $currentTest -> getQuestions();

        foreach ($questions as $key => $question) {
            $questions[$key]['text'] = strip_tags($question['text']);
        }
        $smarty -> assign("T_QUESTIONS", $questions);

        if (isset($_GET['ajax'])) {
            $order    = explode(",", $_GET['order']);
            $previous = 0;
            foreach ($order as $value) {
                $result = explode("-", $value);
                if (in_array($value, array_keys($questions))) {
                    eF_updateTableData("tests_to_questions", array("previous_question_ID" => $previous), "tests_ID=".$currentTest -> test['id']." and questions_ID=".$result[0]);
                }
                $previous = $result[0];
            }
            echo _TREESAVEDSUCCESSFULLY;
            exit;
        }

    } elseif (isset($_GET['show_question']) && eF_checkParameter($_GET['show_question'], 'id')) {
        try {
            $showQuestion = QuestionFactory :: factory($_GET['show_question']);
            $smarty -> assign("T_QUESTION", $showQuestion -> question);
            $smarty -> assign ("T_QUESTION_PREVIEW", $showQuestion -> toHTML(new HTML_Quickform()));
        } catch (Exception $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['delete_question']) && eF_checkParameter($_GET['delete_question'], 'id')) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        try {
            $currentQuestion = QuestionFactory :: factory($_GET['delete_question']);
            $currentQuestion -> delete();
            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&message=$message&message_type=$message_type&tab=question");             //&tab=question is used for the tabber to enable the correct tab
        } catch (Exeption $e) {
            $message      = $e -> getMessage().' ('.$e -> getCode().')';
            $message_type = 'failure';
        }
    } elseif (isset($_GET['add_question']) || (isset($_GET['edit_question']) && eF_checkParameter($_GET['edit_question'], 'id'))) {
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        $load_editor   = true;
        $questionTypes = Question :: $questionTypes;

        isset($_GET['question_type']) && in_array($_GET['question_type'], array_keys($questionTypes)) ? $question_type = $_GET['question_type'] : $question_type = 'multiple_one';
        if (isset($_GET['edit_question'])) {                                                        //We are changing an existing question.
            try {
                $currentQuestion = QuestionFactory :: factory($_GET['edit_question']);
            } catch (Exception $e) {
                $message      = $e -> getMessage().' ('.$e -> getCode().')';
                $message_type = 'failure';
            }

            $postTarget = basename($_SERVER['PHP_SELF'])."?ctg=tests&edit_question=".$currentQuestion -> question['id']."&question_type=".$currentQuestion -> question['type'];
            if (strpos($_SERVER['HTTP_REFERER'], 'edit_test') !== false) {                    //We asked to edit a question through the tests interface, so we must return there after submission
                preg_match("/edit_test=(\d+)/", $_SERVER['HTTP_REFERER'], $matches);
                if (sizeof($matches) > 0) {
                    $postTarget .= '&from_test='.$matches[1];
                }
            }
        } else {
            $postTarget = basename($_SERVER['PHP_SELF'])."?ctg=tests&add_question=1&question_type=".$question_type;
        }

        $form = new HTML_QuickForm("question_form", "post", $postTarget, "", null, true);
        $form -> registerRule('checkParameter', 'callback', 'eF_checkParameter');                          //Register this rule for checking user input with our function, eF_checkParameter

        $optionsArray = $currentContent -> toHTMLSelectOptions();

        $form -> addElement('select', 'content_ID', _UNITPARENT, $optionsArray, 'class = "inputSelect"');  //Build a select box with all content units
        $form -> addRule('content_ID', _THEFIELD.' '._UNITPARENT.' '._ISMANDATORY, 'required');            //The content id must be present and a numeric value.
        $form -> addRule('content_ID', _INVALIDID, 'numeric');
        if (isset($_GET['content_ID'])) {
            $form -> setDefaults(array('content_ID' => $_GET['content_ID']));                              //If a content is specified, then set it to be selected as well
        }

        $form -> addElement('select', 'question_type', _QUESTIONTYPE, $questionTypes, 'class = "inputSelect" id = "question_type" onchange = "window.location = \''.basename($_SERVER['PHP_SELF']).'?ctg=tests&add_question=1&question_type=\'+this.options[this.selectedIndex].value"');     //Depending on user selection, changing the question type reloads the page with the corresponding form fields
        $form -> addRule('question_type', _THEFIELD.' '._QUESTIONTYPE.' '._ISMANDATORY, 'required', null, 'client');
        $form -> addRule('question_type', _INVALIDFIELDDATA, 'callback', 'text');
        $form -> setDefaults(array('question_type' => $question_type));                                             //Set the default selected question type to be 'multiple_one'

        $difficulties = array('high' => _HIGH, 'medium' => _MEDIUM, 'low' => _LOW);
        $form -> addElement('select', 'difficulty', _DIFFICULTY, $difficulties, 'class = "inputSelect"');
        $form -> addRule('difficulty', _THEFIELD.' '._DIFFICULTY.' '._ISMANDATORY, 'required', null, 'client');     //Difficulty is mandatory and can be only a plain string
        $form -> addRule('difficulty', _INVALIDFIELDDATA, 'lettersonly');
        $form -> setDefaults(array('difficulty' => 'medium'));                                                      //Set the default selected difficulty to be 'medium'

        $form -> addElement('textarea', 'question_text', _QUESTIONTEXT, 'class = "mceEditor inputTextarea_QuestionText" style = "width:100%" id = "question_text"');
        $form -> addRule('question_text', _THEFIELD.' '._ISMANDATORY, 'required', null);
        //$form -> addRule('question_text', _INVALIDFIELDDATA, 'checkParameter', 'text');

        $form -> addElement('textarea', 'explanation', _EXPLANATION, 'class = "simpleEditor inputTextarea_QuestionExplanation" style = "width:100%;height:120px"');    //The style needs to be here, since when a textarea is in "display:none" mode, the tinymce does not render the class correctly

        $form -> addElement('submit', 'submit_question', _SAVEQUESTION, 'class = "flatButton"');
        $form -> addElement('submit', 'submit_new_question', _SAVEASNEWQUESTION, 'class = "flatButton"');
        $form -> addElement('submit', 'submit_question_another', _SAVEQUESTIONANDCREATENEW, 'class = "flatButton"');

        if (isset($currentQuestion)) {                                                                         //If we are changing an existing question
            $form -> setDefaults(array('content_ID'    => $currentQuestion -> question['content_ID'],          //Set form values to the stored ones.
                                       'question_type' => $currentQuestion -> question['type'],
                                       'difficulty'    => $currentQuestion -> question['difficulty'],
                                       'question_text' => $currentQuestion -> question['text'],
                                       'explanation'   => $currentQuestion -> question['explanation']));
            $form -> freeze('question_type');                                                                  //The question type cannot be changed
            $smarty -> assign("T_HAS_EXPLANATION", $currentQuestion -> question['explanation']);               //If the question has an explanation, use this smarty tag to set explanation field to be visible by default.
        }

        switch ($_GET['question_type']) { //Depending on the question type, the user might have added new form fields. We need to recreate the form, in order to be able to handle them both in case of succes or failure.
            case 'multiple_one':
                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $values['multiple_one']         = array_values(unserialize($currentQuestion -> question['options']));      //We put array_values to make sure that the array starts from zero
                        $values['correct_multiple_one'] = unserialize($currentQuestion -> question['answer']);
                        $values['correct_multiple_one'] = $values['correct_multiple_one'][0];                          //In multiple_one, only one value is valid. Get this out of the array
                    } else {
                        $values = $form -> getSubmitValues();
                    }

                    //Create each multiple choice from the beginning, this way including any choices the user added himself
                    foreach ($values['multiple_one'] as $key => $value) {
                        $form -> addElement('text', 'multiple_one['.$key.']', null, 'class = "inputText inputText_QuestionChoice"');
                        $form -> addRule('multiple_one['.$key.']', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                        $form -> addRule('multiple_one['.$key.']', _INVALIDFIELDDATA, 'checkParameter', 'text');
                        $form -> setDefaults(array('multiple_one['.$key.']' => $value));
                    }

                    $form -> addElement('select', 'correct_multiple_one', _RIGHTANSWER, range(1, sizeof($values['multiple_one'])), 'id = "correct_multiple_one"');//Rebuild the correct options list, to be as large as the options the user added
                    $form -> setDefaults(array('correct_multiple_one' => $values['correct_multiple_one']));     //Set the selected correct option to be the one the user selected

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'multiple_one',
                                                 'options' => serialize($values['multiple_one']),
                                                 'answer'  => serialize(array($values['correct_multiple_one'])));
                    }
                } else {
                    //By default, only 2 options are displayed
                    $form -> addElement('text', 'multiple_one[0]', _INSERTMULTIPLEQUESTIONS, 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('multiple_one[0]', _THEFIELD.' "'._INSERTMULTIPLEQUESTIONS.'" '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('multiple_one[0]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('text', 'multiple_one[1]', '', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('multiple_one[1]', _THEFIELD.' "'._INSERTMULTIPLEQUESTIONS.'" '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('multiple_one[1]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('select', 'correct_multiple_one', _RIGHTANSWER, array(1, 2), 'id = "correct_multiple_one"');
                }
                break;

            case 'multiple_many':
                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $values['multiple_many']         = unserialize($currentQuestion -> question['options']);
                        $values['correct_multiple_many'] = unserialize($currentQuestion -> question['answer']);
                    } else {
                        $values = $form -> getSubmitValues();
                    }

                    //Create each multiple choice from the beginning, this way including any choices the user added himself
                    foreach ($values['multiple_many'] as $key => $value) {
                        $form -> addElement('text', 'multiple_many['.$key.']', 'Insert Questions', 'class = "inputText inputText_QuestionChoice"');
                        $form -> addRule('multiple_many['.$key.']', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                        $form -> addRule('multiple_many['.$key.']', _INVALIDFIELDDATA, 'checkParameter', 'text');
                        $form -> setDefaults(array('multiple_many['.$key.']' => $value));

                        $form -> addElement('checkbox', 'correct_multiple_many['.$key.']');
                        $form -> setDefaults(array('correct_multiple_many['.$key.']' => $values['correct_multiple_many'][$key]));
                    }

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'multiple_many',
                                                 'options' => serialize($values['multiple_many']),
                                                 'answer'  => serialize($values['correct_multiple_many']));
                    }
                } else {
                    //By default, only 2 options are displayed
                    $form -> addElement('text', 'multiple_many[0]', 'Insert Multiple Questions (many)', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('multiple_many[0]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('multiple_many[0]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('text', 'multiple_many[1]', null, 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('multiple_many[1]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('multiple_many[1]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('checkbox', 'correct_multiple_many[0]');
                    $form -> addElement('checkbox', 'correct_multiple_many[1]');
                }
                break;

            case 'raw_text':
                $form -> addElement('textarea', 'example_answer', _EXAMPLEANSWER, 'class = "inputTextarea_QuestionExample" style = "width:100%" ');
                //$form -> addRule('example_answer', _INVALIDFIELDDATA, 'checkParameter', 'text');

                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $form -> setDefaults(array('example_answer' => $currentQuestion -> question['answer']));
                    }

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'raw_text',
                                                 'options' => '',
                                                 'answer'  => $form -> exportValue('example_answer'));
                    }
                }

                break;

            case 'match':
                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $values['match']         = unserialize($currentQuestion -> question['options']);
                        $values['correct_match'] = unserialize($currentQuestion -> question['answer']);
                    } else {
                        $values = $form -> getSubmitValues();
                    }

                    foreach ($values['match'] as $key => $value) {
                        $form -> addElement('text', 'match['.$key.']', 'Insert Questions', 'class = "inputText inputText_QuestionChoice"');
                        $form -> addRule('match['.$key.']', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                        $form -> addRule('match['.$key.']', _INVALIDFIELDDATA, 'checkParameter', 'text');
                        $form -> setDefaults(array('match['.$key.']' => $value));

                        $form -> addElement('text', 'correct_match['.$key.']', 'Insert Questions', 'class = "inputText inputText_QuestionChoice"');
                        $form -> addRule('correct_match['.$key.']', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                        $form -> addRule('correct_match['.$key.']', _INVALIDFIELDDATA, 'checkParameter', 'text');
                        $form -> setDefaults(array('correct_match['.$key.']' => $values['correct_match'][$key]));
                    }

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'match',
                                                 'options' => serialize($values['match']),
                                                 'answer'  => serialize($values['correct_match']));
                    }
                } else {
                    //By default, only 2 pairs of choices given.
                    $form -> addElement('text', 'match[0]', 'Insert Match Questions', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('match[0]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('match[0]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('text', 'correct_match[0]', 'nsert Match Questions', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('correct_match[0]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('correct_match[0]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('text', 'match[1]', 'sert Match Questions', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('match[1]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('match[1]', _INVALIDFIELDDATA, 'checkParameter', 'text');

                    $form -> addElement('text', 'correct_match[1]', 'ert Match Questions', 'class = "inputText inputText_QuestionChoice"');
                    $form -> addRule('correct_match[1]', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                    $form -> addRule('correct_match[1]', _INVALIDFIELDDATA, 'checkParameter', 'text');
                }
                break;

            case 'empty_spaces':
                $form -> addElement('button', 'generate_empty_spaces', _CREATEEMPTYSPACES, 'class = "flatButton" onclick = "eF_js_createEmptySpaces()"');
                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $values['empty_spaces'] = unserialize($currentQuestion -> question['answer']);
                        //$values['correct_match'] = unserialize($currentQuestion -> question['answer']);
                    } else {
                        $values = $form -> getSubmitValues();
                    }

                    $excerpts = explode('###', $currentQuestion -> question['text']);
                    $smarty -> assign("T_EXCERPTS", $excerpts);

                    foreach ($values['empty_spaces'] as $key => $value) {
                        $form -> addElement('text', 'empty_spaces['.$key.']', null, 'class = "inputText"');
                        $form -> addRule('empty_spaces['.$key.']', _INVALIDFIELDDATA, 'checkParameter', 'text');
                        $form -> setDefaults(array('empty_spaces['.$key.']' => $value));
                    }

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'empty_spaces',
                                                 'options' => '',
                                                 'answer'  => serialize($values['empty_spaces']));
                    }
                }
                break;

            case 'true_false':
                $form -> addElement('select', 'correct_true_false', _RIGHTANSWER, array(0 => _FALSE, 1 => _TRUE));
                $form -> addRule('true_false', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
                if ($form -> isSubmitted() || isset($currentQuestion)) {
                    if (isset($currentQuestion) && !$form -> isSubmitted()) {
                        $values['correct_true_false'] = unserialize($currentQuestion -> question['answer']);
                        $form -> setDefaults(array('correct_true_false' => $values['correct_true_false']));
                    } else {
                        $values = $form -> getSubmitValues();
                    }

                    if ($form -> validate()) {
                        $question_values = array('type'    => 'true_false',
                                                 'options' => '',
                                                 'answer'  => serialize($values['correct_true_false']));
                    }
                }
                break;

            default: break;
        }
        //Common fields and actions for all question types
        if ($form -> isSubmitted()) {
            if ($form -> validate()) {
                $form_values = $form -> exportValues();
                $question_values['text']        = $form_values['question_text'];
                $question_values['content_ID']  = $form_values['content_ID'];
                $question_values['difficulty']  = $form_values['difficulty'];
                $question_values['timestamp']   = time();
                $question_values['explanation'] = $form_values['explanation'];

                if (isset($currentQuestion)) {                                                                //If we are changing an existing question
                    isset($_GET['from_test']) ? $location = '&edit_test='.$_GET['from_test'] : $location = '';
                    if (isset($form_values['submit_new_question'])) {
                        if (eF_insertTableData("questions", $question_values)) {
                            $message      = _SUCCESFULLYADDEDQUESTION;
                            $message_type = 'success';

                            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests$location&message=$message&message_type=$message_type&tab=question");             //&question is used for the tabber to enable the correct tab
                        } else {
                            $message      = _SOMEPROBLEMEMERGED;
                            $message_type = 'failure';
                        }
                    } else {
                        if (eF_updateTableData("questions", $question_values, "id=".$currentQuestion -> question['id'])) {          //Update the question
                            $message      = _SUCCESFULLYUPDATEDQUESTION;
                            $message_type = 'success';

                            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests$location&message=$message&message_type=$message_type&tab=question");             //&question is used for the tabber to enable the correct tab
                        } else {
                            $message      = _SOMEPROBLEMEMERGED;
                            $message_type = 'failure';
                        }
                    }
                } else {                                                                                    //We are inserting a new question
                    //pr($question_values);
                    if (eF_insertTableData("questions", $question_values)) {
                        $message      = _SUCCESFULLYADDEDQUESTION;
                        $message_type = 'success';

                        if ($form -> exportValue('submit_question')) {
                            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&message=$message&message_type=$message_type&tab=question");             //&question is used for the tabber to enable the correct tab
                        } else {
                            header("location:".ltrim(basename($_SERVER['PHP_SELF']), "/")."?ctg=tests&add_question=1&question_type=".$_GET['question_type']."&message=$message&message_type=$message_type");
                        }
                    } else {
                        $message      = _SOMEPROBLEMEMERGED;
                        $message_type = 'failure';
                    }
                }
            }
        }

        $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);


        $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
        $form -> setRequiredNote(_REQUIREDNOTE);
        $form -> accept($renderer);

        $smarty -> assign('T_QUESTION_FORM', $renderer -> toArray());


    } elseif (isset($_POST['selected_action']) && $_POST['selected_action'] == 'delete') {          //Mass deletion of questions
        if (isset($currentUser -> coreAccess['content']) && $currentUser -> coreAccess['content'] != 'change') {
            header("location:".basename($_SERVER['PHP_SELF'])."?ctg=control_panel&message=".urlencode(_UNAUTHORIZEDACCESS)."&message_type=failure");
        }
        foreach ($_POST['questions'] as $key => $value) {
            try {
                $question = QuestionFactory :: factory($value);
                $question -> delete();
            } catch (Exception $e) {
                $messageString .= $e -> getMessage();
            }
        }
        $message = _OPERATIONSUCCESFULLYAPPLIEDON.' '.sizeof($_POST['questions']).' '._QUESTIONS;
        if (isset($messageString)) {
            $message      = implode("<br/>", $messageString);
            $message_type = 'failure';
        }
    } else {
        $smarty -> assign("T_QUESTIONTYPESTRANSLATIONS", Question :: $questionTypes);
        $smarty -> assign("T_QUESTIONDIFFICULTYTRANSLATIONS", array('low' => _LOW, 'medium' => _MEDIUM, 'high' => _HIGH));
        $smarty -> assign("T_UNITS", $currentContent -> toHTMLSelectOptions());

        $select_units = & HTML_QuickForm :: createElement('select', 'question_type', _QUESTIONTYPE, null, 'class = "inputSelect" id = "question_type" onchange = "window.location = \''.basename($_SERVER['PHP_SELF']).'?ctg=tests&add_question=1&question_type=\'+this.options[this.selectedIndex].value"');
        $select_units -> addOption(_ADDQUESTIONOFTYPE, 0);
        $select_units -> addOption('-------------', -1);
        $select_units -> loadArray(Question :: $questionTypes);
        $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
        $select_units -> accept($renderer);
        $smarty -> assign('T_QUESTION_TYPE', $renderer -> toArray());

        isset($_GET['from_unit']) && eF_checkParameter($_GET['from_unit'], 'id') ? $selectedUnit = $_GET['from_unit'] : $selectedUnit = 0;
        $selectedUnit ? $units = $currentContent -> getNodeChildren($selectedUnit) : $units = $currentContent -> tree;
        foreach ($iterator = new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($units)), array('id', 'name')) as $key => $value) {
            $key == 'id' ? $ids[] = $value : $names[] = $value;
        }
        $tests     = eF_getTableData("content,tests", "content.id as content_ID, content.name, tests.*", "ctg_type='tests' AND content.id IN (".implode(",", $ids).") AND content.active=1 and content.id=tests.content_ID", "content.id ASC");
        
        foreach ($tests as $key => $test) {
            $names = array();
            foreach ($iterator = new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> getNodeAncestors($test['content_ID']))), array('name')) as $k => $v) {
                $names[] = $v;
            }
            $tests[$key]['parent_unit'] = implode("&nbsp;&raquo;&nbsp;", array_reverse(array_slice($names, 1)));
        }
        $smarty -> assign("T_TESTS", $tests);

        //$selectedUnit = new EfrontUnit($selectedUnit);
        //$questions = $selectedUnit -> getQuestions();         //This works also, but we are leaving the traditional way for now
        $questions = eF_getTableData("questions", "*", "content_ID IN (".implode(",", $ids).")", "content_ID ASC,  timestamp DESC");     //Retrieve all questions that belong to this unit or its subunits
        foreach ($questions as $key => $question) {
            $names = array();
            foreach ($iterator = new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> getNodeAncestors($question['content_ID']))), array('name')) as $k => $v) {
                $names[] = $v;
            }
            $questions[$key]['parent_unit'] = implode("&nbsp;&raquo;&nbsp;", array_reverse($names));
            $questions[$key]['text']        = strip_tags($question['text']);                            //Strip tags from the question text, so they do not display in the list
        }
        $smarty -> assign("T_QUESTIONS", $questions);

        /*Get a list of questions awaiting to be corrected*/
        $questionsToCorrect = eF_getTableData("done_tests AS d_t, done_questions AS d_q, content AS c, tests, questions as q", "d_t.id as done_tests_ID, d_q.id as done_question_id, c.id AS id, c.name AS name, d_t.score AS score, d_t.users_LOGIN AS usrname, q.text, tests.id as test_id", "c.lessons_ID=".$currentLesson -> lesson['id']." AND d_q.done_tests_ID=d_t.id AND d_t.tests_ID=tests.id AND c.id=tests.content_ID AND q.id = d_q.questions_ID AND d_q.score=-1 AND q.type='raw_text'", "d_t.timestamp ASC");
        array_walk($questionsToCorrect, create_function('&$v', '$v["text"] = strip_tags($v["text"]);'));        //Strip html tags from question titles
        $smarty -> assign("T_QUESTIONS_TO_CORRECT", $questionsToCorrect);
    }





?>