/** * Returns a Form validator Obj * @param string $url * @param string $action add, edit * * @return FormValidator */ public function return_form($url, $action) { $form = new FormValidator('career', 'post', $url); // Setting the form elements $header = get_lang('Add'); if ($action == 'edit') { $header = get_lang('Modify'); } $form->addElement('header', $header); $id = isset($_GET['id']) ? intval($_GET['id']) : ''; $form->addElement('hidden', 'id', $id); $form->addElement('text', 'name', get_lang('Name'), array('size' => '70')); $form->addHtmlEditor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers', 'Width' => '100%', 'Height' => '250')); $status_list = $this->get_status_list(); $form->addElement('select', 'status', get_lang('Status'), $status_list); if ($action == 'edit') { $form->addElement('text', 'created_at', get_lang('CreatedAt')); $form->freeze('created_at'); } if ($action == 'edit') { $form->addButtonSave(get_lang('Modify'), 'submit'); } else { $form->addButtonCreate(get_lang('Add'), 'submit'); } // Setting the defaults $defaults = $this->get($id); if (!empty($defaults['created_at'])) { $defaults['created_at'] = api_convert_and_format_date($defaults['created_at']); } if (!empty($defaults['updated_at'])) { $defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']); } $form->setDefaults($defaults); // Setting the rules $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required'); return $form; }
} } } $form->setDefaults($defaults); if (isset($_POST['send'])) { Security::clear_token(); } $token = Security::get_token(); $form->addElement('hidden', 'sec_token'); //$form->setConstants(array('sec_token' => $token)); $defaults['sec_token'] = $token; $form->addElement('header', get_lang('DisplayTermsConditions')); if (isset($_POST['language'])) { $form->addElement('static', Security::remove_XSS($_POST['language'])); $form->addElement('hidden', 'language', Security::remove_XSS($_POST['language'])); $form->addHtmlEditor('content', get_lang('Content'), true, false, array('ToolbarSet' => 'TermsAndConditions', 'Width' => '100%', 'Height' => '250')); $form->addElement('radio', 'type', '', get_lang('HTMLText'), '0'); $form->addElement('radio', 'type', '', get_lang('PageLink'), '1'); $form->addElement('textarea', 'changes', get_lang('ExplainChanges'), array('width' => '20')); $preview = LegalManager::show_last_condition($term_preview); if ($term_preview['type'] != -1) { $form->addElement('label', get_lang('Preview'), $preview); } // Submit & preview button $navigator_info = api_get_navigator(); //ie6 fix if ($navigator_info['name'] == 'Internet Explorer' && $navigator_info['version'] == '6') { $buttons = '<div class="row" align="center"> <div class="formw"> <input type="submit" name="back" value="' . get_lang('Back') . '"/> <input type="submit" name="preview" value="' . get_lang('Preview') . '"/>
} else { echo '<div><em>' . get_lang('ThereIsNoAThematicSection') . '</em></div>'; } } elseif ($action == 'thematic_add' || $action == 'thematic_edit') { // Display form $form = new FormValidator('thematic_add', 'POST', 'index.php?action=thematic_add&' . api_get_cidreq()); if ($action == 'thematic_edit') { $form->addElement('header', '', get_lang('EditThematicSection')); } $form->addElement('hidden', 'sec_token', $token); $form->addElement('hidden', 'action', $action); if (!empty($thematic_id)) { $form->addElement('hidden', 'thematic_id', $thematic_id); } $form->addText('title', get_lang('Title'), true, array('size' => '50')); $form->addHtmlEditor('content', get_lang('Content'), false, false, array('ToolbarSet' => 'TrainingDescription', 'Height' => '150')); $form->addButtonSave(get_lang('Save')); $show_form = true; if (!empty($thematic_data)) { if (api_get_session_id()) { if ($thematic_data['session_id'] != api_get_session_id()) { $show_form = false; Display::display_error_message(get_lang('NotAllowedClickBack'), false); } } // set default values $default['title'] = $thematic_data['title']; $default['content'] = $thematic_data['content']; $form->setDefaults($default); } // error messages
/** * function which redefines Question::createAnswersForm * @param FormValidator $form */ public function createAnswersForm($form) { $nb_answers = isset($_POST['nb_answers']) ? $_POST['nb_answers'] : 4; $nb_answers += isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0); $obj_ex = Session::read('objExercise'); /* Mise en variable de Affichage "Reponses" et son icone, "N�", "Vrai", "Reponse" */ $html = '<table class="data_table"> <tr> <th width="10px"> ' . get_lang('Number') . ' </th> <th width="10px"> ' . get_lang('True') . ' </th> <th width="50%"> ' . get_lang('Answer') . ' </th>'; $html .= '<th>' . get_lang('Comment') . '</th>'; $html .= '</tr>'; $form->addElement('label', get_lang('Answers') . '<br /> <img src="../img/fill_field.png">', $html); $defaults = array(); $correct = 0; $answer = false; if (!empty($this->id)) { $answer = new Answer($this->id); $answer->read(); if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) { $nb_answers = $answer->nbrAnswers; } } #le nombre de r�ponses est bien enregistr� sous la forme int(nb) /* Ajout mise en forme nb reponse */ $form->addElement('hidden', 'nb_answers'); $boxes_names = array(); /* V�rification : Cr�action d'au moins une r�ponse */ if ($nb_answers < 1) { $nb_answers = 1; Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer')); } //D�but affichage score global dans la modification d'une question $scoreA = "0"; //par reponse $scoreG = "0"; //Global /* boucle pour sauvegarder les donn�es dans le tableau defaults */ for ($i = 1; $i <= $nb_answers; ++$i) { /* si la reponse est de type objet */ if (is_object($answer)) { $defaults['answer[' . $i . ']'] = $answer->answer[$i]; $defaults['comment[' . $i . ']'] = $answer->comment[$i]; $defaults['correct[' . $i . ']'] = $answer->correct[$i]; // start $scoreA = $answer->weighting[$i]; } if ($scoreA > 0) { $scoreG = $scoreG + $scoreA; } //------------- Fin //------------- Debut si un des scores par reponse est egal � 0 : la coche vaut 1 (coch�) if ($scoreA == 0) { $defaults['pts'] = 1; } $renderer =& $form->defaultRenderer(); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment[' . $i . ']'); //$renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting['.$i.']'); $answer_number = $form->addElement('text', 'counter[' . $i . ']', null, 'value="' . $i . '"'); $answer_number->freeze(); $form->addElement('checkbox', 'correct[' . $i . ']', null, null, 'class="checkbox"'); $boxes_names[] = 'correct[' . $i . ']'; $form->addHtmlEditor('answer[' . $i . ']', null, null, array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100')); $form->addRule('answer[' . $i . ']', get_lang('ThisFieldIsRequired'), 'required'); $form->addHtmlEditor('comment[' . $i . ']', null, null, array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '100')); $form->addElement('html', '</tr>'); } //--------- Mise en variable du score global lors d'une modification de la question/r�ponse $defaults['weighting[1]'] = round($scoreG); $form->addElement('html', '</div></div></table>'); //$form -> addElement ('html', '<br />'); $form->add_multiple_required_rule($boxes_names, get_lang('ChooseAtLeastOneCheckbox'), 'multiple_required'); //only 1 answer the all deal ... $form->addElement('text', 'weighting[1]', get_lang('Score')); global $pts; //--------- Creation coche pour ne pas prendre en compte les n�gatifs $form->addElement('checkbox', 'pts', '', get_lang('NoNegativeScore')); $form->addElement('html', '<br />'); // Affiche un message si le score n'est pas renseign� $form->addRule('weighting[1]', get_lang('ThisFieldIsRequired'), 'required'); global $text, $class; if ($obj_ex->edit_exercise_in_lp == true) { $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers'); $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers'); $form->addButtonSave($text, 'submitQuestion'); // setting the save button here and not in the question class.php } $renderer->setElementTemplate('{element} ', 'lessAnswers'); $renderer->setElementTemplate('{element} ', 'submitQuestion'); $renderer->setElementTemplate('{element}', 'moreAnswers'); $form->addElement('html', '</div></div>'); $defaults['correct'] = $correct; if (!empty($this->id)) { $form->setDefaults($defaults); } else { if ($this->isContent == 1) { $form->setDefaults($defaults); } } $form->setConstants(array('nb_answers' => $nb_answers)); }
$url = api_get_self(); } elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') { $form_title = get_lang('EditNews'); $url = api_get_self() . '?id=' . intval($_GET['id']); } $form = new FormValidator('system_announcement', 'post', $url); $form->addElement('header', '', $form_title); $form->addText('title', get_lang('Title'), true); $language_list = api_get_languages(); $language_list_with_keys = array(); $language_list_with_keys['all'] = get_lang('All'); for ($i = 0; $i < count($language_list['name']); $i++) { $language_list_with_keys[$language_list['folder'][$i]] = $language_list['name'][$i]; } $form->addElement('select', 'lang', get_lang('Language'), $language_list_with_keys); $form->addHtmlEditor('content', get_lang('Content'), true, false, array('ToolbarSet' => 'PortalNews', 'Width' => '100%', 'Height' => '300')); $form->addDateRangePicker('range', get_lang('StartTimeWindow'), true, array('id' => 'date_range')); $group = array(); $group[] = $form->createElement('checkbox', 'visible_teacher', null, get_lang('Teacher')); $group[] = $form->createElement('checkbox', 'visible_student', null, get_lang('Student')); $group[] = $form->createElement('checkbox', 'visible_guest', null, get_lang('Guest')); $form->addGroup($group, null, get_lang('Visible'), ''); $form->addElement('hidden', 'id'); $userGroup = new UserGroup(); $group_list = $userGroup->get_all(); if (!empty($group_list)) { $group_list = array_column($group_list, 'name', 'id'); $group_list[0] = get_lang('All'); $form->addElement('select', 'group', get_lang('AnnouncementForGroup'), $group_list); } $values['group'] = isset($values['group']) ? $values['group'] : '0';
/** * @param FormValidator $form * @param $extra_data * @param $form_name * @param bool $admin_permissions * @param null $user_id * @deprecated * @return array */ static function set_extra_fields_in_form($form, $extra_data, $admin_permissions = false, $user_id = null) { $user_id = intval($user_id); // EXTRA FIELDS $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC'); $jquery_ready_content = null; foreach ($extra as $field_details) { if (!$admin_permissions) { if ($field_details[6] == 0) { continue; } } switch ($field_details[2]) { case ExtraField::FIELD_TYPE_TEXT: $form->addElement('text', 'extra_' . $field_details[1], $field_details[3], array('size' => 40)); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); $form->applyFilter('extra_' . $field_details[1], 'html_filter'); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; case ExtraField::FIELD_TYPE_TEXTAREA: $form->addHtmlEditor('extra_' . $field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; case ExtraField::FIELD_TYPE_RADIO: $group = array(); foreach ($field_details[9] as $option_id => $option_details) { $options[$option_details[1]] = $option_details[2]; $group[] = $form->createElement('radio', 'extra_' . $field_details[1], $option_details[1], $option_details[2] . '<br />', $option_details[1]); } $form->addGroup($group, 'extra_' . $field_details[1], $field_details[3], ''); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; case ExtraField::FIELD_TYPE_SELECT: $get_lang_variables = false; if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) { $get_lang_variables = true; } $options = array(); foreach ($field_details[9] as $option_id => $option_details) { if ($get_lang_variables) { $options[$option_details[1]] = get_lang($option_details[2]); } else { $options[$option_details[1]] = $option_details[2]; } } if ($get_lang_variables) { $field_details[3] = get_lang($field_details[3]); } $form->addElement('select', 'extra_' . $field_details[1], $field_details[3], $options, array('id' => 'extra_' . $field_details[1])); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; case ExtraField::FIELD_TYPE_SELECT_MULTIPLE: $options = array(); foreach ($field_details[9] as $option_id => $option_details) { $options[$option_details[1]] = $option_details[2]; } $form->addElement('select', 'extra_' . $field_details[1], $field_details[3], $options, array('multiple' => 'multiple')); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; case ExtraField::FIELD_TYPE_DATE: $form->addDatePicker('extra_' . $field_details[1], $field_details[3]); $defaults['extra_' . $field_details[1]] = date('Y-m-d 12:00:00'); $form->setDefaults($defaults); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DATETIME: $form->addDateTimePicker('extra_' . $field_details[1], $field_details[3]); $defaults['extra_' . $field_details[1]] = date('Y-m-d 12:00:00'); $form->setDefaults($defaults); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DOUBLE_SELECT: foreach ($field_details[9] as $key => $element) { if ($element[2][0] == '*') { $values['*'][$element[0]] = str_replace('*', '', $element[2]); } else { $values[0][$element[0]] = $element[2]; } } $group = ''; $group[] = $form->createElement('select', 'extra_' . $field_details[1], '', $values[0], ''); $group[] = $form->createElement('select', 'extra_' . $field_details[1] . '*', '', $values['*'], ''); $form->addGroup($group, 'extra_' . $field_details[1], $field_details[3], ' '); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } /* Recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form */ if (array_key_exists('extra_' . $field_details[1], $extra_data)) { // exploding all the selected values (of both select forms) $selected_values = explode(';', $extra_data['extra_' . $field_details[1]]); $extra_data['extra_' . $field_details[1]] = array(); // looping through the selected values and assigning the selected values to either the first or second select form foreach ($selected_values as $key => $selected_value) { if (array_key_exists($selected_value, $values[0])) { $extra_data['extra_' . $field_details[1]]['extra_' . $field_details[1]] = $selected_value; } else { $extra_data['extra_' . $field_details[1]]['extra_' . $field_details[1] . '*'] = $selected_value; } } } break; case ExtraField::FIELD_TYPE_DIVIDER: $form->addElement('static', $field_details[1], '<br /><strong>' . $field_details[3] . '</strong>'); break; case ExtraField::FIELD_TYPE_TAG: //the magic should be here $user_tags = UserManager::get_user_tags($user_id, $field_details[0]); $tag_list = ''; if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tag_list .= '<option value="' . $tag['tag'] . '" class="selected">' . $tag['tag'] . '</option>'; } } $multi_select = '<select id="extra_' . $field_details[1] . '" name="extra_' . $field_details[1] . '"> ' . $tag_list . ' </select>'; $form->addElement('label', $field_details[3], $multi_select); $url = api_get_path(WEB_AJAX_PATH) . 'user_manager.ajax.php'; $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content = <<<EOF \$("#extra_{$field_details['1']}").fcbkcomplete({ json_url: "{$url}?a=search_tags&field_id={$field_details['0']}", cache: false, filter_case: true, filter_hide: true, complete_text:"{$complete_text}", firstselected: true, //onremove: "testme", //onselect: "testme", filter_selected: true, newel: true }); EOF; break; case ExtraField::FIELD_TYPE_TIMEZONE: $form->addElement('select', 'extra_' . $field_details[1], $field_details[3], api_get_timezones(), ''); if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } break; case ExtraField::FIELD_TYPE_SOCIAL_PROFILE: // get the social network's favicon $icon_path = UserManager::get_favicon_from_url($extra_data['extra_' . $field_details[1]], $field_details[4]); // special hack for hi5 $leftpad = '1.7'; $top = '0.4'; $domain = parse_url($icon_path, PHP_URL_HOST); if ($domain == 'www.hi5.com' or $domain == 'hi5.com') { $leftpad = '3'; $top = '0'; } // print the input field $form->addElement('text', 'extra_' . $field_details[1], $field_details[3], array('size' => 60, 'style' => 'background-image: url(\'' . $icon_path . '\'); background-repeat: no-repeat; background-position: 0.4em ' . $top . 'em; padding-left: ' . $leftpad . 'em; ')); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } break; case ExtraField::FIELD_TYPE_FILE: $extra_field = 'extra_' . $field_details[1]; $form->addElement('file', $extra_field, $field_details[3], null, ''); if ($extra_file_list = UserManager::build_user_extra_file_list($user_id, $field_details[1], '', true)) { $form->addElement('static', $extra_field . '_list', null, $extra_file_list); } if ($field_details[7] == 0) { $form->freeze($extra_field); } break; case ExtraField::FIELD_TYPE_MOBILE_PHONE_NUMBER: $form->addElement('text', 'extra_' . $field_details[1], $field_details[3] . " (" . get_lang('CountryDialCode') . ")", array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); $form->applyFilter('extra_' . $field_details[1], 'mobile_phone_number_filter'); $form->addRule('extra_' . $field_details[1], get_lang('MobilePhoneNumberWrong'), 'mobile_phone_number'); if (!$admin_permissions) { if ($field_details[7] == 0) { $form->freeze('extra_' . $field_details[1]); } } break; } } $return = array(); $return['jquery_ready_content'] = $jquery_ready_content; return $return; }
/** * Creates the form to create / edit an exercise * @param FormValidator $form */ public function createForm($form, $type = 'full') { if (empty($type)) { $type = 'full'; } // form title if (!empty($_GET['exerciseId'])) { $form_title = get_lang('ModifyExercise'); } else { $form_title = get_lang('NewEx'); } $form->addElement('header', $form_title); // Title. $form->addElement('text', 'exerciseTitle', get_lang('ExerciseName'), array('id' => 'exercise_title')); $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters')); $form->addElement('html', '<div id="advanced_params_options" style="display:none">'); $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150'); if (is_array($type)) { $editor_config = array_merge($editor_config, $type); } $form->addHtmlEditor('exerciseDescription', get_lang('ExerciseDescription'), false, false, $editor_config); if ($type == 'full') { //Can't modify a DirectFeedback question if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) { // feedback type $radios_feedback = array(); $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'), '0', array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')); if (api_get_setting('exercise.enable_quiz_scenario') == 'true') { //Can't convert a question from one feedback to another if there is more than 1 question already added if ($this->selectNbrQuestions() == 0) { $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')); } } $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'), '2', array('id' => 'exerciseType_2')); $form->addGroup($radios_feedback, null, array(get_lang('FeedbackType'), get_lang('FeedbackDisplayOptions')), ''); // Type of results display on the final page $radios_results_disabled = array(); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id' => 'result_disabled_0')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id' => 'result_disabled_2')); //$radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ExamModeWithFinalScoreShowOnlyFinalScoreWithCategoriesIfAvailable'), '3', array('id'=>'result_disabled_3','onclick' => 'check_results_disabled()')); $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), ''); // Type of questions disposition on page $radios = array(); $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')); $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2', array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')); $form->addGroup($radios, null, get_lang('QuestionsPerPage'), ''); } else { // if is Directfeedback but has not questions we can allow to modify the question type if ($this->selectNbrQuestions() == 0) { // feedback type $radios_feedback = array(); $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'), '0', array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')); if (api_get_setting('exercise.enable_quiz_scenario') == 'true') { $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')); } $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'), '2', array('id' => 'exerciseType_2')); $form->addGroup($radios_feedback, null, array(get_lang('FeedbackType'), get_lang('FeedbackDisplayOptions'))); //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"'); $radios_results_disabled = array(); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id' => 'result_disabled_0')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')); $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), ''); // Type of questions disposition on page $radios = array(); $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1'); $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2'); $form->addGroup($radios, null, get_lang('ExerciseType')); } else { //Show options freeze $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id' => 'result_disabled_0')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')); $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')); $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), ''); $result_disable_group->freeze(); //we force the options to the DirectFeedback exercisetype $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT); $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE); // Type of questions disposition on page $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')); $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2', array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')); $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'), ''); $type_group->freeze(); } } // number of random question $max = $this->id > 0 ? $this->selectNbrQuestions() : 10; $option = range(0, $max); $option[0] = get_lang('No'); $option[-1] = get_lang('AllQuestionsShort'); $form->addElement('select', 'randomQuestions', array(get_lang('RandomQuestions'), get_lang('RandomQuestionsHelp')), $option, array('id' => 'randomQuestions')); // Random answers $radios_random_answers = array(); $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'); $radios_random_answers[] = $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0'); $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'), ''); // Random by category $form->addElement('html', '<div class="clear"> </div>'); $radiocat = array(); $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesShuffled'), '1'); $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesSorted'), '2'); $radiocat[] = $form->createElement('radio', 'randomByCat', null, get_lang('No'), '0'); $radioCatGroup = $form->addGroup($radiocat, null, get_lang('RandomQuestionByCategory'), ''); $form->addElement('html', '<div class="clear"> </div>'); // add the radio display the category name for student $radio_display_cat_name = array(); $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'); $radio_display_cat_name[] = $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0'); $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'), ''); // Attempts $attempt_option = range(0, 10); $attempt_option[0] = get_lang('Infinite'); $form->addElement('select', 'exerciseAttempts', get_lang('ExerciseAttempts'), $attempt_option, ['id' => 'exerciseAttempts']); // Exercise time limit $form->addElement('checkbox', 'activate_start_date_check', null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()')); $var = Exercise::selectTimeLimit(); if ($this->start_time != '0000-00-00 00:00:00') { $form->addElement('html', '<div id="start_date_div" style="display:block;">'); } else { $form->addElement('html', '<div id="start_date_div" style="display:none;">'); } $form->addElement('date_time_picker', 'start_time'); $form->addElement('html', '</div>'); $form->addElement('checkbox', 'activate_end_date_check', null, get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()')); if ($this->end_time != '0000-00-00 00:00:00') { $form->addElement('html', '<div id="end_date_div" style="display:block;">'); } else { $form->addElement('html', '<div id="end_date_div" style="display:none;">'); } $form->addElement('date_time_picker', 'end_time'); $form->addElement('html', '</div>'); //$check_option=$this->selectType(); $diplay = 'block'; $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults')); $form->addElement('html', '<div class="clear"> </div>'); $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers')); $form->addElement('html', '<div id="divtimecontrol" style="display:' . $diplay . ';">'); //Timer control //$time_hours_option = range(0,12); //$time_minutes_option = range(0,59); $form->addElement('checkbox', 'enabletimercontrol', null, get_lang('EnableTimerControl'), array('onclick' => 'option_time_expired()', 'id' => 'enabletimercontrol', 'onload' => 'check_load_time()')); $expired_date = (int) $this->selectExpiredTime(); if ($expired_date != '0') { $form->addElement('html', '<div id="timercontrol" style="display:block;">'); } else { $form->addElement('html', '<div id="timercontrol" style="display:none;">'); } $form->addText('enabletimercontroltotalminutes', get_lang('ExerciseTotalDurationInMinutes'), false, ['id' => 'enabletimercontroltotalminutes', 'cols-size' => [2, 2, 8]]); $form->addElement('html', '</div>'); $form->addElement('text', 'pass_percentage', array(get_lang('PassPercentage'), null, '%'), array('id' => 'pass_percentage')); $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric'); // add the text_when_finished textbox $form->addHtmlEditor('text_when_finished', get_lang('TextWhenFinished'), false, false, $editor_config); $defaults = array(); if (api_get_setting('search.search_enabled') === 'true') { require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php'; $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument')); $form->addElement('select_language', 'language', get_lang('SearchFeatureDocumentLanguage')); $specific_fields = get_specific_field_list(); foreach ($specific_fields as $specific_field) { $form->addElement('text', $specific_field['code'], $specific_field['name']); $filter = array('c_id' => "'" . api_get_course_int_id() . "'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\'' . TOOL_QUIZ . '\''); $values = get_specific_field_values_list($filter, array('value')); if (!empty($values)) { $arr_str_values = array(); foreach ($values as $value) { $arr_str_values[] = $value['value']; } $defaults[$specific_field['code']] = implode(', ', $arr_str_values); } } //$form->addElement ('html','</div>'); } $form->addElement('html', '</div>'); //End advanced setting $form->addElement('html', '</div>'); } // submit if (isset($_GET['exerciseId'])) { $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise'); } else { $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise'); } $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required'); if ($type == 'full') { // rules $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric'); $form->addRule('start_time', get_lang('InvalidDate'), 'datetime'); $form->addRule('end_time', get_lang('InvalidDate'), 'datetime'); } // defaults if ($type == 'full') { if ($this->id > 0) { if ($this->random > $this->selectNbrQuestions()) { $defaults['randomQuestions'] = $this->selectNbrQuestions(); } else { $defaults['randomQuestions'] = $this->random; } $defaults['randomAnswers'] = $this->selectRandomAnswers(); $defaults['exerciseType'] = $this->selectType(); $defaults['exerciseTitle'] = $this->get_formated_title(); $defaults['exerciseDescription'] = $this->selectDescription(); $defaults['exerciseAttempts'] = $this->selectAttempts(); $defaults['exerciseFeedbackType'] = $this->selectFeedbackType(); $defaults['results_disabled'] = $this->selectResultsDisabled(); $defaults['propagate_neg'] = $this->selectPropagateNeg(); $defaults['review_answers'] = $this->review_answers; $defaults['randomByCat'] = $this->selectRandomByCat(); $defaults['text_when_finished'] = $this->selectTextWhenFinished(); $defaults['display_category_name'] = $this->selectDisplayCategoryName(); $defaults['pass_percentage'] = $this->selectPassPercentage(); if ($this->start_time != '0000-00-00 00:00:00') { $defaults['activate_start_date_check'] = 1; } if ($this->end_time != '0000-00-00 00:00:00') { $defaults['activate_end_date_check'] = 1; } $defaults['start_time'] = $this->start_time != '0000-00-00 00:00:00' ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00'); $defaults['end_time'] = $this->end_time != '0000-00-00 00:00:00' ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time() + 84600); // Get expired time if ($this->expired_time != '0') { $defaults['enabletimercontrol'] = 1; $defaults['enabletimercontroltotalminutes'] = $this->expired_time; } else { $defaults['enabletimercontroltotalminutes'] = 0; } } else { $defaults['exerciseType'] = 2; $defaults['exerciseAttempts'] = 0; $defaults['randomQuestions'] = 0; $defaults['randomAnswers'] = 0; $defaults['exerciseDescription'] = ''; $defaults['exerciseFeedbackType'] = 0; $defaults['results_disabled'] = 0; $defaults['randomByCat'] = 0; $defaults['text_when_finished'] = ""; $defaults['start_time'] = date('Y-m-d 12:00:00'); $defaults['display_category_name'] = 1; $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600); $defaults['pass_percentage'] = ''; } } else { $defaults['exerciseTitle'] = $this->selectTitle(); $defaults['exerciseDescription'] = $this->selectDescription(); } if (api_get_setting('search.search_enabled') === 'true') { $defaults['index_document'] = 'checked="checked"'; } $form->setDefaults($defaults); // Freeze some elements. if ($this->id != 0 && $this->edit_exercise_in_lp == false) { $elementsToFreeze = array('randomQuestions', 'exerciseAttempts', 'propagate_neg', 'enabletimercontrol', 'review_answers'); foreach ($elementsToFreeze as $elementName) { /** @var HTML_QuickForm_element $element */ $element = $form->getElement($elementName); $element->freeze(); } $radioCatGroup->freeze(); } }
// error messages if (isset($error)) { Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'), false); } if (!isset($error)) { $token = Security::get_token(); } $attendance_weight = floatval($attendance_weight); // display form $form = new FormValidator('attendance_edit', 'POST', 'index.php?action=attendance_edit&' . api_get_cidreq() . '&attendance_id=' . $attendance_id); $form->addElement('header', '', get_lang('Edit')); $form->addElement('hidden', 'sec_token', $token); $form->addElement('hidden', 'attendance_id', $attendance_id); $form->addText('title', get_lang('Title'), true); $form->applyFilter('title', 'html_filter'); $form->addHtmlEditor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); // Adavanced Parameters if (Gradebook::is_active()) { if (!empty($attendance_qualify_title) || !empty($attendance_weight)) { $form->addButtonAdvancedSettings('id_qualify'); $form->addElement('html', '<div id="id_qualify_options" style="display:block">'); $form->addElement('checkbox', 'attendance_qualify_gradebook', '', get_lang('QualifyAttendanceGradebook'), array('checked' => 'true', 'onclick' => 'javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}')); $form->addElement('html', '<div id="options_field" style="display:block">'); } else { $form->addButtonAdvancedSettings('id_qualify'); $form->addElement('html', '<div id="id_qualify_options" style="display:none">'); $form->addElement('checkbox', 'attendance_qualify_gradebook', '', get_lang('QualifyAttendanceGradebook'), 'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"'); $form->addElement('html', '<div id="options_field" style="display:none">'); } GradebookUtils::load_gradebook_select_in_tool($form); $form->addElement('text', 'attendance_qualify_title', get_lang('TitleColumnGradebook'));
/** * function which redefines Question::createAnswersForm * @param FormValidator $form */ function createAnswersForm($form) { $defaults = array(); if (!empty($this->id)) { $objAnswer = new Answer($this->id); $preArray = explode('@@', $objAnswer->selectAnswer(1)); $defaults['formula'] = array_pop($preArray); $defaults['answer'] = array_shift($preArray); $defaults['answer'] = preg_replace("/\\[.*\\]/", "", $defaults['answer']); $defaults['weighting'] = $this->weighting; } else { $defaults['answer'] = get_lang('DefaultTextInBlanks'); } $lowestValue = "1.00"; $highestValue = "20.00"; // javascript // echo '<script> function parseTextNumber(textNumber, floatValue) { if (textNumber.indexOf(".") > -1) { textNumber = parseFloat(textNumber); floatValue.exists = "true"; } else { textNumber = parseInt(textNumber); } return textNumber; } function updateRandomValue(element) { // "floatValue" helps to distinguish between an integer (10) and a float with all 0 decimals (10.00) var floatValue = { exists: "false" }; var index = (element.name).match(/\\[[^\\]]*\\]/g); var lowestValue = parseTextNumber(document.getElementById("lowestValue"+index).value, floatValue); var highestValue = parseTextNumber(document.getElementById("highestValue"+index).value, floatValue); var result = Math.random() * (highestValue - lowestValue) + lowestValue; if (floatValue.exists == "true") { result = parseFloat(result).toFixed(2); } else { result = parseInt(result); } document.getElementById("randomValue"+index).innerHTML = "' . get_lang("ExampleValue") . ': " + result; } CKEDITOR.on("instanceCreated", function(e) { if (e.editor.name === "answer") { e.editor.on("change", updateBlanks); } }); var firstTime = true; function updateBlanks(e) { if (firstTime) { field = document.getElementById("answer"); var answer = field.value; } else { var answer = e.editor.getData(); } var blanks = answer.match(/\\[[^\\]]*\\]/g); var fields = "<div class=\\"form-group\\"><label class=\\"col-sm-2\\">' . get_lang('VariableRanges') . '</label><div class=\\"col-sm-8\\"><table>"; if (blanks!=null) { if (typeof updateBlanks.randomValues === "undefined") { updateBlanks.randomValues = []; } for (i=0 ; i<blanks.length ; i++){ if (document.getElementById("lowestValue["+i+"]") && document.getElementById("highestValue["+i+"]")) { lowestValue = document.getElementById("lowestValue["+i+"]").value; highestValue = document.getElementById("highestValue["+i+"]").value; } else { lowestValue = ' . $lowestValue . '.toFixed(2); highestValue = ' . $highestValue . '.toFixed(2); for (j=0; j<blanks.length; j++) { updateBlanks.randomValues[j] = parseFloat(Math.random() * (highestValue - lowestValue) + lowestValue).toFixed(2); } } fields += "<tr><td><label>"+blanks[i]+"</label></td><td><input class=\\"span1\\" style=\\"margin-left: 0em;\\" size=\\"5\\" value=\\""+lowestValue+"\\" type=\\"text\\" id=\\"lowestValue["+i+"]\\" name=\\"lowestValue["+i+"]\\" onblur=\\"updateRandomValue(this)\\"/></td><td><input class=\\"span1\\" style=\\"margin-left: 0em; width:80px;\\" size=\\"5\\" value=\\""+highestValue+"\\" type=\\"text\\" id=\\"highestValue["+i+"]\\" name=\\"highestValue["+i+"]\\" onblur=\\"updateRandomValue(this)\\"/></td><td><label class=\\"span3\\" id=\\"randomValue["+i+"]\\"/>' . get_lang('ExampleValue') . ': "+updateBlanks.randomValues[i]+"</label></td></tr>"; } } document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>"; if (firstTime) { firstTime = false; } } window.onload = updateBlanks; </script>'; // answer $form->addElement('label', null, '<br /><br />' . get_lang('TypeTextBelow') . ', ' . get_lang('And') . ' ' . get_lang('UseTagForBlank')); $form->addHtmlEditor('answer', Display::return_icon('fill_field.png'), false, array('id' => 'answer', 'onkeyup' => 'javascript: updateBlanks(this);'), array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '350')); $form->addRule('answer', get_lang('GiveText'), 'required'); $form->addRule('answer', get_lang('DefineBlanks'), 'regex', '/\\[.*\\]/'); $form->addElement('label', null, get_lang('IfYouWantOnlyIntegerValuesWriteBothLimitsWithoutDecimals')); $form->addElement('html', '<div id="blanks_weighting"></div>'); $notationListButton = Display::url(get_lang('NotationList'), api_get_path(WEB_PATH) . 'main/exercice/evalmathnotation.php', array('class' => 'btn ajax', 'data-title' => get_lang('NotationList'), '_target' => '_blank')); $form->addElement('label', null, $notationListButton); $form->addElement('label', null, get_lang('FormulaExample')); $form->addElement('text', 'formula', get_lang('Formula'), array('id' => 'formula')); $form->addRule('formula', get_lang('GiveFormula'), 'required'); $form->addElement('text', 'weighting', get_lang('Weighting'), array('id' => 'weighting')); $form->setDefaults(array('weighting' => '10')); $form->addElement('text', 'answerVariations', get_lang('AnswerVariations')); $form->addRule('answerVariations', get_lang('GiveAnswerVariations'), 'required'); $form->setDefaults(array('answerVariations' => '1')); global $text; // setting the save button here and not in the question class.php $form->addButtonSave($text, 'submitQuestion'); if (!empty($this->id)) { $form->setDefaults($defaults); } else { if ($this->isContent == 1) { $form->setDefaults($defaults); } } }
/** * This function displays the form that is used to edit a post. This can be a new thread or a reply. * @param array contains all the information about the current post * @param array contains all the information about the current thread * @param array contains all info about the current forum (to check if attachments are allowed) * @param array contains the default values to fill the form * @return void * * @author Patrick Cool <*****@*****.**>, Ghent University * @version february 2006, dokeos 1.8 */ function show_edit_post_form($forum_setting, $current_post, $current_thread, $current_forum, $form_values = '', $id_attach = 0) { // Initialize the object. $form = new FormValidator('edit_post', 'post', api_get_self() . '?' . api_get_cidreq() . '&forum=' . Security::remove_XSS($_GET['forum']) . '&thread=' . Security::remove_XSS($_GET['thread']) . '&post=' . Security::remove_XSS($_GET['post'])); $form->addElement('header', get_lang('EditPost')); // Setting the form elements. $form->addElement('hidden', 'post_id', $current_post['post_id']); $form->addElement('hidden', 'thread_id', $current_thread['thread_id']); $form->addElement('hidden', 'id_attach', $id_attach); if ($current_post['post_parent_id'] == 0) { $form->addElement('hidden', 'is_first_post_of_thread', '1'); } $form->addElement('text', 'post_title', get_lang('Title')); $form->applyFilter('post_title', 'html_filter'); $form->addHtmlEditor('post_text', get_lang('Text'), null, null, api_is_allowed_to_edit(null, true) ? array('ToolbarSet' => 'Forum', 'Width' => '100%', 'Height' => '400') : array('ToolbarSet' => 'ForumStudent', 'Width' => '100%', 'Height' => '400', 'UserStatus' => 'student')); $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required'); $form->addButtonAdvancedSettings('advanced_params'); $form->addElement('html', '<div id="advanced_params_options" style="display:none">'); if (!isset($_GET['edit'])) { if (Gradebook::is_active()) { $form->addElement('label', '<strong>' . get_lang('AlterQualifyThread') . '</strong>'); $form->addElement('checkbox', 'thread_qualify_gradebook', '', get_lang('QualifyThreadGradebook'), 'onclick="javascript: if(this.checked){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"'); $link_info = GradebookUtils::is_resource_in_course_gradebook(api_get_course_id(), 5, $_GET['thread'], api_get_session_id()); if (!empty($link_info)) { $defaults['thread_qualify_gradebook'] = true; $defaults['category_id'] = $link_info['category_id']; } else { $defaults['thread_qualify_gradebook'] = false; $defaults['category_id'] = ''; } } else { $form->addElement('hidden', 'thread_qualify_gradebook', false); $defaults['thread_qualify_gradebook'] = false; } if (!empty($defaults['thread_qualify_gradebook'])) { $form->addElement('html', '<div id="options_field" style="display:block">'); } else { $form->addElement('html', '<div id="options_field" style="display:none">'); } // Loading gradebook select GradebookUtils::load_gradebook_select_in_tool($form); $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric'), array('value' => $current_thread['thread_qualify_max'], 'style' => 'width:40px')); $form->applyFilter('numeric_calification', 'html_filter'); $form->addElement('text', 'calification_notebook_title', get_lang('TitleColumnGradebook'), array('value' => $current_thread['thread_title_qualify'])); $form->applyFilter('calification_notebook_title', 'html_filter'); $form->addElement('text', 'weight_calification', array(get_lang('QualifyWeight'), null, ''), array('value' => $current_thread['thread_weight'], 'style' => 'width:40px')); $form->applyFilter('weight_calification', 'html_filter'); $group = array(); $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1); $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0); $form->addGroup($group, '', [get_lang('ForumThreadPeerScoring'), get_lang('ForumThreadPeerScoringComment')], ' '); $form->addElement('html', '</div>'); } if ($forum_setting['allow_post_notification']) { $form->addElement('checkbox', 'post_notification', '', get_lang('NotifyByEmail') . ' (' . $current_post['email'] . ')'); } if ($forum_setting['allow_sticky'] && api_is_allowed_to_edit(null, true) && $current_post['post_parent_id'] == 0) { // The sticky checkbox only appears when it is the first post of a thread. $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost')); if ($current_thread['thread_sticky'] == 1) { $defaults['thread_sticky'] = true; } } if ($current_forum['allow_attachments'] == '1' || api_is_allowed_to_edit(null, true)) { if (empty($form_values) && !isset($_POST['SubmitPost'])) { //edit_added_resources('forum_post', $current_post['post_id']); } } $form->addElement('html', '</div>'); $form->addFile('user_upload[]', get_lang('Attachment')); $form->addButton('add_attachment', get_lang('AddAttachment'), 'paperclip', 'default', 'default', null, ['id' => 'reply-add-attachment']); $form->addButtonUpdate(get_lang('ModifyThread'), 'SubmitPost'); // Setting the default values for the form elements. $defaults['post_title'] = $current_post['post_title']; $defaults['post_text'] = $current_post['post_text']; if ($current_post['post_notification'] == 1) { $defaults['post_notification'] = true; } if (!empty($form_values)) { $defaults['post_notification'] = Security::remove_XSS($form_values['post_notification']); $defaults['thread_sticky'] = Security::remove_XSS($form_values['thread_sticky']); } $defaults['thread_peer_qualify'] = intval($current_thread['thread_peer_qualify']); $form->setDefaults($defaults); // The course admin can make a thread sticky (=appears with special icon and always on top). $form->addRule('post_title', get_lang('ThisFieldIsRequired'), 'required'); // Validation or display if ($form->validate()) { $values = $form->exportValues(); if (isset($values['thread_qualify_gradebook']) && $values['thread_qualify_gradebook'] == '1' && empty($values['weight_calification'])) { Display::display_error_message(get_lang('YouMustAssignWeightOfQualification') . ' <a href="javascript:window.history.go(-1);">' . get_lang('Back') . '</a>', false); return false; } return $values; } else { // Delete from $_SESSION forum attachment from other posts clearAttachedFiles($current_post['post_id']); // Get forum attachment ajax table to add it to form $fileData = getAttachmentsAjaxTable($current_post['post_id'], $current_forum['forum_id']); $form->addElement('html', $fileData); $form->display(); } }
/** * This function displays the form that is used to add a post. This can be a new thread or a reply. * @param array $current_forum * @param array $forum_setting * @param string $action is the parameter that determines if we are * 1. newthread: adding a new thread (both empty) => No I-frame * 2. replythread: Replying to a thread ($action = replythread) => I-frame with the complete thread (if enabled) * 3. replymessage: Replying to a message ($action =replymessage) => I-frame with the complete thread (if enabled) (I first thought to put and I-frame with the message only) * 4. quote: Quoting a message ($action= quotemessage) => I-frame with the complete thread (if enabled). The message will be in the reply. (I first thought not to put an I-frame here) * @return void HMTL * @author Patrick Cool <*****@*****.**>, Ghent University * @version february 2006, dokeos 1.8 */ function show_add_post_form($current_forum, $forum_setting, $action = '', $id = '', $form_values = '') { $_user = api_get_user_info(); $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null; // Initialize the object. $myThread = isset($_GET['thread']) ? $_GET['thread'] : ''; $my_forum = isset($_GET['forum']) ? $_GET['forum'] : ''; $my_post = isset($_GET['post']) ? $_GET['post'] : ''; $my_gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : ''; $form = new FormValidator('thread', 'post', api_get_self() . '?forum=' . Security::remove_XSS($my_forum) . '&' . api_get_cidreq() . '&thread=' . Security::remove_XSS($myThread) . '&post=' . Security::remove_XSS($my_post) . '&action=' . $action); $form->setConstants(array('forum' => '5')); // Setting the form elements. $form->addElement('hidden', 'forum_id', intval($my_forum)); $form->addElement('hidden', 'thread_id', intval($myThread)); $form->addElement('hidden', 'gradebook', $my_gradebook); // If anonymous posts are allowed we also display a form to allow the user to put his name or username in. if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) { $form->addElement('text', 'poster_name', get_lang('Name')); $form->applyFilter('poster_name', 'html_filter'); } $form->addElement('text', 'post_title', get_lang('Title')); $form->addHtmlEditor('post_text', get_lang('Text'), true, api_is_allowed_to_edit(null, true) ? array('ToolbarSet' => 'Forum', 'Width' => '100%', 'Height' => '300') : array('ToolbarSet' => 'ForumStudent', 'Width' => '100%', 'Height' => '300', 'UserStatus' => 'student')); $form->addRule('post_text', get_lang('ThisFieldIsRequired'), 'required'); $iframe = null; $myThread = Security::remove_XSS($myThread); if ($forum_setting['show_thread_iframe_on_reply'] && $action != 'newthread' && !empty($myThread)) { $iframe = "<iframe style=\"border: 1px solid black\" src=\"iframe_thread.php?" . api_get_cidreq() . "&forum=" . Security::remove_XSS($my_forum) . "&thread=" . $myThread . "#" . Security::remove_XSS($my_post) . "\" width=\"100%\"></iframe>"; } if (!empty($iframe)) { $form->addElement('label', get_lang('Thread'), $iframe); } $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters')); $form->addElement('html', '<div id="advanced_params_options" style="display:none">'); if ((api_is_course_admin() || api_is_course_coach() || api_is_course_tutor()) && !$myThread) { // Thread qualify if (Gradebook::is_active()) { //Loading gradebook select GradebookUtils::load_gradebook_select_in_tool($form); $form->addElement('checkbox', 'thread_qualify_gradebook', '', get_lang('QualifyThreadGradebook'), 'onclick="javascript:if(this.checked==true){document.getElementById(\'options_field\').style.display = \'block\';}else{document.getElementById(\'options_field\').style.display = \'none\';}"'); } else { $form->addElement('hidden', 'thread_qualify_gradebook', false); } $form->addElement('html', '<div id="options_field" style="display:none">'); $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric')); $form->applyFilter('numeric_calification', 'html_filter'); $form->addElement('text', 'calification_notebook_title', get_lang('TitleColumnGradebook')); $form->applyFilter('calification_notebook_title', 'html_filter'); $form->addElement('text', 'weight_calification', get_lang('QualifyWeight'), array('value' => '0.00', 'onfocus' => "javascript: this.select();")); $form->applyFilter('weight_calification', 'html_filter'); $group = array(); $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('Yes'), 1); $group[] = $form->createElement('radio', 'thread_peer_qualify', null, get_lang('No'), 0); $form->addGroup($group, '', [get_lang('ForumThreadPeerScoring'), get_lang('ForumThreadPeerScoringComment')], ' '); $form->addElement('html', '</div>'); } if ($forum_setting['allow_post_notification'] && isset($_user['user_id'])) { $form->addElement('checkbox', 'post_notification', '', get_lang('NotifyByEmail') . ' (' . $_user['mail'] . ')'); } if ($forum_setting['allow_sticky'] && api_is_allowed_to_edit(null, true) && $action == 'newthread') { $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost')); } if ($current_forum['allow_attachments'] == '1' || api_is_allowed_to_edit(null, true)) { $values = $form->exportValues(); } $form->addElement('html', '</div>'); if (in_array($action, ['quote', 'replymessage'])) { $form->addFile('user_upload[]', get_lang('Attachment')); $form->addButton('add_attachment', get_lang('AddAttachment'), 'paperclip', 'default', 'default', null, ['id' => 'reply-add-attachment']); } else { $form->addFile('user_upload', get_lang('Attachment')); } // Setting the class and text of the form title and submit button. if ($action == 'quote') { $form->addButtonCreate(get_lang('QuoteMessage'), 'SubmitPost'); } elseif ($action == 'replythread') { $form->addButtonCreate(get_lang('ReplyToThread'), 'SubmitPost'); } elseif ($action == 'replymessage') { $form->addButtonCreate(get_lang('ReplyToMessage'), 'SubmitPost'); } else { $form->addButtonCreate(get_lang('CreateThread'), 'SubmitPost'); } if (!empty($form_values)) { $defaults['post_title'] = prepare4display($form_values['post_title']); $defaults['post_text'] = prepare4display($form_values['post_text']); $defaults['post_notification'] = strval(intval($form_values['post_notification'])); $defaults['thread_sticky'] = strval(intval($form_values['thread_sticky'])); $defaults['thread_peer_qualify'] = intval($form_values['thread_peer_qualify']); } else { $defaults['thread_peer_qualify'] = 0; } // If we are quoting a message we have to retrieve the information of the post we are quoting so that // we can add this as default to the textarea. if (($action == 'quote' || $action == 'replymessage') && isset($my_post)) { // We also need to put the parent_id of the post in a hidden form when we are quoting or replying to a message (<> reply to a thread !!!) $form->addElement('hidden', 'post_parent_id', intval($my_post)); // If we are replying or are quoting then we display a default title. $values = get_post_information($my_post); $defaults['post_title'] = get_lang('ReplyShort') . api_html_entity_decode($values['post_title'], ENT_QUOTES); // When we are quoting a message then we have to put that message into the wysiwyg editor. // Note: The style has to be hardcoded here because using class="quote" didn't work. if ($action == 'quote') { $defaults['post_text'] = '<div> </div><div style="margin: 5px;"><div style="font-size: 90%; font-style: italic;">' . get_lang('Quoting') . ' ' . api_get_person_name($values['firstname'], $values['lastname']) . ':</div><div style="color: #006600; font-size: 90%; font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">' . prepare4display($values['post_text']) . '</div></div><div> </div><div> </div>'; } } $form->setDefaults(isset($defaults) ? $defaults : null); // The course admin can make a thread sticky (=appears with special icon and always on top). $form->addRule('post_title', get_lang('ThisFieldIsRequired'), 'required'); if ($current_forum['allow_anonymous'] == 1 && !isset($_user['user_id'])) { $form->addRule('poster_name', get_lang('ThisFieldIsRequired'), 'required'); } // Validation or display if ($form->validate()) { $check = Security::check_token('post'); if ($check) { $values = $form->exportValues(); if (isset($values['thread_qualify_gradebook']) && $values['thread_qualify_gradebook'] == '1' && empty($values['weight_calification'])) { Display::display_error_message(get_lang('YouMustAssignWeightOfQualification') . ' <a href="javascript:window.history.go(-1);">' . get_lang('Back') . '</a>', false); return false; } Security::clear_token(); return $values; } } else { $token = Security::get_token(); $form->addElement('hidden', 'sec_token'); $form->setConstants(array('sec_token' => $token)); // Delete from $_SESSION forum attachment from other posts // and keep only attachments for new post clearAttachedFiles(FORUM_NEW_POST); // Get forum attachment ajax table to add it to form $attachmentAjaxTable = getAttachmentsAjaxTable(0, $current_forum['forum_id']); $ajaxHtml = $attachmentAjaxTable; $form->addElement('html', $ajaxHtml); $form->display(); } }
if (api_get_setting('profile', 'language') !== 'true') { $form->freeze('language'); } //THEME if (is_profile_editable() && api_get_setting('profile.user_selected_theme') == 'true') { $form->addElement('SelectTheme', 'theme', get_lang('Theme')); if (api_get_setting('profile', 'theme') !== 'true') { $form->freeze('theme'); } $form->applyFilter('theme', 'trim'); } // EXTENDED PROFILE this make the page very slow! if (api_get_setting('profile.extended_profile') == 'true') { $width_extended_profile = 500; // MY COMPETENCES $form->addHtmlEditor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')); // MY DIPLOMAS $form->addHtmlEditor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')); // WHAT I AM ABLE TO TEACH $form->addHtmlEditor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')); // MY PRODUCTIONS $form->addElement('file', 'production', get_lang('MyProductions')); if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) { $form->addElement('static', 'productions_list', null, $production_list); } // MY PERSONAL OPEN AREA $form->addHtmlEditor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350')); // openarea is untrimmed for maximum openness $form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes'); $form->applyFilter(array('competences', 'diplomas', 'teach'), 'trim'); }
/** * @param FormValidator $form * * @return array */ public static function setForm(FormValidator &$form, $sessionId = 0) { $categoriesList = SessionManager::get_all_session_category(); $userInfo = api_get_user_info(); $categoriesOptions = array('0' => get_lang('None')); if ($categoriesList != false) { foreach ($categoriesList as $categoryItem) { $categoriesOptions[$categoryItem['id']] = $categoryItem['name']; } } // Database Table Definitions $tbl_user = Database::get_main_table(TABLE_MAIN_USER); $form->addElement('text', 'name', get_lang('SessionName'), array('maxlength' => 50)); $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('name', get_lang('SessionNameAlreadyExists'), 'callback', 'check_session_name'); if (!api_is_platform_admin() && api_is_teacher()) { $form->addElement('select', 'coach_username', get_lang('CoachName'), [api_get_user_id() => $userInfo['complete_name']], array('id' => 'coach_username', 'class' => 'chzn-select', 'style' => 'width:370px;')); } else { $sql = "SELECT COUNT(1) FROM {$tbl_user} WHERE status = 1"; $rs = Database::query($sql); $countUsers = Database::result($rs, 0, 0); if (intval($countUsers) < 50) { $orderClause = "ORDER BY "; $orderClause .= api_sort_by_first_name() ? "firstname, lastname, username" : "lastname, firstname, username"; $sql = "SELECT user_id, lastname, firstname, username\n FROM {$tbl_user}\n WHERE status = '1' " . $orderClause; if (api_is_multiple_url_enabled()) { $userRelAccessUrlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER); $accessUrlId = api_get_current_access_url_id(); if ($accessUrlId != -1) { $sql = "SELECT user.user_id, username, lastname, firstname\n FROM {$tbl_user} user\n INNER JOIN {$userRelAccessUrlTable} url_user\n ON (url_user.user_id = user.user_id)\n WHERE\n access_url_id = {$accessUrlId} AND\n status = 1 " . $orderClause; } } $result = Database::query($sql); $coachesList = Database::store_result($result); $coachesOptions = array(); foreach ($coachesList as $coachItem) { $coachesOptions[$coachItem['user_id']] = api_get_person_name($coachItem['firstname'], $coachItem['lastname']) . ' (' . $coachItem['username'] . ')'; } $form->addElement('select', 'coach_username', get_lang('CoachName'), $coachesOptions); } else { $form->addElement('select_ajax', 'coach_username', get_lang('CoachName'), null, ['url' => api_get_path(WEB_AJAX_PATH) . 'session.ajax.php?a=search_general_coach', 'width' => '100%']); } } $form->addRule('coach_username', get_lang('ThisFieldIsRequired'), 'required'); $form->addHtml('<div id="ajax_list_coachs"></div>'); $form->addButtonAdvancedSettings('advanced_params'); $form->addElement('html', '<div id="advanced_params_options" style="display:none">'); $form->addSelect('session_category', get_lang('SessionCategory'), $categoriesOptions, array('id' => 'session_category', 'class' => 'chzn-select', 'style' => 'width:370px;')); $form->addHtmlEditor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'Minimal')); $form->addElement('checkbox', 'show_description', null, get_lang('ShowDescription')); $visibilityGroup = array(); $visibilityGroup[] = $form->createElement('select', 'session_visibility', null, array(SESSION_VISIBLE_READ_ONLY => get_lang('SessionReadOnly'), SESSION_VISIBLE => get_lang('SessionAccessible'), SESSION_INVISIBLE => api_ucfirst(get_lang('SessionNotAccessible')))); $form->addGroup($visibilityGroup, 'visibility_group', get_lang('SessionVisibility'), null, false); $options = [0 => get_lang('ByDuration'), 1 => get_lang('ByDates')]; $form->addSelect('access', get_lang('Access'), $options, array('onchange' => 'accessSwitcher()', 'id' => 'access')); $form->addElement('html', '<div id="duration" style="display:none">'); $form->addElement('number', 'duration', array(get_lang('SessionDurationTitle'), get_lang('SessionDurationDescription')), array('maxlength' => 50)); $form->addElement('html', '</div>'); $form->addElement('html', '<div id="date_fields" style="display:none">'); // Dates $form->addDateTimePicker('access_start_date', array(get_lang('SessionStartDate'), get_lang('SessionStartDateComment')), array('id' => 'access_start_date')); $form->addDateTimePicker('access_end_date', array(get_lang('SessionEndDate'), get_lang('SessionEndDateComment')), array('id' => 'access_end_date')); $form->addRule(array('access_start_date', 'access_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty'); $form->addDateTimePicker('display_start_date', array(get_lang('SessionDisplayStartDate'), get_lang('SessionDisplayStartDateComment')), array('id' => 'display_start_date')); $form->addDateTimePicker('display_end_date', array(get_lang('SessionDisplayEndDate'), get_lang('SessionDisplayEndDateComment')), array('id' => 'display_end_date')); $form->addRule(array('display_start_date', 'display_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty'); $form->addDateTimePicker('coach_access_start_date', array(get_lang('SessionCoachStartDate'), get_lang('SessionCoachStartDateComment')), array('id' => 'coach_access_start_date')); $form->addDateTimePicker('coach_access_end_date', array(get_lang('SessionCoachEndDate'), get_lang('SessionCoachEndDateComment')), array('id' => 'coach_access_end_date')); $form->addRule(array('coach_access_start_date', 'coach_access_end_date'), get_lang('StartDateMustBeBeforeTheEndDate'), 'compare_datetime_text', '< allow_empty'); $form->addElement('html', '</div>'); $form->addCheckBox('send_subscription_notification', [get_lang('SendSubscriptionNotification'), get_lang('SendAnEmailWhenAUserBeingSubscribed')]); // Extra fields $extra_field = new ExtraField('session'); $extra = $extra_field->addElements($form, $sessionId); $form->addElement('html', '</div>'); $js = $extra['jquery_ready_content']; return ['js' => $js]; }
return !DocumentManager::documentExists($dir . $cleanName . '.html', api_get_course_info(), api_get_session_id(), api_get_group_id()); } // Add group to the form if ($is_certificate_mode) { $form->addText('title', get_lang('CertificateName'), true, array('cols-size' => [2, 10, 0], 'autofocus')); } else { $form->addText('title', get_lang('Title'), true, array('cols-size' => [2, 10, 0], 'autofocus')); } // Show read-only box only in groups if (!empty($groupId)) { $group[] = $form->createElement('checkbox', 'readonly', '', get_lang('ReadOnly')); } $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('title', get_lang('FileExists'), 'callback', 'document_exists'); $current_session_id = api_get_session_id(); $form->addHtmlEditor('content', '', true, false, $editorConfig); // Comment-field $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit); // If we are not in the certificates creation, display a folder chooser for the // new document created if (!$is_certificate_mode && !DocumentManager::is_my_shared_folder($userId, $dir, $current_session_id)) { $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit); //$parent_select = $form->addElement('select', 'curdirpath', array(null, get_lang('DestinationDirectory'))); $parent_select = $form->addSelect('curdirpath', get_lang('DestinationDirectory'), null, array('cols-size' => [2, 10, 0])); // Following two conditions copied from document.inc.php::build_directory_selector() $folder_titles = array(); if (is_array($folders)) { $escaped_folders = array(); foreach ($folders as $key => &$val) { // Hide some folders if ($val == '/HotPotatoes_files' || $val == '/certificates' || basename($val) == 'css') {
/** * function which redefines Question::createAnswersForm * @param FormValidator $form */ public function createAnswersForm($form) { // Getting the exercise list $obj_ex = Session::read('objExercise'); $editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125'); //this line defines how many questions by default appear when creating a choice question // The previous default value was 2. See task #1759. $nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 4; $nb_answers += isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0); /* Types of Feedback $feedback_option[0]=get_lang('Feedback'); $feedback_option[1]=get_lang('DirectFeedback'); $feedback_option[2]=get_lang('NoFeedback'); */ $feedback_title = ''; if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { //Scenario $comment_title = '<th width="20%">' . get_lang('Comment') . '</th>'; $feedback_title = '<th width="20%">' . get_lang('Scenario') . '</th>'; } else { $comment_title = '<th width="40%">' . get_lang('Comment') . '</th>'; } $html = '<table class="table table-striped table-hover"> <thead> <tr style="text-align: center;"> <th width="5%">' . get_lang('Number') . '</th> <th width="5%"> ' . get_lang('True') . '</th> <th width="40%">' . get_lang('Answer') . '</th> ' . $comment_title . ' ' . $feedback_title . ' <th width="10%">' . get_lang('Weighting') . '</th> </tr> </thead> <tbody>'; $form->addHeader(get_lang('Answers')); $form->addHtml($html); $defaults = array(); $correct = 0; if (!empty($this->id)) { $answer = new Answer($this->id); $answer->read(); if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) { $nb_answers = $answer->nbrAnswers; } } $form->addElement('hidden', 'nb_answers'); //Feedback SELECT $question_list = $obj_ex->selectQuestionList(); $select_question = array(); $select_question[0] = get_lang('SelectTargetQuestion'); if (is_array($question_list)) { foreach ($question_list as $key => $questionid) { //To avoid warning messages if (!is_numeric($questionid)) { continue; } $question = Question::read($questionid); $select_question[$questionid] = 'Q' . $key . ' :' . cut($question->selectTitle(), 20); } } $select_question[-1] = get_lang('ExitTest'); $list = new LearnpathList(api_get_user_id()); $flat_list = $list->get_flat_list(); $select_lp_id = array(); $select_lp_id[0] = get_lang('SelectTargetLP'); foreach ($flat_list as $id => $details) { $select_lp_id[$id] = cut($details['lp_name'], 20); } $temp_scenario = array(); if ($nb_answers < 1) { $nb_answers = 1; Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer')); } for ($i = 1; $i <= $nb_answers; ++$i) { $form->addHtml('<tr>'); if (isset($answer) && is_object($answer)) { if ($answer->correct[$i]) { $correct = $i; } $defaults['answer[' . $i . ']'] = $answer->answer[$i]; $defaults['comment[' . $i . ']'] = $answer->comment[$i]; $defaults['weighting[' . $i . ']'] = float_format($answer->weighting[$i], 1); $item_list = explode('@@', $answer->destination[$i]); $try = isset($item_list[0]) ? $item_list[0] : ''; $lp = isset($item_list[1]) ? $item_list[1] : ''; $list_dest = isset($item_list[2]) ? $item_list[2] : ''; $url = isset($item_list[3]) ? $item_list[3] : ''; if ($try == 0) { $try_result = 0; } else { $try_result = 1; } if ($url == 0) { $url_result = ''; } else { $url_result = $url; } $temp_scenario['url' . $i] = $url_result; $temp_scenario['try' . $i] = $try_result; $temp_scenario['lp' . $i] = $lp; $temp_scenario['destination' . $i] = $list_dest; } else { $defaults['answer[1]'] = get_lang('DefaultUniqueAnswer1'); $defaults['weighting[1]'] = 10; $defaults['answer[2]'] = get_lang('DefaultUniqueAnswer2'); $defaults['weighting[2]'] = 0; $temp_scenario['destination' . $i] = array('0'); $temp_scenario['lp' . $i] = array('0'); } $defaults['scenario'] = $temp_scenario; $renderer = $form->defaultRenderer(); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting[' . $i . ']'); $answer_number = $form->addElement('text', 'counter[' . $i . ']', null, ' value = "' . $i . '"'); $answer_number->freeze(); $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox"'); $form->addHtmlEditor('answer[' . $i . ']', null, null, true, $editor_config); $form->addRule('answer[' . $i . ']', get_lang('ThisFieldIsRequired'), 'required'); if ($obj_ex->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { $form->addHtmlEditor('comment[' . $i . ']', null, null, false, $editor_config); // Direct feedback //Adding extra feedback fields $group = array(); $group['try' . $i] = $form->createElement('checkbox', 'try' . $i, null, get_lang('TryAgain')); $group['lp' . $i] = $form->createElement('select', 'lp' . $i, get_lang('SeeTheory') . ': ', $select_lp_id); $group['destination' . $i] = $form->createElement('select', 'destination' . $i, get_lang('GoToQuestion') . ': ', $select_question); $group['url' . $i] = $form->createElement('text', 'url' . $i, get_lang('Other') . ': ', array('class' => 'col-md-2', 'placeholder' => get_lang('Other'))); $form->addGroup($group, 'scenario'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}', 'scenario'); } else { $form->addHtmlEditor('comment[' . $i . ']', null, null, false, $editor_config); } $form->addText('weighting[' . $i . ']', null, null, array('value' => '0')); $form->addHtml('</tr>'); } $form->addHtml('</tbody>'); $form->addHtml('</table>'); global $text; $buttonGroup = []; //ie6 fix if ($obj_ex->edit_exercise_in_lp == true) { //setting the save button here and not in the question class.php $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true); $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true); $buttonGroup[] = $form->addButtonSave($text, 'submitQuestion', true); $form->addGroup($buttonGroup); } // We check the first radio button to be sure a radio button will be check if ($correct == 0) { $correct = 1; } $defaults['correct'] = $correct; if (!empty($this->id)) { $form->setDefaults($defaults); } else { if ($this->isContent == 1) { // Default sample content. $form->setDefaults($defaults); } else { $form->setDefaults(array('correct' => 1)); } } $form->setConstants(array('nb_answers' => $nb_answers)); }
$introduction_section = ''; global $charset; $intro_cmdEdit = empty($_GET['intro_cmdEdit']) ? '' : $_GET['intro_cmdEdit']; $intro_cmdUpdate = isset($_POST['intro_cmdUpdate']); $intro_cmdDel = empty($_GET['intro_cmdDel']) ? '' : $_GET['intro_cmdDel']; $intro_cmdAdd = empty($_GET['intro_cmdAdd']) ? '' : $_GET['intro_cmdAdd']; $courseId = api_get_course_id(); if (!empty($courseId)) { $form = new FormValidator('introduction_text', 'post', api_get_self() . '?' . api_get_cidreq()); } else { $form = new FormValidator('introduction_text'); } $renderer =& $form->defaultRenderer(); $renderer->setCustomElementTemplate('<div style="width: 80%; margin: 0px auto; padding-bottom: 10px; ">{element}</div>'); $config = array('ToolbarSet' => 'IntroductionTool', 'Width' => '100%', 'Height' => '300'); $form->addHtmlEditor('intro_content', null, null, false, $config); $form->addButtonSave(get_lang('SaveIntroText'), 'intro_cmdUpdate'); /* INTRODUCTION MICRO MODULE - COMMANDS SECTION (IF ALLOWED) */ $course_id = api_get_course_int_id(); if ($intro_editAllowed) { /* Replace command */ if ($intro_cmdUpdate) { if ($form->validate()) { $form_values = $form->exportValues(); $intro_content = Security::remove_XSS(stripslashes(api_html_entity_decode($form_values['intro_content'])), COURSEMANAGERLOWSECURITY); $criteria = ['cId' => $course_id, 'id' => $moduleId, 'sessionId' => $session_id]; if (!empty($intro_content)) { /** @var CToolIntro $toolIntro */ $toolIntro = Database::getManager()->getRepository('ChamiloCourseBundle:CToolIntro')->findOneBy($criteria); if ($toolIntro) { $toolIntro->setIntroText($intro_content);
/** * 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 . '. ' . $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"> </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'] . '. ' . $select_items[$lines_count]['answer'] . '</p></div>'; } else { $s .= ' '; } $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 .= ' '; } $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 .= ' '; } $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; }
/** * Returns a Form validator Obj * @todo the form should be auto generated * @param string $url * @param string $action add, edit * * @return FormValidator form validator obj */ public function return_form($url, $action) { $form = new FormValidator('grades', 'post', $url); // Setting the form elements $header = get_lang('Add'); if ($action == 'edit') { $header = get_lang('Modify'); } $form->addElement('header', $header); $id = isset($_GET['id']) ? intval($_GET['id']) : ''; $form->addElement('hidden', 'id', $id); $form->addElement('text', 'name', get_lang('Name'), array('size' => '70')); $form->addHtmlEditor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'Careers', 'Width' => '100%', 'Height' => '250')); $form->addElement('label', get_lang('Components')); // Get components $nr_items = 2; $max = 10; // Setting the defaults $defaults = $this->get($id); $components = $this->get_components($defaults['id']); if ($action == 'edit') { if (!empty($components)) { $nr_items = count($components) - 1; } } $form->addElement('hidden', 'maxvalue', '100'); $form->addElement('hidden', 'minvalue', '0'); $renderer =& $form->defaultRenderer(); $component_array = array(); for ($i = 0; $i <= $max; $i++) { $counter = $i; $form->addElement('text', 'components[' . $i . '][percentage]', null); $form->addElement('text', 'components[' . $i . '][acronym]', null); $form->addElement('text', 'components[' . $i . '][title]', null); $form->addElement('hidden', 'components[' . $i . '][id]', null); $template_percentage = '<div id=' . $i . ' style="display: ' . ($i <= $nr_items ? 'inline' : 'none') . ';" class="control-group"> <p> <label class="control-label">{label}</label> <div class="controls"> <!-- BEGIN required --><span class="form_required">*</span> <!-- END required --> {element} <!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --> % = '; $template_acronym = ' <!-- BEGIN required --><span class="form_required">*</span> <!-- END required --> {element} {label} <!-- BEGIN error --><span class="form_error">{error}</span> <!-- END error -->'; $template_title = ' {element} <!-- BEGIN error --> <span class="form_error">{error}</span><!-- END error --> <a href="javascript:plusItem(' . ($counter + 1) . ')"> <img style="display: ' . ($counter >= $nr_items ? 'inline' : 'none') . ';" id="plus-' . ($counter + 1) . '" src="../img/icons/22/add.png" alt="' . get_lang('Add') . '" title="' . get_lang('Add') . '"></img> </a> <a href="javascript:minItem(' . $counter . ')"> <img style="display: ' . ($counter >= $nr_items ? 'inline' : 'none') . ';" id="min-' . $counter . '" src="../img/delete.png" alt="' . get_lang('Delete') . '" title="' . get_lang('Delete') . '"></img> </a> </div></p></div>'; $renderer->setElementTemplate($template_title, 'components[' . $i . '][title]'); $renderer->setElementTemplate($template_percentage, 'components[' . $i . '][percentage]'); $renderer->setElementTemplate($template_acronym, 'components[' . $i . '][acronym]'); if ($i == 0) { $form->addRule('components[' . $i . '][percentage]', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('components[' . $i . '][title]', get_lang('ThisFieldIsRequired'), 'required'); $form->addRule('components[' . $i . '][acronym]', get_lang('ThisFieldIsRequired'), 'required'); } $form->addRule('components[' . $i . '][percentage]', get_lang('OnlyNumbers'), 'numeric'); $form->addRule(array('components[' . $i . '][percentage]', 'maxvalue'), get_lang('Over100'), 'compare', '<='); $form->addRule(array('components[' . $i . '][percentage]', 'minvalue'), get_lang('UnderMin'), 'compare', '>='); $component_array[] = 'components[' . $i . '][percentage]'; } //New rule added in the formvalidator compare_fields that filters a group of fields in order to compare with the wanted value $form->addRule($component_array, get_lang('AllMustWeight100'), 'compare_fields', '==@100'); $form->addElement('label', '', get_lang('AllMustWeight100')); if ($action == 'edit') { $form->addButtonUpdate(get_lang('Modify')); } else { $form->addButtonCreate(get_lang('Add')); } if (!empty($components)) { $counter = 0; foreach ($components as $component) { foreach ($component as $key => $value) { $defaults['components[' . $counter . '][' . $key . ']'] = $value; } $counter++; } } $form->setDefaults($defaults); // Setting the rules $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required'); return $form; }
/** * 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 . '. ' . $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"> </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'] . '. ' . $select_items[$lines_count]['answer'] . '</p></div>'; } else { $s .= ' '; } $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 .= ' '; } $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 .= ' '; } $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; }
/** * function which redifines Question::createAnswersForm * @param FormValidator $form * @param the answers number to display */ function createAnswersForm($form) { // getting the exercise list $obj_ex = Session::read('objExercise'); $editor_config = array('ToolbarSet' => 'TestProposedAnswer', 'Width' => '100%', 'Height' => '125'); //this line define how many question by default appear when creating a choice question $nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 3; // The previous default value was 2. See task #1759. $nb_answers += isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0); /* Types of Feedback $feedback_option[0]=get_lang('Feedback'); $feedback_option[1]=get_lang('DirectFeedback'); $feedback_option[2]=get_lang('NoFeedback'); */ $feedback_title = ''; $comment_title = ''; if ($obj_ex->selectFeedbackType() == 1) { $editor_config['Width'] = '250'; $editor_config['Height'] = '110'; $comment_title = '<th width="50%" >' . get_lang('Comment') . '</th>'; $feedback_title = '<th width="50%" >' . get_lang('Scenario') . '</th>'; } else { $comment_title = '<th width="50%">' . get_lang('Comment') . '</th>'; } $html = '<table class="table table-striped table-hover">'; $html .= '<thead>'; $html .= '<tr>'; $html .= '<th>' . get_lang('Number') . '</th>'; $html .= '<th>' . get_lang('True') . '</th>'; $html .= '<th width="50%">' . get_lang('Answer') . '</th>'; $html .= $comment_title . $feedback_title; $html .= '<th>' . get_lang('Weighting') . '</th>'; $html .= '</tr>'; $html .= '</thead>'; $html .= '<tbody>'; $form->addHeader(get_lang('Answers')); $form->addHtml($html); $defaults = array(); $correct = 0; $answer = false; if (!empty($this->id)) { $answer = new Answer($this->id); $answer->read(); if (count($answer->nbrAnswers) > 0 && !$form->isSubmitted()) { $nb_answers = $answer->nbrAnswers; } } $temp_scenario = array(); if ($nb_answers < 1) { $nb_answers = 1; Display::display_normal_message(get_lang('YouHaveToCreateAtLeastOneAnswer')); } $editQuestion = isset($_GET['editQuestion']) ? $_GET['editQuestion'] : false; if ($editQuestion) { //fixing $nb_answers $new_list = array(); $count = 1; if (isset($_POST['lessAnswers'])) { $lessFromSession = Session::read('less_answer'); if (!isset($lessFromSession)) { Session::write('less_answer', $this->id); $nb_answers--; } } for ($k = 1; $k <= $nb_answers; ++$k) { if ($answer->position[$k] != '666') { $new_list[$count] = $count; $count++; } } } else { for ($k = 1; $k <= $nb_answers; ++$k) { $new_list[$k] = $k; } } $i = 1; //for ($k = 1 ; $k <= $real_nb_answers; $k++) { foreach ($new_list as $key) { $i = $key; $form->addElement('html', '<tr>'); if (is_object($answer)) { if ($answer->position[$i] == 666) { //we set nothing } else { if ($answer->correct[$i]) { $correct = $i; } $answer_result = $answer->answer[$i]; $weight_result = float_format($answer->weighting[$i], 1); if ($nb_answers == $i) { $weight_result = '0'; } $defaults['answer[' . $i . ']'] = $answer_result; $defaults['comment[' . $i . ']'] = $answer->comment[$i]; $defaults['weighting[' . $i . ']'] = $weight_result; $item_list = explode('@@', $answer->destination[$i]); $try = $item_list[0]; $lp = $item_list[1]; $list_dest = $item_list[2]; $url = $item_list[3]; if ($try == 0) { $try_result = 0; } else { $try_result = 1; } if ($url == 0) { $url_result = ''; } else { $url_result = $url; } $temp_scenario['url' . $i] = $url_result; $temp_scenario['try' . $i] = $try_result; $temp_scenario['lp' . $i] = $lp; $temp_scenario['destination' . $i] = $list_dest; } } $defaults['scenario'] = $temp_scenario; $renderer =& $form->defaultRenderer(); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting[' . $i . ']'); $answer_number = $form->addElement('text', 'counter[' . $i . ']', null, 'value="' . $i . '"'); $answer_number->freeze(); $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"'); $form->addHtmlEditor('answer[' . $i . ']', null, array(), false, $editor_config); $form->addHtmlEditor('comment[' . $i . ']', null, array(), false, $editor_config); $form->addElement('text', 'weighting[' . $i . ']', null, array('style' => 'width: 60px;', 'value' => '0')); $form->addElement('html', '</tr>'); $i++; } if (empty($this->id)) { $form->addElement('hidden', 'new_question', 1); } //Adding the "I don't know" question answer //if (empty($this -> id)) { $i = 666; $form->addHtml('<tr>'); $defaults['answer[' . $i . ']'] = get_lang('DontKnow'); $defaults['weighting[' . $i . ']'] = 0; $defaults['scenario'] = $temp_scenario; $renderer =& $form->defaultRenderer(); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'correct'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'counter[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'answer[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'comment[' . $i . ']'); $renderer->setElementTemplate('<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>', 'weighting[' . $i . ']'); $answer_number = $form->addElement('text', 'counter[' . $i . ']', null, 'value="-"'); $answer_number->freeze(); $form->addElement('hidden', 'position[' . $i . ']', '666'); $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"'); $form->addHtmlEditor('answer[' . $i . ']', null, array(), false, $editor_config); $form->addRule('answer[' . $i . ']', get_lang('ThisFieldIsRequired'), 'required'); $form->addHtmlEditor('comment[' . $i . ']', null, array(), false, $editor_config); //$form->addElement('select', 'destination'.$i, get_lang('SelectQuestion').' : ',$select_question,'multiple'); $form->addText("weighting[{$i}]", null, false, ['style' => 'width: 60px;', 'value' => 0, 'readonly' => 'readonly']); $form->addHTml('</tr>'); $form->addHtml('</tbody></table>'); $buttonGroup = []; global $text, $class; //ie6 fix if ($obj_ex->edit_exercise_in_lp == true) { //setting the save button here and not in the question class.php $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true); $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true); $buttonGroup[] = $form->addButtonSave($text, 'submitQuestion', true); $form->addGroup($buttonGroup); } //We check the first radio button to be sure a radio button will be check if ($correct == 0) { $correct = 1; } $defaults['correct'] = $correct; if (!empty($this->id)) { $form->setDefaults($defaults); } else { $form->setDefaults($defaults); } $form->addElement('hidden', 'nb_answers'); $form->setConstants(array('nb_answers' => $nb_answers)); }
/** * Create a form validator based on an array of form data: * * array( * 'name' => 'zombie_report_parameters', //optional * 'method' => 'GET', //optional * 'items' => array( * array( * 'name' => 'ceiling', * 'label' => 'Ceiling', //optional * 'type' => 'date', * 'default' => date() //optional * ), * array( * 'name' => 'active_only', * 'label' => 'ActiveOnly', * 'type' => 'checkbox', * 'default' => true * ), * array( * 'name' => 'submit_button', * 'type' => 'style_submit_button', * 'value' => get_lang('Search'), * 'attributes' => array('class' => 'search') * ) * ) * ); * * @param array $form_data * @deprecated use normal FormValidator construct * * @return FormValidator */ public static function create($form_data) { if (empty($form_data)) { return null; } $form_name = isset($form_data['name']) ? $form_data['name'] : 'form'; $form_method = isset($form_data['method']) ? $form_data['method'] : 'POST'; $form_action = isset($form_data['action']) ? $form_data['action'] : ''; $form_target = isset($form_data['target']) ? $form_data['target'] : ''; $form_attributes = isset($form_data['attributes']) ? $form_data['attributes'] : null; $form_track_submit = isset($form_data['track_submit']) ? $form_data['track_submit'] : true; $reset = null; $result = new FormValidator($form_name, $form_method, $form_action, $form_target, $form_attributes, $form_track_submit); $defaults = array(); foreach ($form_data['items'] as $item) { $name = $item['name']; $type = isset($item['type']) ? $item['type'] : 'text'; $label = isset($item['label']) ? $item['label'] : ''; if ($type == 'wysiwyg') { $element = $result->addHtmlEditor($name, $label); } else { $element = $result->addElement($type, $name, $label); } if (isset($item['attributes'])) { $attributes = $item['attributes']; $element->setAttributes($attributes); } if (isset($item['value'])) { $value = $item['value']; $element->setValue($value); } if (isset($item['default'])) { $defaults[$name] = $item['default']; } if (isset($item['rules'])) { $rules = $item['rules']; foreach ($rules as $rule) { $message = $rule['message']; $type = $rule['type']; $format = isset($rule['format']) ? $rule['format'] : null; $validation = isset($rule['validation']) ? $rule['validation'] : 'server'; $force = isset($rule['force']) ? $rule['force'] : false; $result->addRule($name, $message, $type, $format, $validation, $reset, $force); } } } $result->setDefaults($defaults); return $result; }
/** * @param FormValidator $form * @param array $extraData * @param bool $admin_permissions * @param int $user_id * @param array $extra * @param int $itemId * @param array $exclude variables of extra field to exclude * @return array */ public function set_extra_fields_in_form($form, $extraData, $admin_permissions = false, $extra = array(), $itemId = null, $exclude = []) { $type = $this->type; $jquery_ready_content = null; if (!empty($extra)) { foreach ($extra as $field_details) { // Getting default value id if is set $defaultValueId = null; if (isset($field_details['options']) && !empty($field_details['options'])) { $valueToFind = null; if (isset($field_details['field_default_value'])) { $valueToFind = $field_details['field_default_value']; } // If a value is found we override the default value if (isset($extraData['extra_' . $field_details['variable']])) { $valueToFind = $extraData['extra_' . $field_details['variable']]; } foreach ($field_details['options'] as $option) { if ($option['option_value'] == $valueToFind) { $defaultValueId = $option['id']; } } } if (!$admin_permissions) { if ($field_details['visible'] == 0) { continue; } if (in_array($field_details['variable'], $exclude)) { continue; } } switch ($field_details['field_type']) { case ExtraField::FIELD_TYPE_TEXT: $form->addElement('text', 'extra_' . $field_details['variable'], $field_details['display_text'], array()); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_TEXTAREA: $form->addHtmlEditor('extra_' . $field_details['variable'], $field_details['display_text'], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_RADIO: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; $group[] = $form->createElement('radio', 'extra_' . $field_details['variable'], $option_details['option_value'], $option_details['display_text'] . '<br />', $option_details['option_value']); } } $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ''); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_CHECKBOX: $group = array(); if (isset($field_details['options']) && !empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; $group[] = $form->createElement('checkbox', 'extra_' . $field_details['variable'], $option_details['option_value'], $option_details['display_text'] . '<br />', $option_details['option_value']); } } else { $fieldVariable = "extra_{$field_details['variable']}"; $checkboxAttributes = array(); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { $checkboxAttributes['checked'] = true; } // We assume that is a switch on/off with 1 and 0 as values $group[] = $form->createElement('checkbox', 'extra_' . $field_details['variable'], null, get_lang('Yes'), $checkboxAttributes); } $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ''); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_SELECT: $get_lang_variables = false; if (in_array($field_details['variable'], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) { $get_lang_variables = true; } // Get extra field workflow $userInfo = api_get_user_info(); $addOptions = array(); $optionsExists = false; global $app; // Check if exist $app['orm.em'] object if (isset($app['orm.em']) && is_object($app['orm.em'])) { $optionsExists = $app['orm.em']->getRepository('ChamiloLMS\\Entity\\ExtraFieldOptionRelFieldOption')->findOneBy(array('fieldId' => $field_details['id'])); } if ($optionsExists) { if (isset($userInfo['status']) && !empty($userInfo['status'])) { $fieldWorkFlow = $app['orm.em']->getRepository('ChamiloLMS\\Entity\\ExtraFieldOptionRelFieldOption')->findBy(array('fieldId' => $field_details['id'], 'relatedFieldOptionId' => $defaultValueId, 'roleId' => $userInfo['status'])); foreach ($fieldWorkFlow as $item) { $addOptions[] = $item->getFieldOptionId(); } } } $options = array(); if (empty($defaultValueId)) { $options[''] = get_lang('SelectAnOption'); } $optionList = array(); if (!empty($field_details['options'])) { foreach ($field_details['options'] as $option_details) { $optionList[$option_details['id']] = $option_details; if ($get_lang_variables) { $options[$option_details['option_value']] = get_lang($option_details['display_text']); } else { if ($optionsExists) { // Adding always the default value if ($option_details['id'] == $defaultValueId) { $options[$option_details['option_value']] = $option_details['display_text']; } else { if (isset($addOptions) && !empty($addOptions)) { // Parsing filters if (in_array($option_details['id'], $addOptions)) { $options[$option_details['option_value']] = $option_details['display_text']; } } } } else { // Normal behaviour $options[$option_details['option_value']] = $option_details['display_text']; } } } if (isset($optionList[$defaultValueId])) { if (isset($optionList[$defaultValueId]['option_value']) && $optionList[$defaultValueId]['option_value'] == 'aprobada') { // @todo function don't exists api_is_question_manager /*if (api_is_question_manager() == false) { $form->freeze(); }*/ } } // Setting priority message if (isset($optionList[$defaultValueId]) && isset($optionList[$defaultValueId]['priority'])) { if (!empty($optionList[$defaultValueId]['priority'])) { $priorityId = $optionList[$defaultValueId]['priority']; $option = new ExtraFieldOption($this->type); $messageType = $option->getPriorityMessageType($priorityId); $form->addElement('label', null, Display::return_message($optionList[$defaultValueId]['priority_message'], $messageType)); } } } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } // chzn-select doesn't work for sessions?? $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], $options, array('id' => 'extra_' . $field_details['variable'])); /* Enable this when field_loggeable is introduced as a table field (2.0) if ($optionsExists && $field_details['field_loggeable'] && !empty($defaultValueId)) { $form->addElement( 'textarea', 'extra_' . $field_details['variable'] . '_comment', $field_details['display_text'] . ' ' . get_lang('Comment') ); $extraFieldValue = new ExtraFieldValue($this->type); $repo = $app['orm.em']->getRepository($extraFieldValue->entityName); $repoLog = $app['orm.em']->getRepository('Gedmo\Loggable\Entity\LogEntry'); $newEntity = $repo->findOneBy( array( $this->handlerEntityId => $itemId, 'fieldId' => $field_details['id'] ) ); // @todo move this in a function inside the class if ($newEntity) { $logs = $repoLog->getLogEntries($newEntity); if (!empty($logs)) { $html = '<b>' . get_lang('LatestChanges') . '</b><br /><br />'; $table = new HTML_Table(array('class' => 'data_table')); $table->setHeaderContents(0, 0, get_lang('Value')); $table->setHeaderContents(0, 1, get_lang('Comment')); $table->setHeaderContents(0, 2, get_lang('ModifyDate')); $table->setHeaderContents(0, 3, get_lang('Username')); $row = 1; foreach ($logs as $log) { $column = 0; $data = $log->getData(); $fieldValue = isset($data['fieldValue']) ? $data['fieldValue'] : null; $comment = isset($data['comment']) ? $data['comment'] : null; $table->setCellContents($row, $column, $fieldValue); $column++; $table->setCellContents($row, $column, $comment); $column++; $table->setCellContents($row, $column, api_get_local_time($log->getLoggedAt()->format('Y-m-d H:i:s'))); $column++; $table->setCellContents($row, $column, $log->getUsername()); $row++; } $form->addElement('label', null, $html.$table->toHtml()); } } } */ if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_SELECT_MULTIPLE: $options = array(); foreach ($field_details['options'] as $option_id => $option_details) { $options[$option_details['option_value']] = $option_details['display_text']; } $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], $options, array('multiple' => 'multiple')); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_DATE: $form->addDatePicker('extra_' . $field_details['variable'], $field_details['display_text']); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DATETIME: $form->addDateTimePicker('extra_' . $field_details['variable'], $field_details['display_text']); $defaults['extra_' . $field_details['variable']] = api_get_local_time(); if (!isset($form->_defaultValues['extra_' . $field_details['variable']])) { $form->setDefaults($defaults); } if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } $form->applyFilter('theme', 'trim'); break; case ExtraField::FIELD_TYPE_DOUBLE_SELECT: $first_select_id = 'first_extra_' . $field_details['variable']; $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php?1=1'; $jquery_ready_content .= ' $("#' . $first_select_id . '").on("change", function() { var id = $(this).val(); if (id) { $.ajax({ url: "' . $url . '&a=get_second_select_options", dataType: "json", data: "type=' . $type . '&field_id=' . $field_details['id'] . '&option_value_id="+id, success: function(data) { $("#second_extra_' . $field_details['variable'] . '").empty(); $.each(data, function(index, value) { $("#second_extra_' . $field_details['variable'] . '").append($("<option/>", { value: index, text: value })); }); }, }); } else { $("#second_extra_' . $field_details['variable'] . '").empty(); } });'; $first_id = null; $second_id = null; if (!empty($extraData)) { $first_id = $extraData['extra_' . $field_details['variable']]['extra_' . $field_details['variable']]; $second_id = $extraData['extra_' . $field_details['variable']]['extra_' . $field_details['variable'] . '_second']; } $options = ExtraField::extra_field_double_select_convert_array_to_ordered_array($field_details['options']); $values = array('' => get_lang('Select')); $second_values = array(); if (!empty($options)) { foreach ($options as $option) { foreach ($option as $sub_option) { if ($sub_option['option_value'] == '0') { $values[$sub_option['id']] = $sub_option['display_text']; } else { if ($first_id === $sub_option['option_value']) { $second_values[$sub_option['id']] = $sub_option['display_text']; } } } } } $group = array(); $group[] = $form->createElement('select', 'extra_' . $field_details['variable'], null, $values, array('id' => $first_select_id)); $group[] = $form->createElement('select', 'extra_' . $field_details['variable'] . '_second', null, $second_values, array('id' => 'second_extra_' . $field_details['variable'])); $form->addGroup($group, 'extra_' . $field_details['variable'], $field_details['display_text'], ' '); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_DIVIDER: $form->addElement('static', $field_details['variable'], '<br /><strong>' . $field_details['display_text'] . '</strong>'); break; case ExtraField::FIELD_TYPE_TAG: $variable = $field_details['variable']; $field_id = $field_details['id']; //Added for correctly translate the extra_field $get_lang_variables = false; if (in_array($variable, ['tags'])) { $get_lang_variables = true; } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } $tagsSelect = $form->addSelect("extra_{$field_details['variable']}", $field_details['display_text']); $tagsSelect->setAttribute('class', null); $tagsSelect->setAttribute('id', "extra_{$field_details['variable']}"); $tagsSelect->setMultiple(true); if ($this->type == 'user') { /* //the magic should be here $user_tags = UserManager::get_user_tags($user_id, $field_details[0]); $tag_list = ''; if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tag_list .= '<option value="'.$tag['tag'].'" class="selected">'.$tag['tag'].'</option>'; } } $multi_select = '<select id="extra_'.$field_details[1].'" name="extra_'.$field_details[1].'"> '.$tag_list.' </select>'; $form->addElement('label', $field_details[3], $multi_select); $url = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php'; $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content = <<<EOF $("#extra_$field_details[1]").fcbkcomplete({ json_url: "$url?a=search_tags&field_id=$field_details[0]", cache: false, filter_case: true, filter_hide: true, complete_text:"$complete_text", firstselected: true, //onremove: "testme", //onselect: "testme", filter_selected: true, newel: true }); EOF; break;*/ // The magic should be here $user_tags = UserManager::get_user_tags($itemId, $field_details['id']); if (is_array($user_tags) && count($user_tags) > 0) { foreach ($user_tags as $tag) { $tagsSelect->addOption($tag['tag'], $tag['tag'], ['selected' => 'selected', 'class' => 'selected']); } } $url = api_get_path(WEB_AJAX_PATH) . 'user_manager.ajax.php'; } else { $em = Database::getManager(); $fieldTags = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag')->findBy(['fieldId' => $field_id, 'itemId' => $itemId]); foreach ($fieldTags as $fieldTag) { $tag = $em->find('ChamiloCoreBundle:Tag', $fieldTag->getTagId()); if (empty($tag)) { continue; } $tagsSelect->addOption($tag->getTag(), $tag->getTag(), ['selected' => 'selected', 'class' => 'selected']); } $url = api_get_path(WEB_AJAX_PATH) . 'extra_field.ajax.php'; } $complete_text = get_lang('StartToType'); //if cache is set to true the jquery will be called 1 time $jquery_ready_content .= <<<EOF \$("#extra_{$variable}").fcbkcomplete({ json_url: "{$url}?a=search_tags&field_id={$field_id}&type={$this->type}", cache: false, filter_case: true, filter_hide: true, complete_text:"{$complete_text}", firstselected: false, filter_selected: true, newel: true }); EOF; break; case ExtraField::FIELD_TYPE_TIMEZONE: $form->addElement('select', 'extra_' . $field_details['variable'], $field_details['display_text'], api_get_timezones(), ''); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_SOCIAL_PROFILE: // get the social network's favicon $extra_data_variable = isset($extraData['extra_' . $field_details['variable']]) ? $extraData['extra_' . $field_details['variable']] : null; $field_default_value = isset($field_details['field_default_value']) ? $field_details['field_default_value'] : null; $icon_path = UserManager::get_favicon_from_url($extra_data_variable, $field_default_value); // special hack for hi5 $leftpad = '1.7'; $top = '0.4'; $domain = parse_url($icon_path, PHP_URL_HOST); if ($domain == 'www.hi5.com' or $domain == 'hi5.com') { $leftpad = '3'; $top = '0'; } // print the input field $form->addElement('text', 'extra_' . $field_details['variable'], $field_details['display_text'], array('size' => 60, 'style' => 'background-image: url(\'' . $icon_path . '\'); background-repeat: no-repeat; background-position: 0.4em ' . $top . 'em; padding-left: ' . $leftpad . 'em; ')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_MOBILE_PHONE_NUMBER: $form->addElement('text', 'extra_' . $field_details[1], $field_details[3] . " (" . get_lang('CountryDialCode') . ")", array('size' => 40, 'placeholder' => '(xx)xxxxxxxxx')); $form->applyFilter('extra_' . $field_details[1], 'stripslashes'); $form->applyFilter('extra_' . $field_details[1], 'trim'); $form->applyFilter('extra_' . $field_details[1], 'mobile_phone_number_filter'); $form->addRule('extra_' . $field_details[1], get_lang('MobilePhoneNumberWrong'), 'mobile_phone_number'); if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } break; case ExtraField::FIELD_TYPE_INTEGER: $form->addElement('number', 'extra_' . $field_details['variable'], $field_details['display_text'], array('class' => 'span1', 'step' => 1)); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $form->applyFilter('extra_' . $field_details['variable'], 'intval'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FILE_IMAGE: $fieldVariable = "extra_{$field_details['variable']}"; $fieldTexts = array($field_details['display_text']); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) { $fieldTexts[] = Display::img(api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], $field_details['display_text'], array('width' => '300')); } } $form->addElement('file', $fieldVariable, $fieldTexts, array('accept' => 'image/*')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif'); $form->addRule('extra_' . $field_details['variable'], get_lang('OnlyImagesAllowed') . ' (' . implode(',', $allowed_picture_types) . ')', 'filetype', $allowed_picture_types); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FLOAT: $form->addElement('number', 'extra_' . $field_details['variable'], $field_details['display_text'], array('class' => 'span1', 'step' => '0.01')); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); $form->applyFilter('extra_' . $field_details['variable'], 'floatval'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_FILE: $fieldVariable = "extra_{$field_details['variable']}"; $fieldTexts = array($field_details['display_text']); if (is_array($extraData) && array_key_exists($fieldVariable, $extraData)) { if (file_exists(api_get_path(SYS_UPLOAD_PATH) . $extraData[$fieldVariable])) { $fieldTexts[] = Display::url(api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], api_get_path(WEB_UPLOAD_PATH) . $extraData[$fieldVariable], array('title' => $field_details['display_text'], 'target' => '_blank')); } } $form->addElement('file', $fieldVariable, $fieldTexts, array()); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); $form->applyFilter('extra_' . $field_details['variable'], 'trim'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_VIDEO_URL: //Added for correctly translate the extra_field $get_lang_variables = false; if (in_array($field_details['variable'], ['video_url'])) { $get_lang_variables = true; } if ($get_lang_variables) { $field_details['display_text'] = get_lang($field_details['display_text']); } $form->addUrl("extra_{$field_details['variable']}", $field_details['display_text'], false, ['placeholder' => 'https://']); break; case ExtraField::FIELD_TYPE_LETTERS_ONLY: $form->addTextLettersOnly("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_ALPHANUMERIC: $form->addTextAlphanumeric("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_LETTERS_SPACE: $form->addTextLettersAndSpaces("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; case ExtraField::FIELD_TYPE_ALPHANUMERIC_SPACE: $form->addTextAlphanumericAndSpaces("extra_{$field_details['variable']}", $field_details['display_text']); $form->applyFilter('extra_' . $field_details['variable'], 'stripslashes'); if (!$admin_permissions) { if ($field_details['visible'] == 0) { $form->freeze('extra_' . $field_details['variable']); } } break; } } } $return = array(); $return['jquery_ready_content'] = $jquery_ready_content; return $return; }
/** * Displays the form to create a new post * @author Toon Keppens * * @param Integer $blog_id */ public static function display_new_comment_form($blog_id, $post_id, $title) { $form = new FormValidator('add_post', 'post', api_get_path(WEB_CODE_PATH) . "blog/blog.php?action=view_post&blog_id=" . intval($blog_id) . "&post_id=" . intval($post_id) . "&" . api_get_cidreq(), null, array('enctype' => 'multipart/form-data')); $header = get_lang('AddNewComment'); if (isset($_GET['task_id'])) { $header = get_lang('ExecuteThisTask'); } $form->addHeader($header); $form->addText('title', get_lang('Title')); $config = array(); if (!api_is_allowed_to_edit()) { $config['ToolbarSet'] = 'ProjectComment'; } else { $config['ToolbarSet'] = 'ProjectCommentStudent'; } $form->addHtmlEditor('comment', get_lang('Comment'), false, false, $config); $form->addFile('user_upload', get_lang('AddAnAttachment')); $form->addTextarea('post_file_comment', get_lang('FileComment')); $form->addHidden('action', null); $form->addHidden('comment_parent_id', 0); if (isset($_GET['task_id'])) { $form->addHidden('new_task_execution_submit', 'true'); $form->addHidden('task_id', intval($_GET['task_id'])); } else { $form->addHidden('new_comment_submit', 'true'); } $form->addButton('save', get_lang('Save')); $form->display(); }
/** * Creates the form to create / edit a question * A subclass can redefine this function to add fields... * @param FormValidator $form */ public function createForm(&$form) { echo '<style> .media { display:none;} </style>'; echo '<script> // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700 function FCKeditor_OnComplete( editorInstance ) { if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name)) { HideFCKEditorByInstanceName (editorInstance.Name); } } function HideFCKEditorByInstanceName ( editorInstanceName ) { if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) { document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media"; } } </script>'; // question name $form->addElement('text', 'questionName', get_lang('Question')); $form->addRule('questionName', get_lang('GiveQuestion'), 'required'); // default content $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null; // Question type $answerType = isset($_REQUEST['answerType']) ? intval($_REQUEST['answerType']) : null; $form->addElement('hidden', 'answerType', $answerType); // html editor $editorConfig = array('ToolbarSet' => 'TestQuestionDescription', 'Height' => '150'); if (!api_is_allowed_to_edit(null, true)) { $editorConfig['UserStatus'] = 'student'; } $form->addButtonAdvancedSettings('advanced_params'); $form->addElement('html', '<div id="advanced_params_options" style="display:none">'); $form->addHtmlEditor('questionDescription', get_lang('QuestionDescription'), false, false, $editorConfig); // hidden values $my_id = isset($_REQUEST['myid']) ? intval($_REQUEST['myid']) : null; $form->addElement('hidden', 'myid', $my_id); if ($this->type != MEDIA_QUESTION) { // Advanced parameters $select_level = Question::get_default_levels(); $form->addElement('select', 'questionLevel', get_lang('Difficulty'), $select_level); // Categories $tabCat = TestCategory::getCategoriesIdAndName(); $form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat); if (in_array($this->type, array(UNIQUE_ANSWER, MULTIPLE_ANSWER))) { $buttonValue = $this->type == UNIQUE_ANSWER ? 'ConvertToMultipleAnswer' : 'ConvertToUniqueAnswer'; $form->addElement('button', 'convertAnswer', get_lang($buttonValue)); } //Medias //$course_medias = Question::prepare_course_media_select(api_get_course_int_id()); //$form->addElement('select', 'parent_id', get_lang('AttachToMedia'), $course_medias); } $form->addElement('html', '</div>'); if (!isset($_GET['fromExercise'])) { switch ($answerType) { case 1: $this->question = get_lang('DefaultUniqueQuestion'); break; case 2: $this->question = get_lang('DefaultMultipleQuestion'); break; case 3: $this->question = get_lang('DefaultFillBlankQuestion'); break; case 4: $this->question = get_lang('DefaultMathingQuestion'); break; case 5: $this->question = get_lang('DefaultOpenQuestion'); break; case 9: $this->question = get_lang('DefaultMultipleQuestion'); break; } } // default values $defaults = array(); $defaults['questionName'] = $this->question; $defaults['questionDescription'] = $this->description; $defaults['questionLevel'] = $this->level; $defaults['questionCategory'] = $this->category; // Came from he question pool if (isset($_GET['fromExercise'])) { $form->setDefaults($defaults); } if (!empty($_REQUEST['myid'])) { $form->setDefaults($defaults); } else { if ($isContent == 1) { $form->setDefaults($defaults); } } }
/** * form to add a category * @todo move to TestCategory.class.php * @param string $action */ function add_category_form($action) { $action = Security::remove_XSS($action); // initiate the object $form = new FormValidator('note', 'post', api_get_self() . '?action=' . $action); // Setting the form elements $form->addElement('header', get_lang('AddACategory')); $form->addElement('text', 'category_name', get_lang('CategoryName'), array('size' => '95')); $form->addHtmlEditor('category_description', get_lang('CategoryDescription'), false, false, array('ToolbarSet' => 'test_category', 'Height' => '200')); $form->addButtonCreate(get_lang('AddTestCategory'), 'SubmitNote'); // setting the rules $form->addRule('category_name', get_lang('ThisFieldIsRequired'), 'required'); // The validation or display if ($form->validate()) { $check = Security::check_token('post'); if ($check) { $values = $form->exportValues(); $v_name = Security::remove_XSS($values['category_name'], COURSEMANAGER); $v_description = Security::remove_XSS($values['category_description'], COURSEMANAGER); $objcat = new TestCategory(0, $v_name, $v_description); if ($objcat->addCategoryInBDD()) { Display::display_confirmation_message(get_lang('AddCategoryDone')); } else { Display::display_confirmation_message(get_lang('AddCategoryNameAlreadyExists')); } } Security::clear_token(); } else { display_goback(); $token = Security::get_token(); $form->addElement('hidden', 'sec_token'); $form->setConstants(array('sec_token' => $token)); $form->display(); } }
/** * */ function show_form_send_ticket() { global $types, $plugin; echo '<div class="divTicket">'; //Category List $categoryList = array(); foreach ($types as $type) { $categoryList[$type['category_id']] = $type['name'] . ": " . $type['description']; } //End Category List //Status List $statusList = array(); $statusAttributes = array('style' => 'display: none;', 'id' => 'status_id', 'for' => 'status_id'); $statusList[NEWTCK] = $plugin->get_lang('StatusNew'); if (api_is_platform_admin()) { $statusAttributes = array('id' => 'status_id', 'for' => 'status_id', 'style' => 'width: 562px;'); $statusList[PENDING] = $plugin->get_lang('StatusPending'); $statusList[UNCONFIRMED] = $plugin->get_lang('StatusUnconfirmed'); $statusList[CLOSE] = $plugin->get_lang('StatusClose'); $statusList[REENVIADO] = $plugin->get_lang('StatusForwarded'); } //End Status List //Source List $sourceList = array(); $sourceAttributes = array('style' => 'display: none;', 'id' => 'source_id', 'for' => 'source_id'); $sourceList[SRC_PLATFORM] = $plugin->get_lang('SrcPlatform'); if (api_is_platform_admin()) { $sourceAttributes = array('id' => 'source_id', 'for' => 'source_id', 'style' => 'width: 562px;'); $sourceList[SRC_EMAIL] = $plugin->get_lang('SrcEmail'); $sourceList[SRC_PHONE] = $plugin->get_lang('SrcPhone'); $sourceList[SRC_PRESC] = $plugin->get_lang('SrcPresential'); } //End Source List //Priority List $priorityList = array(); $priorityList[NORMAL] = $plugin->get_lang('PriorityNormal'); $priorityList[HIGH] = $plugin->get_lang('PriorityHigh'); $priorityList[LOW] = $plugin->get_lang('PriorityLow'); //End Priority List $form = new FormValidator('send_ticket', 'POST', api_get_self(), "", array('enctype' => 'multipart/form-data', 'onsubmit' => 'return validate()', 'class' => 'span8 offset1 form-horizontal')); $form->addElement('hidden', 'user_id_request', '', array('id' => 'user_id_request')); $form->addElement('hidden', 'project_id', '', array('id' => 'project_id')); $form->addElement('hidden', 'other_area', '', array('id' => 'other_area')); $form->addElement('hidden', 'email', '', array('id' => 'email')); $form->addElement('select', 'category_id', get_lang('Category'), $categoryList, array('onchange' => 'changeType()', 'id' => 'category_id', 'for' => 'category_id', 'style' => 'width: 562px;')); $form->addElement('html', Display::div('', array('id' => 'user_request'))); $form->addElement('select', 'status_id', get_lang('Status'), $statusList, $statusAttributes); $form->addElement('select', 'source_id', $plugin->get_lang('Source'), $sourceList, $sourceAttributes); $form->addElement('text', 'subject', get_lang('Subject'), array('id' => 'subject', 'style' => 'width: 550px;')); $form->addElement('text', 'personal_email', $plugin->get_lang('PersonalEmail'), array('id' => 'personal_email', 'style' => 'width: 550px;')); $form->addHtmlEditor('content', get_lang('Message'), false, false, array('ToolbarSet' => 'Profile', 'Width' => '600', 'Height' => '250')); $form->addElement('text', 'phone', get_lang('Phone') . ' (' . $plugin->get_lang('Optional') . ')', array('id' => 'phone')); $form->addElement('select', 'priority_id', $plugin->get_lang('Priority'), $priorityList, array('id' => 'priority_id', 'for' => 'priority_id')); $form->addElement('html', '<span id="filepaths">'); $form->addElement('html', '<div id="filepath_1">'); $form->addElement('file', 'attach_1', get_lang('FilesAttachment')); $form->addElement('html', '</div>'); $form->addElement('html', '</span>'); $form->addElement('html', '<div class="controls">'); $form->addElement('html', '<span id="link-more-attach" >'); $form->addElement('html', '<span class="label label-info" onclick="return add_image_form()">' . get_lang('AddOneMoreFile') . '</span>'); $form->addElement('html', '</span>'); $form->addElement('html', '(' . sprintf(get_lang('MaximunFileSizeX'), format_file_size(api_get_setting('message_max_upload_filesize'))) . ')'); $form->addElement('html', '<br/>'); $form->addElement('button', 'compose', get_lang('SendMessage'), null, null, null, 'save', array('id' => 'btnsubmit')); $form->display(); }
/** * function which redefines Question::createAnswersForm * @param FormValidator $form */ public function createAnswersForm($form) { $defaults = array(); if (!empty($this->id)) { $objectAnswer = new Answer($this->id); $answer = $objectAnswer->selectAnswer(1); $listAnswersInfo = FillBlanks::getAnswerInfo($answer); if ($listAnswersInfo["switchable"]) { $defaults['multiple_answer'] = 1; } else { $defaults['multiple_answer'] = 0; } //take the complete string except after the last '::' $defaults['answer'] = $listAnswersInfo["text"]; $defaults['select_separator'] = $listAnswersInfo["blankseparatornumber"]; $blanksepartornumber = $listAnswersInfo["blankseparatornumber"]; } else { $defaults['answer'] = get_lang('DefaultTextInBlanks'); $defaults['select_separator'] = 0; $blanksepartornumber = 0; } $blankSeparatorStart = self::getStartSeparator($blanksepartornumber); $blankSeparatorEnd = self::getEndSeparator($blanksepartornumber); $setValues = null; if (isset($a_weightings) && count($a_weightings) > 0) { foreach ($a_weightings as $i => $weighting) { $setValues .= 'document.getElementById("weighting[' . $i . ']").value = "' . $weighting . '";'; } } // javascript echo '<script> var blankSeparatortStart = "' . $blankSeparatorStart . '"; var blankSeparatortEnd = "' . $blankSeparatorEnd . '"; var blankSeparatortStartRegexp = getBlankSeparatorRegexp(blankSeparatortStart); var blankSeparatortEndRegexp = getBlankSeparatorRegexp(blankSeparatortEnd); CKEDITOR.on("instanceCreated", function(e) { if (e.editor.name === "answer") { e.editor.on("change", updateBlanks); } }); var firstTime = true; function updateBlanks() { if (firstTime) { var field = document.getElementById("answer"); var answer = field.value; } else { var answer = CKEDITOR.instances["answer"].getData(); } // disable the save button, if not blanks have been created $("button").attr("disabled", "disabled"); $("#defineoneblank").show(); var blanksRegexp = "/"+blankSeparatortStartRegexp+"[^"+blankSeparatortStartRegexp+"]*"+blankSeparatortEndRegexp+"/g"; var blanks = answer.match(eval(blanksRegexp)); var fields = "<div class=\\"form-group \\">"; fields += "<label class=\\"col-sm-2 control-label\\">' . get_lang('Weighting') . '</label>"; fields += "<div class=\\"col-sm-8\\">"; fields += "<table>"; fields += "<tr><th style=\\"padding:0 20px\\">' . get_lang("WordTofind") . '</th><th style=\\"padding:0 20px\\">' . get_lang("QuestionWeighting") . '</th><th style=\\"padding:0 20px\\">' . get_lang("BlankInputSize") . '</th></tr>"; if (blanks != null) { for (var i=0 ; i < blanks.length ; i++){ // remove forbidden characters that causes bugs blanks[i] = removeForbiddenChars(blanks[i]); // trim blanks between brackets blanks[i] = trimBlanksBetweenSeparator(blanks[i], blankSeparatortStart, blankSeparatortEnd); // if the word is empty [] if (blanks[i] == blankSeparatortStartRegexp+blankSeparatortEndRegexp) { break; } // get input size var lainputsize = 200; if ($("#samplesize\\\\["+i+"\\\\]").width()) { lainputsize = $("#samplesize\\\\["+i+"\\\\]").width(); } if (document.getElementById("weighting["+i+"]")) { var value = document.getElementById("weighting["+i+"]").value; } else { var value = "10"; } fields += "<tr>"; fields += "<td>"+blanks[i]+"</td>"; fields += "<td><input style=\\"width:35px\\" value=\\""+value+"\\" type=\\"text\\" id=\\"weighting["+i+"]\\" name=\\"weighting["+i+"]\\" /></td>"; fields += "<td>"; fields += "<input type=\\"button\\" value=\\"-\\" onclick=\\"changeInputSize(-1, "+i+")\\">"; fields += "<input type=\\"button\\" value=\\"+\\" onclick=\\"changeInputSize(1, "+i+")\\">"; fields += "<input value=\\""+blanks[i].substr(1, blanks[i].length - 2)+"\\" style=\\"width:"+lainputsize+"px\\" disabled=disabled id=\\"samplesize["+i+"]\\"/>"; fields += "<input type=\\"hidden\\" id=\\"sizeofinput["+i+"]\\" name=\\"sizeofinput["+i+"]\\" value=\\""+lainputsize+"\\" \\"/>"; fields += "</td>"; fields += "</tr>"; // enable the save button $("button").removeAttr("disabled"); $("#defineoneblank").hide(); } } document.getElementById("blanks_weighting").innerHTML = fields + "</table></div></div>"; if (firstTime) { firstTime = false; '; if (isset($listAnswersInfo) && count($listAnswersInfo["tabweighting"]) > 0) { foreach ($listAnswersInfo["tabweighting"] as $i => $weighting) { if (!empty($i)) { echo 'document.getElementById("weighting[' . $i . ']").value = "' . $weighting . '";'; } } foreach ($listAnswersInfo["tabinputsize"] as $i => $sizeOfInput) { if (!empty($i)) { echo 'document.getElementById("sizeofinput[' . $i . ']").value = "' . $sizeOfInput . '";'; echo '$("#samplesize\\\\[' . $i . '\\\\]").width(' . $sizeOfInput . ');'; } } } echo '} } window.onload = updateBlanks; function getInputSize() { var outTabSize = new Array(); $("input").each(function() { if ($(this).attr("id") && $(this).attr("id").match(/samplesize/)) { var tabidnum = $(this).attr("id").match(/\\d+/); var idnum = tabidnum[0]; var thewidth = $(this).next().attr("value"); tabInputSize[idnum] = thewidth; } }); } function changeInputSize(inCoef, inIdNum) { var currentWidth = $("#samplesize\\\\["+inIdNum+"\\\\]").width(); var newWidth = currentWidth + inCoef * 20; newWidth = Math.max(20, newWidth); newWidth = Math.min(newWidth, 600); $("#samplesize\\\\["+inIdNum+"\\\\]").width(newWidth); $("#sizeofinput\\\\["+inIdNum+"\\\\]").attr("value", newWidth); } function removeForbiddenChars(inTxt) { outTxt = inTxt; outTxt = outTxt.replace(/"/g, ""); // remove the char outTxt = outTxt.replace(/\\x22/g, ""); // remove the char outTxt = outTxt.replace(/"/g, ""); // remove the char outTxt = outTxt.replace(/\\\\/g, ""); // remove the \\ char outTxt = outTxt.replace(/ /g, " "); outTxt = outTxt.replace(/^ +/, ""); outTxt = outTxt.replace(/ +$/, ""); return outTxt; } function changeBlankSeparator() { var separatorNumber = $("#select_separator").val(); var tabSeparator = getSeparatorFromNumber(separatorNumber); blankSeparatortStart = tabSeparator[0]; blankSeparatortEnd = tabSeparator[1]; blankSeparatortStartRegexp = getBlankSeparatorRegexp(blankSeparatortStart); blankSeparatortEndRegexp = getBlankSeparatorRegexp(blankSeparatortEnd); updateBlanks(); } // this function is the same than the PHP one // if modify it modify the php one escapeForRegexp function getBlankSeparatorRegexp(inTxt) { var tabSpecialChar = new Array(".", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":", "-", ")"); for (var i=0; i < tabSpecialChar.length; i++) { if (inTxt == tabSpecialChar[i]) { return "\\\\"+inTxt; } } return inTxt; } // this function is the same than the PHP one // if modify it modify the php one getAllowedSeparator function getSeparatorFromNumber(innumber) { tabSeparator = new Array(); tabSeparator[0] = new Array("[", "]"); tabSeparator[1] = new Array("{", "}"); tabSeparator[2] = new Array("(", ")"); tabSeparator[3] = new Array("*", "*"); tabSeparator[4] = new Array("#", "#"); tabSeparator[5] = new Array("%", "%"); tabSeparator[6] = new Array("$", "$"); return tabSeparator[innumber]; } function trimBlanksBetweenSeparator(inTxt, inSeparatorStart, inSeparatorEnd) { // blankSeparatortStartRegexp // blankSeparatortEndRegexp var result = inTxt result = result.replace(inSeparatorStart, ""); result = result.replace(inSeparatorEnd, ""); result = result.trim(); return inSeparatorStart+result+inSeparatorEnd; } </script>'; // answer $form->addElement('label', null, '<br /><br />' . get_lang('TypeTextBelow') . ', ' . get_lang('And') . ' ' . get_lang('UseTagForBlank')); $form->addHtmlEditor('answer', Display::return_icon('fill_field.png'), ['id' => 'answer', 'onkeyup' => "javascript: updateBlanks(this);"], array('ToolbarSet' => 'TestQuestionDescription')); $form->addRule('answer', get_lang('GiveText'), 'required'); //added multiple answers $form->addElement('checkbox', 'multiple_answer', '', get_lang('FillInBlankSwitchable')); $form->addElement('select', 'select_separator', get_lang("SelectFillTheBlankSeparator"), self::getAllowedSeparatorForSelect(), ' id="select_separator" style="width:150px" onchange="changeBlankSeparator()" '); $form->addElement('label', null, '<input type="button" onclick="updateBlanks()" value="' . get_lang('RefreshBlanks') . '" class="btn btn-default" />'); $form->addElement('html', '<div id="blanks_weighting"></div>'); global $text; // setting the save button here and not in the question class.php $form->addElement('html', '<div id="defineoneblank" style="color:#D04A66; margin-left:160px">' . get_lang('DefineBlanks') . '</div>'); $form->addButtonSave($text, 'submitQuestion'); if (!empty($this->id)) { $form->setDefaults($defaults); } else { if ($this->isContent == 1) { $form->setDefaults($defaults); } } }
} } $captcha = api_get_setting('allow_captcha'); $allowCaptcha = $captcha == 'true'; if ($allowCaptcha) { $ajax = api_get_path(WEB_AJAX_PATH) . 'form.ajax.php?a=get_captcha'; $options = array('width' => 220, 'height' => 90, 'callback' => $ajax . '&var=' . basename(__FILE__, '.php'), 'sessionVar' => basename(__FILE__, '.php'), 'imageOptions' => array('font_size' => 20, 'font_path' => api_get_path(SYS_FONTS_PATH) . 'opensans/', 'font_file' => 'OpenSans-Regular.ttf')); $captcha_question = $form->addElement('CAPTCHA_Image', 'captcha_question', '', $options); $form->addElement('static', null, null, get_lang('ClickOnTheImageForANewOne')); $form->addElement('text', 'captcha', get_lang('EnterTheLettersYouSee'), array('size' => 40)); $form->addRule('captcha', get_lang('EnterTheCharactersYouReadInTheImage'), 'required', null, 'client'); $form->addRule('captcha', get_lang('TheTextYouEnteredDoesNotMatchThePicture'), 'CAPTCHA', $captcha_question); } // EXTENDED FIELDS if (api_get_setting('profile.extended_profile') == 'true' && api_get_setting_in_list('registration.extendedprofile_registration', 'mycomptetences') == 'true') { $form->addHtmlEditor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Register', 'Width' => '100%', 'Height' => '130')); } if (api_get_setting('profile.extended_profile') == 'true' && api_get_setting_in_list('registration.extendedprofile_registration', 'mydiplomas') == 'true') { $form->addHtmlEditor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Register', 'Width' => '100%', 'Height' => '130')); } if (api_get_setting('profile.extended_profile') == 'true' && api_get_setting_in_list('registration.extendedprofile_registration', 'myteach') == 'true') { $form->addHtmlEditor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Register', 'Width' => '100%', 'Height' => '130')); } if (api_get_setting('profile.extended_profile') == 'true' && api_get_setting_in_list('registration.extendedprofile_registration', 'mypersonalopenarea') == 'true') { $form->addHtmlEditor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Register', 'Width' => '100%', 'Height' => '130')); } if (api_get_setting('profile.extended_profile') == 'true') { if (api_get_setting_in_list('registration.extendedprofile_registration', 'mycomptetences') == 'true' && api_get_setting_in_list('registration.extendedprofile_registrationrequired', 'mycomptetences') == 'true') { $form->addRule('competences', get_lang('ThisFieldIsRequired'), 'required'); } if (api_get_setting_in_list('registration.extendedprofile_registration', 'mydiplomas') == 'true' && api_get_setting_in_list('registration.extendedprofile_registrationrequired', 'mydiplomas') == 'true') {
function manage_form($default, $select_from_user_list = null, $sent_to = null) { $group_id = isset($_REQUEST['group_id']) ? intval($_REQUEST['group_id']) : null; $message_id = isset($_GET['message_id']) ? intval($_GET['message_id']) : null; $param_f = isset($_GET['f']) && $_GET['f'] == 'social' ? 'social' : null; $form = new FormValidator('compose_message', null, api_get_self() . '?f=' . $param_f, null, array('enctype' => 'multipart/form-data')); if (empty($group_id)) { if (isset($select_from_user_list)) { $form->addText('id_text_name', get_lang('SendMessageTo'), true, array('id' => 'id_text_name', 'onkeyup' => 'send_request_and_search()', 'autocomplete' => 'off')); $form->addRule('id_text_name', get_lang('ThisFieldIsRequired'), 'required'); $form->addElement('html', '<div id="id_div_search" style="padding:0px" class="message-select-box" > </div>'); $form->addElement('hidden', 'user_list', 0, array('id' => 'user_list')); } else { if (!empty($sent_to)) { $form->addLabel(get_lang('SendMessageTo'), $sent_to); } if (empty($default['users'])) { //fb select $form->addElement('select_ajax', 'users', get_lang('SendMessageTo'), array(), ['multiple' => 'multiple', 'url' => api_get_path(WEB_AJAX_PATH) . 'message.ajax.php?a=find_users']); } else { $form->addElement('hidden', 'hidden_user', $default['users'][0], array('id' => 'hidden_user')); } } } else { $userGroup = new UserGroup(); $group_info = $userGroup->get($group_id); $form->addElement('label', get_lang('ToGroup'), api_xml_http_response_encode($group_info['name'])); $form->addElement('hidden', 'group_id', $group_id); $form->addElement('hidden', 'parent_id', $message_id); } $form->addText('title', get_lang('Subject'), true); $form->addHtmlEditor('content', get_lang('Message'), false, false, array('ToolbarSet' => 'Messages', 'Width' => '100%', 'Height' => '250')); if (isset($_GET['re_id'])) { $message_reply_info = MessageManager::get_message_by_id($_GET['re_id']); $default['title'] = get_lang('MailSubjectReplyShort') . " " . $message_reply_info['title']; $form->addElement('hidden', 're_id', intval($_GET['re_id'])); $form->addElement('hidden', 'save_form', 'save_form'); //adding reply mail $user_reply_info = api_get_user_info($message_reply_info['user_sender_id']); $default['content'] = '<p><br/></p>' . sprintf(get_lang('XWroteY'), $user_reply_info['complete_name'], Security::filter_terms($message_reply_info['content'])); } if (empty($group_id)) { $form->addElement('label', '', '<div id="filepaths" class="form-group"> <div id="filepath_1"> <label>' . get_lang('FilesAttachment') . '</label> <input type="file" name="attach_1"/> <label>' . get_lang('Description') . '</label> <input id="file-descrtiption" type="text" name="legend[]" class="form-control"/> </div> </div>'); $form->addElement('label', '', '<span id="link-more-attach"><a href="javascript://" onclick="return add_image_form()">' . get_lang('AddOneMoreFile') . '</a></span> (' . sprintf(get_lang('MaximunFileSizeX'), format_file_size(api_get_setting('message.message_max_upload_filesize'))) . ')'); } $form->addButtonSend(get_lang('SendMessage'), 'compose'); $form->setRequiredNote('<span class="form_required">*</span> <small>' . get_lang('ThisFieldIsRequired') . '</small>'); if (!empty($group_id) && !empty($message_id)) { $message_info = MessageManager::get_message_by_id($message_id); $default['title'] = get_lang('MailSubjectReplyShort') . " " . $message_info['title']; } $form->setDefaults($default); $html = ''; if ($form->validate()) { $check = Security::check_token('post'); if ($check) { $user_list = $default['users']; $file_comments = $_POST['legend']; $title = $default['title']; $content = $default['content']; $group_id = isset($default['group_id']) ? $default['group_id'] : null; $parent_id = isset($default['parent_id']) ? $default['parent_id'] : null; if (is_array($user_list) && count($user_list) > 0) { //all is well, send the message foreach ($user_list as $user) { $res = MessageManager::send_message($user, $title, $content, $_FILES, $file_comments, $group_id, $parent_id); if ($res) { $html .= MessageManager::display_success_message($user); } } } else { Display::display_error_message('ErrorSendingMessage'); } } Security::clear_token(); } else { $token = Security::get_token(); $form->addElement('hidden', 'sec_token'); $form->setConstants(array('sec_token' => $token)); $html .= $form->returnForm(); } return $html; }
$html = '<tr><td>' . get_lang('ChooseNewsLanguage') . ' : '; $html .= '<select name="news_languages">'; $html .= '<option value="all">' . get_lang('ApplyAllLanguages') . '</option>'; foreach ($_languages['name'] as $key => $value) { $english_name = $_languages['folder'][$key]; if ($language == $english_name) { $html .= '<option value="' . $english_name . '" selected="selected">' . $value . '</option>'; } else { $html .= '<option value="' . $english_name . '">' . $value . '</option>'; } } $html .= '</select></td></tr>'; $form->addElement('html', $html); } $default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open); $form->addHtmlEditor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); $form->addElement('checkbox', 'all_langs', null, get_lang('ApplyAllLanguages'), array('id' => 'all_langs')); $form->addElement('html', '<table id="table_langs" style="margin-left:5px;"><tr>'); $currentLanguage = api_get_language_isocode(); $i = 0; foreach ($_languages['name'] as $key => $value) { $lang_name = $_languages['folder'][$key]; $i++; $checked = null; if ($languageGet == $lang_name) { $checked = "checked"; } $html_langs = '<td width="300">'; $html_langs .= '<label><input type="checkbox" ' . $checked . ' id="lang" name="' . $lang_name . '" /> ' . $value . '<label/>'; $html_langs .= '</td>'; if ($i % 5 == 0) {