/**
  * abstract function which creates the form to create / edit the answers of the question
  * @param the formvalidator instance
  * @param the answers number to display
  */
 function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('answer[' . $i . ']')));
         $comment = trim(str_replace(['<p>', '</p>'], '', $form->getSubmitValue('comment[' . $i . ']')));
         $weighting = trim($form->getSubmitValue('weighting[' . $i . ']'));
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $weighting = abs($weighting);
         } else {
             $weighting = abs($weighting);
             $weighting = -$weighting;
         }
         if ($weighting > 0) {
             $questionWeighting += $weighting;
         }
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
Example #2
0
/**
 * Handles a given Excel spreadsheets as in the template provided
 */
function lp_upload_quiz_action_handling()
{
    global $debug;
    $_course = api_get_course_info();
    $courseId = $_course['real_id'];
    if (!isset($_POST['submit_upload_quiz'])) {
        return;
    }
    // Get the extension of the document.
    $path_info = pathinfo($_FILES['user_upload_quiz']['name']);
    // Check if the document is an Excel document
    if ($path_info['extension'] != 'xls') {
        return;
    }
    // Read the Excel document
    $data = new Spreadsheet_Excel_Reader();
    // Set output Encoding.
    $data->setOutputEncoding(api_get_system_encoding());
    // Reading the xls document.
    $data->read($_FILES['user_upload_quiz']['tmp_name']);
    $correctScore = isset($_POST['correct_score']) ? $_POST['correct_score'] : null;
    $incorrectScore = isset($_POST['incorrect_score']) ? $_POST['incorrect_score'] : null;
    $useCustomScore = isset($_POST['user_custom_score']) ? true : false;
    $propagateNegative = 0;
    if ($useCustomScore && !empty($incorrectScore)) {
        if ($incorrectScore < 0) {
            $propagateNegative = 1;
        }
    }
    // Variables
    $quiz_index = 0;
    $question_title_index = array();
    $question_name_index_init = array();
    $question_name_index_end = array();
    $score_index = array();
    $feedback_true_index = array();
    $feedback_false_index = array();
    $number_questions = 0;
    $question_description_index = array();
    // Reading all the first column items sequentially to create breakpoints
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if ($data->sheets[0]['cells'][$i][1] == 'Quiz' && $i == 1) {
            $quiz_index = $i;
            // Quiz title position, only occurs once
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Question') {
            $question_title_index[] = $i;
            // Question title position line
            $question_name_index_init[] = $i + 1;
            // Questions name 1st position line
            $number_questions++;
        } elseif ($data->sheets[0]['cells'][$i][1] == 'Score') {
            $question_name_index_end[] = $i - 1;
            // Question name position
            $score_index[] = $i;
            // Question score position
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackTrue') {
            $feedback_true_index[] = $i;
            // FeedbackTrue position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'FeedbackFalse') {
            $feedback_false_index[] = $i;
            // FeedbackFalse position (line)
        } elseif ($data->sheets[0]['cells'][$i][1] == 'EnrichQuestion') {
            $question_description_index[] = $i;
        }
    }
    // Variables
    $quiz = array();
    $question = array();
    $new_answer = array();
    $score_list = array();
    $feedback_true_list = array();
    $feedback_false_list = array();
    $question_description = array();
    // Getting questions.
    $k = $z = $q = $l = $m = 0;
    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
        if (is_array($data->sheets[0]['cells'][$i])) {
            $column_data = $data->sheets[0]['cells'][$i];
            // Fill all column with data to have a full array
            for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                if (empty($column_data[$x])) {
                    $data->sheets[0]['cells'][$i][$x] = '';
                }
            }
            // Array filled with data
            $column_data = $data->sheets[0]['cells'][$i];
        } else {
            $column_data = '';
        }
        // Fill quiz data
        if ($quiz_index == $i) {
            // The title always in the first position
            $quiz = $column_data;
        } elseif (in_array($i, $question_title_index)) {
            //a complete line where 1st column is 'Question'
            $question[$k] = $column_data;
            $k++;
        } elseif (in_array($i, $score_index)) {
            //a complete line where 1st column is 'Score'
            $score_list[$z] = $column_data;
            $z++;
        } elseif (in_array($i, $feedback_true_index)) {
            //a complete line where 1st column is 'FeedbackTrue'
            $feedback_true_list[$q] = $column_data;
            $q++;
        } elseif (in_array($i, $feedback_false_index)) {
            //a complete line where 1st column is 'FeedbackFalse' for wrong answers
            $feedback_false_list[$l] = $column_data;
            $l++;
        } elseif (in_array($i, $question_description_index)) {
            //a complete line where 1st column is 'EnrichQuestion'
            $question_description[$m] = $column_data;
            $m++;
        }
    }
    // Get answers
    for ($i = 0; $i < count($question_name_index_init); $i++) {
        for ($j = $question_name_index_init[$i]; $j <= $question_name_index_end[$i]; $j++) {
            if (is_array($data->sheets[0]['cells'][$j])) {
                $column_data = $data->sheets[0]['cells'][$j];
                // Fill all column with data
                for ($x = 1; $x <= $data->sheets[0]['numCols']; $x++) {
                    if (empty($column_data[$x])) {
                        $data->sheets[0]['cells'][$j][$x] = '';
                    }
                }
                $column_data = $data->sheets[0]['cells'][$j];
                // Array filled of data
                if (is_array($data->sheets[0]['cells'][$j]) && count($data->sheets[0]['cells'][$j]) > 0) {
                    $new_answer[$i][$j] = $data->sheets[0]['cells'][$j];
                }
            }
        }
    }
    // Quiz title.
    $quiz_title = $quiz[2];
    if ($quiz_title != '') {
        // Variables
        $type = 2;
        $random = $active = $results = $max_attempt = $expired_time = 0;
        // Make sure feedback is enabled (3 to disable), otherwise the fields
        // added to the XLS are not shown, which is confusing
        $feedback = 0;
        // Quiz object
        $exercise = new Exercise();
        //
        $quiz_id = $exercise->createExercise($quiz_title, $expired_time, $type, $random, $active, $results, $max_attempt, $feedback, $propagateNegative);
        if ($quiz_id) {
            // insert into the item_property table
            api_item_property_update($_course, TOOL_QUIZ, $quiz_id, 'QuizAdded', api_get_user_id());
            // Import questions.
            for ($i = 0; $i < $number_questions; $i++) {
                // Question name
                $question_title = $question[$i][2];
                $question_description_text = "<p></p>";
                if (isset($question_description[$i][2])) {
                    // Question description.
                    $question_description_text = "<p>" . $question_description[$i][2] . "</p>";
                }
                // Unique answers are the only question types available for now
                // through xls-format import
                $question_id = null;
                $detectQuestionType = detectQuestionType($new_answer[$i], $score_list);
                /** @var Question $answer */
                switch ($detectQuestionType) {
                    case FREE_ANSWER:
                        $answer = new FreeAnswer();
                        break;
                    case GLOBAL_MULTIPLE_ANSWER:
                        $answer = new GlobalMultipleAnswer();
                        break;
                    case MULTIPLE_ANSWER:
                        $answer = new MultipleAnswer();
                        break;
                    case UNIQUE_ANSWER:
                    default:
                        $answer = new UniqueAnswer();
                        break;
                }
                if ($question_title != '') {
                    $question_id = $answer->create_question($quiz_id, $question_title, $question_description_text, 0, $answer->type);
                }
                $total = 0;
                if (is_array($new_answer[$i]) && !empty($question_id)) {
                    $id = 1;
                    $answers_data = $new_answer[$i];
                    $globalScore = null;
                    $objAnswer = new Answer($question_id, $courseId);
                    $globalScore = $score_list[$i][3];
                    // Calculate the number of correct answers to divide the
                    // score between them when importing from CSV
                    $numberRightAnswers = 0;
                    foreach ($answers_data as $answer_data) {
                        if (strtolower($answer_data[3]) == 'x') {
                            $numberRightAnswers++;
                        }
                    }
                    foreach ($answers_data as $answer_data) {
                        $answerValue = $answer_data[2];
                        $correct = 0;
                        $score = 0;
                        if (strtolower($answer_data[3]) == 'x') {
                            $correct = 1;
                            $score = $score_list[$i][3];
                            $comment = $feedback_true_list[$i][2];
                        } else {
                            $comment = $feedback_false_list[$i][2];
                            $floatVal = (double) $answer_data[3];
                            if (is_numeric($floatVal)) {
                                $score = $answer_data[3];
                            }
                        }
                        if ($useCustomScore) {
                            if ($correct) {
                                $score = $correctScore;
                            } else {
                                $score = $incorrectScore;
                            }
                        }
                        // Fixing scores:
                        switch ($detectQuestionType) {
                            case GLOBAL_MULTIPLE_ANSWER:
                                $score /= $numberRightAnswers;
                                break;
                            case UNIQUE_ANSWER:
                                break;
                            case MULTIPLE_ANSWER:
                                if (!$correct) {
                                    //$total = $total - $score;
                                }
                                break;
                        }
                        $objAnswer->createAnswer($answerValue, $correct, $comment, $score, $id);
                        $total += $score;
                        $id++;
                    }
                    $objAnswer->save();
                    $questionObj = Question::read($question_id, $courseId);
                    switch ($detectQuestionType) {
                        case GLOBAL_MULTIPLE_ANSWER:
                            $questionObj->updateWeighting($globalScore);
                            break;
                        case UNIQUE_ANSWER:
                        case MULTIPLE_ANSWER:
                        default:
                            $questionObj->updateWeighting($total);
                            break;
                    }
                    $questionObj->save();
                } else {
                    if ($detectQuestionType === FREE_ANSWER) {
                        $questionObj = Question::read($question_id, $courseId);
                        $globalScore = $score_list[$i][3];
                        $questionObj->updateWeighting($globalScore);
                        $questionObj->save();
                    }
                }
            }
        }
        if (isset($_SESSION['lpobject'])) {
            if ($debug > 0) {
                error_log('New LP - SESSION[lpobject] is defined', 0);
            }
            $oLP = unserialize($_SESSION['lpobject']);
            if (is_object($oLP)) {
                if ($debug > 0) {
                    error_log('New LP - oLP is object', 0);
                }
                if (empty($oLP->cc) or $oLP->cc != api_get_course_id()) {
                    if ($debug > 0) {
                        error_log('New LP - Course has changed, discard lp object', 0);
                    }
                    $oLP = null;
                    Session::erase('oLP');
                    Session::erase('lpobject');
                } else {
                    $_SESSION['oLP'] = $oLP;
                }
            }
        }
        if (isset($_SESSION['oLP']) && isset($_GET['lp_id'])) {
            $previous = $_SESSION['oLP']->select_previous_item_id();
            $parent = 0;
            // Add a Quiz as Lp Item
            $_SESSION['oLP']->add_item($parent, $previous, TOOL_QUIZ, $quiz_id, $quiz_title, '');
            // Redirect to home page for add more content
            header('location: ../newscorm/lp_controller.php?' . api_get_cidreq() . '&action=add_item&type=step&lp_id=' . Security::remove_XSS($_GET['lp_id']));
            exit;
        } else {
            //  header('location: exercise.php?' . api_get_cidreq());
            echo '<script>window.location.href = "' . api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidReq() . '&exerciseId=' . $quiz_id . '&session_id=' . api_get_session_id() . '"</script>';
        }
    }
}
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     // Score total
     $answer_score = trim($form->getSubmitValue('weighting[1]'));
     // Reponses correctes
     $nbr_corrects = 0;
     for ($i = 1; $i <= $nb_answers; $i++) {
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $nbr_corrects++;
         }
     }
     // Set question weighting (score total)
     $questionWeighting = $answer_score;
     // Set score per answer
     $nbr_corrects = $nbr_corrects == 0 ? 1 : $nbr_corrects;
     $answer_score = $nbr_corrects == 0 ? 0 : $answer_score;
     $answer_score = $answer_score / $nbr_corrects;
     //$answer_score �quivaut � la valeur d'une bonne r�ponse
     // cr�ation variable pour r�cuperer la valeur de la coche pour la prise en compte des n�gatifs
     $test = $form->getSubmitValue('pts');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if ($goodAnswer) {
             $weighting = abs($answer_score);
         } else {
             if ($test == 1) {
                 $weighting = 0;
             } else {
                 $weighting = -abs($answer_score);
             }
         }
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question --> sert � donner le score total pendant l'examen
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
 /**
  * Function which creates the form to create/edit the answers of the question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $answer = $form->getSubmitValue('answer');
     // Due the ckeditor transform the elements to their HTML value
     //$answer = api_html_entity_decode($answer, ENT_QUOTES, $charset);
     //$answer = htmlentities(api_utf8_encode($answer));
     // remove the :: eventually written by the user
     $answer = str_replace('::', '', $answer);
     // remove starting and ending space and &nbsp;
     $answer = api_preg_replace("/ /", " ", $answer);
     // start and end separator
     $blankStartSeparator = self::getStartSeparator($form->getSubmitValue('select_separator'));
     $blankEndSeparator = self::getEndSeparator($form->getSubmitValue('select_separator'));
     $blankStartSeparatorRegexp = self::escapeForRegexp($blankStartSeparator);
     $blankEndSeparatorRegexp = self::escapeForRegexp($blankEndSeparator);
     // remove spaces at the beginning and the end of text in square brackets
     $answer = preg_replace_callback("/" . $blankStartSeparatorRegexp . "[^]]+" . $blankEndSeparatorRegexp . "/", function ($matches) use($blankStartSeparator, $blankEndSeparator) {
         $matchingResult = $matches[0];
         $matchingResult = trim($matchingResult, $blankStartSeparator);
         $matchingResult = trim($matchingResult, $blankEndSeparator);
         $matchingResult = trim($matchingResult);
         // remove forbidden chars
         $matchingResult = str_replace("/\\/", "", $matchingResult);
         $matchingResult = str_replace('/"/', "", $matchingResult);
         return $blankStartSeparator . $matchingResult . $blankEndSeparator;
     }, $answer);
     // get the blanks weightings
     $nb = preg_match_all('/' . $blankStartSeparatorRegexp . '[^' . $blankStartSeparatorRegexp . ']*' . $blankEndSeparatorRegexp . '/', $answer, $blanks);
     if (isset($_GET['editQuestion'])) {
         $this->weighting = 0;
     }
     /* if we have some [tobefound] in the text
        build the string to save the following in the answers table
        <p>I use a [computer] and a [pen].</p>
        becomes
        <p>I use a [computer] and a [pen].</p>::100,50:100,50@1
            ++++++++-------**
            --- -- --- -- -
            A B  (C) (D)(E)
        +++++++ : required, weighting of each words
        ------- : optional, input width to display, 200 if not present
        ** : equal @1 if "Allow answers order switches" has been checked, @ otherwise
        A : weighting for the word [computer]
        B : weighting for the word [pen]
        C : input width for the word [computer]
        D : input width for the word [pen]
        E : equal @1 if "Allow answers order switches" has been checked, @ otherwise
        */
     if ($nb > 0) {
         $answer .= '::';
         // weighting
         for ($i = 0; $i < $nb; ++$i) {
             // enter the weighting of word $i
             $answer .= $form->getSubmitValue('weighting[' . $i . ']');
             // not the last word, add ","
             if ($i != $nb - 1) {
                 $answer .= ",";
             }
             // calculate the global weighting for the question
             $this->weighting += $form->getSubmitValue('weighting[' . $i . ']');
         }
         // input width
         $answer .= ":";
         for ($i = 0; $i < $nb; ++$i) {
             // enter the width of input for word $i
             $answer .= $form->getSubmitValue('sizeofinput[' . $i . ']');
             // not the last word, add ","
             if ($i != $nb - 1) {
                 $answer .= ",";
             }
         }
     }
     // write the blank separator code number
     // see function getAllowedSeparator
     /*
        0 [...]
        1 {...}
        2 (...)
        3 *...*
        4 #...#
        5 %...%
        6 $...$
     */
     $answer .= ":" . $form->getSubmitValue('select_separator');
     // Allow answers order switches
     $is_multiple = $form->getSubmitValue('multiple_answer');
     $answer .= '@' . $is_multiple;
     $this->save();
     $objAnswer = new Answer($this->id);
     $objAnswer->createAnswer($answer, 0, '', 0, 1);
     $objAnswer->save();
 }
 /**
  * Fills the course database with some required content and example content.
  * @param int Course (int) ID
  * @param string Course directory name (e.g. 'ABC')
  * @param string Language used for content (e.g. 'spanish')
  * @param bool Whether to fill the course with example content
  * @return bool False on error, true otherwise
  * @version 1.2
  * @assert (null, '', '', null) === false
  * @assert (1, 'ABC', null, null) === false
  * @assert (1, 'TEST', 'spanish', true) === true
  */
 public static function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null)
 {
     if (is_null($fill_with_exemplary_content)) {
         $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
     }
     $course_id = intval($course_id);
     if (empty($course_id)) {
         return false;
     }
     $entityManager = Database::getManager();
     $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
     $tools = array();
     $settingsManager = CourseManager::getCourseSettingsManager();
     $settingsManager->setCourse($course);
     $toolList = CourseManager::getToolList();
     $toolList = $toolList->getTools();
     /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
     foreach ($toolList as $tool) {
         $visibility = self::string2binary(api_get_setting_in_list('course.active_tools_on_create', $tool->getName()));
         $toolObject = new CTool();
         $toolObject->setName($tool->getName())->setCategory($tool->getCategory())->setLink($tool->getLink())->setImage($tool->getImage())->setVisibility($visibility)->setAdmin(0)->setTarget($tool->getTarget());
         $tools[] = $toolObject;
         $settings = $settingsManager->loadSettings($tool->getName());
         $settingsManager->saveSettings($tool->getName(), $settings);
     }
     $course->setTools($tools);
     $entityManager->persist($course);
     $entityManager->flush($course);
     $courseInfo = api_get_course_info_by_id($course_id);
     $now = api_get_utc_datetime(time());
     $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
     $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
     $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY);
     $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
     $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
     $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
     $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
     $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
     $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY);
     $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
     $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
     $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
     $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
     $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
     $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
     $visible_for_all = 1;
     $visible_for_course_admin = 0;
     $visible_for_platform_admin = 2;
     /*    Course tools  */
     $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
     if ($alert === 'true') {
         $defaultEmailExerciseAlert = 1;
     } else {
         $defaultEmailExerciseAlert = 0;
     }
     /* course_setting table (courseinfo tool)   */
     $settings = ['email_alert_manager_on_new_doc' => ['default' => 0, 'category' => 'work'], 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'], 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'], 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'], 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'], 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'], 'course_theme' => ['default' => '', 'category' => 'theme'], 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'], 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'], 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' => 'registration'], 'allow_user_view_user_list' => ['default' => 1, 'category' => 'user'], 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' => 'thematic_advance'], 'email_alert_students_on_new_homework' => ['default' => 0, 'category' => 'work'], 'enable_lp_auto_launch' => ['default' => 0, 'category' => 'learning_path'], 'pdf_export_watermark_text' => ['default' => '', 'category' => 'learning_path'], 'allow_public_certificates' => ['default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '', 'category' => 'certificates'], 'documents_default_visibility' => ['default' => 'visible', 'category' => 'document']];
     /*$counter = 1;
       foreach ($settings as $variable => $setting) {
           Database::query(
               "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
                VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
           );
           $counter++;
       }*/
     /* Course homepage tools for platform admin only */
     /* Group tool */
     Database::query("INSERT INTO {$TABLEGROUPCATEGORIES}  (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)\n             VALUES ({$course_id}, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');");
     /*    Example Material  */
     $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
     // Example material should be in the same language as the course is.
     $language_interface_original = $language_interface;
     $now = api_get_utc_datetime();
     $files = [['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0], ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0]];
     $counter = 1;
     foreach ($files as $file) {
         self::insertDocument($course_id, $counter, $file);
         $counter++;
     }
     $sys_course_path = api_get_path(SYS_COURSE_PATH);
     $perm = api_get_permissions_for_new_directories();
     $perm_file = api_get_permissions_for_new_files();
     $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
     if (!is_dir($chat_path)) {
         @mkdir($chat_path, api_get_permissions_for_new_directories());
     }
     /*    Documents   */
     if ($fill_with_exemplary_content) {
         $files = [['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0], ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0], ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0], ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0], ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0], ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]];
         foreach ($files as $file) {
             self::insertDocument($course_id, $counter, $file);
             $counter++;
         }
         // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
         $folders_to_copy_from_default_course = array('images', 'audio', 'flash', 'video', 'certificates');
         $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
         $default_document_array = array();
         foreach ($folders_to_copy_from_default_course as $folder) {
             $default_course_folder_path = $default_course_path . $folder . '/';
             $files = self::browse_folders($default_course_folder_path, array(), $folder);
             $sorted_array = self::sort_pictures($files, 'dir');
             $sorted_array = array_merge($sorted_array, self::sort_pictures($files, 'file'));
             $default_document_array[$folder] = $sorted_array;
         }
         //Light protection (adding index.html in every document folder)
         $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n  </head>\n  <body>\n  </body>\n</html>";
         $example_cert_id = 0;
         if (is_array($default_document_array) && count($default_document_array) > 0) {
             foreach ($default_document_array as $media_type => $array_media) {
                 $path_documents = "/{$media_type}/";
                 //hack until feature #5242 is implemented
                 if ($media_type == 'images') {
                     $media_type = 'images/gallery';
                     $images_folder = $sys_course_path . $course_repository . "/document/images/";
                     if (!is_dir($images_folder)) {
                         //Creating index.html
                         mkdir($images_folder, $perm);
                         $fd = fopen($images_folder . 'index.html', 'w');
                         fwrite($fd, $htmlpage);
                         @chmod($images_folder . 'index.html', $perm_file);
                     }
                 }
                 $course_documents_folder = $sys_course_path . $course_repository . "/document/{$media_type}/";
                 $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
                 if (!is_dir($course_documents_folder)) {
                     // Creating index.html
                     mkdir($course_documents_folder, $perm);
                     $fd = fopen($course_documents_folder . 'index.html', 'w');
                     fwrite($fd, $htmlpage);
                     @chmod($course_documents_folder . 'index.html', $perm_file);
                 }
                 if (is_array($array_media) && count($array_media) > 0) {
                     foreach ($array_media as $key => $value) {
                         if (isset($value['dir']) && !empty($value['dir'])) {
                             if (!is_dir($course_documents_folder . $value['dir'])) {
                                 //Creating folder
                                 mkdir($course_documents_folder . $value['dir'], $perm);
                                 //Creating index.html (for light protection)
                                 $index_html = $course_documents_folder . $value['dir'] . '/index.html';
                                 $fd = fopen($index_html, 'w');
                                 fwrite($fd, $htmlpage);
                                 @chmod($index_html, $perm_file);
                                 //Inserting folder in the DB
                                 $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1);
                                 $temp = explode('/', $folder_path);
                                 $title = $temp[count($temp) - 1];
                                 //hack until feature #5242 is implemented
                                 if ($title == 'gallery') {
                                     $title = get_lang('DefaultCourseImages');
                                 }
                                 if ($media_type == 'images/gallery') {
                                     $folder_path = 'gallery/' . $folder_path;
                                 }
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $folder_path . "','" . $title . "','folder','0')");
                                 $image_id = Database::insert_id();
                                 Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                        VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,0)");
                             }
                         }
                         if (isset($value['file']) && !empty($value['file'])) {
                             if (!file_exists($course_documents_folder . $value['file'])) {
                                 //Copying file
                                 copy($default_course_path . $value['file'], $course_documents_folder . $value['file']);
                                 chmod($course_documents_folder . $value['file'], $perm_file);
                                 //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
                                 $temp = explode('/', $value['file']);
                                 $file_size = filesize($course_documents_folder . $value['file']);
                                 //hack until feature #5242 is implemented
                                 if ($media_type == 'images/gallery') {
                                     $value["file"] = 'gallery/' . $value["file"];
                                 }
                                 //Inserting file in the DB
                                 Database::query("INSERT INTO {$TABLETOOLDOCUMENT} (c_id, path,title,filetype,size)\n                                        VALUES ({$course_id},'{$path_documents}" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','{$file_size}')");
                                 $image_id = Database::insert_id();
                                 if ($image_id) {
                                     $sql = "UPDATE {$TABLETOOLDOCUMENT} SET id = iid WHERE iid = {$image_id}";
                                     Database::query($sql);
                                     if ($path_documents . $value['file'] == '/certificates/default.html') {
                                         $example_cert_id = $image_id;
                                     }
                                     Database::query("INSERT INTO {$TABLEITEMPROPERTY} (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility)\n                                            VALUES ({$course_id},'document',1,'{$now}','{$now}',{$image_id},'DocumentAdded',1,NULL,NULL,1)");
                                     $docId = Database::insert_id();
                                     if ($docId) {
                                         $sql = "UPDATE {$TABLEITEMPROPERTY} SET id = iid WHERE iid = {$docId}";
                                         Database::query($sql);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $agenda = new Agenda();
         $agenda->setType('course');
         $agenda->set_course($courseInfo);
         $agenda->addEvent($now, $now, 0, get_lang('AgendaCreationTitle'), get_lang('AgendaCreationContenu'));
         /*  Links tool */
         $link = new Link();
         $link->setCourse($courseInfo);
         $links = [['c_id' => $course_id, 'url' => 'http://www.google.com', 'title' => 'Google', 'description' => get_lang('Google'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0], ['c_id' => $course_id, 'url' => 'http://www.wikipedia.org', 'title' => 'Wikipedia', 'description' => get_lang('Wikipedia'), 'category_id' => 0, 'on_homepage' => 0, 'target' => '_self', 'session_id' => 0]];
         foreach ($links as $params) {
             $link->save($params);
         }
         /* Announcement tool */
         AnnouncementManager::add_announcement(get_lang('AnnouncementExampleTitle'), get_lang('AnnouncementEx'), ['everyone' => 'everyone'], null, null, $now);
         $manager = Database::getManager();
         /* Introduction text */
         $intro_text = '<p style="text-align: center;">
                         <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
                         <h2>' . self::lang2db(get_lang('IntroductionText')) . '</h2>
                      </p>';
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_COURSE_HOMEPAGE)->setSessionId(0)->setIntroText($intro_text);
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_STUDENTPUBLICATION)->setSessionId(0)->setIntroText(get_lang('IntroductionTwo'));
         $manager->persist($toolIntro);
         $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
         $toolIntro->setCId($course_id)->setId(TOOL_WIKI)->setSessionId(0)->setIntroText(get_lang('IntroductionWiki'));
         $manager->persist($toolIntro);
         $manager->flush();
         /*  Exercise tool */
         $exercise = new Exercise($course_id);
         $exercise->exercise = get_lang('ExerciceEx');
         $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
                     <tr>
                     <td width="110" valign="top" align="left">
                         <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_dokeos/thinking.jpg">
                     </td>
                     <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
                 </table>';
         $exercise->type = 1;
         $exercise->setRandom(0);
         $exercise->active = 1;
         $exercise->results_disabled = 0;
         $exercise->description = $html;
         $exercise->save();
         $exercise_id = $exercise->id;
         $question = new MultipleAnswer();
         $question->question = get_lang('SocraticIrony');
         $question->description = get_lang('ManyAnswers');
         $question->weighting = 10;
         $question->position = 1;
         $question->course = $courseInfo;
         $question->save($exercise_id);
         $questionId = $question->id;
         $answer = new Answer($questionId, $courseInfo['real_id']);
         $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
         $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
         $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
         $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
         $answer->save();
         /* Forum tool */
         require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php';
         $params = ['forum_category_title' => get_lang('ExampleForumCategory'), 'forum_category_comment' => ''];
         $forumCategoryId = store_forumcategory($params, $courseInfo, false);
         $params = ['forum_category' => $forumCategoryId, 'forum_title' => get_lang('ExampleForum'), 'forum_comment' => '', 'default_view_type_group' => ['default_view_type' => 'flat']];
         $forumId = store_forum($params, $courseInfo, true);
         $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
         $params = ['post_title' => get_lang('ExampleThread'), 'forum_id' => $forumId, 'post_text' => get_lang('ExampleThreadContent'), 'calification_notebook_title' => '', 'numeric_calification' => '', 'weight_calification' => '', 'forum_category' => $forumCategoryId, 'thread_peer_qualify' => 0];
         store_thread($forumInfo, $params, $courseInfo, false);
         /* Gradebook tool */
         $course_code = $courseInfo['code'];
         // father gradebook
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',0,100,0,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOK} (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id)\n                VALUES ('{$course_code}','',1,'{$course_code}',{$gbid},100,1,75,NULL,{$example_cert_id})");
         $gbid = Database::insert_id();
         Database::query("INSERT INTO {$TABLEGRADEBOOKLINK} (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked)\n                VALUES (1,{$exercise_id},1,'{$course_code}',{$gbid},'{$now}',100,1,0)");
     }
     //Installing plugins in course
     $app_plugin = new AppPlugin();
     $app_plugin->install_course_plugins($course_id);
     $language_interface = $language_interface_original;
     return true;
 }
 /**
  * Receives the unique answer question type creation form data and creates
  * or updates the answers from that question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $correct = $form->getSubmitValue('correct');
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $weighting = trim($form->getSubmitValue('weighting[' . $i . ']'));
         $scenario = $form->getSubmitValue('scenario');
         //$list_destination = $form -> getSubmitValue('destination'.$i);
         //$destination_str = $form -> getSubmitValue('destination'.$i);
         $try = $scenario['try' . $i];
         $lp = $scenario['lp' . $i];
         $destination = $scenario['destination' . $i];
         $url = trim($scenario['url' . $i]);
         /*
                     How we are going to parse the destination value
         
                    here we parse the destination value which is a string
                     1@@3@@2;4;4;@@http://www.chamilo.org
         
                     where: try_again@@lp_id@@selected_questions@@url
         
                    try_again = is 1 || 0
                    lp_id = id of a learning path (0 if dont select)
                    selected_questions= ids of questions
                    url= an url
         
                     $destination_str='';
                     foreach ($list_destination as $destination_id)
                     {
                         $destination_str.=$destination_id.';';
                     }*/
         $goodAnswer = $correct == $i ? true : false;
         if ($goodAnswer) {
             $nbrGoodAnswers++;
             $weighting = abs($weighting);
             if ($weighting > 0) {
                 $questionWeighting += $weighting;
             }
         }
         if (empty($try)) {
             $try = 0;
         }
         if (empty($lp)) {
             $lp = 0;
         }
         if (empty($destination)) {
             $destination = 0;
         }
         if ($url == '') {
             $url = 0;
         }
         //1@@1;2;@@2;4;4;@@http://www.chamilo.org
         $dest = $try . '@@' . $lp . '@@' . $destination . '@@' . $url;
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i, null, null, $dest);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
     }
     // end for()
     if (empty($msgErr)) {
         for ($i = 1; $i <= $nbrAnswers; $i++) {
             if ($debug > 0) {
                 echo str_repeat('&nbsp;', 4) . '$answerType is HOT_SPOT' . "<br />\n";
             }
             $reponse[$i] = trim($reponse[$i]);
             $comment[$i] = trim($comment[$i]);
             $weighting[$i] = $weighting[$i];
             //it can be float
             if ($weighting[$i]) {
                 $questionWeighting += $weighting[$i];
             }
             // creates answer
             $objAnswer->createAnswer($reponse[$i], '', $comment[$i], $weighting[$i], $i, $hotspot_coordinates[$i], $hotspot_type[$i]);
         }
         // end for()
         // saves the answers into the data base
         $objAnswer->save();
         // sets the total weighting of the question
         $objQuestion->updateWeighting($questionWeighting);
         $objQuestion->save($exerciseId);
         $editQuestion = $questionId;
         unset($modifyAnswers);
         echo '<script type="text/javascript">window.location.href="' . $hotspot_admin_url . '&message=ItemUpdated"</script>';
     }
     if ($debug > 0) {
         echo '$modifyIn was set - end' . "<br />\n";
     }
 } else {
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 function processAnswersCreation($form)
 {
     if (!self::isAnswered()) {
         $table = Database::get_course_table(TABLE_QUIZ_ANSWER);
         Database::delete($table, array('c_id = ? AND question_id = ?' => array($this->course['real_id'], $this->id)));
         $answer = $form->getSubmitValue('answer');
         $formula = $form->getSubmitValue('formula');
         $lowestValues = $form->getSubmitValue('lowestValue');
         $highestValues = $form->getSubmitValue('highestValue');
         $answerVariations = $form->getSubmitValue('answerVariations');
         $this->weighting = $form->getSubmitValue('weighting');
         // Create as many answers as $answerVariations
         for ($j = 0; $j < $answerVariations; $j++) {
             $auxAnswer = $answer;
             $auxFormula = $formula;
             $nb = preg_match_all('/\\[[^\\]]*\\]/', $auxAnswer, $blanks);
             if ($nb > 0) {
                 for ($i = 0; $i < $nb; ++$i) {
                     $blankItem = $blanks[0][$i];
                     $replace = array("[", "]");
                     $newBlankItem = str_replace($replace, "", $blankItem);
                     $newBlankItem = "[" . trim($newBlankItem) . "]";
                     // take random float values when one or both edge values have a decimal point
                     $randomValue = strpos($lowestValues[$i], '.') !== false || strpos($highestValues[$i], '.') !== false ? mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]);
                     $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer);
                     $auxFormula = str_replace($blankItem, $randomValue, $auxFormula);
                 }
                 $math = new EvalMath();
                 $result = $math->evaluate($auxFormula);
                 $result = number_format($result, 2, ".", "");
                 // Remove decimal trailing zeros
                 $result = rtrim($result, "0");
                 // If it is an integer (ends in .00) remove the decimal point
                 if (mb_substr($result, -1) === ".") {
                     $result = str_replace(".", "", $result);
                 }
                 // Attach formula
                 $auxAnswer .= " [" . $result . "]@@" . $formula;
             }
             $this->save();
             $objAnswer = new Answer($this->id);
             $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, '');
             $objAnswer->position = array();
             $objAnswer->save();
         }
     }
 }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $nb_matches = $form->getSubmitValue('nb_matches');
     $nb_options = $form->getSubmitValue('nb_options');
     $this->weighting = 0;
     $position = 0;
     $objAnswer = new Answer($this->id);
     // Insert the options
     for ($i = 1; $i <= $nb_options; ++$i) {
         $position++;
         $option = $form->getSubmitValue('option[' . $i . ']');
         $objAnswer->createAnswer($option, 0, '', 0, $position);
     }
     // Insert the answers
     for ($i = 1; $i <= $nb_matches; ++$i) {
         $position++;
         $answer = $form->getSubmitValue('answer[' . $i . ']');
         $matches = $form->getSubmitValue('matches[' . $i . ']');
         $weighting = $form->getSubmitValue('weighting[' . $i . ']');
         $this->weighting += $weighting;
         $objAnswer->createAnswer($answer, $matches, '', $weighting, $position);
     }
     $objAnswer->save();
     $this->save();
 }
Example #10
0
function add_question($node) {

	$objQuestion = new Question();
	$objQuestion->updateTitle(standard_text_escape($node->content));

	/**
	*Exercice type 1 refers to single response multiple choice question. 
	*Exercice type 2 refers to multiple response multiple choice question. 
	*QTILite allows only single response multiple choice questions.
	**/

	if($node->num_of_correct_answers > 1 ) {
		$objQuestion->updateType(2);
	} else {
		$objQuestion->updateType(1);
	}

	$objQuestion->save();

	$questionId = $objQuestion->selectId();

	$objAnswer = new Answer($questionId);
	$tmp_answer = array();

	if($node->answers) {
		foreach ($node->answers as $answer) {
			$objAnswer->createAnswer($answer['answer'], $answer['correct'], $answer['feedback'], $answer['weight'], 1);
		}
		$objAnswer->save();
	}
}
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator $form
  */
 public function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     $options_count = $form->getSubmitValue('options_count');
     $course_id = api_get_course_int_id();
     $correct = array();
     $options = Question::readQuestionOption($this->id, $course_id);
     if (!empty($options)) {
         foreach ($options as $option_data) {
             $id = $option_data['id'];
             unset($option_data['id']);
             Question::updateQuestionOption($id, $option_data, $course_id);
         }
     } else {
         for ($i = 1; $i <= 3; $i++) {
             $last_id = Question::saveQuestionOption($this->id, $this->options[$i], $course_id, $i);
             $correct[$i] = $last_id;
         }
     }
     /* Getting quiz_question_options (true, false, doubt) because
        it's possible that there are more options in the future */
     $new_options = Question::readQuestionOption($this->id, $course_id);
     $sorted_by_position = array();
     foreach ($new_options as $item) {
         $sorted_by_position[$item['position']] = $item;
     }
     /* Saving quiz_question.extra values that has the correct scores of
        the true, false, doubt options registered in this format
        XX:YY:ZZZ where XX is a float score value.*/
     $extra_values = array();
     for ($i = 1; $i <= 3; $i++) {
         $score = trim($form->getSubmitValue('option[' . $i . ']'));
         $extra_values[] = $score;
     }
     $this->setExtra(implode(':', $extra_values));
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $goodAnswer = trim($form->getSubmitValue('correct[' . $i . ']'));
         if (empty($options)) {
             //If this is the first time that the question is created when
             // change the default values from the form 1 and 2 by the correct "option id" registered
             $goodAnswer = $sorted_by_position[$goodAnswer]['id'];
         }
         $questionWeighting += $extra_values[0];
         //By default 0 has the correct answers
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, '', $i);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }
            } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                if ($debug > 0) {
                    echo str_repeat('&nbsp;', 4) . '$answerType is MULTIPLE_ANSWER' . "<br />\n";
                }
                // a bad answer can't have a positive weighting
                $weighting[$i] = 0 - abs($weighting[$i]);
            }
            // checks if field is empty
            if (empty($reponse[$i]) && $reponse[$i] != '0') {
                $msgErr = get_lang('GiveAnswers');
                // clears answers already recorded into the Answer object
                $objAnswer->cancel();
                break;
            } else {
                // adds the answer into the object
                $objAnswer->createAnswer($reponse[$i], $goodAnswer, $comment[$i], $weighting[$i], $i);
                //added
                //if($_REQUEST['myid']==1)
                $mainurl = "admin.php";
                //	else
                //  $mainurl="question_pool.php";
                ?>
                <script>
                    window.location.href='<?php 
                echo $mainurl;
                ?>
';
                </script>
                <?php 
            }
        }
 /**
  * abstract function which creates the form to create / edit the answers of the question
  * @param FormValidator instance
  */
 public function processAnswersCreation($form)
 {
     $questionWeighting = $nbrGoodAnswers = 0;
     $correct = $form->getSubmitValue('correct');
     $objAnswer = new Answer($this->id);
     $nb_answers = $form->getSubmitValue('nb_answers');
     for ($i = 1; $i <= $nb_answers; $i++) {
         $answer = trim($form->getSubmitValue('answer[' . $i . ']'));
         $comment = trim($form->getSubmitValue('comment[' . $i . ']'));
         $weighting = trim($form->getSubmitValue('weighting[' . $i . ']'));
         $scenario = $form->getSubmitValue('scenario');
         //$list_destination = $form -> getSubmitValue('destination'.$i);
         //$destination_str = $form -> getSubmitValue('destination'.$i);
         $try = $scenario['try' . $i];
         $lp = $scenario['lp' . $i];
         $destination = $scenario['destination' . $i];
         $url = trim($scenario['url' . $i]);
         $goodAnswer = $correct == $i ? true : false;
         if ($goodAnswer) {
             $nbrGoodAnswers++;
             $weighting = abs($weighting);
             if ($weighting > 0) {
                 $questionWeighting += $weighting;
             }
         }
         if (empty($try)) {
             $try = 0;
         }
         if (empty($lp)) {
             $lp = 0;
         }
         if (empty($destination)) {
             $destination = 0;
         }
         if ($url == '') {
             $url = 0;
         }
         //1@@1;2;@@2;4;4;@@http://www.chamilo.org
         $dest = $try . '@@' . $lp . '@@' . $destination . '@@' . $url;
         $objAnswer->createAnswer($answer, $goodAnswer, $comment, $weighting, $i, null, null, $dest);
     }
     // saves the answers into the data base
     $objAnswer->save();
     // sets the total weighting of the question
     $this->updateWeighting($questionWeighting);
     $this->save();
 }