public function process()
 {
     $results = array();
     foreach ($this->rows as $row_val) {
         $search_show_unlinked_results = api_get_setting('search_show_unlinked_results') == 'true';
         $course_visible_for_user = api_is_course_visible_for_user(NULL, $row_val['courseid']);
         // can view course?
         if ($course_visible_for_user || $search_show_unlinked_results) {
             // is visible?
             $visibility = api_get_item_visibility(api_get_course_info($row_val['courseid']), TOOL_DOCUMENT, $row_val['xapian_data'][SE_DATA]['doc_id']);
             if ($visibility) {
                 list($thumbnail, $image, $name, $author, $url) = $this->get_information($row_val['courseid'], $row_val['xapian_data'][SE_DATA]['doc_id']);
                 $result = array('toolid' => TOOL_DOCUMENT, 'score' => $row_val['score'], 'url' => $url, 'thumbnail' => $thumbnail, 'image' => $image, 'title' => $name, 'author' => $author);
                 if ($course_visible_for_user) {
                     $results[] = $result;
                 } else {
                     // course not visible for user
                     if ($search_show_unlinked_results) {
                         $result['url'] = '';
                         $results[] = $result;
                     }
                 }
             }
         }
     }
     // get information to sort
     foreach ($results as $key => $row) {
         $score[$key] = $row['score'];
     }
     // Sort results with score descending
     array_multisort($score, SORT_DESC, $results);
     return $results;
 }
    public function process() {
        $results = array();

        foreach ($this->links as $courseid => $one_course_links) {
            $course_info = api_get_course_info($courseid);
            $search_show_unlinked_results = (api_get_setting('search_show_unlinked_results') == 'true');
            $course_visible_for_user = api_is_course_visible_for_user(NULL, $courseid);
            // can view course?
            if ($course_visible_for_user || $search_show_unlinked_results) {
                $result = NULL;
                foreach ($one_course_links['links'] as $one_link) {
                    // is visible?
                    $visibility = api_get_item_visibility($course_info, TOOL_LINK, $one_link['link_id']);
                    if ($visibility) {
                        // if one is visible let show the result for a course
                        // also asume all data of this item like the data of the whole group of links(Ex. author)
                        list($thumbnail, $image, $name, $author, $url) = $this->get_information($courseid, $one_link['link_id']);
                        $result_tmp = array(
                            'toolid' => TOOL_LINK,
                            'score' => $one_course_links['total_score'] / (count($one_course_links) - 1), // not count total_score array item
                            'url' => $url,
                            'thumbnail' => $thumbnail,
                            'image' => $image,
                            'title' => $name,
                            'author' => $author,
                        );
                        if ($course_visible_for_user) {
                            $result = $result_tmp;
                        } else { // course not visible for user
                            if ($search_show_unlinked_results) {
                                $result_tmp['url'] = '';
                                $result = $result_tmp;
                            }
                        }
                        break;
                    }
                }
                if (!is_null($result)) {
                    // if there is at least one link item found show link to course Links tool page
                    $results[] = $result;
                }
            }
        }

        // get information to sort
        foreach ($results as $key => $row) {
            $score[$key] = $row['score'];
        }

        // Sort results with score descending
        array_multisort($score, SORT_DESC, $results);

        return $results;
    }
 public function process()
 {
     $results = array();
     foreach ($this->learnpaths as $courseid => $learnpaths) {
         $search_show_unlinked_results = api_get_setting('search_show_unlinked_results') == 'true';
         $course_visible_for_user = api_is_course_visible_for_user(NULL, $courseid);
         // can view course?
         if ($course_visible_for_user || $search_show_unlinked_results) {
             foreach ($learnpaths as $lp_id => $lp) {
                 // is visible?
                 $visibility = api_get_item_visibility(api_get_course_info($courseid), TOOL_LEARNPATH, $lp_id);
                 if ($visibility) {
                     list($thumbnail, $image, $name, $author) = $this->get_information($courseid, $lp_id, $lp['has_document_id']);
                     $url = api_get_path(WEB_PATH) . 'main/newscorm/lp_controller.php?cidReq=%s&action=view&lp_id=%s';
                     $url = sprintf($url, $courseid, $lp_id);
                     $result = array('toolid' => TOOL_LEARNPATH, 'score' => $lp['total_score'] / (count($lp) - 1), 'url' => $url, 'thumbnail' => $thumbnail, 'image' => $image, 'title' => $name, 'author' => $author);
                     if ($course_visible_for_user) {
                         $results[] = $result;
                     } else {
                         // course not visible for user
                         if ($search_show_unlinked_results) {
                             $result['url'] = '';
                             $results[] = $result;
                         }
                     }
                 }
             }
         }
     }
     // get information to sort
     foreach ($results as $key => $row) {
         $score[$key] = $row['score'];
     }
     // Sort results with score descending
     array_multisort($score, SORT_DESC, $results);
     return $results;
 }
예제 #4
0
                                 }
                             }
                         } else {
                             $number_of_questions = $rowi;
                         }*/
     $number_of_questions = $exercise_obj->getQuestionCount();
     if ($row['random'] > 0 && $row['random'] != -1) {
         $number_of_questions = $number_of_questions . ' (' . $row['random'] . ' ' . get_lang('Random') . ') ';
     }
     //Attempts
     //$attempts = get_count_exam_results($my_exercise_id).' '.get_lang('Attempts');
     //$item .=  Display::tag('td',$attempts);
     $item .= Display::tag('td', $number_of_questions);
 } else {
     // Student only
     $visibility = api_get_item_visibility($course_info, TOOL_QUIZ, $my_exercise_id);
     if ($visibility == 0) {
         continue;
     }
     // if time is actived show link to exercise
     if ($time_limits) {
         if ($is_actived_time) {
             $url = '<a ' . $alt_title . '  href="overview.php?' . api_get_cidreq() . $myorigin . $mylpid . $mylpitemid . '&exerciseId=' . $my_exercise_id . '">' . $cut_title . '</a>';
         } else {
             $url = $row['title'];
         }
     } else {
         $url = '<a ' . $alt_title . '  href="overview.php?' . api_get_cidreq() . $myorigin . $mylpid . $mylpitemid . '&exerciseId=' . $my_exercise_id . '">' . $cut_title . '</a>';
     }
     //Link of the exercise
     $item = Display::tag('td', $url . ' ' . $session_img);
 /**
  * This functions swithes the visibility a course resource
  * using the visibility field in 'item_property'
  * @param    array    the course array
  * @param    int     ID of the element of the corresponding type
  * @return   bool    False on failure, True on success
  */
 public static function change_visibility_announcement($_course, $id)
 {
     $session_id = api_get_session_id();
     $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $id, $session_id);
     if ($item_visibility == '1') {
         api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'invisible', api_get_user_id());
     } else {
         api_item_property_update($_course, TOOL_ANNOUNCEMENT, $id, 'visible', api_get_user_id());
     }
     return true;
 }
예제 #6
0
 /**
  * Get the progress of a exercise
  * @param   int $sessionId  The session ID (session.id)
  * @param   int $courseId   The course ID (course.id)
  * @param   int $exerciseId The quiz ID (c_quiz.id)
  * @param   int $answer     The answer status (0 = incorrect, 1 = correct, 2 = both)
  * @param   array   $options    An array of options you can pass to the query (limit, where and order)
  * @return array An array with the data of exercise(s) progress
  */
 public static function get_exercise_progress($sessionId = 0, $courseId = 0, $exerciseId = 0, $date_from = null, $date_to = null, $options = array())
 {
     $sessionId = intval($sessionId);
     $courseId = intval($courseId);
     $exerciseId = intval($exerciseId);
     $date_from = Database::escape_string($date_from);
     $date_to = Database::escape_string($date_to);
     /*
      * This method gets the data by blocks, as previous attempts at one single
      * query made it take ages. The logic of query division is described below
      */
     // Get tables names
     $tuser = Database::get_main_table(TABLE_MAIN_USER);
     $tquiz = Database::get_course_table(TABLE_QUIZ_TEST);
     $tquiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
     $tquiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
     $tquiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
     $ttrack_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
     $ttrack_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
     $sessions = array();
     $courses = array();
     // if session ID is defined but course ID is empty, get all the courses
     // from that session
     if (!empty($sessionId) && empty($courseId)) {
         // $courses is an array of course int id as index and course details hash as value
         $courses = SessionManager::get_course_list_by_session_id($sessionId);
         $sessions[$sessionId] = api_get_session_info($sessionId);
     } elseif (empty($sessionId) && !empty($courseId)) {
         // if, to the contrary, course is defined but not sessions, get the sessions that include this course
         // $sessions is an array like: [0] => ('id' => 3, 'name' => 'Session 35'), [1] => () etc;
         $course = api_get_course_info_by_id($courseId);
         $sessionsTemp = SessionManager::get_session_by_course($courseId);
         $courses[$courseId] = $course;
         foreach ($sessionsTemp as $sessionItem) {
             $sessions[$sessionItem['id']] = $sessionItem;
         }
     } elseif (!empty($courseId) && !empty($sessionId)) {
         //none is empty
         $course = api_get_course_info_by_id($courseId);
         $courses[$courseId] = array($course['code']);
         $courses[$courseId]['code'] = $course['code'];
         $sessions[$sessionId] = api_get_session_info($sessionId);
     } else {
         //both are empty, not enough data, return an empty array
         return array();
     }
     // Now we have two arrays of courses and sessions with enough data to proceed
     // If no course could be found, we shouldn't return anything.
     // Sessions can be empty (then we only return the pure-course-context results)
     if (count($courses) < 1) {
         return array();
     }
     $data = array();
     // The following loop is less expensive than what it seems:
     // - if a course was defined, then we only loop through sessions
     // - if a session was defined, then we only loop through courses
     // - if a session and a course were defined, then we only loop once
     foreach ($courses as $courseIdx => $courseData) {
         $where = '';
         $whereParams = array();
         $whereSessionParams = '';
         if (count($sessions > 0)) {
             foreach ($sessions as $sessionIdx => $sessionData) {
                 if (!empty($sessionIdx)) {
                     $whereSessionParams .= $sessionIdx . ',';
                 }
             }
             $whereSessionParams = substr($whereSessionParams, 0, -1);
         }
         if (!empty($exerciseId)) {
             $exerciseId = intval($exerciseId);
             $where .= ' AND q.id = %d ';
             $whereParams[] = $exerciseId;
         }
         /*
          * This feature has been disabled for now, to avoid having to
          * join two very large tables
         //2 = show all questions (wrong and correct answered)
         if ($answer != 2) {
             $answer = intval($answer);
             //$where .= ' AND qa.correct = %d';
             //$whereParams[] = $answer;
         }
         */
         $limit = '';
         if (!empty($options['limit'])) {
             $limit = " LIMIT " . $options['limit'];
         }
         if (!empty($options['where'])) {
             $where .= ' AND ' . Database::escape_string($options['where']);
         }
         $order = '';
         if (!empty($options['order'])) {
             $order = " ORDER BY " . $options['order'];
         }
         if (!empty($date_to) && !empty($date_from)) {
             $where .= sprintf(" AND (te.start_date BETWEEN '%s 00:00:00' AND '%s 23:59:59')", $date_from, $date_to);
         }
         $sql = "SELECT\n                te.session_id,\n                ta.id as attempt_id,\n                te.exe_user_id as user_id,\n                te.exe_id as exercise_attempt_id,\n                ta.question_id,\n                ta.answer as answer_id,\n                ta.tms as time,\n                te.exe_exo_id as quiz_id,\n                CONCAT ('c', q.c_id, '_e', q.id) as exercise_id,\n                q.title as quiz_title,\n                qq.description as description\n                FROM {$ttrack_exercises} te\n                INNER JOIN {$ttrack_attempt} ta ON ta.exe_id = te.exe_id\n                INNER JOIN {$tquiz} q ON q.id = te.exe_exo_id\n                INNER JOIN {$tquiz_rel_question} rq ON rq.exercice_id = q.id AND rq.c_id = q.c_id\n                INNER JOIN {$tquiz_question} qq\n                ON\n                    qq.id = rq.question_id AND\n                    qq.c_id = rq.c_id AND\n                    qq.position = rq.question_order AND\n                    ta.question_id = rq.question_id\n                WHERE\n                    te.c_id = {$courseIdx} " . (empty($whereSessionParams) ? '' : "AND te.session_id IN ({$whereSessionParams})") . "\n                    AND q.c_id = {$courseIdx}\n                    {$where} {$order} {$limit}";
         $sql_query = vsprintf($sql, $whereParams);
         // Now browse through the results and get the data
         $rs = Database::query($sql_query);
         $userIds = array();
         $questionIds = array();
         $answerIds = array();
         while ($row = Database::fetch_array($rs)) {
             //only show if exercise is visible
             if (api_get_item_visibility($courseData, 'quiz', $row['exercise_id'])) {
                 $userIds[$row['user_id']] = $row['user_id'];
                 $questionIds[$row['question_id']] = $row['question_id'];
                 $answerIds[$row['question_id']][$row['answer_id']] = $row['answer_id'];
                 $row['session'] = $sessions[$row['session_id']];
                 $data[] = $row;
             }
         }
         // Now fill questions data. Query all questions and answers for this test to avoid
         $sqlQuestions = "SELECT tq.c_id, tq.id as question_id, tq.question, tqa.id_auto,\n                            tqa.answer, tqa.correct, tq.position, tqa.id_auto as answer_id\n                            FROM {$tquiz_question} tq, {$tquiz_answer} tqa\n                            WHERE\n                                tqa.question_id = tq.id AND\n                                tqa.c_id = tq.c_id AND\n                                tq.c_id = {$courseIdx} AND\n                                tq.id IN (" . implode(',', $questionIds) . ")";
         $resQuestions = Database::query($sqlQuestions);
         $answer = array();
         $question = array();
         while ($rowQuestion = Database::fetch_assoc($resQuestions)) {
             $questionId = $rowQuestion['question_id'];
             $answerId = $rowQuestion['answer_id'];
             $answer[$questionId][$answerId] = array('position' => $rowQuestion['position'], 'question' => $rowQuestion['question'], 'answer' => $rowQuestion['answer'], 'correct' => $rowQuestion['correct']);
             $question[$questionId]['question'] = $rowQuestion['question'];
         }
         // Now fill users data
         $sqlUsers = "SELECT user_id, username, lastname, firstname\n                         FROM {$tuser}\n                         WHERE user_id IN (" . implode(',', $userIds) . ")";
         $resUsers = Database::query($sqlUsers);
         while ($rowUser = Database::fetch_assoc($resUsers)) {
             $users[$rowUser['user_id']] = $rowUser;
         }
         foreach ($data as $id => $row) {
             $rowQuestId = $row['question_id'];
             $rowAnsId = $row['answer_id'];
             $data[$id]['session'] = $sessions[$row['session_id']]['name'];
             $data[$id]['firstname'] = $users[$row['user_id']]['firstname'];
             $data[$id]['lastname'] = $users[$row['user_id']]['lastname'];
             $data[$id]['username'] = $users[$row['user_id']]['username'];
             $data[$id]['answer'] = $answer[$rowQuestId][$rowAnsId]['answer'];
             $data[$id]['correct'] = $answer[$rowQuestId][$rowAnsId]['correct'] == 0 ? get_lang('No') : get_lang('Yes');
             $data[$id]['question'] = $question[$rowQuestId]['question'];
             $data[$id]['question_id'] = $rowQuestId;
             $data[$id]['description'] = $row['description'];
         }
         /*
         The minimum expected array structure at the end is:
         attempt_id,
         session name,
         exercise_id,
         quiz_title,
         username,
         lastname,
         firstname,
         time,
         question_id,
         question,
         answer,
         */
     }
     return $data;
 }
예제 #7
0
 /**
  *  Checks if the exercise is visible due a lot of conditions - visibility, time limits, student attempts
  * @return bool true if is active
  */
 public function is_visible($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $filter_by_admin = true)
 {
     // 1. By default the exercise is visible
     $is_visible = true;
     $message = null;
     // 1.1 Admins and teachers can access to the exercise
     if ($filter_by_admin) {
         if (api_is_platform_admin() || api_is_course_admin()) {
             return array('value' => true, 'message' => '');
         }
     }
     // Deleted exercise.
     if ($this->active == -1) {
         return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
     }
     // Checking visibility in the item_property table.
     $visibility = api_get_item_visibility(api_get_course_info(), TOOL_QUIZ, $this->id, api_get_session_id());
     if ($visibility == 0 || $visibility == 2) {
         $this->active = 0;
     }
     // 2. If the exercise is not active.
     if (empty($lp_id)) {
         // 2.1 LP is OFF
         if ($this->active == 0) {
             return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
         }
     } else {
         // 2.1 LP is loaded
         if ($this->active == 0 && !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
             return array('value' => false, 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false));
         }
     }
     //3. We check if the time limits are on
     $limit_time_exists = !empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00' || !empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00' ? true : false;
     if ($limit_time_exists) {
         $time_now = time();
         if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
             $is_visible = $time_now - api_strtotime($this->start_time, 'UTC') > 0 ? true : false;
         }
         if ($is_visible == false) {
             $message = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($this->start_time));
         }
         if ($is_visible == true) {
             if ($this->end_time != '0000-00-00 00:00:00') {
                 $is_visible = (api_strtotime($this->end_time, 'UTC') > $time_now) > 0 ? true : false;
                 if ($is_visible == false) {
                     $message = sprintf(get_lang('ExerciseAvailableUntilX'), api_convert_and_format_date($this->end_time));
                 }
             }
         }
         if ($is_visible == false && $this->start_time != '0000-00-00 00:00:00' && $this->end_time != '0000-00-00 00:00:00') {
             $message = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'), api_convert_and_format_date($this->start_time), api_convert_and_format_date($this->end_time));
         }
     }
     // 4. We check if the student have attempts
     $exerciseAttempts = $this->selectAttempts();
     if ($is_visible) {
         if ($exerciseAttempts > 0) {
             $attempt_count = Event::get_attempt_count_not_finished(api_get_user_id(), $this->id, $lp_id, $lp_item_id, $lp_item_view_id);
             if ($attempt_count >= $exerciseAttempts) {
                 $message = sprintf(get_lang('ReachedMaxAttempts'), $this->name, $exerciseAttempts);
                 $is_visible = false;
             }
         }
     }
     if (!empty($message)) {
         $message = Display::return_message($message, 'warning', false);
     }
     return array('value' => $is_visible, 'message' => $message);
 }
예제 #8
0
    /**
     * Shows a question
     *
     * @param int    $questionId question id
     * @param bool   $only_questions if true only show the questions, no exercise title
     * @param bool   $origin  i.e = learnpath
     * @param string $current_item current item from the list of questions
     * @param bool   $show_title
     * @param bool   $freeze
     * @param array  $user_choice
     * @param bool   $show_comment
     * @param bool   $exercise_feedback
     * @param bool   $show_answers
     * */
    public static function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false)
    {
        $course_id = api_get_course_int_id();
        // Change false to true in the following line to enable answer hinting
        $debug_mark_answer = $show_answers;
        // Reads question information
        if (!($objQuestionTmp = Question::read($questionId))) {
            // Question not found
            return false;
        }
        if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
            $show_comment = false;
        }
        $answerType = $objQuestionTmp->selectType();
        $pictureName = $objQuestionTmp->selectPicture();
        $s = '';
        if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
            // Question is not a hotspot
            if (!$only_questions) {
                $questionDescription = $objQuestionTmp->selectDescription();
                if ($show_title) {
                    TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
                    echo Display::div($current_item . '. ' . $objQuestionTmp->selectTitle(), array('class' => 'question_title'));
                }
                if (!empty($questionDescription)) {
                    echo Display::div($questionDescription, array('class' => 'question_description'));
                }
            }
            if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
                return '';
            }
            echo '<div class="question_options row">';
            // construction of the Answer object (also gets all answers details)
            $objAnswerTmp = new Answer($questionId);
            $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
            $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
            // For "matching" type here, we need something a little bit special
            // because the match between the suggestions and the answers cannot be
            // done easily (suggestions and answers are in the same table), so we
            // have to go through answers first (elems with "correct" value to 0).
            $select_items = array();
            //This will contain the number of answers on the left side. We call them
            // suggestions here, for the sake of comprehensions, while the ones
            // on the right side are called answers
            $num_suggestions = 0;
            if (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
                if ($answerType == DRAGGABLE) {
                    $s .= '<div class="col-md-12 ui-widget ui-helper-clearfix">
                        <div class="clearfix">
                        <ul class="exercise-draggable-answer ui-helper-reset ui-helper-clearfix">';
                } else {
                    $s .= '<div id="drag' . $questionId . '_question" class="drag_question">
                           <table class="data_table">';
                }
                // Iterate through answers
                $x = 1;
                //mark letters for each answer
                $letter = 'A';
                $answer_matching = array();
                $cpt1 = array();
                for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                    if ($answerCorrect == 0) {
                        // options (A, B, C, ...) that will be put into the list-box
                        // have the "correct" field set to 0 because they are answer
                        $cpt1[$x] = $letter;
                        $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer);
                        $x++;
                        $letter++;
                    }
                }
                $i = 1;
                $select_items[0]['id'] = 0;
                $select_items[0]['letter'] = '--';
                $select_items[0]['answer'] = '';
                foreach ($answer_matching as $id => $value) {
                    $select_items[$i]['id'] = $value['id_auto'];
                    $select_items[$i]['letter'] = $cpt1[$id];
                    $select_items[$i]['answer'] = $value['answer'];
                    $i++;
                }
                $user_choice_array_position = array();
                if (!empty($user_choice)) {
                    foreach ($user_choice as $item) {
                        $user_choice_array_position[$item['position']] = $item['answer'];
                    }
                }
                $num_suggestions = $nbrAnswers - $x + 1;
            } elseif ($answerType == FREE_ANSWER) {
                $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
                $form = new FormValidator('free_choice_' . $questionId);
                $config = array('ToolbarSet' => 'TestFreeAnswer');
                $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
                $form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
                $s .= $form->returnForm();
            } elseif ($answerType == ORAL_EXPRESSION) {
                // Add nanog
                if (api_get_setting('document.enable_nanogong') == 'true') {
                    //@todo pass this as a parameter
                    global $exercise_stat_info, $exerciseId, $exe_id;
                    if (!empty($exercise_stat_info)) {
                        $params = array('exercise_id' => $exercise_stat_info['exe_exo_id'], 'exe_id' => $exercise_stat_info['exe_id'], 'question_id' => $questionId);
                    } else {
                        $params = array('exercise_id' => $exerciseId, 'exe_id' => 'temp_exe', 'question_id' => $questionId);
                    }
                    $nano = new Nanogong($params);
                    echo $nano->show_button();
                }
                $form = new FormValidator('free_choice_' . $questionId);
                $config = array('ToolbarSet' => 'TestFreeAnswer');
                $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
                //$form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
                $s .= $form->returnForm();
            }
            // Now navigate through the possible answers, using the max number of
            // answers for the question as a limiter
            $lines_count = 1;
            // a counter for matching-type answers
            if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                $header = Display::tag('th', get_lang('Options'));
                foreach ($objQuestionTmp->options as $item) {
                    if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                        if (in_array($item, $objQuestionTmp->options)) {
                            $header .= Display::tag('th', get_lang($item));
                        } else {
                            $header .= Display::tag('th', $item);
                        }
                    } else {
                        $header .= Display::tag('th', $item);
                    }
                }
                if ($show_comment) {
                    $header .= Display::tag('th', get_lang('Feedback'));
                }
                $s .= '<table class="table table-hover table-striped">';
                $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
            }
            if ($show_comment) {
                if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
                    $header = Display::tag('th', get_lang('Options'));
                    if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
                        $header .= Display::tag('th', get_lang('Feedback'));
                    }
                    $s .= '<table class="table table-hover table-striped">';
                    $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
                }
            }
            $matching_correct_answer = 0;
            $user_choice_array = array();
            if (!empty($user_choice)) {
                foreach ($user_choice as $item) {
                    $user_choice_array[] = $item['answer'];
                }
            }
            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                $answer = $objAnswerTmp->selectAnswer($answerId);
                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                $comment = $objAnswerTmp->selectComment($answerId);
                $attributes = array();
                // Unique answer
                if (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, UNIQUE_ANSWER_IMAGE])) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    if ($show_comment) {
                        $s .= '<tr><td>';
                    }
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        if ($show_comment) {
                            if (empty($comment)) {
                                $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image" style="text-align: center">';
                            } else {
                                $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image col-xs-6 col-sm-12" style="text-align: center">';
                            }
                        } else {
                            $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image col-xs-6 col-md-3" style="text-align: center">';
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $s .= Display::input('hidden', 'choice2[' . $questionId . ']', '0');
                    $answer_input = null;
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $attributes['style'] = 'display: none;';
                        $answer = '<div class="thumbnail">' . $answer . '</div>';
                    }
                    $answer_input .= '<label class="radio">';
                    $answer_input .= Display::input('radio', 'choice[' . $questionId . ']', $numAnswer, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $answer_input .= "</div>";
                    }
                    if ($show_comment) {
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    $answer = Security::remove_XSS($answer, STUDENT);
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                        $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                        $answer_input = '<label class="checkbox">';
                        $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', $numAnswer, $attributes);
                        $answer_input .= $answer;
                        $answer_input .= '</label>';
                        if ($show_comment) {
                            $s .= '<tr><td>';
                            $s .= $answer_input;
                            $s .= '</td>';
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                            $s .= '</tr>';
                        } else {
                            $s .= $answer_input;
                        }
                    } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                        $my_choice = array();
                        if (!empty($user_choice_array)) {
                            foreach ($user_choice_array as $item) {
                                $item = explode(':', $item);
                                $my_choice[$item[0]] = $item[1];
                            }
                        }
                        $s .= '<tr>';
                        $s .= Display::tag('td', $answer);
                        if (!empty($quiz_question_options)) {
                            foreach ($quiz_question_options as $id => $item) {
                                if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
                                    $attributes = array('checked' => 1, 'selected' => 1);
                                } else {
                                    $attributes = array();
                                }
                                if ($debug_mark_answer) {
                                    if ($id == $answerCorrect) {
                                        $attributes['checked'] = 1;
                                        $attributes['selected'] = 1;
                                    }
                                }
                                $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $id, $attributes), array('style' => ''));
                            }
                        }
                        if ($show_comment) {
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                        }
                        $s .= '</tr>';
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
                    // multiple answers
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $answer_input .= '<label class="checkbox">';
                    $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', 1, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($show_comment) {
                        $s .= '<tr>';
                        $s .= '<td>';
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                    $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $my_choice = array();
                    if (!empty($user_choice_array)) {
                        foreach ($user_choice_array as $item) {
                            $item = explode(':', $item);
                            if (isset($item[1]) && isset($item[0])) {
                                $my_choice[$item[0]] = $item[1];
                            }
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $s .= '<tr>';
                    $s .= Display::tag('td', $answer);
                    foreach ($objQuestionTmp->options as $key => $item) {
                        if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
                            $attributes = array('checked' => 1, 'selected' => 1);
                        } else {
                            $attributes = array();
                        }
                        if ($debug_mark_answer) {
                            if ($key == $answerCorrect) {
                                $attributes['checked'] = 1;
                                $attributes['selected'] = 1;
                            }
                        }
                        $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $key, $attributes));
                    }
                    if ($show_comment) {
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                    }
                    $s .= '</tr>';
                } elseif ($answerType == FILL_IN_BLANKS) {
                    // display the question, with field empty, for student to fill it,
                    // or filled to display the answer in the Question preview of the exercice/admin.php page
                    $displayForStudent = true;
                    $listAnswerInformations = FillBlanks::getAnswerInfo($answer);
                    $separatorStartRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorstart']);
                    $separatorEndRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorend']);
                    list($answer) = explode('::', $answer);
                    //Correct answers
                    $correctAnswerList = $listAnswerInformations['tabwords'];
                    //Student's answer
                    $studentAnswerList = array();
                    if (isset($user_choice[0]['answer'])) {
                        $arrayStudentAnswer = FillBlanks::getAnswerInfo($user_choice[0]['answer'], true);
                        $studentAnswerList = $arrayStudentAnswer['studentanswer'];
                    }
                    // If the question must be shown with the answer (in page exercice/admin.php) for teacher preview
                    // set the student-answer to the correct answer
                    if ($debug_mark_answer) {
                        $studentAnswerList = $correctAnswerList;
                        $displayForStudent = false;
                    }
                    if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
                        $answer = "";
                        for ($i = 0; $i < count($listAnswerInformations["commonwords"]) - 1; $i++) {
                            // display the common word
                            $answer .= $listAnswerInformations["commonwords"][$i];
                            // display the blank word
                            $correctItem = $listAnswerInformations["tabwords"][$i];
                            $correctItemRegexp = $correctItem;
                            // replace / with \/ to allow the preg_replace bellow and all the regexp char
                            $correctItemRegexp = FillBlanks::getRegexpProtected($correctItemRegexp);
                            if (isset($studentAnswerList[$i])) {
                                // If student already started this test and answered this question,
                                // fill the blank with his previous answers
                                // may be "" if student viewed the question, but did not fill the blanks
                                $correctItem = $studentAnswerList[$i];
                            }
                            $attributes["style"] = "width:" . $listAnswerInformations["tabinputsize"][$i] . "px";
                            $answer .= FillBlanks::getFillTheBlankHtml($separatorStartRegexp, $separatorEndRegexp, $correctItemRegexp, $questionId, $correctItem, $attributes, $answer, $listAnswerInformations, $displayForStudent, $i);
                        }
                        // display the last common word
                        $answer .= $listAnswerInformations["commonwords"][$i];
                    } else {
                        // display empty [input] with the right width for student to fill it
                        $separatorStartRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorstart']);
                        $separatorEndRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorend']);
                        $answer = "";
                        for ($i = 0; $i < count($listAnswerInformations["commonwords"]) - 1; $i++) {
                            // display the common words
                            $answer .= $listAnswerInformations["commonwords"][$i];
                            // display the blank word
                            $attributes["style"] = "width:" . $listAnswerInformations["tabinputsize"][$i] . "px";
                            $correctItem = $listAnswerInformations["tabwords"][$i];
                            $correctItemRegexp = $correctItem;
                            // replace / with \/ to allow the preg_replace bellow and all the regexp char
                            $correctItemRegexp = FillBlanks::getRegexpProtected($correctItemRegexp);
                            $answer .= FillBlanks::getFillTheBlankHtml($separatorStartRegexp, $separatorEndRegexp, $correctItemRegexp, $questionId, '', $attributes, $answer, $listAnswerInformations, $displayForStudent, $i);
                        }
                        // display the last common word
                        $answer .= $listAnswerInformations["commonwords"][$i];
                    }
                    $s .= $answer;
                } elseif ($answerType == CALCULATED_ANSWER) {
                    /*
                     * In the CALCULATED_ANSWER test
                     * you mustn't have [ and ] in the textarea
                     * you mustn't have @@ in the textarea
                     * the text to find mustn't be empty or contains only spaces
                     * the text to find mustn't contains HTML tags
                     * the text to find mustn't contains char "
                     */
                    if ($origin !== null) {
                        global $exe_id;
                        $trackAttempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
                        $sql = 'SELECT answer
                                FROM ' . $trackAttempts . '
                                WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId;
                        $rsLastAttempt = Database::query($sql);
                        $rowLastAttempt = Database::fetch_array($rsLastAttempt);
                        $answer = $rowLastAttempt['answer'];
                        if (empty($answer)) {
                            $calculatedAnswerId = [];
                            $calculatedAnswerId[$questionId] = mt_rand(1, $nbrAnswers);
                            $answer = $objAnswerTmp->selectAnswer($calculatedAnswerId[$questionId]);
                            Session::write('calculatedAnswerId', $calculatedAnswerId);
                        }
                    }
                    list($answer) = explode('@@', $answer);
                    // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
                    api_preg_match_all('/\\[[^]]+\\]/', $answer, $correctAnswerList);
                    // get student answer to display it if student go back to previous calculated answer question in a test
                    if (isset($user_choice[0]['answer'])) {
                        api_preg_match_all('/\\[[^]]+\\]/', $answer, $studentAnswerList);
                        $studentAnswerListTobecleaned = $studentAnswerList[0];
                        $studentAnswerList = array();
                        for ($i = 0; $i < count($studentAnswerListTobecleaned); $i++) {
                            $answerCorrected = $studentAnswerListTobecleaned[$i];
                            $answerCorrected = api_preg_replace('| / <font color="green"><b>.*$|', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('/^\\[/', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('|^<font color="red"><s>|', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('|</s></font>$|', '', $answerCorrected);
                            $answerCorrected = '[' . $answerCorrected . ']';
                            $studentAnswerList[] = $answerCorrected;
                        }
                    }
                    // If display preview of answer in test view for exemple, set the student answer to the correct answers
                    if ($debug_mark_answer) {
                        // contain the rights answers surronded with brackets
                        $studentAnswerList = $correctAnswerList[0];
                    }
                    /*
                    Split the response by bracket
                    tabComments is an array with text surrounding the text to find
                    we add a space before and after the answerQuestion to be sure to
                    have a block of text before and after [xxx] patterns
                    so we have n text to find ([xxx]) and n+1 block of texts before,
                    between and after the text to find
                    */
                    $tabComments = api_preg_split('/\\[[^]]+\\]/', ' ' . $answer . ' ');
                    if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
                        $answer = "";
                        $i = 0;
                        foreach ($studentAnswerList as $studentItem) {
                            // remove surronding brackets
                            $studentResponse = api_substr($studentItem, 1, api_strlen($studentItem) - 2);
                            $size = strlen($studentItem);
                            $attributes['class'] = self::detectInputAppropriateClass($size);
                            $answer .= $tabComments[$i] . Display::input('text', "choice[{$questionId}][]", $studentResponse, $attributes);
                            $i++;
                        }
                        $answer .= $tabComments[$i];
                    } else {
                        // display exercise with empty input fields
                        // every [xxx] are replaced with an empty input field
                        foreach ($correctAnswerList[0] as $item) {
                            $size = strlen($item);
                            $attributes['class'] = self::detectInputAppropriateClass($size);
                            $answer = str_replace($item, Display::input('text', "choice[{$questionId}][]", '', $attributes), $answer);
                        }
                    }
                    if ($origin !== null) {
                        $s = $answer;
                        break;
                    } else {
                        $s .= $answer;
                    }
                } elseif ($answerType == MATCHING) {
                    // matching type, showing suggestions and answers
                    // TODO: replace $answerId by $numAnswer
                    if ($answerCorrect != 0) {
                        // only show elements to be answered (not the contents of
                        // the select boxes, who are corrrect = 0)
                        $s .= '<tr><td width="45%" valign="top">';
                        $parsed_answer = $answer;
                        //left part questions
                        $s .= '<p class="indent">' . $lines_count . '.&nbsp;' . $parsed_answer . '</p></td>';
                        //middle part (matches selects)
                        $s .= '<td width="10%" valign="top" align="center" >
                                <div class="select-matching">
                                <select name="choice[' . $questionId . '][' . $numAnswer . ']">';
                        // fills the list-box
                        foreach ($select_items as $key => $val) {
                            // set $debug_mark_answer to true at function start to
                            // show the correct answer with a suffix '-x'
                            $selected = '';
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selected = 'selected="selected"';
                                }
                            }
                            //$user_choice_array_position
                            if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
                                $selected = 'selected="selected"';
                            }
                            $s .= '<option value="' . $val['id'] . '" ' . $selected . '>' . $val['letter'] . '</option>';
                        }
                        // end foreach()
                        $s .= '</select></div></td><td width="5%" class="separate">&nbsp;</td>';
                        $s .= '<td width="40%" valign="top" >';
                        if (isset($select_items[$lines_count])) {
                            $s .= '<div class="text-right"><p class="indent">' . $select_items[$lines_count]['letter'] . '.&nbsp; ' . $select_items[$lines_count]['answer'] . '</p></div>';
                        } else {
                            $s .= '&nbsp;';
                        }
                        $s .= '</td>';
                        $s .= '</tr>';
                        $lines_count++;
                        //if the left side of the "matching" has been completely
                        // shown but the right side still has values to show...
                        if ($lines_count - 1 == $num_suggestions) {
                            // if it remains answers to shown at the right side
                            while (isset($select_items[$lines_count])) {
                                $s .= '<tr>
                                      <td colspan="2"></td>
                                      <td valign="top">';
                                $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'];
                                $s .= "</td>\n                                </tr>";
                                $lines_count++;
                            }
                            // end while()
                        }
                        // end if()
                        $matching_correct_answer++;
                    }
                } elseif ($answerType == DRAGGABLE) {
                    if ($answerCorrect != 0) {
                        $parsed_answer = $answer;
                        /*$lines_count = '';
                          $data = $objAnswerTmp->getAnswerByAutoId($numAnswer);
                          $data = $objAnswerTmp->getAnswerByAutoId($data['correct']);
                          $lines_count = $data['answer'];*/
                        $windowId = $questionId . '_' . $lines_count;
                        $s .= '<li class="touch-items" id="' . $windowId . '">';
                        $s .= Display::div($parsed_answer, ['id' => "window_{$windowId}", 'class' => "window{$questionId}_question_draggable exercise-draggable-answer-option"]);
                        $selectedValue = 0;
                        $draggableSelectOptions = [];
                        foreach ($select_items as $key => $val) {
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selectedValue = $val['id'];
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selectedValue = $val['id'];
                            }
                            $draggableSelectOptions[$val['id']] = $val['letter'];
                        }
                        $s .= Display::select("choice[{$questionId}][{$numAnswer}]", $draggableSelectOptions, $selectedValue, ['id' => "window_{$windowId}_select", 'class' => 'select_option', 'style' => 'display: none;'], false);
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            $s .= <<<JAVASCRIPT
                                <script>
                                    \$(function() {
                                        DraggableAnswer.deleteItem(
                                            \$('#{$questionId}_{$selectedValue}'),
                                            \$('#drop_{$windowId}')
                                        );
                                    });
                                </script>
JAVASCRIPT;
                        }
                        if (isset($select_items[$lines_count])) {
                            $s .= Display::div(Display::tag('b', $select_items[$lines_count]['letter']) . $select_items[$lines_count]['answer'], ['id' => "window_{$windowId}_answer", 'style' => 'display: none;']);
                        } else {
                            $s .= '&nbsp;';
                        }
                        $lines_count++;
                        if ($lines_count - 1 == $num_suggestions) {
                            while (isset($select_items[$lines_count])) {
                                $s .= Display::tag('b', $select_items[$lines_count]['letter']);
                                $s .= $select_items[$lines_count]['answer'];
                                $lines_count++;
                            }
                        }
                        $matching_correct_answer++;
                        $s .= '</li>';
                    }
                } elseif ($answerType == MATCHING_DRAGGABLE) {
                    if ($answerId == 1) {
                        echo $objAnswerTmp->getJs();
                    }
                    if ($answerCorrect != 0) {
                        $parsed_answer = $answer;
                        $windowId = "{$questionId}_{$lines_count}";
                        $s .= <<<HTML
                            <tr>
                                <td widht="45%">
                                    <div id="window_{$windowId}" class="window window_left_question window{$questionId}_question">
                                        <strong>{$lines_count}.</strong> {$parsed_answer}
                                    </div>
                                </td>
                                <td width="10%">
HTML;
                        $selectedValue = 0;
                        $selectedPosition = 0;
                        $questionOptions = [];
                        $iTempt = 0;
                        foreach ($select_items as $key => $val) {
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selectedValue = $val['id'];
                                    $selectedPosition = $iTempt;
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selectedValue = $val['id'];
                                $selectedPosition = $iTempt;
                            }
                            $questionOptions[$val['id']] = $val['letter'];
                            $iTempt++;
                        }
                        $s .= Display::select("choice[{$questionId}][{$numAnswer}]", $questionOptions, $selectedValue, ['id' => "window_{$windowId}_select", 'class' => 'hidden'], false);
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            // Show connect if is not freeze (question preview)
                            if (!$freeze) {
                                $s .= <<<JAVASCRIPT
                                <script>
                                    \$(document).on('ready', function () {
                                        jsPlumb.ready(function() {
                                            jsPlumb.connect({
                                                source: 'window_{$windowId}',
                                                target: 'window_{$questionId}_{$selectedPosition}_answer',
                                                endpoint: ['Blank', {radius: 15}],
                                                anchors: ['RightMiddle', 'LeftMiddle'],
                                                paintStyle: {strokeStyle: '#8A8888', lineWidth: 8},
                                                connector: [
                                                    MatchingDraggable.connectorType,
                                                    {curvines: MatchingDraggable.curviness}
                                                ]
                                            });
                                        });
                                    });
                                </script>
JAVASCRIPT;
                            }
                        }
                        $s .= <<<HTML
                            </td>
                            <td width="45%">
HTML;
                        if (isset($select_items[$lines_count])) {
                            $s .= <<<HTML
                                <div id="window_{$windowId}_answer" class="window window_right_question">
                                    <strong>{$select_items[$lines_count]['letter']}.</strong> {$select_items[$lines_count]['answer']}
                                </div>
HTML;
                        } else {
                            $s .= '&nbsp;';
                        }
                        $s .= '</td></tr>';
                        $lines_count++;
                        if ($lines_count - 1 == $num_suggestions) {
                            while (isset($select_items[$lines_count])) {
                                $s .= <<<HTML
                                    <tr>
                                        <td colspan="2"></td>
                                        <td>
                                            <strong>{$select_items[$lines_count]['letter']}</strong>
                                            {$select_items[$lines_count]['answer']}
                                        </td>
                                    </tr>
HTML;
                                $lines_count++;
                            }
                        }
                        $matching_correct_answer++;
                    }
                }
            }
            // end for()
            if ($show_comment) {
                $s .= '</table>';
            } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER_TRUE_FALSE, MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE])) {
                $s .= '</table>';
            }
            if ($answerType == DRAGGABLE) {
                $s .= "</ul>";
                $s .= "</div>";
                //clearfix
                $counterAnswer = 1;
                $s .= '<div class="col-md-12"><div class="row">';
                for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $windowId = $questionId . '_' . $counterAnswer;
                    if ($answerCorrect) {
                        $s .= Display::div($counterAnswer, ['id' => "drop_{$windowId}", 'class' => 'droppable col-md-2']);
                        $counterAnswer++;
                    }
                }
                $s .= '</div>';
                // row
                $s .= '</div>';
                // col-md-12
                $s .= '</div>';
                // col-md-12 ui-widget ui-helper-clearfix
            }
            if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
                $s .= '</div>';
                //drag_question
            }
            $s .= '</div>';
            //question_options row
            // destruction of the Answer object
            unset($objAnswerTmp);
            // destruction of the Question object
            unset($objQuestionTmp);
            if ($origin != 'export') {
                echo $s;
            } else {
                return $s;
            }
        } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
            global $exerciseId, $exe_id;
            // Question is a HOT_SPOT
            //checking document/images visibility
            if (api_is_platform_admin() || api_is_course_admin()) {
                $course = api_get_course_info();
                $doc_id = DocumentManager::get_document_id($course, '/images/' . $pictureName);
                if (is_numeric($doc_id)) {
                    $images_folder_visibility = api_get_item_visibility($course, 'document', $doc_id, api_get_session_id());
                    if (!$images_folder_visibility) {
                        //This message is shown only to the course/platform admin if the image is set to visibility = false
                        Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
                    }
                }
            }
            $questionName = $objQuestionTmp->selectTitle();
            $questionDescription = $objQuestionTmp->selectDescription();
            if ($freeze) {
                echo "\n                    <script>\n                        \$(document).on('ready', function () {\n                            new " . ($answerType == HOT_SPOT ? "HotspotQuestion" : "DelineationQuestion") . "({\n                                questionId: {$questionId},\n                                exerciseId: {$exerciseId},\n                                selector: '#hotspot-preview-{$questionId}',\n                                for: 'preview'\n                            });\n                        });\n                    </script>\n                    <div id=\"hotspot-preview-{$questionId}\"></div>\n                ";
                return;
            }
            // Get the answers, make a list
            $objAnswerTmp = new Answer($questionId);
            $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
            // get answers of hotpost
            $answers_hotspot = array();
            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
                $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
            }
            $answerList = '';
            if ($answerType != HOT_SPOT_DELINEATION) {
                $answerList = '
                    <div class="well well-sm">
                        <h5 class="page-header">' . get_lang('HotspotZones') . '</h5>
                        <ol>
                ';
                if (!empty($answers_hotspot)) {
                    ksort($answers_hotspot);
                    $countAnswers = 1;
                    foreach ($answers_hotspot as $value) {
                        $answerList .= "<li><p>{$countAnswers} - {$value}</p></li>";
                        $countAnswers++;
                    }
                }
                $answerList .= '
                        </ol>
                    </div>
                ';
            }
            if (!$only_questions) {
                if ($show_title) {
                    TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
                    echo '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
                }
                //@todo I need to the get the feedback type
                echo <<<HOTSPOT
                    <input type="hidden" name="hidden_hotspot_id" value="{$questionId}" />
                    <div class="exercise_questions">
                        {$questionDescription}
                        <div class="row">
HOTSPOT;
            }
            $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
            $s .= "\n                            <div class=\"col-sm-8 col-md-9\">\n                                <div class=\"hotspot-image\"></div>\n                                <script>\n                                    \$(document).on('ready', function () {\n                                        new " . ($answerType == HOT_SPOT_DELINEATION ? 'DelineationQuestion' : 'HotspotQuestion') . "({\n                                            questionId: {$questionId},\n                                            exerciseId: {$exe_id},\n                                            selector: '#question_div_' + {$questionId} + ' .hotspot-image',\n                                            for: 'user'\n                                        });\n                                    });\n                                </script>\n                            </div>\n                            <div class=\"col-sm-4 col-md-3\">\n                                {$answerList}\n                            </div>\n            ";
            echo <<<HOTSPOT
                            {$s}
                        </div>
                    </div>
HOTSPOT;
        }
        return $nbrAnswers;
    }
예제 #9
0
 /**
  * Get all the files and directories of a relative path.
  * @param string $path relative path to be base path.
  * @return array of file and path information.
  * <code>array(0=>array('relative'=>'fullpath',...), 1=>array('filename'=>fileinfo array(),...)</code>
  * fileinfo array: <code>array('url'=>'full url',
  *                       'relative'=>'relative to base',
  *                        'fullpath'=>'full file path',
  *                        'image'=>imageInfo array() false if not image,
  *                        'stat' => filestat)</code>
  */
 function getFiles($path)
 {
     $files = array();
     $dirs = array();
     if (!$this->isValidBase()) {
         return array($files, $dirs);
     }
     $path = Files::fixPath($path);
     $base = Files::fixPath($this->getBaseDir());
     $fullpath = Files::makePath($base, $path);
     $d = @dir($fullpath);
     if (empty($d)) {
         $path = Files::fixPath('/');
         $base = Files::fixPath($this->getBaseDir());
         $fullpath = Files::makePath($base, $path);
         $d = @dir($fullpath);
     }
     $in_group = api_is_in_group();
     $user_id = api_get_user_id();
     // check templates files in bd
     $tbl_system_template = Database::get_main_table(TABLE_MAIN_SYSTEM_TEMPLATE);
     $sql = "SELECT image FROM {$tbl_system_template} ";
     $res = Database::query($sql);
     $files_templates = array();
     while ($row = Database::fetch_row($res)) {
         $files_templates[] = $row[0];
     }
     while (false !== ($entry = $d->read())) {
         if (in_array($entry, $files_templates)) {
             continue;
         }
         if (substr($entry, 0, 1) != '.' && strpos($entry, '_DELETED_') === false && strpos($entry, 'chat_files') === false && strpos($entry, 'css') === false && strpos($entry, 'HotPotatoes_files') === false && ($in_group || !$in_group && strpos($entry, '_groupdocs') === false)) {
             $is_dir = is_dir($fullpath . $entry);
             if ($is_dir) {
                 $dir_entry = Files::fixPath($fullpath . $entry);
                 /*
                 if (strpos($dir_entry, '/shared_folder/') !== false)
                 {
                 	if (!preg_match('/.*\/shared_folder\/$/', $dir_entry))
                 	{
                 		//all students can see the shared_folder
                 		if (strpos($dir_entry, '/shared_folder/sf_user_'.$user_id.'/') === true)
                 		{
                 			continue;
                 		}
                 	}
                 }
                 */
             }
             if ($is_dir && !$this->isThumbDir($entry)) {
                 global $_course;
                 if (isset($_course) && !empty($_course) && isset($_course['code'])) {
                     //checking visibility
                     $base_dir = substr($dir_entry, 0, strpos($dir_entry, '/document/') + 9);
                     $new_dir = substr($dir_entry, strlen($base_dir), -1);
                     //
                     $doc_id = DocumentManager::get_document_id($_course, $new_dir);
                     $visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
                 }
                 //Teachers can access to hidden files and directories as they can in the tool documents
                 /*
                 if ($visible_status=='0' || $visible_status=='-1') {
                 	continue;
                 }
                 */
                 $relative = Files::fixPath($path . $entry);
                 $full = Files::fixPath($fullpath . $entry);
                 $count = $this->countFiles($full);
                 $dirs[$relative] = array('fullpath' => $full, 'entry' => $entry, 'count' => $count);
             } else {
                 if (is_file($fullpath . $entry) && !$this->isThumb($entry) && !$this->isTmpFile($entry)) {
                     $img = $this->getImageInfo($fullpath . $entry);
                     if (!(!is_array($img) && $this->config['validate_images'])) {
                         global $_course;
                         if (!empty($_course) && isset($_course['code'])) {
                             //checking visibility
                             $base_dir = substr($fullpath . $entry, 0, strpos($fullpath . $entry, '/document/') + 9);
                             $new_dir = substr($fullpath . $entry, strlen($base_dir));
                             $doc_id = DocumentManager::get_document_id($_course, $new_dir);
                             $visible_status = api_get_item_visibility($_course, TOOL_DOCUMENT, $doc_id);
                         }
                         //Teachers can access to hidden files and directories as they can in the tool documents
                         /*
                         if ($visible_status=='0' || $visible_status=='-1') {
                         	continue;
                         }
                         */
                         $file['url'] = Files::makePath($this->config['base_url'], $path) . $entry;
                         $file['relative'] = $path . $entry;
                         $file['fullpath'] = $fullpath . $entry;
                         $file['image'] = $img;
                         $file['stat'] = stat($fullpath . $entry);
                         $files[$entry] = $file;
                     }
                 }
             }
         }
     }
     $d->close();
     ksort($dirs);
     ksort($files);
     return array($dirs, $files);
 }
예제 #10
0
        $doc_url = substr($doc_url, 0, $dul);
    }
    //create the path
    $document_explorer = api_get_path(WEB_COURSE_PATH) . api_get_course_path();
    //redirect
    header('Location: ' . $document_explorer);
}
$tbl_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
$tbl_forum_post = Database::get_course_table(TABLE_FORUM_POST);
$course_id = api_get_course_int_id();
$courseInfo = api_get_course_info_by_id($course_id);
// launch event
Event::event_download($doc_url);
$sql = 'SELECT thread_id, forum_id,filename
        FROM ' . $tbl_forum_post . '  f
        INNER JOIN ' . $tbl_forum_attachment . ' a
        ON a.post_id=f.post_id
        WHERE
            f.c_id = ' . $course_id . ' AND
            a.c_id = ' . $course_id . ' AND
            path LIKE BINARY "' . $doc_url . '"';
$result = Database::query($sql);
$row = Database::fetch_array($result);
$forum_thread_visibility = api_get_item_visibility($courseInfo, TOOL_FORUM_THREAD, $row['thread_id'], api_get_session_id());
$forum_forum_visibility = api_get_item_visibility($courseInfo, TOOL_FORUM, $row['forum_id'], api_get_session_id());
if ($forum_thread_visibility == 1 && $forum_forum_visibility == 1) {
    if (Security::check_abs_path($full_file_name, api_get_path(SYS_COURSE_PATH) . $courseInfo['path'] . '/upload/forum/')) {
        DocumentManager::file_send_for_download($full_file_name, true, $row['filename']);
    }
}
exit;
예제 #11
0
 /**
  * @param $stok
  * @param $announcement_number
  * @param bool $getCount
  * @param null $start
  * @param null $limit
  * @param string $sidx
  * @param string $sord
  * @param string $titleToSearch
  * @param int $userIdToSearch
  *
  * @return array
  */
 public static function getAnnouncements($stok, $announcement_number, $getCount = false, $start = null, $limit = null, $sidx = '', $sord = '', $titleToSearch = '', $userIdToSearch = 0)
 {
     $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $user_id = api_get_user_id();
     $group_id = api_get_group_id();
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id, true, true, 'announcement.session_id');
     $course_id = api_get_course_int_id();
     $_course = api_get_course_info();
     $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id());
     $allowUserEditSetting = api_get_course_setting('announcement.allow_user_edit_announcement');
     $select = ' DISTINCT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date';
     if ($getCount) {
         $select = ' COUNT(announcement.iid) count';
     }
     $searchCondition = '';
     if (!empty($titleToSearch)) {
         $titleToSearch = Database::escape_string($titleToSearch);
         $searchCondition .= " AND (title LIKE '%{$titleToSearch}%')";
     }
     if (!empty($userIdToSearch)) {
         $userIdToSearch = intval($userIdToSearch);
         $searchCondition .= " AND (ip.insert_user_id = {$userIdToSearch})";
     }
     if (api_is_allowed_to_edit(false, true) || $allowUserEditSetting && !api_is_anonymous()) {
         // A.1. you are a course admin with a USER filter
         // => see only the messages of this specific user + the messages of the group (s)he is member of.
         //if (!empty($user_id)) {
         if (0) {
             if (is_array($group_memberships) && count($group_memberships) > 0) {
                 $sql = "SELECT {$select}\n                            FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                announcement.id = ip.ref AND\n                                ip.tool = 'announcement' AND\n                                (\n                                    ip.to_user_id = {$user_id} OR\n                                    ip.to_group_id IS NULL OR\n                                    ip.to_group_id IN (0, " . implode(", ", $group_memberships) . ")\n                                ) AND\n                                ip.visibility IN ('1', '0')\n                                {$condition_session}\n                                {$searchCondition}\n                            ORDER BY display_order DESC";
             } else {
                 $sql = "SELECT {$select}\n                            FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                announcement.id = ip.ref AND\n                                ip.tool ='announcement' AND\n                                (ip.to_user_id = {$user_id} OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND\n                                ip.visibility IN ('1', '0')\n                            {$condition_session}\n                            {$searchCondition}\n                            ORDER BY display_order DESC";
             }
         } elseif ($group_id != 0) {
             // A.2. you are a course admin with a GROUP filter
             // => see only the messages of this specific group
             $sql = "SELECT {$select}\n                        FROM {$tbl_announcement} announcement INNER JOIN {$tbl_item_property} ip\n                        ON (announcement.id = ip.ref AND ip.tool='announcement')\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            ip.visibility<>'2' AND\n                            (ip.to_group_id = {$group_id} OR ip.to_group_id='0' OR ip.to_group_id IS NULL)\n                            {$condition_session}\n                            {$searchCondition}\n                        ORDER BY display_order DESC";
             //GROUP BY ip.ref
         } else {
             // A.3 you are a course admin without any group or user filter
             // A.3.a you are a course admin without user or group filter but WITH studentview
             // => see all the messages of all the users and groups without editing possibilities
             if (isset($isStudentView) && $isStudentView == "true") {
                 $sql = "SELECT {$select}\n                        FROM {$tbl_announcement} announcement INNER JOIN {$tbl_item_property} ip\n                        ON (announcement.id = ip.ref AND ip.tool='announcement')\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            ip.tool='announcement' AND\n                            ip.visibility='1'\n                            {$condition_session}\n                            {$searchCondition}\n                        ORDER BY display_order DESC";
                 //GROUP BY ip.ref
             } else {
                 // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
                 // => see all the messages of all the users and groups with editing possibilities
                 $sql = "SELECT {$select}\n                            FROM {$tbl_announcement} announcement INNER JOIN {$tbl_item_property} ip\n                            ON (announcement.id = ip.ref AND ip.tool='announcement')\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                (ip.visibility='0' or ip.visibility='1')\n                                {$condition_session}\n                                {$searchCondition}\n                            ORDER BY display_order DESC";
                 //GROUP BY ip.ref
             }
         }
     } else {
         // STUDENT
         if (is_array($group_memberships) && count($group_memberships) > 0) {
             if ($allowUserEditSetting && !api_is_anonymous()) {
                 if ($group_id == 0) {
                     // No group
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR (\n                                ip.to_user_id='" . $user_id . "' OR\n                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . implode(", ", $group_memberships) . "))\n                            )\n                        ) ";
                 } else {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . $group_id . ")\n                        )";
                 }
             } else {
                 if ($group_id == 0) {
                     $cond_user_id = " AND (\n                            ip.to_user_id = {$user_id} AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . implode(", ", $group_memberships) . "))\n                        ) ";
                 } else {
                     $cond_user_id = " AND (\n                            ip.to_user_id = {$user_id} AND (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . $group_id . "))\n                        )";
                 }
             }
             $sql = "SELECT {$select}\n                        FROM {$tbl_announcement} announcement,\n                        {$tbl_item_property} ip\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref\n                            AND ip.tool='announcement'\n                            {$cond_user_id}\n                            {$condition_session}\n                            {$searchCondition}\n                            AND ip.visibility='1'\n                        ORDER BY display_order DESC";
         } else {
             if ($user_id) {
                 if ($allowUserEditSetting && !api_is_anonymous()) {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . api_get_user_id() . "' OR\n                            (ip.to_user_id='" . $user_id . "' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL))\n                        ) ";
                 } else {
                     $cond_user_id = " AND (ip.to_user_id='" . $user_id . "' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
                 }
                 $sql = "SELECT {$select}\n\t\t\t\t\t\tFROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n\t\t\t\t\t\tWHERE\n    \t\t\t\t\t\tannouncement.c_id = {$course_id} AND\n\t\t\t\t\t\t\tip.c_id = {$course_id} AND\n    \t\t\t\t\t\tannouncement.id = ip.ref AND\n    \t\t\t\t\t\tip.tool='announcement'\n    \t\t\t\t\t\t{$cond_user_id}\n    \t\t\t\t\t\t{$condition_session}\n    \t\t\t\t\t\t{$searchCondition}\n    \t\t\t\t\t\tAND ip.visibility='1'\n    \t\t\t\t\t\tAND announcement.session_id IN(0, " . $session_id . ")\n\t\t\t\t\t\tORDER BY display_order DESC";
             } else {
                 if ($allowUserEditSetting && !api_is_anonymous()) {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR ip.to_group_id='0' OR ip.to_group_id IS NULL\n                        )";
                 } else {
                     $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
                 }
                 $sql = "SELECT {$select}\n\t\t\t\t\t\tFROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n\t\t\t\t\t\tWHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref AND\n                            ip.tool='announcement'\n                            {$cond_user_id}\n                            {$condition_session}\n                            {$searchCondition}\n                            AND\n                            ip.visibility='1' AND\n                            announcement.session_id IN ( 0," . api_get_session_id() . ")";
             }
         }
     }
     if (!is_null($start) && !is_null($limit)) {
         $start = intval($start);
         $limit = intval($limit);
         $sql .= " LIMIT {$start}, {$limit}";
     }
     $result = Database::query($sql);
     if ($getCount) {
         $result = Database::fetch_array($result, 'ASSOC');
         return $result['count'];
     }
     $iterator = 1;
     $bottomAnnouncement = $announcement_number;
     $origin = null;
     $displayed = [];
     $results = [];
     $actionUrl = api_get_path(WEB_CODE_PATH) . 'announcements/announcements.php?' . api_get_cidreq();
     while ($myrow = Database::fetch_array($result, 'ASSOC')) {
         if (!in_array($myrow['id'], $displayed)) {
             $sent_to_icon = '';
             // the email icon
             if ($myrow['email_sent'] == '1') {
                 $sent_to_icon = ' ' . Display::return_icon('email.gif', get_lang('AnnounceSentByEmail'));
             }
             $title = $myrow['title'] . $sent_to_icon;
             $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id);
             $myrow['visibility'] = $item_visibility;
             // show attachment list
             $attachment_list = AnnouncementManager::get_attachment($myrow['id']);
             $attachment_icon = '';
             if (count($attachment_list) > 0) {
                 $attachment_icon = ' ' . Display::return_icon('attachment.gif', get_lang('Attachment'));
             }
             /* TITLE */
             $user_info = api_get_user_info($myrow['insert_user_id']);
             $username = sprintf(get_lang("LoginX"), $user_info['username']);
             $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title' => $username));
             $title = Display::url($title . $attachment_icon, $actionUrl . '&action=view&id=' . $myrow['id']);
             //$html .= Display::tag('td', $username_span, array('class' => 'announcements-list-line-by-user'));
             //$html .= Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), array('class' => 'announcements-list-line-datetime'));
             $modify_icons = '';
             // we can edit if : we are the teacher OR the element belongs to
             // the session we are coaching OR the option to allow users to edit is on
             if (api_is_allowed_to_edit(false, true) || api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']) || api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) {
                 $modify_icons = "<a href=\"" . $actionUrl . "&action=modify&id=" . $myrow['id'] . "\">" . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . "</a>";
                 if ($myrow['visibility'] == 1) {
                     $image_visibility = "visible";
                     $alt_visibility = get_lang('Hide');
                 } else {
                     $image_visibility = "invisible";
                     $alt_visibility = get_lang('Visible');
                 }
                 $modify_icons .= "<a href=\"" . $actionUrl . "&origin=" . $origin . "&action=showhide&id=" . $myrow['id'] . "&sec_token=" . $stok . "\">" . Display::return_icon($image_visibility . '.png', $alt_visibility, '', ICON_SIZE_SMALL) . "</a>";
                 // DISPLAY MOVE UP COMMAND only if it is not the top announcement
                 if ($iterator != 1) {
                     $modify_icons .= "<a href=\"" . $actionUrl . "&action=move&up=" . $myrow["id"] . "&sec_token=" . $stok . "\">" . Display::return_icon('up.gif', get_lang('Up')) . "</a>";
                 } else {
                     $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
                 }
                 if ($iterator < $bottomAnnouncement) {
                     $modify_icons .= "<a href=\"" . $actionUrl . "&action=move&down=" . $myrow["id"] . "&sec_token=" . $stok . "\">" . Display::return_icon('down.gif', get_lang('Down')) . "</a>";
                 } else {
                     $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
                 }
                 if (api_is_allowed_to_edit(false, true)) {
                     $modify_icons .= "<a href=\"" . $actionUrl . "&action=delete&id=" . $myrow['id'] . "&sec_token=" . $stok . "\" onclick=\"javascript:if(!confirm('" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, api_get_system_encoding())) . "')) return false;\">" . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . "</a>";
                 }
                 $iterator++;
             } else {
                 $modify_icons = Display::url(Display::return_icon('default.png'), $actionUrl . '&action=view&id=' . $myrow['id']);
             }
             $announcement = ['id' => $myrow["id"], 'title' => $title, 'username' => $username_span, 'insert_date' => api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), 'actions' => $modify_icons];
             $results[] = $announcement;
         }
         $displayed[] = $myrow['id'];
     }
     return $results;
 }
 /**
  * This method is the constructor for the learnpathList. It gets a list of available learning paths from
  * the database and creates the learnpath objects. This list depends on the user that is connected
  * (only displays) items if he has enough permissions to view them.
  * @param	integer		User ID
  * @param	string		Optional course code (otherwise we use api_get_course_id())
  * @param	int			Optional session id (otherwise we use api_get_session_id())
  * @return	void
  */
 function __construct($user_id, $course_code = null, $session_id = null, $order_by = null, $check_publication_dates = false, $filter_by_category = null)
 {
     $course_info = api_get_course_info($course_code);
     $lp_table = Database::get_course_table(TABLE_LP_MAIN);
     $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
     $this->course_code = $course_code;
     $this->user_id = $user_id;
     $course_id = $course_info['real_id'];
     if (empty($course_id)) {
         return false;
     }
     // Condition for the session.
     if (isset($session_id)) {
         $session_id = intval($session_id);
     } else {
         $session_id = api_get_session_id();
     }
     $condition_session = api_get_session_condition($session_id, true, true);
     $order = "ORDER BY display_order ASC, name ASC";
     if (isset($order_by)) {
         $order = Database::parse_conditions(array('order' => $order_by));
     }
     $now = api_get_utc_datetime();
     $time_conditions = '';
     if ($check_publication_dates) {
         $time_conditions = " AND (\n                (publicated_on <> '0000-00-00 00:00:00' AND publicated_on < '{$now}'  AND expired_on <> '0000-00-00 00:00:00'  AND expired_on > '{$now}' )  OR\n                (publicated_on <> '0000-00-00 00:00:00'  AND publicated_on < '{$now}'  AND expired_on = '0000-00-00 00:00:00') OR\n                (publicated_on = '0000-00-00 00:00:00'   AND expired_on <> '0000-00-00 00:00:00' AND expired_on > '{$now}') OR\n                (publicated_on = '0000-00-00 00:00:00'   AND expired_on = '0000-00-00 00:00:00' )\n            )";
     }
     $category_filter = null;
     if (isset($filter_by_category)) {
         $filter_by_category = intval($filter_by_category);
         $category_filter = " AND category_id = {$filter_by_category}";
     }
     $sql = "SELECT * FROM {$lp_table} WHERE c_id = {$course_id} {$time_conditions} {$condition_session} {$category_filter} {$order}";
     $res = Database::query($sql);
     $names = array();
     while ($row = Database::fetch_array($res, 'ASSOC')) {
         // Check if published.
         $pub = '';
         // Use domesticate here instead of Database::escape_string because
         // it prevents ' to be slashed and the input (done by learnpath.class.php::toggle_visibility())
         // is done using domesticate()
         $myname = Text::domesticate($row['name']);
         $mylink = 'newscorm/lp_controller.php?action=view&lp_id=' . $row['id'] . '&id_session=' . $session_id;
         $sql2 = "SELECT * FROM {$tbl_tool} WHERE c_id = {$course_id} AND (name='{$myname}' and image='scormbuilder.gif' and link LIKE '{$mylink}%')";
         //error_log('New LP - learnpathList::__construct - getting visibility - '.$sql2, 0);
         $res2 = Database::query($sql2);
         if (Database::num_rows($res2) > 0) {
             $row2 = Database::fetch_array($res2);
             $pub = $row2['visibility'];
         } else {
             $pub = 'i';
         }
         // Check if visible
         $vis = api_get_item_visibility(api_get_course_info($course_code), 'learnpath', $row['id'], $session_id);
         if (!empty($row['created_on']) && $row['created_on'] != '0000-00-00 00:00:00') {
             $row['created_on'] = $row['created_on'];
         } else {
             $row['created_on'] = '';
         }
         if (!empty($row['modified_on']) && $row['modified_on'] != '0000-00-00 00:00:00') {
             $row['modified_on'] = $row['modified_on'];
         } else {
             $row['modified_on'] = '';
         }
         if (!empty($row['publicated_on']) && $row['publicated_on'] != '0000-00-00 00:00:00') {
             $row['publicated_on'] = $row['publicated_on'];
         } else {
             $row['publicated_on'] = '';
         }
         if (!empty($row['expired_on']) && $row['expired_on'] != '0000-00-00 00:00:00') {
             $row['expired_on'] = $row['expired_on'];
         } else {
             $row['expired_on'] = '';
         }
         //@todo user LP object
         $this->list[$row['id']] = array('lp_type' => $row['lp_type'], 'lp_session' => $row['session_id'], 'lp_name' => stripslashes($row['name']), 'lp_desc' => stripslashes($row['description']), 'lp_path' => $row['path'], 'lp_view_mode' => $row['default_view_mod'], 'lp_force_commit' => $row['force_commit'], 'lp_maker' => stripslashes($row['content_maker']), 'lp_proximity' => $row['content_local'], 'lp_encoding' => api_get_system_encoding(), 'lp_visibility' => $vis, 'lp_published' => $pub, 'lp_prevent_reinit' => $row['prevent_reinit'], 'seriousgame_mode' => $row['seriousgame_mode'], 'lp_scorm_debug' => $row['debug'], 'lp_display_order' => $row['display_order'], 'lp_preview_image' => stripslashes($row['preview_image']), 'autolaunch' => $row['autolunch'], 'session_id' => $row['session_id'], 'created_on' => $row['created_on'], 'modified_on' => $row['modified_on'], 'publicated_on' => $row['publicated_on'], 'expired_on' => $row['expired_on'], 'category_id' => $row['category_id'], 'subscribe_users' => $row['subscribe_users']);
         $names[$row['name']] = $row['id'];
     }
     $this->alpha_list = asort($names);
 }
예제 #13
0
/**
 * @param array $courseInfo
 * @param int $workId
 * @return bool
 */
function protectWork($courseInfo, $workId)
{
    $userId = api_get_user_id();
    $groupId = api_get_group_id();
    $sessionId = api_get_session_id();
    $workData = get_work_data_by_id($workId);
    if (empty($workData) || empty($courseInfo)) {
        api_not_allowed(true);
    }
    if (api_is_platform_admin() || api_is_allowed_to_edit()) {
        return true;
    }
    $workId = $workData['id'];
    if ($workData['active'] != 1) {
        api_not_allowed(true);
    }
    $visibility = api_get_item_visibility($courseInfo, 'work', $workId, $sessionId);
    if ($visibility != 1) {
        api_not_allowed(true);
    }
    allowOnlySubscribedUser($userId, $workId, $courseInfo['real_id']);
    if (!empty($groupId)) {
        $showWork = GroupManager::user_has_access($userId, $groupId, GroupManager::GROUP_TOOL_WORK);
        if (!$showWork) {
            api_not_allowed(true);
        }
    }
}
예제 #14
0
             $number_of_questions = $random_number_of_question . ' ' . $random_label;
             //Bug if we set a random value bigger than the real number of questions
             if ($random_number_of_question > $rowi) {
                 $number_of_questions = $rowi . ' ' . $random_label;
             }
         }
     } else {
         $number_of_questions = $rowi;
     }
     //Attempts
     //$attempts = ExerciseLib::get_count_exam_results($row['id']).' '.get_lang('Attempts');
     //$item .=  Display::tag('td',$attempts);
     $item .= Display::tag('td', $number_of_questions);
 } else {
     // Student only.
     $visibility = api_get_item_visibility($courseInfo, TOOL_QUIZ, $my_exercise_id, $sessionId);
     if ($visibility == 0) {
         continue;
     }
     $url = '<a ' . $alt_title . '  href="overview.php?' . api_get_cidreq() . $myorigin . $mylpid . $mylpitemid . '&exerciseId=' . $row['id'] . '">' . $cut_title . '</a>';
     // Link of the exercise.
     $item = Display::tag('td', $url . ' ' . $session_img);
     // Count number exercise questions.
     /*$sql = "SELECT count(*) FROM $TBL_EXERCISE_QUESTION
                             WHERE c_id = $courseId AND exercice_id = ".$row['id'];
                     $sqlresult = Database::query($sql);
                     $rowi = Database::result($sqlresult, 0);
     
                     if ($row['random'] > 0) {
                         $row['random'].' '.api_strtolower(get_lang(($row['random'] > 1 ? 'Questions' : 'Question')));
                     } else {
예제 #15
0
    /**
     * Shows a question
     * @param Question $objQuestionTmp
     * @param bool $only_questions if true only show the questions, no exercise title
     * @param bool $origin origin i.e = learnpath
     * @param string $current_item current item from the list of questions
     * @param bool $show_title
     * @param bool $freeze
     * @param array $user_choice
     * @param bool $show_comment
     * @param null $exercise_feedback
     * @param bool $show_answers
     * @param null $modelType
     * @param bool $categoryMinusOne
     * @return bool|null|string
     */
    public function showQuestion(Question $objQuestionTmp, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false, $modelType = null, $categoryMinusOne = true)
    {
        // Text direction for the current language
        //$is_ltr_text_direction = api_get_text_direction() != 'rtl';
        // Change false to true in the following line to enable answer hinting
        $debug_mark_answer = $show_answers;
        //api_is_allowed_to_edit() && false;
        // Reads question information
        if (!$objQuestionTmp) {
            // Question not found
            return false;
        }
        $html = null;
        $questionId = $objQuestionTmp->id;
        if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
            $show_comment = false;
        }
        $answerType = $objQuestionTmp->selectType();
        $pictureName = $objQuestionTmp->selectPicture();
        $s = null;
        $form = new FormValidator('question');
        $renderer = $form->defaultRenderer();
        $form_template = '{content}';
        $renderer->setFormTemplate($form_template);
        if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
            // Question is not a hotspot
            if (!$only_questions) {
                $questionDescription = $objQuestionTmp->selectDescription();
                if ($show_title) {
                    $categoryName = TestCategory::getCategoryNamesForQuestion($objQuestionTmp->id, null, true, $categoryMinusOne);
                    $html .= $categoryName;
                    $html .= Display::div($current_item . '. ' . $objQuestionTmp->selectTitle(), array('class' => 'question_title'));
                    if (!empty($questionDescription)) {
                        $html .= Display::div($questionDescription, array('class' => 'question_description'));
                    }
                } else {
                    $html .= '<div class="media">';
                    $html .= '<div class="pull-left">';
                    $html .= '<div class="media-object">';
                    $html .= Display::div($current_item, array('class' => 'question_no_title'));
                    $html .= '</div>';
                    $html .= '</div>';
                    $html .= '<div class="media-body">';
                    if (!empty($questionDescription)) {
                        $html .= Display::div($questionDescription, array('class' => 'question_description'));
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                }
            }
            if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
                return null;
            }
            $html .= '<div class="question_options">';
            // construction of the Answer object (also gets all answers details)
            $objAnswerTmp = new Answer($questionId, null, $this);
            $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
            $course_id = api_get_course_int_id();
            $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
            // For "matching" type here, we need something a little bit special
            // because the match between the suggestions and the answers cannot be
            // done easily (suggestions and answers are in the same table), so we
            // have to go through answers first (elems with "correct" value to 0).
            $select_items = array();
            //This will contain the number of answers on the left side. We call them
            // suggestions here, for the sake of comprehensions, while the ones
            // on the right side are called answers
            $num_suggestions = 0;
            if ($answerType == MATCHING || $answerType == DRAGGABLE) {
                if ($answerType == DRAGGABLE) {
                    $s .= '<div class="ui-widget ui-helper-clearfix">
                            <ul class="drag_question ui-helper-reset ui-helper-clearfix">';
                } else {
                    $s .= '<div id="drag' . $questionId . '_question" class="drag_question">';
                    $s .= '<table class="data_table">';
                }
                $j = 1;
                //iterate through answers
                $letter = 'A';
                //mark letters for each answer
                $answer_matching = array();
                $capital_letter = array();
                //for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
                foreach ($objAnswerTmp->answer as $answerId => $answer_item) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $answer = $objAnswerTmp->selectAnswer($answerId);
                    if ($answerCorrect == 0) {
                        // options (A, B, C, ...) that will be put into the list-box
                        // have the "correct" field set to 0 because they are answer
                        $capital_letter[$j] = $letter;
                        //$answer_matching[$j]=$objAnswerTmp->selectAnswerByAutoId($numAnswer);
                        $answer_matching[$j] = array('id' => $answerId, 'answer' => $answer);
                        $j++;
                        $letter++;
                    }
                }
                $i = 1;
                $select_items[0]['id'] = 0;
                $select_items[0]['letter'] = '--';
                $select_items[0]['answer'] = '';
                foreach ($answer_matching as $id => $value) {
                    $select_items[$i]['id'] = $value['id'];
                    $select_items[$i]['letter'] = $capital_letter[$id];
                    $select_items[$i]['answer'] = $value['answer'];
                    $i++;
                }
                $num_suggestions = $nbrAnswers - $j + 1;
            } elseif ($answerType == FREE_ANSWER) {
                $content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
                $toolBar = 'TestFreeAnswer';
                if ($modelType == EXERCISE_MODEL_TYPE_COMMITTEE) {
                    $toolBar = 'TestFreeAnswerStrict';
                }
                $form->addElement('html_editor', "choice[" . $questionId . "]", null, array('id' => "choice[" . $questionId . "]"), array('ToolbarSet' => $toolBar));
                $form->setDefaults(array("choice[" . $questionId . "]" => $content));
                $s .= $form->return_form();
            } elseif ($answerType == ORAL_EXPRESSION) {
                // Add nanogong
                if (api_get_setting('document.enable_nanogong') == 'true') {
                    //@todo pass this as a parameter
                    global $exercise_stat_info, $exerciseId;
                    if (!empty($exercise_stat_info)) {
                        $params = array('exercise_id' => $exercise_stat_info['exe_exo_id'], 'exe_id' => $exercise_stat_info['exe_id'], 'question_id' => $questionId);
                    } else {
                        $params = array('exercise_id' => $exerciseId, 'exe_id' => 'temp_exe', 'question_id' => $questionId);
                    }
                    $nano = new Nanogong($params);
                    $s .= $nano->show_button();
                }
                $form->addElement('html_editor', "choice[" . $questionId . "]", null, array('id' => "choice[" . $questionId . "]"), array('ToolbarSet' => 'TestFreeAnswer'));
                //$form->setDefaults(array("choice[".$questionId."]" => $content));
                $s .= $form->return_form();
            }
            // Now navigate through the possible answers, using the max number of
            // answers for the question as a limiter
            $lines_count = 1;
            // a counter for matching-type answers
            if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                $header = Display::tag('th', get_lang('Options'));
                foreach ($objQuestionTmp->options as $item) {
                    $header .= Display::tag('th', $item);
                }
                if ($show_comment) {
                    $header .= Display::tag('th', get_lang('Feedback'));
                }
                $s .= '<table class="data_table">';
                $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
            }
            if ($show_comment) {
                if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
                    $header = Display::tag('th', get_lang('Options'));
                    if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
                        $header .= Display::tag('th', get_lang('Feedback'));
                    }
                    $s .= '<table class="data_table">';
                    $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
                }
            }
            $matching_correct_answer = 0;
            $user_choice_array = array();
            if (!empty($user_choice)) {
                foreach ($user_choice as $item) {
                    $user_choice_array[] = $item['answer'];
                }
            }
            foreach ($objAnswerTmp->answer as $answerId => $answer_item) {
                $answer = $objAnswerTmp->selectAnswer($answerId);
                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                $comment = $objAnswerTmp->selectComment($answerId);
                //$numAnswer       = $objAnswerTmp->selectAutoId($answerId);
                $numAnswer = $answerId;
                $attributes = array();
                // Unique answer
                if (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION))) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    $answer = Security::remove_XSS($answer);
                    $s .= Display::input('hidden', 'choice2[' . $questionId . ']', '0');
                    $answer_input = null;
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $attributes['style'] = 'display:none';
                        $answer_input .= '<div id="answer' . $questionId . $numAnswer . '" style="float:left" class="highlight_image_default highlight_image">';
                    }
                    $answer_input .= '<label class="radio">';
                    $answer_input .= Display::input('radio', 'choice[' . $questionId . ']', $numAnswer, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $answer_input .= "</div>";
                    }
                    if ($show_comment) {
                        $s .= '<tr><td>';
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_TRUE_FALSE, GLOBAL_MULTIPLE_ANSWER))) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    $answer = Security::remove_XSS($answer);
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                        $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                        $answer_input = '<label class="checkbox">';
                        $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', $numAnswer, $attributes);
                        $answer_input .= $answer;
                        $answer_input .= '</label>';
                        if ($show_comment) {
                            $s .= '<tr><td>';
                            $s .= $answer_input;
                            $s .= '</td>';
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                            $s .= '</tr>';
                        } else {
                            $s .= $answer_input;
                        }
                    } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                        $my_choice = array();
                        if (!empty($user_choice_array)) {
                            foreach ($user_choice_array as $item) {
                                $item = explode(':', $item);
                                $my_choice[$item[0]] = $item[1];
                            }
                        }
                        $s .= '<tr>';
                        $s .= Display::tag('td', $answer);
                        if (!empty($quiz_question_options)) {
                            foreach ($quiz_question_options as $id => $item) {
                                $id = $item['iid'];
                                if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
                                    $attributes = array('checked' => 1, 'selected' => 1);
                                } else {
                                    $attributes = array();
                                }
                                if ($debug_mark_answer) {
                                    if ($id == $answerCorrect) {
                                        $attributes['checked'] = 1;
                                        $attributes['selected'] = 1;
                                    }
                                }
                                $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $id, $attributes), array('style' => ''));
                            }
                        }
                        if ($show_comment) {
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                        }
                        $s .= '</tr>';
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
                    // multiple answers
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    $answer = Security::remove_XSS($answer);
                    $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $answer_input .= '<label class="checkbox">';
                    $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', 1, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($show_comment) {
                        $s .= '<tr>';
                        $s .= '<td>';
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                    $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $my_choice = array();
                    if (!empty($user_choice_array)) {
                        foreach ($user_choice_array as $item) {
                            $item = explode(':', $item);
                            $my_choice[$item[0]] = $item[1];
                        }
                    }
                    $answer = Security::remove_XSS($answer);
                    $s .= '<tr>';
                    $s .= Display::tag('td', $answer);
                    foreach ($objQuestionTmp->options as $key => $item) {
                        if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
                            $attributes = array('checked' => 1, 'selected' => 1);
                        } else {
                            $attributes = array();
                        }
                        if ($debug_mark_answer) {
                            if ($key == $answerCorrect) {
                                $attributes['checked'] = 1;
                                $attributes['selected'] = 1;
                            }
                        }
                        $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $key, $attributes));
                    }
                    if ($show_comment) {
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                    }
                    $s .= '</tr>';
                } elseif ($answerType == FILL_IN_BLANKS) {
                    list($answer) = explode('::', $answer);
                    //Correct answer
                    api_preg_match_all('/\\[[^]]+\\]/', $answer, $correct_answer_list);
                    //Student's answezr
                    if (isset($user_choice[0]['answer'])) {
                        api_preg_match_all('/\\[[^]]+\\]/', $user_choice[0]['answer'], $student_answer_list);
                        $student_answer_list = $student_answer_list[0];
                    }
                    //If debug
                    if ($debug_mark_answer) {
                        $student_answer_list = $correct_answer_list[0];
                    }
                    if (!empty($correct_answer_list) && !empty($student_answer_list)) {
                        $correct_answer_list = $correct_answer_list[0];
                        $i = 0;
                        foreach ($correct_answer_list as $correct_item) {
                            $value = null;
                            if (isset($student_answer_list[$i]) && !empty($student_answer_list[$i])) {
                                //Cleaning student answer list
                                $value = strip_tags($student_answer_list[$i]);
                                $value = api_substr($value, 1, api_strlen($value) - 2);
                                $value = explode('/', $value);
                                if (!empty($value[0])) {
                                    $value = str_replace('&nbsp;', '', trim($value[0]));
                                }
                                $correct_item = preg_quote($correct_item);
                                $correct_item = api_preg_replace('|/|', '\\/', $correct_item);
                                // to prevent error if there is a / in the text to find
                                $answer = api_preg_replace('/' . $correct_item . '/', Display::input('text', "choice[{$questionId}][]", $value), $answer, 1);
                            }
                            $i++;
                        }
                    } else {
                        $answer = api_preg_replace('/\\[[^]]+\\]/', Display::input('text', "choice[{$questionId}][]", '', $attributes), $answer);
                    }
                    $s .= $answer;
                } elseif ($answerType == MATCHING) {
                    // matching type, showing suggestions and answers
                    // TODO: replace $answerId by $numAnswer
                    if ($lines_count == 1) {
                        $s .= $objAnswerTmp->getJs();
                    }
                    if ($answerCorrect != 0) {
                        // only show elements to be answered (not the contents of
                        // the select boxes, who are correct = 0)
                        $s .= '<tr><td width="45%">';
                        $parsed_answer = $answer;
                        $windowId = $questionId . '_' . $lines_count;
                        //left part questions
                        $s .= ' <div id="window_' . $windowId . '" class="window window_left_question window' . $questionId . '_question">
                                    <b>' . $lines_count . '</b>.&nbsp' . $parsed_answer . '
                                </div>
                                </td>';
                        // middle part (matches selects)
                        $s .= '<td width="10%" align="center">&nbsp;&nbsp;';
                        $s .= '<div style="display:block">';
                        $s .= '<select id="window_' . $windowId . '_select" name="choice[' . $questionId . '][' . $numAnswer . ']">';
                        $selectedValue = 0;
                        // fills the list-box
                        $item = 0;
                        foreach ($select_items as $val) {
                            // set $debug_mark_answer to true at public static function start to
                            // show the correct answer with a suffix '-x'
                            $selected = '';
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selected = 'selected="selected"';
                                    $selectedValue = $val['id'];
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selected = 'selected="selected"';
                                $selectedValue = $val['id'];
                            }
                            //$s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].'</option>';
                            $s .= '<option value="' . $item . '" ' . $selected . '>' . $val['letter'] . '</option>';
                            $item++;
                        }
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            $s .= '<script>
                                jsPlumb.ready(function() {
                                    jsPlumb.connect({
                                        source: "window_' . $windowId . '",
                                        target: "window_' . $questionId . '_' . $selectedValue . '_answer",
                                        endpoint:["Blank", { radius:15 }],
                                        anchor:["RightMiddle","LeftMiddle"],
                                        paintStyle:{ strokeStyle:"#8a8888" , lineWidth:8 },
                                        connector: [connectorType, { curviness: curvinessValue } ],
                                    })
                                });
                                </script>';
                        }
                        $s .= '</select></div></td>';
                        $s .= '<td width="45%" valign="top" >';
                        if (isset($select_items[$lines_count])) {
                            $s .= '<div id="window_' . $windowId . '_answer" class="window window_right_question">
                                    <b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'] . '
                                  </div>';
                        } else {
                            $s .= '&nbsp;';
                        }
                        $s .= '</td>';
                        $s .= '</tr>';
                        $lines_count++;
                        //if the left side of the "matching" has been completely
                        // shown but the right side still has values to show...
                        if ($lines_count - 1 == $num_suggestions) {
                            // if it remains answers to shown at the right side
                            while (isset($select_items[$lines_count])) {
                                $s .= '<tr>
                                      <td colspan="2"></td>
                                      <td valign="top">';
                                $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b>';
                                $s .= $select_items[$lines_count]['answer'];
                                $s .= "</td>\n                                </tr>";
                                $lines_count++;
                            }
                            // end while()
                        }
                        // end if()
                        $matching_correct_answer++;
                    }
                } elseif ($answerType == DRAGGABLE) {
                    // matching type, showing suggestions and answers
                    // TODO: replace $answerId by $numAnswer
                    if ($answerCorrect != 0) {
                        // only show elements to be answered (not the contents of
                        // the select boxes, who are correct = 0)
                        $s .= '<td>';
                        $parsed_answer = $answer;
                        $windowId = $questionId . '_' . $numAnswer;
                        //67_293 - 67_294
                        //left part questions
                        $s .= '<li class="ui-state-default" id="' . $windowId . '">';
                        $s .= ' <div id="window_' . $windowId . '" class="window' . $questionId . '_question_draggable question_draggable">
                                   ' . $parsed_answer . '
                                </div>';
                        $s .= '<div style="display:none">';
                        $s .= '<select id="window_' . $windowId . '_select" name="choice[' . $questionId . '][' . $numAnswer . ']" class="select_option">';
                        $selectedValue = 0;
                        // fills the list-box
                        $item = 0;
                        foreach ($select_items as $val) {
                            // set $debug_mark_answer to true at function start to
                            // show the correct answer with a suffix '-x'
                            $selected = '';
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selected = 'selected="selected"';
                                    $selectedValue = $val['id'];
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selected = 'selected="selected"';
                                $selectedValue = $val['id'];
                            }
                            //$s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].'</option>';
                            $s .= '<option value="' . $item . '" ' . $selected . '>' . $val['letter'] . '</option>';
                            $item++;
                        }
                        $s .= '</select>';
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            $s .= '<script>
                                $(function() {
                                    deleteItem($("#' . $questionId . '_' . $selectedValue . '"), $("#drop_' . $windowId . '"));
                                });
                                </script>';
                        }
                        if (isset($select_items[$lines_count])) {
                            $s .= '<div id="window_' . $windowId . '_answer" class="">
                                    <b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'] . '
                                  </div>';
                        } else {
                            $s .= '&nbsp;';
                        }
                        $lines_count++;
                        //if the left side of the "matching" has been completely
                        // shown but the right side still has values to show...
                        if ($lines_count - 1 == $num_suggestions) {
                            // if it remains answers to shown at the right side
                            while (isset($select_items[$lines_count])) {
                                $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b>';
                                $s .= $select_items[$lines_count]['answer'];
                                $lines_count++;
                            }
                        }
                        $s .= '</div>';
                        $matching_correct_answer++;
                        $s .= '</li>';
                    }
                }
            }
            // end for()
            if ($show_comment) {
                $s .= '</table>';
            } else {
                if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                    $s .= '</table>';
                }
            }
            if ($answerType == DRAGGABLE) {
                $s .= '</ul><div class="clear"></div>';
                $counterAnswer = 1;
                foreach ($objAnswerTmp->answer as $answerId => $answer_item) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $windowId = $questionId . '_' . $counterAnswer;
                    if ($answerCorrect == 0) {
                        $s .= '<div id="drop_' . $windowId . '" class="droppable ui-state-default">' . $counterAnswer . '</div>';
                        $counterAnswer++;
                    }
                }
            }
            if ($answerType == MATCHING) {
                $s .= '</div>';
            }
            $s .= '</div>';
            // destruction of the Answer object
            unset($objAnswerTmp);
            // destruction of the Question object
            unset($objQuestionTmp);
            $html .= $s;
            return $html;
        } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
            // Question is a HOT_SPOT
            //checking document/images visibility
            if (api_is_platform_admin() || api_is_course_admin()) {
                $course = api_get_course_info();
                $doc_id = DocumentManager::get_document_id($course, '/images/' . $pictureName);
                if (is_numeric($doc_id)) {
                    $images_folder_visibility = api_get_item_visibility($course, 'document', $doc_id, api_get_session_id());
                    if (!$images_folder_visibility) {
                        //This message is shown only to the course/platform admin if the image is set to visibility = false
                        Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
                    }
                }
            }
            $questionName = $objQuestionTmp->selectTitle();
            $questionDescription = $objQuestionTmp->selectDescription();
            if ($freeze) {
                $s .= Display::img($objQuestionTmp->selectPicturePath());
                $html .= $s;
                return $html;
            }
            // Get the answers, make a list
            $objAnswerTmp = new Answer($questionId);
            // get answers of hotpost
            $answers_hotspot = array();
            foreach ($objAnswerTmp->answer as $answerId => $answer_item) {
                //$answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
                $answers_hotspot[$answerId] = $objAnswerTmp->selectAnswer($answerId);
            }
            // display answers of hotpost order by id
            $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>' . get_lang('HotspotZones') . '</b><dl>';
            if (!empty($answers_hotspot)) {
                ksort($answers_hotspot);
                foreach ($answers_hotspot as $key => $value) {
                    $answer_list .= '<dt>' . $key . '.- ' . $value . '</dt><br />';
                }
            }
            $answer_list .= '</dl></div>';
            if ($answerType == HOT_SPOT_DELINEATION) {
                $answer_list = '';
                $swf_file = 'hotspot_delineation_user';
                $swf_height = 405;
            } else {
                $swf_file = 'hotspot_user';
                $swf_height = 436;
            }
            if (!$only_questions) {
                if ($show_title) {
                    $html .= TestCategory::getCategoryNamesForQuestion($objQuestionTmp->id);
                    $html .= '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
                    $html .= $questionDescription;
                } else {
                    $html .= '<div class="media">';
                    $html .= '<div class="pull-left">';
                    $html .= '<div class="media-object">';
                    $html .= Display::div($current_item . '. ', array('class' => 'question_no_title'));
                    $html .= '</div>';
                    $html .= '</div>';
                    $html .= '<div class="media-body">';
                    if (!empty($questionDescription)) {
                        $html .= Display::div($questionDescription, array('class' => 'question_description'));
                    }
                    $html .= '</div>';
                    $html .= '</div>';
                }
                //@todo I need to the get the feedback type
                $html .= '<input type="hidden" name="hidden_hotspot_id" value="' . $questionId . '" />';
                $html .= '<table class="exercise_questions">
                           <tr>
                            <td valign="top" colspan="2">';
                $html .= '</td></tr>';
            }
            $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
            $s .= ' <script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
                    <script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
                    <script type="text/javascript">
                    <!--
                    // Globals
                    // Major version of Flash required
                    var requiredMajorVersion = 7;
                    // Minor version of Flash required
                    var requiredMinorVersion = 0;
                    // Minor version of Flash required
                    var requiredRevision = 0;
                    // the version of javascript supported
                    var jsVersion = 1.0;
                    // -->
                    </script>
                    <script language="VBScript" type="text/vbscript">
                    <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
                    Function VBGetSwfVer(i)
                      on error resume next
                      Dim swControl, swVersion
                      swVersion = 0

                      set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
                      if (IsObject(swControl)) then
                        swVersion = swControl.GetVariable("$version")
                      end if
                      VBGetSwfVer = swVersion
                    End Function
                    // -->
                    </script>

                    <script language="JavaScript1.1" type="text/javascript">
                    <!-- // Detect Client Browser type
                    var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
                    var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
                    var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
                    jsVersion = 1.1;
                    // JavaScript helper required to detect Flash Player PlugIn version information
                    function JSGetSwfVer(i) {
                        // NS/Opera version >= 3 check for Flash plugin in plugin array
                        if (navigator.plugins != null && navigator.plugins.length > 0) {
                            if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
                                var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
                                var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
                                descArray = flashDescription.split(" ");
                                tempArrayMajor = descArray[2].split(".");
                                versionMajor = tempArrayMajor[0];
                                versionMinor = tempArrayMajor[1];
                                if ( descArray[3] != "" ) {
                                    tempArrayMinor = descArray[3].split("r");
                                } else {
                                    tempArrayMinor = descArray[4].split("r");
                                }
                                versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
                                flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
                            } else {
                                flashVer = -1;
                            }
                        }
                        // MSN/WebTV 2.6 supports Flash 4
                        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
                        // WebTV 2.5 supports Flash 3
                        else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
                        // older WebTV supports Flash 2
                        else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
                        // Can\'t detect in all other cases
                        else {
                            flashVer = -1;
                        }
                        return flashVer;
                    }
                    // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available

                    function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
                        reqVer = parseFloat(reqMajorVer + "." + reqRevision);
                        // loop backwards through the versions until we find the newest version
                        for (i=25;i>0;i--) {
                            if (isIE && isWin && !isOpera) {
                                versionStr = VBGetSwfVer(i);
                            } else {
                                versionStr = JSGetSwfVer(i);
                            }
                            if (versionStr == -1 ) {
                                return false;
                            } else if (versionStr != 0) {
                                if(isIE && isWin && !isOpera) {
                                    tempArray         = versionStr.split(" ");
                                    tempString        = tempArray[1];
                                    versionArray      = tempString .split(",");
                                } else {
                                    versionArray      = versionStr.split(".");
                                }
                                versionMajor      = versionArray[0];
                                versionMinor      = versionArray[1];
                                versionRevision   = versionArray[2];

                                versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
                                versionNum        = parseFloat(versionString);
                                // is the major.revision >= requested major.revision AND the minor version >= requested minor
                                if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
                                    return true;
                                } else {
                                    return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
                                }
                            }
                        }
                    }
                    // -->
                    </script>';
            $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
                    <script>
                        // Version check based upon the values entered above in "Globals"
                        var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

                        // Check to see if the version meets the requirements for playback
                        if (hasReqestedVersion) {  // if we\'ve detected an acceptable version
                            var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" width="600" height="' . $swf_height . '">\'
                                        + \'<param name="wmode" value="transparent">\'
                                        + \'<param name="movie" value="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" />\'
                                        + \'<\\/object>\';
                            document.write(oeTags);   // embed the Flash Content SWF when all tests are passed
                        } else {  // flash is too old or we can\'t detect the plugin
                            var alternateContent = "Error<br \\/>"
                                + "Hotspots requires Macromedia Flash 7.<br \\/>"
                                + "<a href=\\"http://www.macromedia.com/go/getflash/\\">Get Flash<\\/a>";
                            document.write(alternateContent);  // insert non-flash content
                        }
                    </script>
                    </td>
                    <td valign="top" align="left">' . $answer_list . '</td></tr>
                    </table>
            </td></tr>';
            $html .= $s;
            $html .= '</table>';
            return $html;
        }
        return $nbrAnswers;
    }
예제 #16
0
/**
 * Shows a question
 *
 * @param int    $questionId question id
 * @param bool   $only_questions if true only show the questions, no exercise title
 * @param bool   $origin  i.e = learnpath
 * @param string $current_item current item from the list of questions
 * @param bool   $show_title
 * @param bool   $freeze
 * @param array  $user_choice
 * @param bool   $show_comment
 * @param bool   $exercise_feedback
 * @param bool   $show_answers
 * */
function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false)
{
    // Text direction for the current language
    $is_ltr_text_direction = api_get_text_direction() != 'rtl';
    // Change false to true in the following line to enable answer hinting
    $debug_mark_answer = $show_answers;
    //api_is_allowed_to_edit() && false;
    // Reads question information
    if (!($objQuestionTmp = Question::read($questionId))) {
        // Question not found
        return false;
    }
    if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
        $show_comment = false;
    }
    $answerType = $objQuestionTmp->selectType();
    $pictureName = $objQuestionTmp->selectPicture();
    $s = '';
    if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
        // Question is not a hotspot
        if (!$only_questions) {
            $questionDescription = $objQuestionTmp->selectDescription();
            if ($show_title) {
                Testcategory::displayCategoryAndTitle($objQuestionTmp->id);
                echo Display::div($current_item . '. ' . $objQuestionTmp->selectTitle(), array('class' => 'question_title'));
            }
            if (!empty($questionDescription)) {
                echo Display::div($questionDescription, array('class' => 'question_description'));
            }
        }
        if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
            return '';
        }
        echo '<div class="question_options">';
        // construction of the Answer object (also gets all answers details)
        $objAnswerTmp = new Answer($questionId);
        $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
        $course_id = api_get_course_int_id();
        $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
        // For "matching" type here, we need something a little bit special
        // because the match between the suggestions and the answers cannot be
        // done easily (suggestions and answers are in the same table), so we
        // have to go through answers first (elems with "correct" value to 0).
        $select_items = array();
        //This will contain the number of answers on the left side. We call them
        // suggestions here, for the sake of comprehensions, while the ones
        // on the right side are called answers
        $num_suggestions = 0;
        if ($answerType == MATCHING) {
            $s .= '<table class="data_table">';
            // Iterate through answers
            $x = 1;
            //mark letters for each answer
            $letter = 'A';
            $answer_matching = array();
            $cpt1 = array();
            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                $answer = $objAnswerTmp->selectAnswer($answerId);
                if ($answerCorrect == 0) {
                    // options (A, B, C, ...) that will be put into the list-box
                    // have the "correct" field set to 0 because they are answer
                    $cpt1[$x] = $letter;
                    $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer);
                    $x++;
                    $letter++;
                }
            }
            $i = 1;
            $select_items[0]['id'] = 0;
            $select_items[0]['letter'] = '--';
            $select_items[0]['answer'] = '';
            foreach ($answer_matching as $id => $value) {
                $select_items[$i]['id'] = $value['id'];
                $select_items[$i]['letter'] = $cpt1[$id];
                $select_items[$i]['answer'] = $value['answer'];
                $i++;
            }
            $user_choice_array_position = array();
            if (!empty($user_choice)) {
                foreach ($user_choice as $item) {
                    $user_choice_array_position[$item['position']] = $item['answer'];
                }
            }
            $num_suggestions = $nbrAnswers - $x + 1;
        } elseif ($answerType == FREE_ANSWER) {
            $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
            $oFCKeditor = new FCKeditor("choice[" . $questionId . "]");
            $oFCKeditor->ToolbarSet = 'TestFreeAnswer';
            $oFCKeditor->Width = '100%';
            $oFCKeditor->Height = '200';
            $oFCKeditor->Value = $fck_content;
            $s .= $oFCKeditor->CreateHtml();
        } elseif ($answerType == ORAL_EXPRESSION) {
            //Add nanog
            if (api_get_setting('enable_nanogong') == 'true') {
                require_once api_get_path(LIBRARY_PATH) . 'nanogong.lib.php';
                //@todo pass this as a parameter
                global $exercise_stat_info, $exerciseId, $exe_id;
                if (!empty($exercise_stat_info)) {
                    $params = array('exercise_id' => $exercise_stat_info['exe_exo_id'], 'exe_id' => $exercise_stat_info['exe_id'], 'question_id' => $questionId);
                } else {
                    $params = array('exercise_id' => $exerciseId, 'exe_id' => 'temp_exe', 'question_id' => $questionId);
                }
                $nano = new Nanogong($params);
                echo $nano->show_button();
            }
            $oFCKeditor = new FCKeditor("choice[" . $questionId . "]");
            $oFCKeditor->ToolbarSet = 'TestFreeAnswer';
            $oFCKeditor->Width = '100%';
            $oFCKeditor->Height = '150';
            $oFCKeditor->ToolbarStartExpanded = false;
            $oFCKeditor->Value = '';
            $s .= $oFCKeditor->CreateHtml();
        }
        // Now navigate through the possible answers, using the max number of
        // answers for the question as a limiter
        $lines_count = 1;
        // a counter for matching-type answers
        if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
            $header = Display::tag('th', get_lang('Options'));
            foreach ($objQuestionTmp->options as $item) {
                if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                    if (in_array($item, $objQuestionTmp->options)) {
                        $header .= Display::tag('th', get_lang($item));
                    } else {
                        $header .= Display::tag('th', $item);
                    }
                } else {
                    $header .= Display::tag('th', $item);
                }
            }
            if ($show_comment) {
                $header .= Display::tag('th', get_lang('Feedback'));
            }
            $s .= '<table class="data_table">';
            $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
        }
        if ($show_comment) {
            if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
                $header = Display::tag('th', get_lang('Options'));
                if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
                    $header .= Display::tag('th', get_lang('Feedback'));
                }
                $s .= '<table class="data_table">';
                $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
            }
        }
        $matching_correct_answer = 0;
        $user_choice_array = array();
        if (!empty($user_choice)) {
            foreach ($user_choice as $item) {
                $user_choice_array[] = $item['answer'];
            }
        }
        for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
            $answer = $objAnswerTmp->selectAnswer($answerId);
            $answerCorrect = $objAnswerTmp->isCorrect($answerId);
            $numAnswer = $objAnswerTmp->selectAutoId($answerId);
            $comment = $objAnswerTmp->selectComment($answerId);
            $attributes = array();
            // Unique answer
            if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
                $input_id = 'choice-' . $questionId . '-' . $answerId;
                if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
                    $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                } else {
                    $attributes = array('id' => $input_id);
                }
                if ($debug_mark_answer) {
                    if ($answerCorrect) {
                        $attributes['checked'] = 1;
                        $attributes['selected'] = 1;
                    }
                }
                $answer = Security::remove_XSS($answer, STUDENT);
                $s .= Display::input('hidden', 'choice2[' . $questionId . ']', '0');
                $answer_input = '<label class="radio">';
                $answer_input .= Display::input('radio', 'choice[' . $questionId . ']', $numAnswer, $attributes);
                $answer_input .= $answer;
                $answer_input .= '</label>';
                if ($show_comment) {
                    $s .= '<tr><td>';
                    $s .= $answer_input;
                    $s .= '</td>';
                    $s .= '<td>';
                    $s .= $comment;
                    $s .= '</td>';
                    $s .= '</tr>';
                } else {
                    $s .= $answer_input;
                }
            } elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                $input_id = 'choice-' . $questionId . '-' . $answerId;
                $answer = Security::remove_XSS($answer, STUDENT);
                if (in_array($numAnswer, $user_choice_array)) {
                    $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                } else {
                    $attributes = array('id' => $input_id);
                }
                if ($debug_mark_answer) {
                    if ($answerCorrect) {
                        $attributes['checked'] = 1;
                        $attributes['selected'] = 1;
                    }
                }
                if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                    $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $answer_input = '<label class="checkbox">';
                    $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', $numAnswer, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($show_comment) {
                        $s .= '<tr><td>';
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                    $my_choice = array();
                    if (!empty($user_choice_array)) {
                        foreach ($user_choice_array as $item) {
                            $item = explode(':', $item);
                            $my_choice[$item[0]] = $item[1];
                        }
                    }
                    $s .= '<tr>';
                    $s .= Display::tag('td', $answer);
                    if (!empty($quiz_question_options)) {
                        foreach ($quiz_question_options as $id => $item) {
                            if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
                                $attributes = array('checked' => 1, 'selected' => 1);
                            } else {
                                $attributes = array();
                            }
                            if ($debug_mark_answer) {
                                if ($id == $answerCorrect) {
                                    $attributes['checked'] = 1;
                                    $attributes['selected'] = 1;
                                }
                            }
                            $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $id, $attributes), array('style' => ''));
                        }
                    }
                    if ($show_comment) {
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                    }
                    $s .= '</tr>';
                }
            } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
                // multiple answers
                $input_id = 'choice-' . $questionId . '-' . $answerId;
                if (in_array($numAnswer, $user_choice_array)) {
                    $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                } else {
                    $attributes = array('id' => $input_id);
                }
                if ($debug_mark_answer) {
                    if ($answerCorrect) {
                        $attributes['checked'] = 1;
                        $attributes['selected'] = 1;
                    }
                }
                $answer = Security::remove_XSS($answer, STUDENT);
                $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                $answer_input .= '<label class="checkbox">';
                $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', 1, $attributes);
                $answer_input .= $answer;
                $answer_input .= '</label>';
                if ($show_comment) {
                    $s .= '<tr>';
                    $s .= '<td>';
                    $s .= $answer_input;
                    $s .= '</td>';
                    $s .= '<td>';
                    $s .= $comment;
                    $s .= '</td>';
                    $s .= '</tr>';
                } else {
                    $s .= $answer_input;
                }
            } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                $my_choice = array();
                if (!empty($user_choice_array)) {
                    foreach ($user_choice_array as $item) {
                        $item = explode(':', $item);
                        $my_choice[$item[0]] = $item[1];
                    }
                }
                $answer = Security::remove_XSS($answer, STUDENT);
                $s .= '<tr>';
                $s .= Display::tag('td', $answer);
                foreach ($objQuestionTmp->options as $key => $item) {
                    if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
                        $attributes = array('checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array();
                    }
                    if ($debug_mark_answer) {
                        if ($key == $answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $key, $attributes));
                }
                if ($show_comment) {
                    $s .= '<td>';
                    $s .= $comment;
                    $s .= '</td>';
                }
                $s .= '</tr>';
            } elseif ($answerType == FILL_IN_BLANKS) {
                /*
                 * In the FILL_IN_BLANKS test
                 * you mustn't have [ and ] in the textarea
                 * you mustn't have :: in the textarea
                 * the text to find mustn't be empty or contains only spaces
                 * the text to find mustn't contains HTML tags
                 * the text to find mustn't contains char "
                 */
                list($answer) = explode('::', $answer);
                // $correct_answer_list array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
                api_preg_match_all('/\\[[^]]+\\]/', $answer, $correct_answer_list);
                // get student answer to display it if student go back to previous fillBlank answer question in a test
                if (isset($user_choice[0]['answer'])) {
                    api_preg_match_all('/\\[[^]]+\\]/', $user_choice[0]['answer'], $student_answer_list);
                    $student_answer_list_tobecleaned = $student_answer_list[0];
                    $student_answer_list = array();
                    // here we got the student answer in a test
                    // let's clean up the results
                    /*
                    Array
                    (
                        [0] => Array
                        (
                            [0] => [<font color="red"><s>yer</s></font> / <font color="green"><b>ici</b></font>]
                            [1] => [<font color="red"><s>plop</s></font> / <font color="green"><b>/p</b></font>]
                        )
                    )
                    */
                    for ($i = 0; $i < count($student_answer_list_tobecleaned); $i++) {
                        $answer_corrected = $student_answer_list_tobecleaned[$i];
                        /*
                         * we got if student answer is wrong
                         * [<font color="red"><s>rrr</s></font> / <font color="green"><b>/p</b></font>]
                         * or if student answer is good
                         * [plop / <font color="green"><b>plop</b></font>]
                         * or if student didn't answer []
                         */
                        $answer_corrected = api_preg_replace('| / <font color="green"><b>.*$|', '', $answer_corrected);
                        /*
                         * we got [<font color="red"><s>rrr</s></font> or [plop or [
                         */
                        $answer_corrected = api_preg_replace('/^\\[/', '', $answer_corrected);
                        /*
                         * we got <font color="red"><s>rrr</s></font> or plop
                         * non breakable spaces &nbsp;&nbsp;&nbsp; from /main/exercice/exercise.class.php have been removed l 2391 and l 2370
                         */
                        $answer_corrected = api_preg_replace('|^<font color="red"><s>|', '', $answer_corrected);
                        $answer_corrected = api_preg_replace('|</s></font>$|', '', $answer_corrected);
                        $answer_corrected = '[' . $answer_corrected . ']';
                        /*
                         * we got [rrr] or [plop] or []
                         */
                        $student_answer_list[] = $answer_corrected;
                    }
                }
                // If display preview of answer in test view for exemple, set the student answer to the correct answers
                if ($debug_mark_answer) {
                    // contain the rights answers surronded with brackets
                    $student_answer_list = $correct_answer_list[0];
                }
                /*
                Split the response by bracket
                tab_comments is an array with text surrounding the text to find
                we add a space before and after the answer_question to be sure to
                have a block of text before and after [xxx] patterns
                so we have n text to find ([xxx]) and n+1 block of texts before,
                between and after the text to find
                */
                $tab_comments = api_preg_split('/\\[[^]]+\\]/', ' ' . $answer . ' ');
                if (!empty($correct_answer_list) && !empty($student_answer_list)) {
                    $answer = "";
                    $i = 0;
                    foreach ($student_answer_list as $student_item) {
                        // remove surronding brackets
                        $student_response = api_substr($student_item, 1, api_strlen($student_item) - 2);
                        $size = strlen($student_item);
                        $attributes['class'] = detectInputAppropriateClass($size);
                        $answer .= $tab_comments[$i] . Display::input('text', "choice[{$questionId}][]", $student_response, $attributes);
                        $i++;
                    }
                    $answer .= $tab_comments[$i];
                } else {
                    // display exercise with empty input fields
                    // every [xxx] are replaced with an empty input field
                    foreach ($correct_answer_list[0] as $item) {
                        $size = strlen($item);
                        $attributes['class'] = detectInputAppropriateClass($size);
                        $answer = str_replace($item, Display::input('text', "choice[{$questionId}][]", '', $attributes), $answer);
                    }
                    /*$answer = api_preg_replace(
                      '/\[[^]]+\]/',
                      Display::input(
                          'text',
                          "choice[$questionId][]",
                          '',
                          $attributes
                      ), $answer);*/
                }
                $s .= $answer;
            } elseif ($answerType == CALCULATED_ANSWER) {
                /*
                 * In the CALCULATED_ANSWER test
                 * you mustn't have [ and ] in the textarea
                 * you mustn't have @@ in the textarea
                 * the text to find mustn't be empty or contains only spaces
                 * the text to find mustn't contains HTML tags
                 * the text to find mustn't contains char "
                 */
                if ($origin !== null) {
                    global $exe_id;
                    $trackAttempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
                    $sqlTrackAttempt = 'SELECT answer FROM ' . $trackAttempts . ' WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId;
                    $rsLastAttempt = Database::query($sqlTrackAttempt);
                    $rowLastAttempt = Database::fetch_array($rsLastAttempt);
                    $answer = $rowLastAttempt['answer'];
                    if (empty($answer)) {
                        $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(1, $nbrAnswers);
                        $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]);
                    }
                }
                list($answer) = explode('@@', $answer);
                // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
                api_preg_match_all('/\\[[^]]+\\]/', $answer, $correctAnswerList);
                // get student answer to display it if student go back to previous calculated answer question in a test
                if (isset($user_choice[0]['answer'])) {
                    api_preg_match_all('/\\[[^]]+\\]/', $answer, $studentAnswerList);
                    $studentAnswerListTobecleaned = $studentAnswerList[0];
                    $studentAnswerList = array();
                    for ($i = 0; $i < count($studentAnswerListTobecleaned); $i++) {
                        $answerCorrected = $studentAnswerListTobecleaned[$i];
                        $answerCorrected = api_preg_replace('| / <font color="green"><b>.*$|', '', $answerCorrected);
                        $answerCorrected = api_preg_replace('/^\\[/', '', $answerCorrected);
                        $answerCorrected = api_preg_replace('|^<font color="red"><s>|', '', $answerCorrected);
                        $answerCorrected = api_preg_replace('|</s></font>$|', '', $answerCorrected);
                        $answerCorrected = '[' . $answerCorrected . ']';
                        $studentAnswerList[] = $answerCorrected;
                    }
                }
                // If display preview of answer in test view for exemple, set the student answer to the correct answers
                if ($debug_mark_answer) {
                    // contain the rights answers surronded with brackets
                    $studentAnswerList = $correctAnswerList[0];
                }
                /*
                Split the response by bracket
                tabComments is an array with text surrounding the text to find
                we add a space before and after the answerQuestion to be sure to
                have a block of text before and after [xxx] patterns
                so we have n text to find ([xxx]) and n+1 block of texts before,
                between and after the text to find
                */
                $tabComments = api_preg_split('/\\[[^]]+\\]/', ' ' . $answer . ' ');
                if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
                    $answer = "";
                    $i = 0;
                    foreach ($studentAnswerList as $studentItem) {
                        // remove surronding brackets
                        $studentResponse = api_substr($studentItem, 1, api_strlen($studentItem) - 2);
                        $size = strlen($studentItem);
                        $attributes['class'] = detectInputAppropriateClass($size);
                        $answer .= $tabComments[$i] . Display::input('text', "choice[{$questionId}][]", $studentResponse, $attributes);
                        $i++;
                    }
                    $answer .= $tabComments[$i];
                } else {
                    // display exercise with empty input fields
                    // every [xxx] are replaced with an empty input field
                    foreach ($correctAnswerList[0] as $item) {
                        $size = strlen($item);
                        $attributes['class'] = detectInputAppropriateClass($size);
                        $answer = str_replace($item, Display::input('text', "choice[{$questionId}][]", '', $attributes), $answer);
                    }
                }
                if ($origin !== null) {
                    $s = $answer;
                    break;
                } else {
                    $s .= $answer;
                }
            } elseif ($answerType == MATCHING) {
                // matching type, showing suggestions and answers
                // TODO: replace $answerId by $numAnswer
                if ($answerCorrect != 0) {
                    // only show elements to be answered (not the contents of
                    // the select boxes, who are corrrect = 0)
                    $s .= '<tr><td width="45%" valign="top">';
                    $parsed_answer = $answer;
                    //left part questions
                    $s .= ' <span style="float:left; width:8%;"><b>' . $lines_count . '</b>.&nbsp;</span>
    					 	<span style="float:left; width:92%;">' . $parsed_answer . '</span></td>';
                    //middle part (matches selects)
                    $s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
    			            <select name="choice[' . $questionId . '][' . $numAnswer . ']">';
                    // fills the list-box
                    foreach ($select_items as $key => $val) {
                        // set $debug_mark_answer to true at function start to
                        // show the correct answer with a suffix '-x'
                        $selected = '';
                        if ($debug_mark_answer) {
                            if ($val['id'] == $answerCorrect) {
                                $selected = 'selected="selected"';
                            }
                        }
                        //$user_choice_array_position
                        if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
                            $selected = 'selected="selected"';
                        }
                        /*if (isset($user_choice_array[$matching_correct_answer]) && $val['id'] == $user_choice_array[$matching_correct_answer]['answer']) {
                              $selected = 'selected="selected"';
                          }*/
                        $s .= '<option value="' . $val['id'] . '" ' . $selected . '>' . $val['letter'] . '</option>';
                    }
                    // end foreach()
                    $s .= '</select></td>';
                    $s .= '<td width="45%" valign="top" >';
                    if (isset($select_items[$lines_count])) {
                        $s .= '<span style="float:left; width:5%;"><b>' . $select_items[$lines_count]['letter'] . '.</b></span>' . '<span style="float:left; width:95%;">' . $select_items[$lines_count]['answer'] . '</span>';
                    } else {
                        $s .= '&nbsp;';
                    }
                    $s .= '</td>';
                    $s .= '</tr>';
                    $lines_count++;
                    //if the left side of the "matching" has been completely
                    // shown but the right side still has values to show...
                    if ($lines_count - 1 == $num_suggestions) {
                        // if it remains answers to shown at the right side
                        while (isset($select_items[$lines_count])) {
                            $s .= '<tr>
    							  <td colspan="2"></td>
    							  <td valign="top">';
                            $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'];
                            $s .= "</td>\n    \t\t\t\t\t\t</tr>";
                            $lines_count++;
                        }
                        // end while()
                    }
                    // end if()
                    $matching_correct_answer++;
                }
            }
        }
        // end for()
        if ($show_comment) {
            $s .= '</table>';
        } else {
            if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                $s .= '</table>';
            }
        }
        $s .= '</div>';
        // destruction of the Answer object
        unset($objAnswerTmp);
        // destruction of the Question object
        unset($objQuestionTmp);
        if ($origin != 'export') {
            echo $s;
        } else {
            return $s;
        }
    } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
        // Question is a HOT_SPOT
        //checking document/images visibility
        if (api_is_platform_admin() || api_is_course_admin()) {
            require_once api_get_path(LIBRARY_PATH) . 'document.lib.php';
            $course = api_get_course_info();
            $doc_id = DocumentManager::get_document_id($course, '/images/' . $pictureName);
            if (is_numeric($doc_id)) {
                $images_folder_visibility = api_get_item_visibility($course, 'document', $doc_id, api_get_session_id());
                if (!$images_folder_visibility) {
                    //This message is shown only to the course/platform admin if the image is set to visibility = false
                    Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
                }
            }
        }
        $questionName = $objQuestionTmp->selectTitle();
        $questionDescription = $objQuestionTmp->selectDescription();
        if ($freeze) {
            echo Display::img($objQuestionTmp->selectPicturePath());
            return;
        }
        // Get the answers, make a list
        $objAnswerTmp = new Answer($questionId);
        $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
        // get answers of hotpost
        $answers_hotspot = array();
        for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
            $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
            $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
        }
        // display answers of hotpost order by id
        $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>' . get_lang('HotspotZones') . '</b><dl>';
        if (!empty($answers_hotspot)) {
            ksort($answers_hotspot);
            foreach ($answers_hotspot as $key => $value) {
                $answer_list .= '<dt>' . $key . '.- ' . $value . '</dt><br />';
            }
        }
        $answer_list .= '</dl></div>';
        if ($answerType == HOT_SPOT_DELINEATION) {
            $answer_list = '';
            $swf_file = 'hotspot_delineation_user';
            $swf_height = 405;
        } else {
            $swf_file = 'hotspot_user';
            $swf_height = 436;
        }
        if (!$only_questions) {
            if ($show_title) {
                Testcategory::displayCategoryAndTitle($objQuestionTmp->id);
                echo '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
            }
            //@todo I need to the get the feedback type
            echo '<input type="hidden" name="hidden_hotspot_id" value="' . $questionId . '" />';
            echo '<table class="exercise_questions" >
    			  <tr>
    		  		<td valign="top" colspan="2">';
            echo $questionDescription;
            echo '</td></tr>';
        }
        $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
        $s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
    					<script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
    					<script type="text/javascript">
    					<!--
    					// Globals
    					// Major version of Flash required
    					var requiredMajorVersion = 7;
    					// Minor version of Flash required
    					var requiredMinorVersion = 0;
    					// Minor version of Flash required
    					var requiredRevision = 0;
    					// the version of javascript supported
    					var jsVersion = 1.0;
    					// -->
    					</script>
    					<script language="VBScript" type="text/vbscript">
    					<!-- // Visual basic helper required to detect Flash Player ActiveX control version information
    					Function VBGetSwfVer(i)
    					  on error resume next
    					  Dim swControl, swVersion
    					  swVersion = 0

    					  set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
    					  if (IsObject(swControl)) then
    					    swVersion = swControl.GetVariable("$version")
    					  end if
    					  VBGetSwfVer = swVersion
    					End Function
    					// -->
    					</script>

    					<script language="JavaScript1.1" type="text/javascript">
    					<!-- // Detect Client Browser type
    					var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
    					var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
    					var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
    					jsVersion = 1.1;
    					// JavaScript helper required to detect Flash Player PlugIn version information
    					function JSGetSwfVer(i) {
    						// NS/Opera version >= 3 check for Flash plugin in plugin array
    						if (navigator.plugins != null && navigator.plugins.length > 0) {
    							if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
    								var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
    					      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
    								descArray = flashDescription.split(" ");
    								tempArrayMajor = descArray[2].split(".");
    								versionMajor = tempArrayMajor[0];
    								versionMinor = tempArrayMajor[1];
    								if ( descArray[3] != "" ) {
    									tempArrayMinor = descArray[3].split("r");
    								} else {
    									tempArrayMinor = descArray[4].split("r");
    								}
    					      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
    					            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
    					      	} else {
    								flashVer = -1;
    							}
    						}
    						// MSN/WebTV 2.6 supports Flash 4
    						else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    						// WebTV 2.5 supports Flash 3
    						else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    						// older WebTV supports Flash 2
    						else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    						// Can\'t detect in all other cases
    						else
    						{
    							flashVer = -1;
    						}
    						return flashVer;
    					}
    					// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available

    					function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
    					 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
    					   	// loop backwards through the versions until we find the newest version
    						for (i=25;i>0;i--) {
    							if (isIE && isWin && !isOpera) {
    								versionStr = VBGetSwfVer(i);
    							} else {
    								versionStr = JSGetSwfVer(i);
    							}
    							if (versionStr == -1 ) {
    								return false;
    							} else if (versionStr != 0) {
    								if(isIE && isWin && !isOpera) {
    									tempArray         = versionStr.split(" ");
    									tempString        = tempArray[1];
    									versionArray      = tempString .split(",");
    								} else {
    									versionArray      = versionStr.split(".");
    								}
    								versionMajor      = versionArray[0];
    								versionMinor      = versionArray[1];
    								versionRevision   = versionArray[2];

    								versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
    								versionNum        = parseFloat(versionString);
    					        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
    								if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
    									return true;
    								} else {
    									return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
    								}
    							}
    						}
    					}
    					// -->
    					</script>';
        $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
    				<script>
    					<!--
    					// Version check based upon the values entered above in "Globals"
    					var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

    					// Check to see if the version meets the requirements for playback
    					if (hasReqestedVersion) {  // if we\'ve detected an acceptable version
    					    var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" width="600" height="' . $swf_height . '">\'
    					    			+ \'<param name="wmode" value="transparent">\'
    									+ \'<param name="movie" value="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" />\'
    									+ \'<\\/object>\';
    					    document.write(oeTags);   // embed the Flash Content SWF when all tests are passed
    					} else {  // flash is too old or we can\'t detect the plugin
    						var alternateContent = "Error<br \\/>"
    							+ "Hotspots requires Macromedia Flash 7.<br \\/>"
    							+ "<a href=\\"http://www.macromedia.com/go/getflash/\\">Get Flash<\\/a>";
    						document.write(alternateContent);  // insert non-flash content
    					}
    					// -->
    				</script>
    				</td>
    				<td valign="top" align="left">' . $answer_list . '</td></tr>
    				</table>
    	</td></tr>';
        echo $s;
        echo '</table>';
    }
    return $nbrAnswers;
}
예제 #17
0
 /**
  * Creates a list with all the links in it
  * @return string
  */
 public function get_links()
 {
     $selfUrl = api_get_self();
     $courseIdReq = api_get_cidreq();
     $course = api_get_course_info();
     $course_id = $course['real_id'];
     $tbl_link = Database::get_course_table(TABLE_LINK);
     $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
     $moveEverywhereIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id, true, null, "link.session_id");
     $sql = "SELECT link.id as link_id,\n                    link.title as link_title,\n                    link.category_id as category_id,\n                    link_category.category_title as category_title\n                FROM {$tbl_link} as link\n                LEFT JOIN {$linkCategoryTable} as link_category\n                ON link.category_id = link_category.id\n                WHERE link.c_id = " . $course_id . " {$condition_session}\n                ORDER BY link_category.category_title ASC, link.title ASC";
     $links = Database::query($sql);
     $categorizedLinks = array();
     $categories = array();
     while ($link = Database::fetch_array($links)) {
         if (!$link['category_id']) {
             $link['category_title'] = get_lang('Uncategorized');
         }
         $categories[$link['category_id']] = $link['category_title'];
         $categorizedLinks[$link['category_id']][$link['link_id']] = $link['link_title'];
     }
     $linksHtmlCode = '<script>
         function toggle_tool(tool, id){
             if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
                 document.getElementById(tool+"_"+id+"_content").style.display = "block";
                 document.getElementById(tool+"_"+id+"_opener").src = "' . api_get_path(WEB_IMG_PATH) . 'remove.gif";
             } else {
                 document.getElementById(tool+"_"+id+"_content").style.display = "none";
                 document.getElementById(tool+"_"+id+"_opener").src = "' . api_get_path(WEB_IMG_PATH) . 'add.gif";
             }
         }
     </script>
     <ul class="lp_resource">
         <li class="lp_resource_element">
             <img alt="" src="../img/linksnew.gif" style="margin-right:5px;width:16px"/>
             <a href="' . api_get_path(REL_CODE_PATH) . 'link/link.php?' . $courseIdReq . '&action=addlink&lp_id=' . $this->lp_id . '" title="' . get_lang('LinkAdd') . '">' . get_lang('LinkAdd') . '</a>
         </li>';
     foreach ($categorizedLinks as $categoryId => $links) {
         $linkNodes = null;
         foreach ($links as $key => $title) {
             if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
                 $linkNodes .= '<li class="lp_resource_element" data_id="' . $key . '" data_type="' . TOOL_LINK . '" title="' . $title . '" >
                     <a class="moved" href="#">' . $moveEverywhereIcon . '</a>
                     <img alt="" src="../img/lp_link.gif" style="margin-right:5px;width:16px"/>
                     <a href="' . $selfUrl . '?' . $courseIdReq . '&action=add_item&type=' . TOOL_LINK . '&file=' . $key . '&lp_id=' . $this->lp_id . '">' . Security::remove_XSS($title) . '</a>
                 </li>';
             }
         }
         $linksHtmlCode .= '<li>
             <a style="cursor:hand" onclick="javascript: toggle_tool(\'' . TOOL_LINK . '\',' . $categoryId . ')"
             style="vertical-align:middle">
                 <img src="' . api_get_path(WEB_IMG_PATH) . 'add.gif" id="' . TOOL_LINK . '_' . $categoryId . '_opener"
                 align="absbottom" />
             </a>
             <span style="vertical-align:middle">' . Security::remove_XSS($categories[$categoryId]) . '</span>
         </li>
         <div style="display:none" id="' . TOOL_LINK . '_' . $categoryId . '_content">' . $linkNodes . '</div>';
     }
     $linksHtmlCode .= '</ul>';
     return $linksHtmlCode;
 }
예제 #18
0
    /**
     * Shows a question
     *
     * @param int    $questionId question id
     * @param bool   $only_questions if true only show the questions, no exercise title
     * @param bool   $origin  i.e = learnpath
     * @param string $current_item current item from the list of questions
     * @param bool   $show_title
     * @param bool   $freeze
     * @param array  $user_choice
     * @param bool   $show_comment
     * @param bool   $exercise_feedback
     * @param bool   $show_answers
     * */
    public static function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false)
    {
        $course_id = api_get_course_int_id();
        // Change false to true in the following line to enable answer hinting
        $debug_mark_answer = $show_answers;
        // Reads question information
        if (!($objQuestionTmp = Question::read($questionId))) {
            // Question not found
            return false;
        }
        if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
            $show_comment = false;
        }
        $answerType = $objQuestionTmp->selectType();
        $pictureName = $objQuestionTmp->selectPicture();
        $s = '';
        if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
            // Question is not a hotspot
            if (!$only_questions) {
                $questionDescription = $objQuestionTmp->selectDescription();
                if ($show_title) {
                    TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
                    echo Display::div($current_item . '. ' . $objQuestionTmp->selectTitle(), array('class' => 'question_title'));
                }
                if (!empty($questionDescription)) {
                    echo Display::div($questionDescription, array('class' => 'question_description'));
                }
            }
            if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
                return '';
            }
            echo '<div class="question_options row">';
            // construction of the Answer object (also gets all answers details)
            $objAnswerTmp = new Answer($questionId);
            $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
            $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
            // For "matching" type here, we need something a little bit special
            // because the match between the suggestions and the answers cannot be
            // done easily (suggestions and answers are in the same table), so we
            // have to go through answers first (elems with "correct" value to 0).
            $select_items = array();
            //This will contain the number of answers on the left side. We call them
            // suggestions here, for the sake of comprehensions, while the ones
            // on the right side are called answers
            $num_suggestions = 0;
            if (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
                if ($answerType == DRAGGABLE) {
                    $s .= '<div class="col-md-12 ui-widget ui-helper-clearfix">
                        <div class="clearfix">
                        <ul class="exercise-draggable-answer ui-helper-reset ui-helper-clearfix">';
                } else {
                    $s .= <<<HTML
                        <div id="drag{$questionId}_question" class="drag_question">
                            <table class="data_table">
HTML;
                }
                // Iterate through answers
                $x = 1;
                //mark letters for each answer
                $letter = 'A';
                $answer_matching = array();
                $cpt1 = array();
                for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                    if ($answerCorrect == 0) {
                        // options (A, B, C, ...) that will be put into the list-box
                        // have the "correct" field set to 0 because they are answer
                        $cpt1[$x] = $letter;
                        $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer);
                        $x++;
                        $letter++;
                    }
                }
                $i = 1;
                $select_items[0]['id'] = 0;
                $select_items[0]['letter'] = '--';
                $select_items[0]['answer'] = '';
                foreach ($answer_matching as $id => $value) {
                    $select_items[$i]['id'] = $value['id'];
                    $select_items[$i]['letter'] = $cpt1[$id];
                    $select_items[$i]['answer'] = $value['answer'];
                    $i++;
                }
                $user_choice_array_position = array();
                if (!empty($user_choice)) {
                    foreach ($user_choice as $item) {
                        $user_choice_array_position[$item['position']] = $item['answer'];
                    }
                }
                $num_suggestions = $nbrAnswers - $x + 1;
            } elseif ($answerType == FREE_ANSWER) {
                $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
                $form = new FormValidator('free_choice_' . $questionId);
                $config = array('ToolbarSet' => 'TestFreeAnswer');
                $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
                $form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
                $s .= $form->returnForm();
            } elseif ($answerType == ORAL_EXPRESSION) {
                // Add nanog
                if (api_get_setting('enable_nanogong') == 'true') {
                    //@todo pass this as a parameter
                    global $exercise_stat_info, $exerciseId, $exe_id;
                    if (!empty($exercise_stat_info)) {
                        $params = array('exercise_id' => $exercise_stat_info['exe_exo_id'], 'exe_id' => $exercise_stat_info['exe_id'], 'question_id' => $questionId);
                    } else {
                        $params = array('exercise_id' => $exerciseId, 'exe_id' => 'temp_exe', 'question_id' => $questionId);
                    }
                    $nano = new Nanogong($params);
                    echo $nano->show_button();
                }
                $form = new FormValidator('free_choice_' . $questionId);
                $config = array('ToolbarSet' => 'TestFreeAnswer');
                $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
                //$form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
                $s .= $form->return_form();
            }
            // Now navigate through the possible answers, using the max number of
            // answers for the question as a limiter
            $lines_count = 1;
            // a counter for matching-type answers
            if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                $header = Display::tag('th', get_lang('Options'));
                foreach ($objQuestionTmp->options as $item) {
                    if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                        if (in_array($item, $objQuestionTmp->options)) {
                            $header .= Display::tag('th', get_lang($item));
                        } else {
                            $header .= Display::tag('th', $item);
                        }
                    } else {
                        $header .= Display::tag('th', $item);
                    }
                }
                if ($show_comment) {
                    $header .= Display::tag('th', get_lang('Feedback'));
                }
                $s .= '<table class="table table-hover table-striped">';
                $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
            }
            if ($show_comment) {
                if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
                    $header = Display::tag('th', get_lang('Options'));
                    if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
                        $header .= Display::tag('th', get_lang('Feedback'));
                    }
                    $s .= '<table class="table table-hover table-striped">';
                    $s .= Display::tag('tr', $header, array('style' => 'text-align:left;'));
                }
            }
            $matching_correct_answer = 0;
            $user_choice_array = array();
            if (!empty($user_choice)) {
                foreach ($user_choice as $item) {
                    $user_choice_array[] = $item['answer'];
                }
            }
            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                $answer = $objAnswerTmp->selectAnswer($answerId);
                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                $comment = $objAnswerTmp->selectComment($answerId);
                $attributes = array();
                // Unique answer
                if (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, UNIQUE_ANSWER_IMAGE])) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    if ($show_comment) {
                        $s .= '<tr><td>';
                    }
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        if ($show_comment) {
                            if (empty($comment)) {
                                $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image" style="text-align: center">';
                            } else {
                                $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image col-xs-6 col-sm-12" style="text-align: center">';
                            }
                        } else {
                            $s .= '<div id="answer' . $questionId . $numAnswer . '" ' . 'class="exercise-unique-answer-image col-xs-6 col-md-3" style="text-align: center">';
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $s .= Display::input('hidden', 'choice2[' . $questionId . ']', '0');
                    $answer_input = null;
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $attributes['style'] = 'display: none;';
                        $answer = '<div class="thumbnail">' . $answer . '</div>';
                    }
                    $answer_input .= '<label class="radio">';
                    $answer_input .= Display::input('radio', 'choice[' . $questionId . ']', $numAnswer, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($answerType == UNIQUE_ANSWER_IMAGE) {
                        $answer_input .= "</div>";
                    }
                    if ($show_comment) {
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    $answer = Security::remove_XSS($answer, STUDENT);
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
                        $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                        $answer_input = '<label class="checkbox">';
                        $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', $numAnswer, $attributes);
                        $answer_input .= $answer;
                        $answer_input .= '</label>';
                        if ($show_comment) {
                            $s .= '<tr><td>';
                            $s .= $answer_input;
                            $s .= '</td>';
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                            $s .= '</tr>';
                        } else {
                            $s .= $answer_input;
                        }
                    } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
                        $my_choice = array();
                        if (!empty($user_choice_array)) {
                            foreach ($user_choice_array as $item) {
                                $item = explode(':', $item);
                                $my_choice[$item[0]] = $item[1];
                            }
                        }
                        $s .= '<tr>';
                        $s .= Display::tag('td', $answer);
                        if (!empty($quiz_question_options)) {
                            foreach ($quiz_question_options as $id => $item) {
                                if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
                                    $attributes = array('checked' => 1, 'selected' => 1);
                                } else {
                                    $attributes = array();
                                }
                                if ($debug_mark_answer) {
                                    if ($id == $answerCorrect) {
                                        $attributes['checked'] = 1;
                                        $attributes['selected'] = 1;
                                    }
                                }
                                $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $id, $attributes), array('style' => ''));
                            }
                        }
                        if ($show_comment) {
                            $s .= '<td>';
                            $s .= $comment;
                            $s .= '</td>';
                        }
                        $s .= '</tr>';
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
                    // multiple answers
                    $input_id = 'choice-' . $questionId . '-' . $answerId;
                    if (in_array($numAnswer, $user_choice_array)) {
                        $attributes = array('id' => $input_id, 'checked' => 1, 'selected' => 1);
                    } else {
                        $attributes = array('id' => $input_id);
                    }
                    if ($debug_mark_answer) {
                        if ($answerCorrect) {
                            $attributes['checked'] = 1;
                            $attributes['selected'] = 1;
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $answer_input .= '<label class="checkbox">';
                    $answer_input .= Display::input('checkbox', 'choice[' . $questionId . '][' . $numAnswer . ']', 1, $attributes);
                    $answer_input .= $answer;
                    $answer_input .= '</label>';
                    if ($show_comment) {
                        $s .= '<tr>';
                        $s .= '<td>';
                        $s .= $answer_input;
                        $s .= '</td>';
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                        $s .= '</tr>';
                    } else {
                        $s .= $answer_input;
                    }
                } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
                    $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
                    $my_choice = array();
                    if (!empty($user_choice_array)) {
                        foreach ($user_choice_array as $item) {
                            $item = explode(':', $item);
                            if (isset($item[1]) && isset($item[0])) {
                                $my_choice[$item[0]] = $item[1];
                            }
                        }
                    }
                    $answer = Security::remove_XSS($answer, STUDENT);
                    $s .= '<tr>';
                    $s .= Display::tag('td', $answer);
                    foreach ($objQuestionTmp->options as $key => $item) {
                        if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
                            $attributes = array('checked' => 1, 'selected' => 1);
                        } else {
                            $attributes = array();
                        }
                        if ($debug_mark_answer) {
                            if ($key == $answerCorrect) {
                                $attributes['checked'] = 1;
                                $attributes['selected'] = 1;
                            }
                        }
                        $s .= Display::tag('td', Display::input('radio', 'choice[' . $questionId . '][' . $numAnswer . ']', $key, $attributes));
                    }
                    if ($show_comment) {
                        $s .= '<td>';
                        $s .= $comment;
                        $s .= '</td>';
                    }
                    $s .= '</tr>';
                } elseif ($answerType == FILL_IN_BLANKS) {
                    // display the question, with field empty, for student to fill it,
                    // or filled to display the answer in the Question preview of the exercice/admin.php page
                    $displayForStudent = true;
                    $listAnswerInformations = FillBlanks::getAnswerInfo($answer);
                    $separatorStartRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorstart']);
                    $separatorEndRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorend']);
                    list($answer) = explode('::', $answer);
                    //Correct answers
                    $correctAnswerList = $listAnswerInformations['tabwords'];
                    //Student's answer
                    $studentAnswerList = array();
                    if (isset($user_choice[0]['answer'])) {
                        $arrayStudentAnswer = FillBlanks::getAnswerInfo($user_choice[0]['answer'], true);
                        $studentAnswerList = $arrayStudentAnswer['studentanswer'];
                    }
                    // If the question must be shown with the answer (in page exercice/admin.php) for teacher preview
                    // set the student-answer to the correct answer
                    if ($debug_mark_answer) {
                        $studentAnswerList = $correctAnswerList;
                        $displayForStudent = false;
                    }
                    if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
                        $answer = "";
                        for ($i = 0; $i < count($listAnswerInformations["commonwords"]) - 1; $i++) {
                            // display the common word
                            $answer .= $listAnswerInformations["commonwords"][$i];
                            // display the blank word
                            $correctItem = $listAnswerInformations["tabwords"][$i];
                            $correctItemRegexp = $correctItem;
                            // replace / with \/ to allow the preg_replace bellow and all the regexp char
                            $correctItemRegexp = FillBlanks::getRegexpProtected($correctItemRegexp);
                            if (isset($studentAnswerList[$i])) {
                                // If student already started this test and answered this question,
                                // fill the blank with his previous answers
                                // may be "" if student viewed the question, but did not fill the blanks
                                $correctItem = $studentAnswerList[$i];
                            }
                            $attributes["style"] = "width:" . $listAnswerInformations["tabinputsize"][$i] . "px";
                            $answer .= FillBlanks::getFillTheBlankHtml($separatorStartRegexp, $separatorEndRegexp, $correctItemRegexp, $questionId, $correctItem, $attributes, $answer, $listAnswerInformations, $displayForStudent, $i);
                        }
                        // display the last common word
                        $answer .= $listAnswerInformations["commonwords"][$i];
                    } else {
                        // display empty [input] with the right width for student to fill it
                        $separatorStartRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorstart']);
                        $separatorEndRegexp = FillBlanks::escapeForRegexp($listAnswerInformations['blankseparatorend']);
                        $answer = "";
                        for ($i = 0; $i < count($listAnswerInformations["commonwords"]) - 1; $i++) {
                            // display the common words
                            $answer .= $listAnswerInformations["commonwords"][$i];
                            // display the blank word
                            $attributes["style"] = "width:" . $listAnswerInformations["tabinputsize"][$i] . "px";
                            $correctItem = $listAnswerInformations["tabwords"][$i];
                            $correctItemRegexp = $correctItem;
                            // replace / with \/ to allow the preg_replace bellow and all the regexp char
                            $correctItemRegexp = FillBlanks::getRegexpProtected($correctItemRegexp);
                            $answer .= FillBlanks::getFillTheBlankHtml($separatorStartRegexp, $separatorEndRegexp, $correctItemRegexp, $questionId, '', $attributes, $answer, $listAnswerInformations, $displayForStudent, $i);
                        }
                        // display the last common word
                        $answer .= $listAnswerInformations["commonwords"][$i];
                    }
                    $s .= $answer;
                } elseif ($answerType == CALCULATED_ANSWER) {
                    /*
                     * In the CALCULATED_ANSWER test
                     * you mustn't have [ and ] in the textarea
                     * you mustn't have @@ in the textarea
                     * the text to find mustn't be empty or contains only spaces
                     * the text to find mustn't contains HTML tags
                     * the text to find mustn't contains char "
                     */
                    if ($origin !== null) {
                        global $exe_id;
                        $trackAttempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
                        $sqlTrackAttempt = 'SELECT answer FROM ' . $trackAttempts . '
                                            WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId;
                        $rsLastAttempt = Database::query($sqlTrackAttempt);
                        $rowLastAttempt = Database::fetch_array($rsLastAttempt);
                        $answer = $rowLastAttempt['answer'];
                        if (empty($answer)) {
                            $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(1, $nbrAnswers);
                            $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]);
                        }
                    }
                    list($answer) = explode('@@', $answer);
                    // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
                    api_preg_match_all('/\\[[^]]+\\]/', $answer, $correctAnswerList);
                    // get student answer to display it if student go back to previous calculated answer question in a test
                    if (isset($user_choice[0]['answer'])) {
                        api_preg_match_all('/\\[[^]]+\\]/', $answer, $studentAnswerList);
                        $studentAnswerListTobecleaned = $studentAnswerList[0];
                        $studentAnswerList = array();
                        for ($i = 0; $i < count($studentAnswerListTobecleaned); $i++) {
                            $answerCorrected = $studentAnswerListTobecleaned[$i];
                            $answerCorrected = api_preg_replace('| / <font color="green"><b>.*$|', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('/^\\[/', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('|^<font color="red"><s>|', '', $answerCorrected);
                            $answerCorrected = api_preg_replace('|</s></font>$|', '', $answerCorrected);
                            $answerCorrected = '[' . $answerCorrected . ']';
                            $studentAnswerList[] = $answerCorrected;
                        }
                    }
                    // If display preview of answer in test view for exemple, set the student answer to the correct answers
                    if ($debug_mark_answer) {
                        // contain the rights answers surronded with brackets
                        $studentAnswerList = $correctAnswerList[0];
                    }
                    /*
                    Split the response by bracket
                    tabComments is an array with text surrounding the text to find
                    we add a space before and after the answerQuestion to be sure to
                    have a block of text before and after [xxx] patterns
                    so we have n text to find ([xxx]) and n+1 block of texts before,
                    between and after the text to find
                    */
                    $tabComments = api_preg_split('/\\[[^]]+\\]/', ' ' . $answer . ' ');
                    if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
                        $answer = "";
                        $i = 0;
                        foreach ($studentAnswerList as $studentItem) {
                            // remove surronding brackets
                            $studentResponse = api_substr($studentItem, 1, api_strlen($studentItem) - 2);
                            $size = strlen($studentItem);
                            $attributes['class'] = self::detectInputAppropriateClass($size);
                            $answer .= $tabComments[$i] . Display::input('text', "choice[{$questionId}][]", $studentResponse, $attributes);
                            $i++;
                        }
                        $answer .= $tabComments[$i];
                    } else {
                        // display exercise with empty input fields
                        // every [xxx] are replaced with an empty input field
                        foreach ($correctAnswerList[0] as $item) {
                            $size = strlen($item);
                            $attributes['class'] = self::detectInputAppropriateClass($size);
                            $answer = str_replace($item, Display::input('text', "choice[{$questionId}][]", '', $attributes), $answer);
                        }
                    }
                    if ($origin !== null) {
                        $s = $answer;
                        break;
                    } else {
                        $s .= $answer;
                    }
                } elseif ($answerType == MATCHING) {
                    // matching type, showing suggestions and answers
                    // TODO: replace $answerId by $numAnswer
                    if ($answerCorrect != 0) {
                        // only show elements to be answered (not the contents of
                        // the select boxes, who are corrrect = 0)
                        $s .= '<tr><td width="45%" valign="top">';
                        $parsed_answer = $answer;
                        //left part questions
                        $s .= '<p class="indent">' . $lines_count . '.&nbsp;' . $parsed_answer . '</p></td>';
                        //middle part (matches selects)
                        $s .= '<td width="10%" valign="top" align="center" >
                                <div class="select-matching">
                                <select name="choice[' . $questionId . '][' . $numAnswer . ']">';
                        // fills the list-box
                        foreach ($select_items as $key => $val) {
                            // set $debug_mark_answer to true at function start to
                            // show the correct answer with a suffix '-x'
                            $selected = '';
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selected = 'selected="selected"';
                                }
                            }
                            //$user_choice_array_position
                            if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
                                $selected = 'selected="selected"';
                            }
                            $s .= '<option value="' . $val['id'] . '" ' . $selected . '>' . $val['letter'] . '</option>';
                        }
                        // end foreach()
                        $s .= '</select></div></td><td width="5%" class="separate">&nbsp;</td>';
                        $s .= '<td width="40%" valign="top" >';
                        if (isset($select_items[$lines_count])) {
                            $s .= '<div class="text-right"><p class="indent">' . $select_items[$lines_count]['letter'] . '.&nbsp; ' . $select_items[$lines_count]['answer'] . '</p></div>';
                        } else {
                            $s .= '&nbsp;';
                        }
                        $s .= '</td>';
                        $s .= '</tr>';
                        $lines_count++;
                        //if the left side of the "matching" has been completely
                        // shown but the right side still has values to show...
                        if ($lines_count - 1 == $num_suggestions) {
                            // if it remains answers to shown at the right side
                            while (isset($select_items[$lines_count])) {
                                $s .= '<tr>
                                      <td colspan="2"></td>
                                      <td valign="top">';
                                $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'];
                                $s .= "</td>\n                                </tr>";
                                $lines_count++;
                            }
                            // end while()
                        }
                        // end if()
                        $matching_correct_answer++;
                    }
                } elseif ($answerType == DRAGGABLE) {
                    if ($answerCorrect != 0) {
                        $parsed_answer = $answer;
                        /*$lines_count = '';
                          $data = $objAnswerTmp->getAnswerByAutoId($numAnswer);
                          $data = $objAnswerTmp->getAnswerByAutoId($data['correct']);
                          $lines_count = $data['answer'];*/
                        $windowId = $questionId . '_' . $lines_count;
                        $s .= '<li class="touch-items" id="' . $windowId . '">';
                        $s .= Display::div($parsed_answer, ['id' => "window_{$windowId}", 'class' => "window{$questionId}_question_draggable exercise-draggable-answer-option"]);
                        $selectedValue = 0;
                        $draggableSelectOptions = [];
                        foreach ($select_items as $key => $val) {
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selectedValue = $val['id'];
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selectedValue = $val['id'];
                            }
                            $draggableSelectOptions[$val['id']] = $val['letter'];
                        }
                        $s .= Display::select("choice[{$questionId}][{$numAnswer}]", $draggableSelectOptions, $selectedValue, ['id' => "window_{$windowId}_select", 'class' => 'select_option', 'style' => 'display: none;'], false);
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            $s .= <<<JAVASCRIPT
                                <script>
                                    \$(function() {
                                        DraggableAnswer.deleteItem(
                                            \$('#{$questionId}_{$selectedValue}'),
                                            \$('#drop_{$windowId}')
                                        );
                                    });
                                </script>
JAVASCRIPT;
                        }
                        if (isset($select_items[$lines_count])) {
                            $s .= Display::div(Display::tag('b', $select_items[$lines_count]['letter']) . $select_items[$lines_count]['answer'], ['id' => "window_{$windowId}_answer", 'style' => 'display: none;']);
                        } else {
                            $s .= '&nbsp;';
                        }
                        $lines_count++;
                        if ($lines_count - 1 == $num_suggestions) {
                            while (isset($select_items[$lines_count])) {
                                $s .= Display::tag('b', $select_items[$lines_count]['letter']);
                                $s .= $select_items[$lines_count]['answer'];
                                $lines_count++;
                            }
                        }
                        $matching_correct_answer++;
                        $s .= '</li>';
                    }
                } elseif ($answerType == MATCHING_DRAGGABLE) {
                    if ($answerId == 1) {
                        echo $objAnswerTmp->getJs();
                    }
                    if ($answerCorrect != 0) {
                        $parsed_answer = $answer;
                        $windowId = "{$questionId}_{$lines_count}";
                        $s .= <<<HTML
                            <tr>
                                <td widht="45%">
                                    <div id="window_{$windowId}" class="window window_left_question window{$questionId}_question">
                                        <strong>{$lines_count}.</strong> {$parsed_answer}
                                    </div>
                                </td>
                                <td width="10%">
HTML;
                        $selectedValue = 0;
                        $questionOptions = [];
                        foreach ($select_items as $key => $val) {
                            if ($debug_mark_answer) {
                                if ($val['id'] == $answerCorrect) {
                                    $selectedValue = $val['id'];
                                }
                            }
                            if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
                                $selectedValue = $val['id'];
                            }
                            $questionOptions[$val['id']] = $val['letter'];
                        }
                        $s .= Display::select("choice[{$questionId}][{$numAnswer}]", $questionOptions, $selectedValue, ['id' => "window_{$windowId}_select", 'class' => 'hidden'], false);
                        if (!empty($answerCorrect) && !empty($selectedValue)) {
                            // Show connect if is not freeze (question preview)
                            if (!$freeze) {
                                $s .= <<<JAVASCRIPT
                                <script>
                                    jsPlumb.ready(function() {
                                        jsPlumb.connect({
                                            source: 'window_{$windowId}',
                                            target: 'window_{$questionId}_{$selectedValue}_answer',
                                            endpoint: ['Blank', {radius: 15}],
                                            anchors: ['RightMiddle', 'LeftMiddle'],
                                            paintStyle: {strokeStyle: '#8A8888', lineWidth: 8},
                                            connector: [
                                                MatchingDraggable.connectorType,
                                                {curvines: MatchingDraggable.curviness}
                                            ]
                                        });
                                    });
                                </script>
JAVASCRIPT;
                            }
                        }
                        $s .= <<<HTML
                            </td>
                            <td width="45%">
HTML;
                        if (isset($select_items[$lines_count])) {
                            $s .= <<<HTML
                                <div id="window_{$windowId}_answer" class="window window_right_question">
                                    <strong>{$select_items[$lines_count]['letter']}.</strong> {$select_items[$lines_count]['answer']}
                                </div>
HTML;
                        } else {
                            $s .= '&nbsp;';
                        }
                        $s .= '</td></tr>';
                        $lines_count++;
                        if ($lines_count - 1 == $num_suggestions) {
                            while (isset($select_items[$lines_count])) {
                                $s .= <<<HTML
                                    <tr>
                                        <td colspan="2"></td>
                                        <td>
                                            <strong>{$select_items[$lines_count]['letter']}</strong>
                                            {$select_items[$lines_count]['answer']}
                                        </td>
                                    </tr>
HTML;
                                $lines_count++;
                            }
                        }
                        $matching_correct_answer++;
                    }
                }
            }
            // end for()
            if ($show_comment) {
                $s .= '</table>';
            } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER_TRUE_FALSE, MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE])) {
                $s .= '</table>';
            }
            if ($answerType == DRAGGABLE) {
                $s .= "</ul></div>";
                $counterAnswer = 1;
                $s .= '<div class="col-md-12"><div class="row">';
                for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                    $answerCorrect = $objAnswerTmp->isCorrect($answerId);
                    $windowId = $questionId . '_' . $counterAnswer;
                    if ($answerCorrect) {
                        $s .= Display::div($counterAnswer, ['id' => "drop_{$windowId}", 'class' => 'droppable col-md-2']);
                        $counterAnswer++;
                    }
                }
                $s .= '</div></div>';
            }
            if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
                $s .= '</div>';
            }
            $s .= '</div>';
            // destruction of the Answer object
            unset($objAnswerTmp);
            // destruction of the Question object
            unset($objQuestionTmp);
            if ($origin != 'export') {
                echo $s;
            } else {
                return $s;
            }
        } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
            // Question is a HOT_SPOT
            //checking document/images visibility
            if (api_is_platform_admin() || api_is_course_admin()) {
                $course = api_get_course_info();
                $doc_id = DocumentManager::get_document_id($course, '/images/' . $pictureName);
                if (is_numeric($doc_id)) {
                    $images_folder_visibility = api_get_item_visibility($course, 'document', $doc_id, api_get_session_id());
                    if (!$images_folder_visibility) {
                        //This message is shown only to the course/platform admin if the image is set to visibility = false
                        Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
                    }
                }
            }
            $questionName = $objQuestionTmp->selectTitle();
            $questionDescription = $objQuestionTmp->selectDescription();
            if ($freeze) {
                echo Display::img($objQuestionTmp->selectPicturePath());
                return;
            }
            // Get the answers, make a list
            $objAnswerTmp = new Answer($questionId);
            $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
            // get answers of hotpost
            $answers_hotspot = array();
            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
                $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
                $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
            }
            // display answers of hotpost order by id
            $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>' . get_lang('HotspotZones') . '</b><dl>';
            if (!empty($answers_hotspot)) {
                ksort($answers_hotspot);
                foreach ($answers_hotspot as $key => $value) {
                    $answer_list .= '<dt>' . $key . '.- ' . $value . '</dt><br />';
                }
            }
            $answer_list .= '</dl></div>';
            if ($answerType == HOT_SPOT_DELINEATION) {
                $answer_list = '';
                $swf_file = 'hotspot_delineation_user';
                $swf_height = 405;
            } else {
                $swf_file = 'hotspot_user';
                $swf_height = 436;
            }
            if (!$only_questions) {
                if ($show_title) {
                    TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
                    echo '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
                }
                //@todo I need to the get the feedback type
                echo '<input type="hidden" name="hidden_hotspot_id" value="' . $questionId . '" />';
                echo '<table class="exercise_questions" >
                      <tr>
                        <td valign="top" colspan="2">';
                echo $questionDescription;
                echo '</td></tr>';
            }
            $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
            $s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
                            <script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
                            <script type="text/javascript">
                            <!--
                            // Globals
                            // Major version of Flash required
                            var requiredMajorVersion = 7;
                            // Minor version of Flash required
                            var requiredMinorVersion = 0;
                            // Minor version of Flash required
                            var requiredRevision = 0;
                            // the version of javascript supported
                            var jsVersion = 1.0;
                            // -->
                            </script>
                            <script language="VBScript" type="text/vbscript">
                            <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
                            Function VBGetSwfVer(i)
                              on error resume next
                              Dim swControl, swVersion
                              swVersion = 0

                              set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
                              if (IsObject(swControl)) then
                                swVersion = swControl.GetVariable("$version")
                              end if
                              VBGetSwfVer = swVersion
                            End Function
                            // -->
                            </script>

                            <script language="JavaScript1.1" type="text/javascript">
                            <!-- // Detect Client Browser type
                            var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
                            var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
                            var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
                            jsVersion = 1.1;
                            // JavaScript helper required to detect Flash Player PlugIn version information
                            function JSGetSwfVer(i) {
                                // NS/Opera version >= 3 check for Flash plugin in plugin array
                                if (navigator.plugins != null && navigator.plugins.length > 0) {
                                    if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
                                        var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
                                        var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
                                        descArray = flashDescription.split(" ");
                                        tempArrayMajor = descArray[2].split(".");
                                        versionMajor = tempArrayMajor[0];
                                        versionMinor = tempArrayMajor[1];
                                        if ( descArray[3] != "" ) {
                                            tempArrayMinor = descArray[3].split("r");
                                        } else {
                                            tempArrayMinor = descArray[4].split("r");
                                        }
                                        versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
                                        flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
                                    } else {
                                        flashVer = -1;
                                    }
                                }
                                // MSN/WebTV 2.6 supports Flash 4
                                else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
                                // WebTV 2.5 supports Flash 3
                                else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
                                // older WebTV supports Flash 2
                                else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
                                // Can\'t detect in all other cases
                                else
                                {
                                    flashVer = -1;
                                }
                                return flashVer;
                            }
                            // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available

                            function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
                                reqVer = parseFloat(reqMajorVer + "." + reqRevision);
                                // loop backwards through the versions until we find the newest version
                                for (i=25;i>0;i--) {
                                    if (isIE && isWin && !isOpera) {
                                        versionStr = VBGetSwfVer(i);
                                    } else {
                                        versionStr = JSGetSwfVer(i);
                                    }
                                    if (versionStr == -1 ) {
                                        return false;
                                    } else if (versionStr != 0) {
                                        if(isIE && isWin && !isOpera) {
                                            tempArray         = versionStr.split(" ");
                                            tempString        = tempArray[1];
                                            versionArray      = tempString .split(",");
                                        } else {
                                            versionArray      = versionStr.split(".");
                                        }
                                        versionMajor      = versionArray[0];
                                        versionMinor      = versionArray[1];
                                        versionRevision   = versionArray[2];

                                        versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
                                        versionNum        = parseFloat(versionString);
                                        // is the major.revision >= requested major.revision AND the minor version >= requested minor
                                        if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
                                            return true;
                                        } else {
                                            return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
                                        }
                                    }
                                }
                            }
                            // -->
                            </script>';
            $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
                        <script>
                            <!--
                            // Version check based upon the values entered above in "Globals"
                            var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

                            // Check to see if the version meets the requirements for playback
                            if (hasReqestedVersion) {  // if we\'ve detected an acceptable version
                                var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&canClick:' . $canClick . '" width="600" height="' . $swf_height . '">\'
                                            + \'<param name="wmode" value="transparent">\'
                                            + \'<param name="movie" value="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&canClick:' . $canClick . '" />\'
                                            + \'<\\/object>\';
                                document.write(oeTags);   // embed the Flash Content SWF when all tests are passed
                            } else {  // flash is too old or we can\'t detect the plugin
                                var alternateContent = "Error<br \\/>"
                                    + "Hotspots requires Macromedia Flash 7.<br \\/>"
                                    + "<a href=\\"http://www.macromedia.com/go/getflash/\\">Get Flash<\\/a>";
                                document.write(alternateContent);  // insert non-flash content
                            }
                            // -->
                        </script>
                        </td>
                        <td valign="top" align="left">' . $answer_list . '</td></tr>
                        </table>
            </td></tr>';
            echo $s;
            echo '</table>';
        }
        return $nbrAnswers;
    }
 /**
  * @param $stok
  * @param $announcement_number
  */
 public static function getAnnouncements($stok, $announcement_number)
 {
     $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
     $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
     $user_id = api_get_user_id();
     $group_id = api_get_group_id();
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id, true, true, 'announcement.session_id');
     $course_id = api_get_course_int_id();
     $_course = api_get_course_info();
     $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id());
     $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
     if (api_is_allowed_to_edit(false, true) || $allowUserEditSetting && !api_is_anonymous()) {
         // A.1. you are a course admin with a USER filter
         // => see only the messages of this specific user + the messages of the group (s)he is member of.
         //if (!empty($user_id)) {
         if (0) {
             if (is_array($group_memberships) && count($group_memberships) > 0) {
                 $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n                            FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                announcement.id = ip.ref AND\n                                ip.tool = 'announcement' AND\n                                (\n                                    ip.to_user_id = {$user_id} OR\n                                    ip.to_group_id IS NULL OR\n                                    ip.to_group_id IN (0, " . implode(", ", $group_memberships) . ")\n                                ) AND\n                                ip.visibility IN ('1', '0')\n                                {$condition_session}\n                            ORDER BY display_order DESC";
             } else {
                 $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n                            FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                announcement.id = ip.ref AND\n                                ip.tool ='announcement' AND\n                                (ip.to_user_id = {$user_id} OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND\n                                ip.visibility IN ('1', '0')\n                            {$condition_session}\n                            ORDER BY display_order DESC";
             }
         } elseif ($group_id != 0) {
             // A.2. you are a course admin with a GROUP filter
             // => see only the messages of this specific group
             $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n                        FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref\n                            AND ip.tool='announcement'\n                            AND ip.visibility<>'2'\n                            AND (ip.to_group_id = {$group_id} OR ip.to_group_id='0' OR ip.to_group_id IS NULL)\n                            {$condition_session}\n                        GROUP BY ip.ref\n                        ORDER BY display_order DESC";
         } else {
             // A.3 you are a course admin without any group or user filter
             // A.3.a you are a course admin without user or group filter but WITH studentview
             // => see all the messages of all the users and groups without editing possibilities
             if (isset($isStudentView) and $isStudentView == "true") {
                 $sql = "SELECT\n                        announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n                        FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref\n                            AND ip.tool='announcement'\n                            AND ip.visibility='1'\n                            {$condition_session}\n                        GROUP BY ip.ref\n                        ORDER BY display_order DESC";
             } else {
                 // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
                 // => see all the messages of all the users and groups with editing possibilities
                 $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n                            FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n                            WHERE\n                                announcement.c_id = {$course_id} AND\n                                ip.c_id = {$course_id} AND\n                                announcement.id = ip.ref\n                                AND ip.tool='announcement'\n                                AND (ip.visibility='0' or ip.visibility='1')\n                                {$condition_session}\n                            GROUP BY ip.ref\n                            ORDER BY display_order DESC";
             }
         }
     } else {
         // STUDENT
         if (is_array($group_memberships) && count($group_memberships) > 0) {
             if ($allowUserEditSetting && !api_is_anonymous()) {
                 if (api_get_group_id() == 0) {
                     // No group
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR (\n                                ip.to_user_id='" . $user_id . "' OR\n                                (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . implode(", ", $group_memberships) . "))\n                            )\n                        ) ";
                 } else {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . $group_id . ")\n                        )";
                 }
             } else {
                 if (api_get_group_id() == 0) {
                     $cond_user_id = " AND (\n                            ip.to_user_id={$user_id} OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . implode(", ", $group_memberships) . "))\n                        ) ";
                 } else {
                     $cond_user_id = " AND (\n                            ip.to_user_id={$user_id} OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, " . api_get_group_id() . "))\n                        )";
                 }
             }
             $sql = "SELECT\n                            announcement.*,\n                            ip.visibility,\n                            ip.to_group_id,\n                            ip.insert_user_id,\n                            ip.insert_date\n                        FROM {$tbl_announcement} announcement,\n                        {$tbl_item_property} ip\n                        WHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref\n                            AND ip.tool='announcement'\n                            {$cond_user_id}\n                            {$condition_session} AND\n                            ip.visibility='1'\n                        ORDER BY display_order DESC";
         } else {
             if ($user_id) {
                 if ($allowUserEditSetting && !api_is_anonymous()) {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . api_get_user_id() . "' OR\n                            (ip.to_user_id='" . $user_id . "' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL))\n                        ) ";
                 } else {
                     $cond_user_id = " AND (ip.to_user_id='" . $user_id . "' AND (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
                 }
                 $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n\t\t\t\t\t\tFROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n\t\t\t\t\t\tWHERE\n    \t\t\t\t\t\tannouncement.c_id = {$course_id} AND\n\t\t\t\t\t\t\tip.c_id = {$course_id} AND\n    \t\t\t\t\t\tannouncement.id = ip.ref AND\n    \t\t\t\t\t\tip.tool='announcement'\n    \t\t\t\t\t\t{$cond_user_id}\n    \t\t\t\t\t\t{$condition_session}\n    \t\t\t\t\t\tAND ip.visibility='1'\n    \t\t\t\t\t\tAND announcement.session_id IN(0, " . api_get_session_id() . ")\n\t\t\t\t\t\tORDER BY display_order DESC";
             } else {
                 if ($allowUserEditSetting && !api_is_anonymous()) {
                     $cond_user_id = " AND (\n                            ip.lastedit_user_id = '" . $user_id . "' OR ip.to_group_id='0' OR ip.to_group_id IS NULL\n                        )";
                 } else {
                     $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
                 }
                 $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date\n\t\t\t\t\t\tFROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n\t\t\t\t\t\tWHERE\n                            announcement.c_id = {$course_id} AND\n                            ip.c_id = {$course_id} AND\n                            announcement.id = ip.ref AND\n                            ip.tool='announcement'\n                            {$cond_user_id}\n                            {$condition_session} AND\n                            ip.visibility='1' AND\n                            announcement.session_id IN ( 0," . api_get_session_id() . ")";
             }
         }
     }
     $result = Database::query($sql);
     $num_rows = Database::num_rows($result);
     $html = null;
     if ($num_rows == 0) {
         if ((api_is_allowed_to_edit(false, true) or api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) and (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath')) {
             $html .= '<div id="no-data-view">';
             $html .= '<h3>' . get_lang('Announcements') . '</h3>';
             $html .= Display::return_icon('valves.png', '', array(), 64);
             $html .= '<div class="controls">';
             $html .= Display::url(get_lang('AddAnnouncement'), api_get_self() . "?" . api_get_cidreq() . "&action=add", array('class' => 'btn btn-primary'));
             $html .= '</div>';
             $html .= '</div>';
         } else {
             $html = Display::return_message(get_lang('NoAnnouncements'), 'warning');
         }
         return $html;
     }
     $iterator = 1;
     $bottomAnnouncement = $announcement_number;
     $origin = null;
     $html .= '<table width="100%" class="data_table announcements-list">';
     $ths = Display::tag('th', get_lang('Title'));
     $ths .= Display::tag('th', get_lang('By'));
     $ths .= Display::tag('th', get_lang('LastUpdateDate'));
     if (api_is_allowed_to_edit(false, true) or api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']) or api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) {
         $ths .= Display::tag('th', get_lang('Modify'));
     }
     $html .= Display::tag('tr', $ths);
     $displayed = array();
     while ($myrow = Database::fetch_array($result, 'ASSOC')) {
         if (!in_array($myrow['id'], $displayed)) {
             $sent_to_icon = '';
             // the email icon
             if ($myrow['email_sent'] == '1') {
                 $sent_to_icon = ' ' . Display::return_icon('email.gif', get_lang('AnnounceSentByEmail'));
             }
             $title = $myrow['title'] . $sent_to_icon;
             $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id);
             $myrow['visibility'] = $item_visibility;
             // the styles
             if ($myrow['visibility'] == '0') {
                 $style = 'invisible';
             } else {
                 $style = '';
             }
             $html .= '<tr class="announcements-list-line">';
             // show attachment list
             $attachment_list = AnnouncementManager::get_attachment($myrow['id']);
             $attachment_icon = '';
             if (count($attachment_list) > 0) {
                 $attachment_icon = ' ' . Display::return_icon('attachment.gif', get_lang('Attachment'));
             }
             /* TITLE */
             $user_info = api_get_user_info($myrow['insert_user_id']);
             $username = sprintf(get_lang("LoginX"), $user_info['username']);
             $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title' => $username));
             $title = Display::url($title . $attachment_icon, api_get_self() . '?' . api_get_cidreq() . '&action=view&id=' . $myrow['id']);
             $html .= Display::tag('td', Security::remove_XSS($title), array('class' => 'announcements-list-line-title ' . $style));
             $html .= Display::tag('td', $username_span, array('class' => 'announcements-list-line-by-user'));
             $html .= Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), array('class' => 'announcements-list-line-datetime'));
             // we can edit if : we are the teacher OR the element belongs to
             // the session we are coaching OR the option to allow users to edit is on
             if (api_is_allowed_to_edit(false, true) or api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']) or api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) {
                 $modify_icons = "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=modify&id=" . $myrow['id'] . "\">" . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . "</a>";
                 if ($myrow['visibility'] == 1) {
                     $image_visibility = "visible";
                     $alt_visibility = get_lang('Hide');
                 } else {
                     $image_visibility = "invisible";
                     $alt_visibility = get_lang('Visible');
                 }
                 $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&origin=" . $origin . "&action=showhide&id=" . $myrow['id'] . "&sec_token=" . $stok . "\">" . Display::return_icon($image_visibility . '.png', $alt_visibility, '', ICON_SIZE_SMALL) . "</a>";
                 // DISPLAY MOVE UP COMMAND only if it is not the top announcement
                 if ($iterator != 1) {
                     $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=move&up=" . $myrow["id"] . "&sec_token=" . $stok . "\">" . Display::return_icon('up.gif', get_lang('Up')) . "</a>";
                 } else {
                     $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
                 }
                 if ($iterator < $bottomAnnouncement) {
                     $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=move&down=" . $myrow["id"] . "&sec_token=" . $stok . "\">" . Display::return_icon('down.gif', get_lang('Down')) . "</a>";
                 } else {
                     $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
                 }
                 if (api_is_allowed_to_edit(false, true)) {
                     $modify_icons .= "<a href=\"" . api_get_self() . "?" . api_get_cidreq() . "&action=delete&id=" . $myrow['id'] . "&sec_token=" . $stok . "\" onclick=\"javascript:if(!confirm('" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, api_get_system_encoding())) . "')) return false;\">" . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . "</a>";
                 }
                 $iterator++;
                 $html .= Display::tag('td', $modify_icons, array('class' => 'announcements-list-line-actions'));
             }
             $html .= "</tr>";
         }
         $displayed[] = $myrow['id'];
     }
     $html .= "</table>";
     return $html;
 }
예제 #20
0
if (is_dir($full_file_name)) {
    //remove last slash if present
    //$doc_url = ($doc_url{strlen($doc_url)-1}=='/')?substr($doc_url,0,strlen($doc_url)-1):$doc_url;
    //mod_rewrite can change /some/path/ to /some/path// in some cases, so clean them all off (René)
    while ($doc_url[$dul = strlen($doc_url) - 1] == '/') {
        $doc_url = substr($doc_url, 0, $dul);
    }
    //create the path
    $document_explorer = api_get_path(WEB_COURSE_PATH) . api_get_course_path();
    // home course path
    //redirect
    header('Location: ' . $document_explorer);
}
$tbl_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
$tbl_forum_post = Database::get_course_table(TABLE_FORUM_POST);
$course_id = api_get_course_int_id();
// launch event
event_download($doc_url);
$sql = 'SELECT thread_id, forum_id,filename FROM ' . $tbl_forum_post . '  f  INNER JOIN ' . $tbl_forum_attachment . ' a
        ON a.post_id=f.post_id 
      WHERE f.c_id = ' . $course_id . ' AND a.c_id = ' . $course_id . ' AND path LIKE BINARY "' . $doc_url . '"';
$result = Database::query($sql);
$row = Database::fetch_array($result);
$forum_thread_visibility = api_get_item_visibility(api_get_course_info($course_code), TOOL_FORUM_THREAD, $row['thread_id'], api_get_session_id());
$forum_forum_visibility = api_get_item_visibility(api_get_course_info($course_code), TOOL_FORUM, $row['forum_id'], api_get_session_id());
if ($forum_thread_visibility == 1 && $forum_forum_visibility == 1) {
    if (Security::check_abs_path($full_file_name, api_get_path(SYS_COURSE_PATH) . api_get_course_path() . '/upload/forum/')) {
        DocumentManager::file_send_for_download($full_file_name, TRUE, $row['filename']);
    }
}
exit;
예제 #21
0
 if (api_is_allowed_to_edit(false, true) or api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id']) or api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) {
     $ths .= Display::tag('th width="12%"', get_lang('Modify'));
 }
 echo Display::tag('tr', $ths);
 $displayed = array();
 while ($myrow = Database::fetch_array($result, 'ASSOC')) {
     if (!in_array($myrow['id'], $displayed)) {
         $sent_to_icon = '';
         // the email icon
         if ($myrow['email_sent'] == '1') {
             $sent_to_icon = ' ' . Display::return_icon('email.gif', get_lang('AnnounceSentByEmail'));
         }
         $title = $myrow['title'] . $sent_to_icon;
         /* DATE */
         $last_post_datetime = $myrow['end_date'];
         $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id);
         $myrow['visibility'] = $item_visibility;
         // the styles
         if ($myrow['visibility'] == '0') {
             $style = 'invisible';
         } else {
             $style = '';
         }
         echo '<tr class="announcements-list-line">';
         // show attachment list
         $attachment_list = array();
         $attachment_list = AnnouncementManager::get_attachment($myrow['id']);
         $attachment_icon = '';
         if (count($attachment_list) > 0) {
             $attachment_icon = ' ' . Display::return_icon('attachment.gif', get_lang('Attachment'));
         }
예제 #22
0
 /**
  * Creates a list with all the links in it
  * @return string
  */
 public function get_links()
 {
     $course_id = api_get_course_int_id();
     $tbl_link = Database::get_course_table(TABLE_LINK);
     $session_id = api_get_session_id();
     $condition_session = api_get_session_condition($session_id);
     $sql_link = "SELECT id, title FROM {$tbl_link} WHERE c_id = " . $course_id . " {$condition_session} ORDER BY title ASC";
     $res_link = Database::query($sql_link);
     $return = '<ul class="lp_resource">';
     $return .= '<li class="lp_resource_element">';
     $return .= Display::return_icon('linksnew.gif');
     $return .= '<a href="' . api_get_path(REL_CODE_PATH) . 'link/link.php?' . api_get_cidreq() . '&action=addlink&amp;lp_id=' . $this->lp_id . '" title="' . get_lang('LinkAdd') . '">' . get_lang('LinkAdd') . '</a>';
     $return .= '</li>';
     $course_info = api_get_course_info();
     while ($row_link = Database::fetch_array($res_link)) {
         $item_visibility = api_get_item_visibility($course_info, TOOL_LINK, $row_link['id'], $session_id);
         if ($item_visibility != 2) {
             $return .= '<li class="lp_resource_element" data_id="' . $row_link['id'] . '" data_type="' . TOOL_LINK . '" title="' . $row_link['title'] . '" >';
             $return .= '<a class="moved" href="#">';
             $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
             $return .= '</a> ';
             $return .= Display::return_icon('lp_link.gif');
             $return .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&amp;action=add_item&amp;type=' . TOOL_LINK . '&amp;file=' . $row_link['id'] . '&amp;lp_id=' . $this->lp_id . '">' . $row_link['title'] . '</a>';
             $return .= '</li>';
         }
     }
     $return .= '</ul>';
     return $return;
 }
 /**
  *  Gets a list of lessons  of the given course_code and session_id
  *  This functions doesn't need user_id
  *  @param string $course_code Text code of the course
  *  @param int  $session_id Id of session
  *  @return array List of lessons with lessons id as keys
  */
 public static function get_course_lessons($course_code, $session_id)
 {
     $table = Database::get_course_table(TABLE_LP_MAIN);
     $course = api_get_course_info($course_code);
     // @todo AND session_id = %s ?
     $sql = "SELECT * FROM {$table} WHERE c_id = %s ";
     $sql_query = sprintf($sql, $course['real_id']);
     $result = Database::query($sql_query);
     $lessons = array();
     while ($row = Database::fetch_array($result)) {
         if (api_get_item_visibility($course, 'learnpath', $row['id'], $session_id)) {
             $lessons[$row['id']] = $row;
         }
     }
     return $lessons;
 }
예제 #24
0
*
* @package chamilo.learnpath
*/
require_once '../inc/global.inc.php';
$_SESSION['whereami'] = 'lp/impress';
$this_section = SECTION_COURSES;
//To prevent the template class
$show_learnpath = true;
api_protect_course_script();
$lp_id = intval($_GET['lp_id']);
// Check if the learning path is visible for student - (LP requisites)
if (!api_is_allowed_to_edit(null, true) && !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
    api_not_allowed();
}
//Checking visibility (eye icon)
$visibility = api_get_item_visibility(api_get_course_info(), TOOL_LEARNPATH, $lp_id, $action, api_get_user_id(), api_get_session_id());
if (!api_is_allowed_to_edit(null, true) && intval($visibility) == 0) {
    api_not_allowed();
}
if (empty($_SESSION['oLP'])) {
    api_not_allowed(true);
}
$debug = 0;
if ($debug) {
    error_log('------ Entering lp_impress.php -------');
}
$course_code = api_get_course_id();
$course_id = api_get_course_int_id();
$htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH) . 'javascript/impress/impress-demo.css');
$list = $_SESSION['oLP']->get_toc();
$is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
예제 #25
0
    /**
     * Creates a list with all the links in it
     * @return string
     */
    public function get_links()
    {
        require_once api_get_path(LIBRARY_PATH).'link.lib.php';

        $course_id = api_get_course_int_id();
        $tbl_link = Database::get_course_table(TABLE_LINK);

        $session_id = api_get_session_id();
        $condition_session = api_get_session_condition($session_id);

        $sql = "SELECT id, title, category_id FROM $tbl_link
                WHERE c_id = ".$course_id." $condition_session
                ORDER BY title ASC";
        $res_link = Database::query($sql);

        $return = '<ul class="lp_resource">';
        $return .= '<li class="lp_resource_element">';
        $return .= '<img alt="" src="../img/linksnew.gif" style="margin-right:5px;width:16px" title="" />';
        $return .= '<a href="' . api_get_path(REL_CODE_PATH) . 'link/link.php?' . api_get_cidreq() . '&action=addlink&amp;lp_id=' . $this->lp_id . '" title="' . get_lang('LinkAdd') . '">' . get_lang('LinkAdd') . '</a>';
        $return .= '</li>';
        $course_info = api_get_course_info();

        $linkCategories = getLinkCategories($course_id, $session_id);
        $categoryIdList = array();
        if (!empty($linkCategories)) {
            foreach ($linkCategories as $categoryInfo) {
                $categoryIdList[] = $categoryInfo['id'];
            }
        }

        while ($row_link = Database :: fetch_array($res_link)) {

            // Check if category exists if not then consider as deleted.
            if (!empty($row_link['category_id'])) {
                $categoryId = $row_link['category_id'];
                if (!in_array($categoryId, $categoryIdList)) {
                    continue;
                }
            }

            $item_visibility = api_get_item_visibility(
                $course_info,
                TOOL_LINK,
                $row_link['id'],
                $session_id
            );
            if ($item_visibility != 2)  {
                $return .= '<li class="lp_resource_element" data_id="'.$row_link['id'].'" data_type="'.TOOL_LINK.'" title="'.$row_link['title'].'" >';
                $return .= '<a class="moved" href="#">';
                $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
                $return .= '</a> ';
                $return .= '<img alt="" src="../img/lp_link.gif" style="margin-right:5px;" title="" />';
                $return .= '<a href="' . api_get_self().'?'.api_get_cidreq().'&amp;action=add_item&amp;type=' . TOOL_LINK . '&amp;file=' . $row_link['id'] . '&amp;lp_id=' . $this->lp_id . '">'.
                    $row_link['title'].
                    '</a>';
                $return .= '</li>';
            }
        }
        $return .= '</ul>';

        return $return;
    }