MDL-45565 core_message: Fixed strangers array
[moodle.git] / mod / quiz / edit.php
blob9cbf9c97523631fb938876074acc9de432296762
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Page to edit quizzes
21 * This page generally has two columns:
22 * The right column lists all available questions in a chosen category and
23 * allows them to be edited or more to be added. This column is only there if
24 * the quiz does not already have student attempts
25 * The left column lists all questions that have been added to the current quiz.
26 * The lecturer can add questions from the right hand list to the quiz or remove them
28 * The script also processes a number of actions:
29 * Actions affecting a quiz:
30 * up and down Changes the order of questions and page breaks
31 * addquestion Adds a single question to the quiz
32 * add Adds several selected questions to the quiz
33 * addrandom Adds a certain number of random questions to the quiz
34 * repaginate Re-paginates the quiz
35 * delete Removes a question from the quiz
36 * savechanges Saves the order and grades for questions in the quiz
38 * @package mod_quiz
39 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 require_once('../../config.php');
45 require_once($CFG->dirroot . '/mod/quiz/editlib.php');
46 require_once($CFG->dirroot . '/mod/quiz/addrandomform.php');
47 require_once($CFG->dirroot . '/question/category_class.php');
50 /**
51 * Callback function called from question_list() function
52 * (which is called from showbank())
53 * Displays button in form with checkboxes for each question.
55 function module_specific_buttons($cmid, $cmoptions) {
56 global $OUTPUT;
57 $params = array(
58 'type' => 'submit',
59 'name' => 'add',
60 'value' => $OUTPUT->larrow() . ' ' . get_string('addtoquiz', 'quiz'),
62 if ($cmoptions->hasattempts) {
63 $params['disabled'] = 'disabled';
65 return html_writer::empty_tag('input', $params);
68 /**
69 * Callback function called from question_list() function
70 * (which is called from showbank())
72 function module_specific_controls($totalnumber, $recurse, $category, $cmid, $cmoptions) {
73 global $OUTPUT;
74 $out = '';
75 $catcontext = context::instance_by_id($category->contextid);
76 if (has_capability('moodle/question:useall', $catcontext)) {
77 if ($cmoptions->hasattempts) {
78 $disabled = ' disabled="disabled"';
79 } else {
80 $disabled = '';
82 $randomusablequestions =
83 question_bank::get_qtype('random')->get_available_questions_from_category(
84 $category->id, $recurse);
85 $maxrand = count($randomusablequestions);
86 if ($maxrand > 0) {
87 for ($i = 1; $i <= min(10, $maxrand); $i++) {
88 $randomcount[$i] = $i;
90 for ($i = 20; $i <= min(100, $maxrand); $i += 10) {
91 $randomcount[$i] = $i;
93 } else {
94 $randomcount[0] = 0;
95 $disabled = ' disabled="disabled"';
98 $out = '<strong><label for="menurandomcount">'.get_string('addrandomfromcategory', 'quiz').
99 '</label></strong><br />';
100 $attributes = array();
101 $attributes['disabled'] = $disabled ? 'disabled' : null;
102 $select = html_writer::select($randomcount, 'randomcount', '1', null, $attributes);
103 $out .= get_string('addrandom', 'quiz', $select);
104 $out .= '<input type="hidden" name="recurse" value="'.$recurse.'" />';
105 $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />';
106 $out .= ' <input type="submit" name="addrandom" value="'.
107 get_string('addtoquiz', 'quiz').'"' . $disabled . ' />';
108 $out .= $OUTPUT->help_icon('addarandomquestion', 'quiz');
110 return $out;
113 // These params are only passed from page request to request while we stay on
114 // this page otherwise they would go in question_edit_setup.
115 $quiz_reordertool = optional_param('reordertool', -1, PARAM_BOOL);
116 $quiz_qbanktool = optional_param('qbanktool', -1, PARAM_BOOL);
117 $scrollpos = optional_param('scrollpos', '', PARAM_INT);
119 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
120 question_edit_setup('editq', '/mod/quiz/edit.php', true);
122 $defaultcategoryobj = question_make_default_categories($contexts->all());
123 $defaultcategory = $defaultcategoryobj->id . ',' . $defaultcategoryobj->contextid;
125 if ($quiz_qbanktool > -1) {
126 $thispageurl->param('qbanktool', $quiz_qbanktool);
127 set_user_preference('quiz_qbanktool_open', $quiz_qbanktool);
128 } else {
129 $quiz_qbanktool = get_user_preferences('quiz_qbanktool_open', 0);
132 if ($quiz_reordertool > -1) {
133 $thispageurl->param('reordertool', $quiz_reordertool);
134 set_user_preference('quiz_reordertab', $quiz_reordertool);
135 } else {
136 $quiz_reordertool = get_user_preferences('quiz_reordertab', 0);
139 $canaddrandom = $contexts->have_cap('moodle/question:useall');
140 $canaddquestion = (bool) $contexts->having_add_and_use();
142 $quizhasattempts = quiz_has_attempts($quiz->id);
144 $PAGE->set_url($thispageurl);
146 // Get the course object and related bits.
147 $course = $DB->get_record('course', array('id' => $quiz->course));
148 if (!$course) {
149 print_error('invalidcourseid', 'error');
152 $questionbank = new quiz_question_bank_view($contexts, $thispageurl, $course, $cm, $quiz);
153 $questionbank->set_quiz_has_attempts($quizhasattempts);
155 // You need mod/quiz:manage in addition to question capabilities to access this page.
156 require_capability('mod/quiz:manage', $contexts->lowest());
158 // Log this visit.
159 $params = array(
160 'courseid' => $course->id,
161 'context' => $contexts->lowest(),
162 'other' => array(
163 'quizid' => $quiz->id
166 $event = \mod_quiz\event\edit_page_viewed::create($params);
167 $event->trigger();
169 // Process commands ============================================================
171 // Get the list of question ids had their check-boxes ticked.
172 $selectedslots = array();
173 $params = (array) data_submitted();
174 foreach ($params as $key => $value) {
175 if (preg_match('!^s([0-9]+)$!', $key, $matches)) {
176 $selectedslots[] = $matches[1];
180 $afteractionurl = new moodle_url($thispageurl);
181 if ($scrollpos) {
182 $afteractionurl->param('scrollpos', $scrollpos);
184 if (($up = optional_param('up', false, PARAM_INT)) && confirm_sesskey()) {
185 quiz_move_question_up($quiz, $up);
186 quiz_delete_previews($quiz);
187 redirect($afteractionurl);
190 if (($down = optional_param('down', false, PARAM_INT)) && confirm_sesskey()) {
191 quiz_move_question_down($quiz, $down);
192 quiz_delete_previews($quiz);
193 redirect($afteractionurl);
196 if (optional_param('repaginate', false, PARAM_BOOL) && confirm_sesskey()) {
197 // Re-paginate the quiz.
198 $questionsperpage = optional_param('questionsperpage', $quiz->questionsperpage, PARAM_INT);
199 quiz_repaginate_questions($quiz->id, $questionsperpage );
200 quiz_delete_previews($quiz);
201 redirect($afteractionurl);
204 if (($addquestion = optional_param('addquestion', 0, PARAM_INT)) && confirm_sesskey()) {
205 // Add a single question to the current quiz.
206 quiz_require_question_use($addquestion);
207 $addonpage = optional_param('addonpage', 0, PARAM_INT);
208 quiz_add_quiz_question($addquestion, $quiz, $addonpage);
209 quiz_delete_previews($quiz);
210 quiz_update_sumgrades($quiz);
211 $thispageurl->param('lastchanged', $addquestion);
212 redirect($afteractionurl);
215 if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
216 // Add selected questions to the current quiz.
217 $rawdata = (array) data_submitted();
218 foreach ($rawdata as $key => $value) { // Parse input for question ids.
219 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
220 $key = $matches[1];
221 quiz_require_question_use($key);
222 quiz_add_quiz_question($key, $quiz);
225 quiz_delete_previews($quiz);
226 quiz_update_sumgrades($quiz);
227 redirect($afteractionurl);
230 if ((optional_param('addrandom', false, PARAM_BOOL)) && confirm_sesskey()) {
231 // Add random questions to the quiz.
232 $recurse = optional_param('recurse', 0, PARAM_BOOL);
233 $addonpage = optional_param('addonpage', 0, PARAM_INT);
234 $categoryid = required_param('categoryid', PARAM_INT);
235 $randomcount = required_param('randomcount', PARAM_INT);
236 quiz_add_random_questions($quiz, $addonpage, $categoryid, $randomcount, $recurse);
238 quiz_delete_previews($quiz);
239 quiz_update_sumgrades($quiz);
240 redirect($afteractionurl);
243 if (optional_param('addnewpagesafterselected', null, PARAM_CLEAN) &&
244 !empty($selectedslots) && confirm_sesskey()) {
245 foreach ($selectedslots as $slot) {
246 quiz_add_page_break_after_slot($quiz, $slot);
248 quiz_delete_previews($quiz);
249 redirect($afteractionurl);
252 $addpage = optional_param('addpage', false, PARAM_INT);
253 if ($addpage !== false && confirm_sesskey()) {
254 quiz_add_page_break_after_slot($quiz, $addpage);
255 quiz_delete_previews($quiz);
256 redirect($afteractionurl);
259 $deleteemptypage = optional_param('deleteemptypage', false, PARAM_INT);
260 if (($deleteemptypage !== false) && confirm_sesskey()) {
261 quiz_delete_empty_page($quiz, $deleteemptypage);
262 quiz_delete_previews($quiz);
263 redirect($afteractionurl);
266 $remove = optional_param('remove', false, PARAM_INT);
267 if ($remove && confirm_sesskey() && quiz_has_question_use($quiz, $remove)) {
268 // Remove a question from the quiz.
269 // We require the user to have the 'use' capability on the question,
270 // so that then can add it back if they remove the wrong one by mistake,
271 // but, if the question is missing, it can always be removed.
272 quiz_remove_slot($quiz, $remove);
273 quiz_delete_previews($quiz);
274 quiz_update_sumgrades($quiz);
275 redirect($afteractionurl);
278 if (optional_param('quizdeleteselected', false, PARAM_BOOL) &&
279 !empty($selectedslots) && confirm_sesskey()) {
280 // Work backwards, since removing a question renumbers following slots.
281 foreach (array_reverse($selectedslots) as $slot) {
282 if (quiz_has_question_use($quiz, $slot)) {
283 quiz_remove_slot($quiz, $slot);
286 quiz_delete_previews($quiz);
287 quiz_update_sumgrades($quiz);
288 redirect($afteractionurl);
291 if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey()) {
292 $deletepreviews = false;
293 $recomputesummarks = false;
295 $rawdata = (array) data_submitted();
296 $moveonpagequestions = array();
297 $moveselectedonpage = optional_param('moveselectedonpagetop', 0, PARAM_INT);
298 if (!$moveselectedonpage) {
299 $moveselectedonpage = optional_param('moveselectedonpagebottom', 0, PARAM_INT);
302 $newslotorder = array();
303 foreach ($rawdata as $key => $value) {
304 if (preg_match('!^g([0-9]+)$!', $key, $matches)) {
305 // Parse input for question -> grades.
306 $slotnumber = $matches[1];
307 $newgrade = unformat_float($value);
308 quiz_update_slot_maxmark($DB->get_record('quiz_slots',
309 array('quizid' => $quiz->id, 'slot' => $slotnumber), '*', MUST_EXIST), $newgrade);
310 $deletepreviews = true;
311 $recomputesummarks = true;
313 } else if (preg_match('!^o(pg)?([0-9]+)$!', $key, $matches)) {
314 // Parse input for ordering info.
315 $slotnumber = $matches[2];
316 // Make sure two questions don't overwrite each other. If we get a second
317 // question with the same position, shift the second one along to the next gap.
318 $value = clean_param($value, PARAM_INT);
319 while (array_key_exists($value, $newslotorder)) {
320 $value++;
322 if ($matches[1]) {
323 // This is a page-break entry.
324 $newslotorder[$value] = 0;
325 } else {
326 $newslotorder[$value] = $slotnumber;
328 $deletepreviews = true;
332 if ($moveselectedonpage) {
334 // Make up a $newslotorder, then let the next if statement do the work.
335 $oldslots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id), 'slot');
337 $beforepage = array();
338 $onpage = array();
339 $afterpage = array();
340 foreach ($oldslots as $oldslot) {
341 if (in_array($oldslot->slot, $selectedslots)) {
342 $onpage[] = $oldslot;
343 } else if ($oldslot->page <= $moveselectedonpage) {
344 $beforepage[] = $oldslot;
345 } else {
346 $afterpage[] = $oldslot;
350 $newslotorder = array();
351 $currentpage = 1;
352 $index = 10;
353 foreach ($beforepage as $slot) {
354 while ($currentpage < $slot->page) {
355 $newslotorder[$index] = 0;
356 $index += 10;
357 $currentpage += 1;
359 $newslotorder[$index] = $slot->slot;
360 $index += 10;
363 while ($currentpage < $moveselectedonpage) {
364 $newslotorder[$index] = 0;
365 $index += 10;
366 $currentpage += 1;
368 foreach ($onpage as $slot) {
369 $newslotorder[$index] = $slot->slot;
370 $index += 10;
373 foreach ($afterpage as $slot) {
374 while ($currentpage < $slot->page) {
375 $newslotorder[$index] = 0;
376 $index += 10;
377 $currentpage += 1;
379 $newslotorder[$index] = $slot->slot;
380 $index += 10;
384 // If ordering info was given, reorder the questions.
385 if ($newslotorder) {
386 ksort($newslotorder);
387 $currentpage = 1;
388 $currentslot = 1;
389 $slotreorder = array();
390 $slotpages = array();
391 foreach ($newslotorder as $slotnumber) {
392 if ($slotnumber == 0) {
393 $currentpage += 1;
394 continue;
396 $slotreorder[$slotnumber] = $currentslot;
397 $slotpages[$currentslot] = $currentpage;
398 $currentslot += 1;
400 $trans = $DB->start_delegated_transaction();
401 update_field_with_unique_index('quiz_slots',
402 'slot', $slotreorder, array('quizid' => $quiz->id));
403 foreach ($slotpages as $slotnumber => $page) {
404 $DB->set_field('quiz_slots', 'page', $page, array('quizid' => $quiz->id, 'slot' => $slotnumber));
406 $trans->allow_commit();
407 $deletepreviews = true;
410 // If rescaling is required save the new maximum.
411 $maxgrade = unformat_float(optional_param('maxgrade', -1, PARAM_RAW));
412 if ($maxgrade >= 0) {
413 quiz_set_grade($maxgrade, $quiz);
416 if ($deletepreviews) {
417 quiz_delete_previews($quiz);
419 if ($recomputesummarks) {
420 quiz_update_sumgrades($quiz);
421 quiz_update_all_attempt_sumgrades($quiz);
422 quiz_update_all_final_grades($quiz);
423 quiz_update_grades($quiz, 0, true);
425 redirect($afteractionurl);
428 $questionbank->process_actions($thispageurl, $cm);
430 // End of process commands =====================================================
432 $PAGE->requires->skip_link_to('questionbank',
433 get_string('skipto', 'access', get_string('questionbank', 'question')));
434 $PAGE->requires->skip_link_to('quizcontentsblock',
435 get_string('skipto', 'access', get_string('questionsinthisquiz', 'quiz')));
436 $PAGE->set_title(get_string('editingquizx', 'quiz', format_string($quiz->name)));
437 $PAGE->set_heading($course->fullname);
438 $node = $PAGE->settingsnav->find('mod_quiz_edit', navigation_node::TYPE_SETTING);
439 if ($node) {
440 $node->make_active();
442 echo $OUTPUT->header();
444 // Initialise the JavaScript.
445 $quizeditconfig = new stdClass();
446 $quizeditconfig->url = $thispageurl->out(true, array('qbanktool' => '0'));
447 $quizeditconfig->dialoglisteners = array();
448 $numberoflisteners = $DB->get_field_sql("
449 SELECT COALESCE(MAX(page), 1)
450 FROM {quiz_slots}
451 WHERE quizid = ?", array($quiz->id));
453 for ($pageiter = 1; $pageiter <= $numberoflisteners; $pageiter++) {
454 $quizeditconfig->dialoglisteners[] = 'addrandomdialoglaunch_' . $pageiter;
456 $PAGE->requires->data_for_js('quiz_edit_config', $quizeditconfig);
457 $PAGE->requires->js('/question/qengine.js');
458 $module = array(
459 'name' => 'mod_quiz_edit',
460 'fullpath' => '/mod/quiz/edit.js',
461 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
462 'strings' => array(),
463 'async' => false,
465 $PAGE->requires->js_init_call('quiz_edit_init', null, false, $module);
467 // Print the tabs to switch mode.
468 if ($quiz_reordertool) {
469 $currenttab = 'reorder';
470 } else {
471 $currenttab = 'edit';
473 $tabs = array(array(
474 new tabobject('edit', new moodle_url($thispageurl,
475 array('reordertool' => 0)), get_string('editingquiz', 'quiz')),
476 new tabobject('reorder', new moodle_url($thispageurl,
477 array('reordertool' => 1)), get_string('orderingquiz', 'quiz')),
479 print_tabs($tabs, $currenttab);
481 if ($quiz_qbanktool) {
482 $bankclass = '';
483 $quizcontentsclass = '';
484 } else {
485 $bankclass = 'collapsed ';
486 $quizcontentsclass = 'quizwhenbankcollapsed';
489 echo '<div class="questionbankwindow ' . $bankclass . 'block">';
490 echo '<div class="header"><div class="title"><h2>';
491 echo get_string('questionbankcontents', 'quiz') .
492 '&nbsp;[<a href="' . $thispageurl->out(true, array('qbanktool' => '1')) .
493 '" id="showbankcmd">' . get_string('show').
494 '</a><a href="' . $thispageurl->out(true, array('qbanktool' => '0')) .
495 '" id="hidebankcmd">' . get_string('hide').
496 '</a>]';
497 echo '</h2></div></div><div class="content">';
499 echo '<span id="questionbank"></span>';
500 echo '<div class="container">';
501 echo '<div id="module" class="module">';
502 echo '<div class="bd">';
503 $questionbank->display('editq',
504 $pagevars['qpage'],
505 $pagevars['qperpage'],
506 $pagevars['cat'], $pagevars['recurse'], $pagevars['showhidden'],
507 $pagevars['qbshowtext']);
508 echo '</div>';
509 echo '</div>';
510 echo '</div>';
512 echo '</div></div>';
514 echo '<div class="quizcontents ' . $quizcontentsclass . '" id="quizcontentsblock">';
515 if ($quiz->shufflequestions) {
516 $repaginatingdisabledhtml = 'disabled="disabled"';
517 $repaginatingdisabled = true;
518 } else {
519 $repaginatingdisabledhtml = '';
520 $repaginatingdisabled = false;
522 if ($quiz_reordertool) {
523 echo '<div class="repaginatecommand"><button id="repaginatecommand" ' .
524 $repaginatingdisabledhtml.'>'.
525 get_string('repaginatecommand', 'quiz').'...</button>';
526 echo '</div>';
529 if ($quiz_reordertool) {
530 echo $OUTPUT->heading_with_help(get_string('orderingquizx', 'quiz', format_string($quiz->name)),
531 'orderandpaging', 'quiz');
532 } else {
533 echo $OUTPUT->heading(get_string('editingquizx', 'quiz', format_string($quiz->name)), 2);
534 echo $OUTPUT->help_icon('editingquiz', 'quiz', get_string('basicideasofquiz', 'quiz'));
536 quiz_print_status_bar($quiz);
538 $tabindex = 0;
539 quiz_print_grading_form($quiz, $thispageurl, $tabindex);
541 $notifystrings = array();
542 if ($quizhasattempts) {
543 $reviewlink = quiz_attempt_summary_link_to_reports($quiz, $cm, $contexts->lowest());
544 $notifystrings[] = get_string('cannoteditafterattempts', 'quiz', $reviewlink);
546 if ($quiz->shufflequestions) {
547 $updateurl = new moodle_url("$CFG->wwwroot/course/mod.php",
548 array('return' => 'true', 'update' => $quiz->cmid, 'sesskey' => sesskey()));
549 $updatelink = '<a href="'.$updateurl->out().'">' . get_string('updatethis', '',
550 get_string('modulename', 'quiz')) . '</a>';
551 $notifystrings[] = get_string('shufflequestionsselected', 'quiz', $updatelink);
553 if (!empty($notifystrings)) {
554 echo $OUTPUT->box('<p>' . implode('</p><p>', $notifystrings) . '</p>', 'statusdisplay');
557 if ($quiz_reordertool) {
558 $perpage = array();
559 $perpage[0] = get_string('allinone', 'quiz');
560 for ($i = 1; $i <= 50; ++$i) {
561 $perpage[$i] = $i;
563 $gostring = get_string('go');
564 echo '<div id="repaginatedialog"><div class="hd">';
565 echo get_string('repaginatecommand', 'quiz');
566 echo '</div><div class="bd">';
567 echo '<form action="edit.php" method="post">';
568 echo '<fieldset class="invisiblefieldset">';
569 echo html_writer::input_hidden_params($thispageurl);
570 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
571 // YUI does not submit the value of the submit button so we need to add the value.
572 echo '<input type="hidden" name="repaginate" value="'.$gostring.'" />';
573 $attributes = array();
574 $attributes['disabled'] = $repaginatingdisabledhtml ? 'disabled' : null;
575 $select = html_writer::select(
576 $perpage, 'questionsperpage', $quiz->questionsperpage, null, $attributes);
577 print_string('repaginate', 'quiz', $select);
578 echo '<div class="quizquestionlistcontrols">';
579 echo ' <input type="submit" name="repaginate" value="'. $gostring . '" ' .
580 $repaginatingdisabledhtml.' />';
581 echo '</div></fieldset></form></div></div>';
584 if ($quiz_reordertool) {
585 echo '<div class="reorder">';
586 } else {
587 echo '<div class="editq">';
590 quiz_print_question_list($quiz, $thispageurl, true, $quiz_reordertool, $quiz_qbanktool,
591 $quizhasattempts, $defaultcategoryobj, $canaddquestion, $canaddrandom);
592 echo '</div>';
594 // Close <div class="quizcontents">.
595 echo '</div>';
597 if (!$quiz_reordertool && $canaddrandom) {
598 $randomform = new quiz_add_random_form(new moodle_url('/mod/quiz/addrandom.php'), $contexts);
599 $randomform->set_data(array(
600 'category' => $pagevars['cat'],
601 'returnurl' => $thispageurl->out_as_local_url(false),
602 'cmid' => $cm->id,
605 <div id="randomquestiondialog">
606 <div class="hd"><?php print_string('addrandomquestiontoquiz', 'quiz', $quiz->name); ?>
607 <span id="pagenumber"><!-- JavaScript will insert the page number here. -->
608 </span>
609 </div>
610 <div class="bd"><?php
611 $randomform->display();
612 ?></div>
613 </div>
614 <?php
616 echo $OUTPUT->footer();