[ Index ] |
PHP Cross Reference of Unnamed Project |
[Summary view] [Print] [Text view]
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. 13 // 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/>. 16 17 /** 18 * Back-end code for handling data about quizzes and the current user's attempt. 19 * 20 * There are classes for loading all the information about a quiz and attempts, 21 * and for displaying the navigation panel. 22 * 23 * @package mod_quiz 24 * @copyright 2008 onwards Tim Hunt 25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 26 */ 27 28 29 defined('MOODLE_INTERNAL') || die(); 30 31 32 /** 33 * Class for quiz exceptions. Just saves a couple of arguments on the 34 * constructor for a moodle_exception. 35 * 36 * @copyright 2008 Tim Hunt 37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 38 * @since Moodle 2.0 39 */ 40 class moodle_quiz_exception extends moodle_exception { 41 public function __construct($quizobj, $errorcode, $a = null, $link = '', $debuginfo = null) { 42 if (!$link) { 43 $link = $quizobj->view_url(); 44 } 45 parent::__construct($errorcode, 'quiz', $link, $a, $debuginfo); 46 } 47 } 48 49 50 /** 51 * A class encapsulating a quiz and the questions it contains, and making the 52 * information available to scripts like view.php. 53 * 54 * Initially, it only loads a minimal amout of information about each question - loading 55 * extra information only when necessary or when asked. The class tracks which questions 56 * are loaded. 57 * 58 * @copyright 2008 Tim Hunt 59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 60 * @since Moodle 2.0 61 */ 62 class quiz { 63 /** @var stdClass the course settings from the database. */ 64 protected $course; 65 /** @var stdClass the course_module settings from the database. */ 66 protected $cm; 67 /** @var stdClass the quiz settings from the database. */ 68 protected $quiz; 69 /** @var context the quiz context. */ 70 protected $context; 71 72 /** @var array of questions augmented with slot information. */ 73 protected $questions = null; 74 /** @var array of quiz_section rows. */ 75 protected $sections = null; 76 /** @var quiz_access_manager the access manager for this quiz. */ 77 protected $accessmanager = null; 78 /** @var bool whether the current user has capability mod/quiz:preview. */ 79 protected $ispreviewuser = null; 80 81 // Constructor ============================================================= 82 /** 83 * Constructor, assuming we already have the necessary data loaded. 84 * 85 * @param object $quiz the row from the quiz table. 86 * @param object $cm the course_module object for this quiz. 87 * @param object $course the row from the course table for the course we belong to. 88 * @param bool $getcontext intended for testing - stops the constructor getting the context. 89 */ 90 public function __construct($quiz, $cm, $course, $getcontext = true) { 91 $this->quiz = $quiz; 92 $this->cm = $cm; 93 $this->quiz->cmid = $this->cm->id; 94 $this->course = $course; 95 if ($getcontext && !empty($cm->id)) { 96 $this->context = context_module::instance($cm->id); 97 } 98 } 99 100 /** 101 * Static function to create a new quiz object for a specific user. 102 * 103 * @param int $quizid the the quiz id. 104 * @param int $userid the the userid. 105 * @return quiz the new quiz object 106 */ 107 public static function create($quizid, $userid = null) { 108 global $DB; 109 110 $quiz = quiz_access_manager::load_quiz_and_settings($quizid); 111 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST); 112 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST); 113 114 // Update quiz with override information. 115 if ($userid) { 116 $quiz = quiz_update_effective_access($quiz, $userid); 117 } 118 119 return new quiz($quiz, $cm, $course); 120 } 121 122 /** 123 * Create a {@link quiz_attempt} for an attempt at this quiz. 124 * @param object $attemptdata row from the quiz_attempts table. 125 * @return quiz_attempt the new quiz_attempt object. 126 */ 127 public function create_attempt_object($attemptdata) { 128 return new quiz_attempt($attemptdata, $this->quiz, $this->cm, $this->course); 129 } 130 131 // Functions for loading more data ========================================= 132 133 /** 134 * Load just basic information about all the questions in this quiz. 135 */ 136 public function preload_questions() { 137 $this->questions = question_preload_questions(null, 138 'slot.maxmark, slot.id AS slotid, slot.slot, slot.page', 139 '{quiz_slots} slot ON slot.quizid = :quizid AND q.id = slot.questionid', 140 array('quizid' => $this->quiz->id), 'slot.slot'); 141 } 142 143 /** 144 * Fully load some or all of the questions for this quiz. You must call 145 * {@link preload_questions()} first. 146 * 147 * @param array $questionids question ids of the questions to load. null for all. 148 */ 149 public function load_questions($questionids = null) { 150 if ($this->questions === null) { 151 throw new coding_exception('You must call preload_questions before calling load_questions.'); 152 } 153 if (is_null($questionids)) { 154 $questionids = array_keys($this->questions); 155 } 156 $questionstoprocess = array(); 157 foreach ($questionids as $id) { 158 if (array_key_exists($id, $this->questions)) { 159 $questionstoprocess[$id] = $this->questions[$id]; 160 } 161 } 162 get_question_options($questionstoprocess); 163 } 164 165 /** 166 * Get an instance of the {@link \mod_quiz\structure} class for this quiz. 167 * @return \mod_quiz\structure describes the questions in the quiz. 168 */ 169 public function get_structure() { 170 return \mod_quiz\structure::create_for_quiz($this); 171 } 172 173 // Simple getters ========================================================== 174 /** @return int the course id. */ 175 public function get_courseid() { 176 return $this->course->id; 177 } 178 179 /** @return object the row of the course table. */ 180 public function get_course() { 181 return $this->course; 182 } 183 184 /** @return int the quiz id. */ 185 public function get_quizid() { 186 return $this->quiz->id; 187 } 188 189 /** @return object the row of the quiz table. */ 190 public function get_quiz() { 191 return $this->quiz; 192 } 193 194 /** @return string the name of this quiz. */ 195 public function get_quiz_name() { 196 return $this->quiz->name; 197 } 198 199 /** @return int the quiz navigation method. */ 200 public function get_navigation_method() { 201 return $this->quiz->navmethod; 202 } 203 204 /** @return int the number of attempts allowed at this quiz (0 = infinite). */ 205 public function get_num_attempts_allowed() { 206 return $this->quiz->attempts; 207 } 208 209 /** @return int the course_module id. */ 210 public function get_cmid() { 211 return $this->cm->id; 212 } 213 214 /** @return object the course_module object. */ 215 public function get_cm() { 216 return $this->cm; 217 } 218 219 /** @return object the module context for this quiz. */ 220 public function get_context() { 221 return $this->context; 222 } 223 224 /** 225 * @return bool wether the current user is someone who previews the quiz, 226 * rather than attempting it. 227 */ 228 public function is_preview_user() { 229 if (is_null($this->ispreviewuser)) { 230 $this->ispreviewuser = has_capability('mod/quiz:preview', $this->context); 231 } 232 return $this->ispreviewuser; 233 } 234 235 /** 236 * @return whether any questions have been added to this quiz. 237 */ 238 public function has_questions() { 239 if ($this->questions === null) { 240 $this->preload_questions(); 241 } 242 return !empty($this->questions); 243 } 244 245 /** 246 * @param int $id the question id. 247 * @return object the question object with that id. 248 */ 249 public function get_question($id) { 250 return $this->questions[$id]; 251 } 252 253 /** 254 * @param array $questionids question ids of the questions to load. null for all. 255 */ 256 public function get_questions($questionids = null) { 257 if (is_null($questionids)) { 258 $questionids = array_keys($this->questions); 259 } 260 $questions = array(); 261 foreach ($questionids as $id) { 262 if (!array_key_exists($id, $this->questions)) { 263 throw new moodle_exception('cannotstartmissingquestion', 'quiz', $this->view_url()); 264 } 265 $questions[$id] = $this->questions[$id]; 266 $this->ensure_question_loaded($id); 267 } 268 return $questions; 269 } 270 271 /** 272 * Get all the sections in this quiz. 273 * @return array 0, 1, 2, ... => quiz_sections row from the database. 274 */ 275 public function get_sections() { 276 global $DB; 277 if ($this->sections === null) { 278 $this->sections = array_values($DB->get_records('quiz_sections', 279 array('quizid' => $this->get_quizid()), 'firstslot')); 280 } 281 return $this->sections; 282 } 283 284 /** 285 * Return quiz_access_manager and instance of the quiz_access_manager class 286 * for this quiz at this time. 287 * @param int $timenow the current time as a unix timestamp. 288 * @return quiz_access_manager and instance of the quiz_access_manager class 289 * for this quiz at this time. 290 */ 291 public function get_access_manager($timenow) { 292 if (is_null($this->accessmanager)) { 293 $this->accessmanager = new quiz_access_manager($this, $timenow, 294 has_capability('mod/quiz:ignoretimelimits', $this->context, null, false)); 295 } 296 return $this->accessmanager; 297 } 298 299 /** 300 * Wrapper round the has_capability funciton that automatically passes in the quiz context. 301 */ 302 public function has_capability($capability, $userid = null, $doanything = true) { 303 return has_capability($capability, $this->context, $userid, $doanything); 304 } 305 306 /** 307 * Wrapper round the require_capability funciton that automatically passes in the quiz context. 308 */ 309 public function require_capability($capability, $userid = null, $doanything = true) { 310 return require_capability($capability, $this->context, $userid, $doanything); 311 } 312 313 // URLs related to this attempt ============================================ 314 /** 315 * @return string the URL of this quiz's view page. 316 */ 317 public function view_url() { 318 global $CFG; 319 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $this->cm->id; 320 } 321 322 /** 323 * @return string the URL of this quiz's edit page. 324 */ 325 public function edit_url() { 326 global $CFG; 327 return $CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $this->cm->id; 328 } 329 330 /** 331 * @param int $attemptid the id of an attempt. 332 * @param int $page optional page number to go to in the attempt. 333 * @return string the URL of that attempt. 334 */ 335 public function attempt_url($attemptid, $page = 0) { 336 global $CFG; 337 $url = $CFG->wwwroot . '/mod/quiz/attempt.php?attempt=' . $attemptid; 338 if ($page) { 339 $url .= '&page=' . $page; 340 } 341 return $url; 342 } 343 344 /** 345 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter. 346 */ 347 public function start_attempt_url($page = 0) { 348 $params = array('cmid' => $this->cm->id, 'sesskey' => sesskey()); 349 if ($page) { 350 $params['page'] = $page; 351 } 352 return new moodle_url('/mod/quiz/startattempt.php', $params); 353 } 354 355 /** 356 * @param int $attemptid the id of an attempt. 357 * @return string the URL of the review of that attempt. 358 */ 359 public function review_url($attemptid) { 360 return new moodle_url('/mod/quiz/review.php', array('attempt' => $attemptid)); 361 } 362 363 /** 364 * @param int $attemptid the id of an attempt. 365 * @return string the URL of the review of that attempt. 366 */ 367 public function summary_url($attemptid) { 368 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $attemptid)); 369 } 370 371 // Bits of content ========================================================= 372 373 /** 374 * @param bool $notused not used. 375 * @return string an empty string. 376 * @deprecated since 3.1. This sort of functionality is now entirely handled by quiz access rules. 377 */ 378 public function confirm_start_attempt_message($notused) { 379 debugging('confirm_start_attempt_message is deprecated. ' . 380 'This sort of functionality is now entirely handled by quiz access rules.'); 381 return ''; 382 } 383 384 /** 385 * If $reviewoptions->attempt is false, meaning that students can't review this 386 * attempt at the moment, return an appropriate string explaining why. 387 * 388 * @param int $when One of the mod_quiz_display_options::DURING, 389 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants. 390 * @param bool $short if true, return a shorter string. 391 * @return string an appropraite message. 392 */ 393 public function cannot_review_message($when, $short = false) { 394 395 if ($short) { 396 $langstrsuffix = 'short'; 397 $dateformat = get_string('strftimedatetimeshort', 'langconfig'); 398 } else { 399 $langstrsuffix = ''; 400 $dateformat = ''; 401 } 402 403 if ($when == mod_quiz_display_options::DURING || 404 $when == mod_quiz_display_options::IMMEDIATELY_AFTER) { 405 return ''; 406 } else if ($when == mod_quiz_display_options::LATER_WHILE_OPEN && $this->quiz->timeclose && 407 $this->quiz->reviewattempt & mod_quiz_display_options::AFTER_CLOSE) { 408 return get_string('noreviewuntil' . $langstrsuffix, 'quiz', 409 userdate($this->quiz->timeclose, $dateformat)); 410 } else { 411 return get_string('noreview' . $langstrsuffix, 'quiz'); 412 } 413 } 414 415 /** 416 * @param string $title the name of this particular quiz page. 417 * @return array the data that needs to be sent to print_header_simple as the $navigation 418 * parameter. 419 */ 420 public function navigation($title) { 421 global $PAGE; 422 $PAGE->navbar->add($title); 423 return ''; 424 } 425 426 // Private methods ========================================================= 427 /** 428 * Check that the definition of a particular question is loaded, and if not throw an exception. 429 * @param $id a questionid. 430 */ 431 protected function ensure_question_loaded($id) { 432 if (isset($this->questions[$id]->_partiallyloaded)) { 433 throw new moodle_quiz_exception($this, 'questionnotloaded', $id); 434 } 435 } 436 437 /** 438 * Return all the question types used in this quiz. 439 * 440 * @param boolean $includepotential if the quiz include random questions, setting this flag to true will make the function to 441 * return all the possible question types in the random questions category 442 * @return array a sorted array including the different question types 443 * @since Moodle 3.1 444 */ 445 public function get_all_question_types_used($includepotential = false) { 446 $questiontypes = array(); 447 448 // To control if we need to look in categories for questions. 449 $qcategories = array(); 450 451 // We must be careful with random questions, if we find a random question we must assume that the quiz may content 452 // any of the questions in the referenced category (or subcategories). 453 foreach ($this->get_questions() as $questiondata) { 454 if ($questiondata->qtype == 'random' and $includepotential) { 455 $includesubcategories = (bool) $questiondata->questiontext; 456 if (!isset($qcategories[$questiondata->category])) { 457 $qcategories[$questiondata->category] = false; 458 } 459 if ($includesubcategories) { 460 $qcategories[$questiondata->category] = true; 461 } 462 } else { 463 if (!in_array($questiondata->qtype, $questiontypes)) { 464 $questiontypes[] = $questiondata->qtype; 465 } 466 } 467 } 468 469 if (!empty($qcategories)) { 470 // We have to look for all the question types in these categories. 471 $categoriestolook = array(); 472 foreach ($qcategories as $cat => $includesubcats) { 473 if ($includesubcats) { 474 $categoriestolook = array_merge($categoriestolook, question_categorylist($cat)); 475 } else { 476 $categoriestolook[] = $cat; 477 } 478 } 479 $questiontypesincategories = question_bank::get_all_question_types_in_categories($categoriestolook); 480 $questiontypes = array_merge($questiontypes, $questiontypesincategories); 481 } 482 $questiontypes = array_unique($questiontypes); 483 sort($questiontypes); 484 485 return $questiontypes; 486 } 487 } 488 489 490 /** 491 * This class extends the quiz class to hold data about the state of a particular attempt, 492 * in addition to the data about the quiz. 493 * 494 * @copyright 2008 Tim Hunt 495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 496 * @since Moodle 2.0 497 */ 498 class quiz_attempt { 499 500 /** @var string to identify the in progress state. */ 501 const IN_PROGRESS = 'inprogress'; 502 /** @var string to identify the overdue state. */ 503 const OVERDUE = 'overdue'; 504 /** @var string to identify the finished state. */ 505 const FINISHED = 'finished'; 506 /** @var string to identify the abandoned state. */ 507 const ABANDONED = 'abandoned'; 508 509 /** @var int maximum number of slots in the quiz for the review page to default to show all. */ 510 const MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL = 50; 511 512 /** @var quiz object containing the quiz settings. */ 513 protected $quizobj; 514 515 /** @var stdClass the quiz_attempts row. */ 516 protected $attempt; 517 518 /** @var question_usage_by_activity the question usage for this quiz attempt. */ 519 protected $quba; 520 521 /** 522 * @var array of slot information. These objects contain ->slot (int), 523 * ->requireprevious (bool), ->questionids (int) the original question for random questions, 524 * ->firstinsection (bool), ->section (stdClass from $this->sections). 525 * This does not contain page - get that from {@link get_question_page()} - 526 * or maxmark - get that from $this->quba. 527 */ 528 protected $slots; 529 530 /** @var array of quiz_sections rows, with a ->lastslot field added. */ 531 protected $sections; 532 533 /** @var array page no => array of slot numbers on the page in order. */ 534 protected $pagelayout; 535 536 /** @var array slot => displayed question number for this slot. (E.g. 1, 2, 3 or 'i'.) */ 537 protected $questionnumbers; 538 539 /** @var array slot => page number for this slot. */ 540 protected $questionpages; 541 542 /** @var mod_quiz_display_options cache for the appropriate review options. */ 543 protected $reviewoptions = null; 544 545 // Constructor ============================================================= 546 /** 547 * Constructor assuming we already have the necessary data loaded. 548 * 549 * @param object $attempt the row of the quiz_attempts table. 550 * @param object $quiz the quiz object for this attempt and user. 551 * @param object $cm the course_module object for this quiz. 552 * @param object $course the row from the course table for the course we belong to. 553 * @param bool $loadquestions (optional) if true, the default, load all the details 554 * of the state of each question. Else just set up the basic details of the attempt. 555 */ 556 public function __construct($attempt, $quiz, $cm, $course, $loadquestions = true) { 557 global $DB; 558 559 $this->attempt = $attempt; 560 $this->quizobj = new quiz($quiz, $cm, $course); 561 562 if (!$loadquestions) { 563 return; 564 } 565 566 $this->quba = question_engine::load_questions_usage_by_activity($this->attempt->uniqueid); 567 $this->slots = $DB->get_records('quiz_slots', 568 array('quizid' => $this->get_quizid()), 'slot', 569 'slot, requireprevious, questionid'); 570 $this->sections = array_values($DB->get_records('quiz_sections', 571 array('quizid' => $this->get_quizid()), 'firstslot')); 572 573 $this->link_sections_and_slots(); 574 $this->determine_layout(); 575 $this->number_questions(); 576 } 577 578 /** 579 * Used by {create()} and {create_from_usage_id()}. 580 * @param array $conditions passed to $DB->get_record('quiz_attempts', $conditions). 581 */ 582 protected static function create_helper($conditions) { 583 global $DB; 584 585 $attempt = $DB->get_record('quiz_attempts', $conditions, '*', MUST_EXIST); 586 $quiz = quiz_access_manager::load_quiz_and_settings($attempt->quiz); 587 $course = $DB->get_record('course', array('id' => $quiz->course), '*', MUST_EXIST); 588 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $course->id, false, MUST_EXIST); 589 590 // Update quiz with override information. 591 $quiz = quiz_update_effective_access($quiz, $attempt->userid); 592 593 return new quiz_attempt($attempt, $quiz, $cm, $course); 594 } 595 596 /** 597 * Static function to create a new quiz_attempt object given an attemptid. 598 * 599 * @param int $attemptid the attempt id. 600 * @return quiz_attempt the new quiz_attempt object 601 */ 602 public static function create($attemptid) { 603 return self::create_helper(array('id' => $attemptid)); 604 } 605 606 /** 607 * Static function to create a new quiz_attempt object given a usage id. 608 * 609 * @param int $usageid the attempt usage id. 610 * @return quiz_attempt the new quiz_attempt object 611 */ 612 public static function create_from_usage_id($usageid) { 613 return self::create_helper(array('uniqueid' => $usageid)); 614 } 615 616 /** 617 * @param string $state one of the state constants like IN_PROGRESS. 618 * @return string the human-readable state name. 619 */ 620 public static function state_name($state) { 621 return quiz_attempt_state_name($state); 622 } 623 624 /** 625 * Let each slot know which section it is part of. 626 */ 627 protected function link_sections_and_slots() { 628 foreach ($this->sections as $i => $section) { 629 if (isset($this->sections[$i + 1])) { 630 $section->lastslot = $this->sections[$i + 1]->firstslot - 1; 631 } else { 632 $section->lastslot = count($this->slots); 633 } 634 for ($slot = $section->firstslot; $slot <= $section->lastslot; $slot += 1) { 635 $this->slots[$slot]->section = $section; 636 } 637 } 638 } 639 640 /** 641 * Parse attempt->layout to populate the other arrays the represent the layout. 642 */ 643 protected function determine_layout() { 644 $this->pagelayout = array(); 645 646 // Break up the layout string into pages. 647 $pagelayouts = explode(',0', $this->attempt->layout); 648 649 // Strip off any empty last page (normally there is one). 650 if (end($pagelayouts) == '') { 651 array_pop($pagelayouts); 652 } 653 654 // File the ids into the arrays. 655 // Tracking which is the first slot in each section in this attempt is 656 // trickier than you might guess, since the slots in this section 657 // may be shuffled, so $section->firstslot (the lowest numbered slot in 658 // the section) may not be the first one. 659 $unseensections = $this->sections; 660 $this->pagelayout = array(); 661 foreach ($pagelayouts as $page => $pagelayout) { 662 $pagelayout = trim($pagelayout, ','); 663 if ($pagelayout == '') { 664 continue; 665 } 666 $this->pagelayout[$page] = explode(',', $pagelayout); 667 foreach ($this->pagelayout[$page] as $slot) { 668 $sectionkey = array_search($this->slots[$slot]->section, $unseensections); 669 if ($sectionkey !== false) { 670 $this->slots[$slot]->firstinsection = true; 671 unset($unseensections[$sectionkey]); 672 } else { 673 $this->slots[$slot]->firstinsection = false; 674 } 675 } 676 } 677 } 678 679 /** 680 * Work out the number to display for each question/slot. 681 */ 682 protected function number_questions() { 683 $number = 1; 684 foreach ($this->pagelayout as $page => $slots) { 685 foreach ($slots as $slot) { 686 if ($length = $this->is_real_question($slot)) { 687 $this->questionnumbers[$slot] = $number; 688 $number += $length; 689 } else { 690 $this->questionnumbers[$slot] = get_string('infoshort', 'quiz'); 691 } 692 $this->questionpages[$slot] = $page; 693 } 694 } 695 } 696 697 /** 698 * If the given page number is out of range (before the first page, or after 699 * the last page, chnage it to be within range). 700 * @param int $page the requested page number. 701 * @return int a safe page number to use. 702 */ 703 public function force_page_number_into_range($page) { 704 return min(max($page, 0), count($this->pagelayout) - 1); 705 } 706 707 // Simple getters ========================================================== 708 public function get_quiz() { 709 return $this->quizobj->get_quiz(); 710 } 711 712 public function get_quizobj() { 713 return $this->quizobj; 714 } 715 716 /** @return int the course id. */ 717 public function get_courseid() { 718 return $this->quizobj->get_courseid(); 719 } 720 721 /** @return int the course id. */ 722 public function get_course() { 723 return $this->quizobj->get_course(); 724 } 725 726 /** @return int the quiz id. */ 727 public function get_quizid() { 728 return $this->quizobj->get_quizid(); 729 } 730 731 /** @return string the name of this quiz. */ 732 public function get_quiz_name() { 733 return $this->quizobj->get_quiz_name(); 734 } 735 736 /** @return int the quiz navigation method. */ 737 public function get_navigation_method() { 738 return $this->quizobj->get_navigation_method(); 739 } 740 741 /** @return object the course_module object. */ 742 public function get_cm() { 743 return $this->quizobj->get_cm(); 744 } 745 746 /** @return object the course_module object. */ 747 public function get_cmid() { 748 return $this->quizobj->get_cmid(); 749 } 750 751 /** 752 * @return bool wether the current user is someone who previews the quiz, 753 * rather than attempting it. 754 */ 755 public function is_preview_user() { 756 return $this->quizobj->is_preview_user(); 757 } 758 759 /** @return int the number of attempts allowed at this quiz (0 = infinite). */ 760 public function get_num_attempts_allowed() { 761 return $this->quizobj->get_num_attempts_allowed(); 762 } 763 764 /** @return int number fo pages in this quiz. */ 765 public function get_num_pages() { 766 return count($this->pagelayout); 767 } 768 769 /** 770 * @param int $timenow the current time as a unix timestamp. 771 * @return quiz_access_manager and instance of the quiz_access_manager class 772 * for this quiz at this time. 773 */ 774 public function get_access_manager($timenow) { 775 return $this->quizobj->get_access_manager($timenow); 776 } 777 778 /** @return int the attempt id. */ 779 public function get_attemptid() { 780 return $this->attempt->id; 781 } 782 783 /** @return int the attempt unique id. */ 784 public function get_uniqueid() { 785 return $this->attempt->uniqueid; 786 } 787 788 /** @return object the row from the quiz_attempts table. */ 789 public function get_attempt() { 790 return $this->attempt; 791 } 792 793 /** @return int the number of this attemp (is it this user's first, second, ... attempt). */ 794 public function get_attempt_number() { 795 return $this->attempt->attempt; 796 } 797 798 /** @return string one of the quiz_attempt::IN_PROGRESS, FINISHED, OVERDUE or ABANDONED constants. */ 799 public function get_state() { 800 return $this->attempt->state; 801 } 802 803 /** @return int the id of the user this attempt belongs to. */ 804 public function get_userid() { 805 return $this->attempt->userid; 806 } 807 808 /** @return int the current page of the attempt. */ 809 public function get_currentpage() { 810 return $this->attempt->currentpage; 811 } 812 813 public function get_sum_marks() { 814 return $this->attempt->sumgrades; 815 } 816 817 /** 818 * @return bool whether this attempt has been finished (true) or is still 819 * in progress (false). Be warned that this is not just state == self::FINISHED, 820 * it also includes self::ABANDONED. 821 */ 822 public function is_finished() { 823 return $this->attempt->state == self::FINISHED || $this->attempt->state == self::ABANDONED; 824 } 825 826 /** @return bool whether this attempt is a preview attempt. */ 827 public function is_preview() { 828 return $this->attempt->preview; 829 } 830 831 /** 832 * Is this someone dealing with their own attempt or preview? 833 * 834 * @return bool true => own attempt/preview. false => reviewing someone elses. 835 */ 836 public function is_own_attempt() { 837 global $USER; 838 return $this->attempt->userid == $USER->id; 839 } 840 841 /** 842 * @return bool whether this attempt is a preview belonging to the current user. 843 */ 844 public function is_own_preview() { 845 global $USER; 846 return $this->is_own_attempt() && 847 $this->is_preview_user() && $this->attempt->preview; 848 } 849 850 /** 851 * Is the current user allowed to review this attempt. This applies when 852 * {@link is_own_attempt()} returns false. 853 * @return bool whether the review should be allowed. 854 */ 855 public function is_review_allowed() { 856 if (!$this->has_capability('mod/quiz:viewreports')) { 857 return false; 858 } 859 860 $cm = $this->get_cm(); 861 if ($this->has_capability('moodle/site:accessallgroups') || 862 groups_get_activity_groupmode($cm) != SEPARATEGROUPS) { 863 return true; 864 } 865 866 // Check the users have at least one group in common. 867 $teachersgroups = groups_get_activity_allowed_groups($cm); 868 $studentsgroups = groups_get_all_groups( 869 $cm->course, $this->attempt->userid, $cm->groupingid); 870 return $teachersgroups && $studentsgroups && 871 array_intersect(array_keys($teachersgroups), array_keys($studentsgroups)); 872 } 873 874 /** 875 * Has the student, in this attempt, engaged with the quiz in a non-trivial way? 876 * That is, is there any question worth a non-zero number of marks, where 877 * the student has made some response that we have saved? 878 * @return bool true if we have saved a response for at least one graded question. 879 */ 880 public function has_response_to_at_least_one_graded_question() { 881 foreach ($this->quba->get_attempt_iterator() as $qa) { 882 if ($qa->get_max_mark() == 0) { 883 continue; 884 } 885 if ($qa->get_num_steps() > 1) { 886 return true; 887 } 888 } 889 return false; 890 } 891 892 /** 893 * Get extra summary information about this attempt. 894 * 895 * Some behaviours may be able to provide interesting summary information 896 * about the attempt as a whole, and this method provides access to that data. 897 * To see how this works, try setting a quiz to one of the CBM behaviours, 898 * and then look at the extra information displayed at the top of the quiz 899 * review page once you have sumitted an attempt. 900 * 901 * In the return value, the array keys are identifiers of the form 902 * qbehaviour_behaviourname_meaningfullkey. For qbehaviour_deferredcbm_highsummary. 903 * The values are arrays with two items, title and content. Each of these 904 * will be either a string, or a renderable. 905 * 906 * @param question_display_options $options the display options for this quiz attempt at this time. 907 * @return array as described above. 908 */ 909 public function get_additional_summary_data(question_display_options $options) { 910 return $this->quba->get_summary_information($options); 911 } 912 913 /** 914 * Get the overall feedback corresponding to a particular mark. 915 * @param $grade a particular grade. 916 */ 917 public function get_overall_feedback($grade) { 918 return quiz_feedback_for_grade($grade, $this->get_quiz(), 919 $this->quizobj->get_context()); 920 } 921 922 /** 923 * Wrapper round the has_capability funciton that automatically passes in the quiz context. 924 */ 925 public function has_capability($capability, $userid = null, $doanything = true) { 926 return $this->quizobj->has_capability($capability, $userid, $doanything); 927 } 928 929 /** 930 * Wrapper round the require_capability funciton that automatically passes in the quiz context. 931 */ 932 public function require_capability($capability, $userid = null, $doanything = true) { 933 return $this->quizobj->require_capability($capability, $userid, $doanything); 934 } 935 936 /** 937 * Check the appropriate capability to see whether this user may review their own attempt. 938 * If not, prints an error. 939 */ 940 public function check_review_capability() { 941 if ($this->get_attempt_state() == mod_quiz_display_options::IMMEDIATELY_AFTER) { 942 $capability = 'mod/quiz:attempt'; 943 } else { 944 $capability = 'mod/quiz:reviewmyattempts'; 945 } 946 947 // These next tests are in a slighly funny order. The point is that the 948 // common and most performance-critical case is students attempting a quiz 949 // so we want to check that permisison first. 950 951 if ($this->has_capability($capability)) { 952 // User has the permission that lets you do the quiz as a student. Fine. 953 return; 954 } 955 956 if ($this->has_capability('mod/quiz:viewreports') || 957 $this->has_capability('mod/quiz:preview')) { 958 // User has the permission that lets teachers review. Fine. 959 return; 960 } 961 962 // They should not be here. Trigger the standard no-permission error 963 // but using the name of the student capability. 964 // We know this will fail. We just want the stadard exception thown. 965 $this->require_capability($capability); 966 } 967 968 /** 969 * Checks whether a user may navigate to a particular slot 970 */ 971 public function can_navigate_to($slot) { 972 switch ($this->get_navigation_method()) { 973 case QUIZ_NAVMETHOD_FREE: 974 return true; 975 break; 976 case QUIZ_NAVMETHOD_SEQ: 977 return false; 978 break; 979 } 980 return true; 981 } 982 983 /** 984 * @return int one of the mod_quiz_display_options::DURING, 985 * IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants. 986 */ 987 public function get_attempt_state() { 988 return quiz_attempt_state($this->get_quiz(), $this->attempt); 989 } 990 991 /** 992 * Wrapper that the correct mod_quiz_display_options for this quiz at the 993 * moment. 994 * 995 * @return question_display_options the render options for this user on this attempt. 996 */ 997 public function get_display_options($reviewing) { 998 if ($reviewing) { 999 if (is_null($this->reviewoptions)) { 1000 $this->reviewoptions = quiz_get_review_options($this->get_quiz(), 1001 $this->attempt, $this->quizobj->get_context()); 1002 if ($this->is_own_preview()) { 1003 // It should always be possible for a teacher to review their 1004 // own preview irrespective of the review options settings. 1005 $this->reviewoptions->attempt = true; 1006 } 1007 } 1008 return $this->reviewoptions; 1009 1010 } else { 1011 $options = mod_quiz_display_options::make_from_quiz($this->get_quiz(), 1012 mod_quiz_display_options::DURING); 1013 $options->flags = quiz_get_flag_option($this->attempt, $this->quizobj->get_context()); 1014 return $options; 1015 } 1016 } 1017 1018 /** 1019 * Wrapper that the correct mod_quiz_display_options for this quiz at the 1020 * moment. 1021 * 1022 * @param bool $reviewing true for review page, else attempt page. 1023 * @param int $slot which question is being displayed. 1024 * @param moodle_url $thispageurl to return to after the editing form is 1025 * submitted or cancelled. If null, no edit link will be generated. 1026 * 1027 * @return question_display_options the render options for this user on this 1028 * attempt, with extra info to generate an edit link, if applicable. 1029 */ 1030 public function get_display_options_with_edit_link($reviewing, $slot, $thispageurl) { 1031 $options = clone($this->get_display_options($reviewing)); 1032 1033 if (!$thispageurl) { 1034 return $options; 1035 } 1036 1037 if (!($reviewing || $this->is_preview())) { 1038 return $options; 1039 } 1040 1041 $question = $this->quba->get_question($slot); 1042 if (!question_has_capability_on($question, 'edit', $question->category)) { 1043 return $options; 1044 } 1045 1046 $options->editquestionparams['cmid'] = $this->get_cmid(); 1047 $options->editquestionparams['returnurl'] = $thispageurl; 1048 1049 return $options; 1050 } 1051 1052 /** 1053 * @param int $page page number 1054 * @return bool true if this is the last page of the quiz. 1055 */ 1056 public function is_last_page($page) { 1057 return $page == count($this->pagelayout) - 1; 1058 } 1059 1060 /** 1061 * Return the list of slot numbers for either a given page of the quiz, or for the 1062 * whole quiz. 1063 * 1064 * @param mixed $page string 'all' or integer page number. 1065 * @return array the requested list of slot numbers. 1066 */ 1067 public function get_slots($page = 'all') { 1068 if ($page === 'all') { 1069 $numbers = array(); 1070 foreach ($this->pagelayout as $numbersonpage) { 1071 $numbers = array_merge($numbers, $numbersonpage); 1072 } 1073 return $numbers; 1074 } else { 1075 return $this->pagelayout[$page]; 1076 } 1077 } 1078 1079 /** 1080 * Return the list of slot numbers for either a given page of the quiz, or for the 1081 * whole quiz. 1082 * 1083 * @param mixed $page string 'all' or integer page number. 1084 * @return array the requested list of slot numbers. 1085 */ 1086 public function get_active_slots($page = 'all') { 1087 $activeslots = array(); 1088 foreach ($this->get_slots($page) as $slot) { 1089 if (!$this->is_blocked_by_previous_question($slot)) { 1090 $activeslots[] = $slot; 1091 } 1092 } 1093 return $activeslots; 1094 } 1095 1096 /** 1097 * Get the question_attempt object for a particular question in this attempt. 1098 * @param int $slot the number used to identify this question within this attempt. 1099 * @return question_attempt 1100 */ 1101 public function get_question_attempt($slot) { 1102 return $this->quba->get_question_attempt($slot); 1103 } 1104 1105 /** 1106 * Get the question_attempt object for a particular question in this attempt. 1107 * @param int $slot the number used to identify this question within this attempt. 1108 * @return question_attempt 1109 */ 1110 public function all_question_attempts_originally_in_slot($slot) { 1111 $qas = array(); 1112 foreach ($this->quba->get_attempt_iterator() as $qa) { 1113 if ($qa->get_metadata('originalslot') == $slot) { 1114 $qas[] = $qa; 1115 } 1116 } 1117 $qas[] = $this->quba->get_question_attempt($slot); 1118 return $qas; 1119 } 1120 1121 /** 1122 * Is a particular question in this attempt a real question, or something like a description. 1123 * @param int $slot the number used to identify this question within this attempt. 1124 * @return int whether that question is a real question. Actually returns the 1125 * question length, which could theoretically be greater than one. 1126 */ 1127 public function is_real_question($slot) { 1128 return $this->quba->get_question($slot)->length; 1129 } 1130 1131 /** 1132 * Is a particular question in this attempt a real question, or something like a description. 1133 * @param int $slot the number used to identify this question within this attempt. 1134 * @return bool whether that question is a real question. 1135 */ 1136 public function is_question_flagged($slot) { 1137 return $this->quba->get_question_attempt($slot)->is_flagged(); 1138 } 1139 1140 /** 1141 * Checks whether the question in this slot requires the previous question to have been completed. 1142 * 1143 * @param int $slot the number used to identify this question within this attempt. 1144 * @return bool whether the previous question must have been completed before this one can be seen. 1145 */ 1146 public function is_blocked_by_previous_question($slot) { 1147 return $slot > 1 && isset($this->slots[$slot]) && $this->slots[$slot]->requireprevious && 1148 !$this->slots[$slot]->section->shufflequestions && 1149 !$this->slots[$slot - 1]->section->shufflequestions && 1150 $this->get_navigation_method() != QUIZ_NAVMETHOD_SEQ && 1151 !$this->get_question_state($slot - 1)->is_finished() && 1152 $this->quba->can_question_finish_during_attempt($slot - 1); 1153 } 1154 1155 /** 1156 * Is it possible for this question to be re-started within this attempt? 1157 * 1158 * @param int $slot the number used to identify this question within this attempt. 1159 * @return whether the student should be given the option to restart this question now. 1160 */ 1161 public function can_question_be_redone_now($slot) { 1162 return $this->get_quiz()->canredoquestions && !$this->is_finished() && 1163 $this->get_question_state($slot)->is_finished(); 1164 } 1165 1166 /** 1167 * Given a slot in this attempt, which may or not be a redone question, return the original slot. 1168 * 1169 * @param int $slot identifies a particular question in this attempt. 1170 * @return int the slot where this question was originally. 1171 */ 1172 public function get_original_slot($slot) { 1173 $originalslot = $this->quba->get_question_attempt_metadata($slot, 'originalslot'); 1174 if ($originalslot) { 1175 return $originalslot; 1176 } else { 1177 return $slot; 1178 } 1179 } 1180 1181 /** 1182 * Get the displayed question number for a slot. 1183 * @param int $slot the number used to identify this question within this attempt. 1184 * @return string the displayed question number for the question in this slot. 1185 * For example '1', '2', '3' or 'i'. 1186 */ 1187 public function get_question_number($slot) { 1188 return $this->questionnumbers[$slot]; 1189 } 1190 1191 /** 1192 * If the section heading, if any, that should come just before this slot. 1193 * @param int $slot identifies a particular question in this attempt. 1194 * @return string the required heading, or null if there is not one here. 1195 */ 1196 public function get_heading_before_slot($slot) { 1197 if ($this->slots[$slot]->firstinsection) { 1198 return $this->slots[$slot]->section->heading; 1199 } else { 1200 return null; 1201 } 1202 } 1203 1204 /** 1205 * Return the page of the quiz where this question appears. 1206 * @param int $slot the number used to identify this question within this attempt. 1207 * @return int the page of the quiz this question appears on. 1208 */ 1209 public function get_question_page($slot) { 1210 return $this->questionpages[$slot]; 1211 } 1212 1213 /** 1214 * Return the grade obtained on a particular question, if the user is permitted 1215 * to see it. You must previously have called load_question_states to load the 1216 * state data about this question. 1217 * 1218 * @param int $slot the number used to identify this question within this attempt. 1219 * @return string the formatted grade, to the number of decimal places specified 1220 * by the quiz. 1221 */ 1222 public function get_question_name($slot) { 1223 return $this->quba->get_question($slot)->name; 1224 } 1225 1226 /** 1227 * Return the {@link question_state} that this question is in. 1228 * 1229 * @param int $slot the number used to identify this question within this attempt. 1230 * @return question_state the state this question is in. 1231 */ 1232 public function get_question_state($slot) { 1233 return $this->quba->get_question_state($slot); 1234 } 1235 1236 /** 1237 * Return the grade obtained on a particular question, if the user is permitted 1238 * to see it. You must previously have called load_question_states to load the 1239 * state data about this question. 1240 * 1241 * @param int $slot the number used to identify this question within this attempt. 1242 * @param bool $showcorrectness Whether right/partial/wrong states should 1243 * be distinguised. 1244 * @return string the formatted grade, to the number of decimal places specified 1245 * by the quiz. 1246 */ 1247 public function get_question_status($slot, $showcorrectness) { 1248 return $this->quba->get_question_state_string($slot, $showcorrectness); 1249 } 1250 1251 /** 1252 * Return the grade obtained on a particular question, if the user is permitted 1253 * to see it. You must previously have called load_question_states to load the 1254 * state data about this question. 1255 * 1256 * @param int $slot the number used to identify this question within this attempt. 1257 * @param bool $showcorrectness Whether right/partial/wrong states should 1258 * be distinguised. 1259 * @return string class name for this state. 1260 */ 1261 public function get_question_state_class($slot, $showcorrectness) { 1262 return $this->quba->get_question_state_class($slot, $showcorrectness); 1263 } 1264 1265 /** 1266 * Return the grade obtained on a particular question. 1267 * You must previously have called load_question_states to load the state 1268 * data about this question. 1269 * 1270 * @param int $slot the number used to identify this question within this attempt. 1271 * @return string the formatted grade, to the number of decimal places specified by the quiz. 1272 */ 1273 public function get_question_mark($slot) { 1274 return quiz_format_question_grade($this->get_quiz(), $this->quba->get_question_mark($slot)); 1275 } 1276 1277 /** 1278 * Get the time of the most recent action performed on a question. 1279 * @param int $slot the number used to identify this question within this usage. 1280 * @return int timestamp. 1281 */ 1282 public function get_question_action_time($slot) { 1283 return $this->quba->get_question_action_time($slot); 1284 } 1285 1286 /** 1287 * Return the question type name for a given slot within the current attempt. 1288 * 1289 * @param int $slot the number used to identify this question within this attempt. 1290 * @return string the question type name 1291 * @since Moodle 3.1 1292 */ 1293 public function get_question_type_name($slot) { 1294 return $this->quba->get_question($slot)->get_type_name(); 1295 } 1296 1297 /** 1298 * Get the time remaining for an in-progress attempt, if the time is short 1299 * enought that it would be worth showing a timer. 1300 * @param int $timenow the time to consider as 'now'. 1301 * @return int|false the number of seconds remaining for this attempt. 1302 * False if there is no limit. 1303 */ 1304 public function get_time_left_display($timenow) { 1305 if ($this->attempt->state != self::IN_PROGRESS) { 1306 return false; 1307 } 1308 return $this->get_access_manager($timenow)->get_time_left_display($this->attempt, $timenow); 1309 } 1310 1311 1312 /** 1313 * @return int the time when this attempt was submitted. 0 if it has not been 1314 * submitted yet. 1315 */ 1316 public function get_submitted_date() { 1317 return $this->attempt->timefinish; 1318 } 1319 1320 /** 1321 * If the attempt is in an applicable state, work out the time by which the 1322 * student should next do something. 1323 * @return int timestamp by which the student needs to do something. 1324 */ 1325 public function get_due_date() { 1326 $deadlines = array(); 1327 if ($this->quizobj->get_quiz()->timelimit) { 1328 $deadlines[] = $this->attempt->timestart + $this->quizobj->get_quiz()->timelimit; 1329 } 1330 if ($this->quizobj->get_quiz()->timeclose) { 1331 $deadlines[] = $this->quizobj->get_quiz()->timeclose; 1332 } 1333 if ($deadlines) { 1334 $duedate = min($deadlines); 1335 } else { 1336 return false; 1337 } 1338 1339 switch ($this->attempt->state) { 1340 case self::IN_PROGRESS: 1341 return $duedate; 1342 1343 case self::OVERDUE: 1344 return $duedate + $this->quizobj->get_quiz()->graceperiod; 1345 1346 default: 1347 throw new coding_exception('Unexpected state: ' . $this->attempt->state); 1348 } 1349 } 1350 1351 // URLs related to this attempt ============================================ 1352 /** 1353 * @return string quiz view url. 1354 */ 1355 public function view_url() { 1356 return $this->quizobj->view_url(); 1357 } 1358 1359 /** 1360 * @return string the URL of this quiz's edit page. Needs to be POSTed to with a cmid parameter. 1361 */ 1362 public function start_attempt_url($slot = null, $page = -1) { 1363 if ($page == -1 && !is_null($slot)) { 1364 $page = $this->get_question_page($slot); 1365 } else { 1366 $page = 0; 1367 } 1368 return $this->quizobj->start_attempt_url($page); 1369 } 1370 1371 /** 1372 * @param int $slot if speified, the slot number of a specific question to link to. 1373 * @param int $page if specified, a particular page to link to. If not givem deduced 1374 * from $slot, or goes to the first page. 1375 * @param int $questionid a question id. If set, will add a fragment to the URL 1376 * to jump to a particuar question on the page. 1377 * @param int $thispage if not -1, the current page. Will cause links to other things on 1378 * this page to be output as only a fragment. 1379 * @return string the URL to continue this attempt. 1380 */ 1381 public function attempt_url($slot = null, $page = -1, $thispage = -1) { 1382 return $this->page_and_question_url('attempt', $slot, $page, false, $thispage); 1383 } 1384 1385 /** 1386 * @return string the URL of this quiz's summary page. 1387 */ 1388 public function summary_url() { 1389 return new moodle_url('/mod/quiz/summary.php', array('attempt' => $this->attempt->id)); 1390 } 1391 1392 /** 1393 * @return string the URL of this quiz's summary page. 1394 */ 1395 public function processattempt_url() { 1396 return new moodle_url('/mod/quiz/processattempt.php'); 1397 } 1398 1399 /** 1400 * @param int $slot indicates which question to link to. 1401 * @param int $page if specified, the URL of this particular page of the attempt, otherwise 1402 * the URL will go to the first page. If -1, deduce $page from $slot. 1403 * @param bool|null $showall if true, the URL will be to review the entire attempt on one page, 1404 * and $page will be ignored. If null, a sensible default will be chosen. 1405 * @param int $thispage if not -1, the current page. Will cause links to other things on 1406 * this page to be output as only a fragment. 1407 * @return string the URL to review this attempt. 1408 */ 1409 public function review_url($slot = null, $page = -1, $showall = null, $thispage = -1) { 1410 return $this->page_and_question_url('review', $slot, $page, $showall, $thispage); 1411 } 1412 1413 /** 1414 * By default, should this script show all questions on one page for this attempt? 1415 * @param string $script the script name, e.g. 'attempt', 'summary', 'review'. 1416 * @return whether show all on one page should be on by default. 1417 */ 1418 public function get_default_show_all($script) { 1419 return $script == 'review' && count($this->questionpages) < self::MAX_SLOTS_FOR_DEFAULT_REVIEW_SHOW_ALL; 1420 } 1421 1422 // Bits of content ========================================================= 1423 1424 /** 1425 * If $reviewoptions->attempt is false, meaning that students can't review this 1426 * attempt at the moment, return an appropriate string explaining why. 1427 * 1428 * @param bool $short if true, return a shorter string. 1429 * @return string an appropraite message. 1430 */ 1431 public function cannot_review_message($short = false) { 1432 return $this->quizobj->cannot_review_message( 1433 $this->get_attempt_state(), $short); 1434 } 1435 1436 /** 1437 * Initialise the JS etc. required all the questions on a page. 1438 * @param mixed $page a page number, or 'all'. 1439 */ 1440 public function get_html_head_contributions($page = 'all', $showall = false) { 1441 if ($showall) { 1442 $page = 'all'; 1443 } 1444 $result = ''; 1445 foreach ($this->get_slots($page) as $slot) { 1446 $result .= $this->quba->render_question_head_html($slot); 1447 } 1448 $result .= question_engine::initialise_js(); 1449 return $result; 1450 } 1451 1452 /** 1453 * Initialise the JS etc. required by one question. 1454 * @param int $questionid the question id. 1455 */ 1456 public function get_question_html_head_contributions($slot) { 1457 return $this->quba->render_question_head_html($slot) . 1458 question_engine::initialise_js(); 1459 } 1460 1461 /** 1462 * Print the HTML for the start new preview button, if the current user 1463 * is allowed to see one. 1464 */ 1465 public function restart_preview_button() { 1466 global $OUTPUT; 1467 if ($this->is_preview() && $this->is_preview_user()) { 1468 return $OUTPUT->single_button(new moodle_url( 1469 $this->start_attempt_url(), array('forcenew' => true)), 1470 get_string('startnewpreview', 'quiz')); 1471 } else { 1472 return ''; 1473 } 1474 } 1475 1476 /** 1477 * Generate the HTML that displayes the question in its current state, with 1478 * the appropriate display options. 1479 * 1480 * @param int $slot identifies the question in the attempt. 1481 * @param bool $reviewing is the being printed on an attempt or a review page. 1482 * @param mod_quiz_renderer $renderer the quiz renderer. 1483 * @param moodle_url $thispageurl the URL of the page this question is being printed on. 1484 * @return string HTML for the question in its current state. 1485 */ 1486 public function render_question($slot, $reviewing, mod_quiz_renderer $renderer, $thispageurl = null) { 1487 if ($this->is_blocked_by_previous_question($slot)) { 1488 $placeholderqa = $this->make_blocked_question_placeholder($slot); 1489 1490 $displayoptions = $this->get_display_options($reviewing); 1491 $displayoptions->manualcomment = question_display_options::HIDDEN; 1492 $displayoptions->history = question_display_options::HIDDEN; 1493 $displayoptions->readonly = true; 1494 1495 return html_writer::div($placeholderqa->render($displayoptions, 1496 $this->get_question_number($this->get_original_slot($slot))), 1497 'mod_quiz-blocked_question_warning'); 1498 } 1499 1500 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, null); 1501 } 1502 1503 /** 1504 * Helper used by {@link render_question()} and {@link render_question_at_step()}. 1505 * 1506 * @param int $slot identifies the question in the attempt. 1507 * @param bool $reviewing is the being printed on an attempt or a review page. 1508 * @param moodle_url $thispageurl the URL of the page this question is being printed on. 1509 * @param mod_quiz_renderer $renderer the quiz renderer. 1510 * @param int|null $seq the seq number of the past state to display. 1511 * @return string HTML fragment. 1512 */ 1513 protected function render_question_helper($slot, $reviewing, $thispageurl, mod_quiz_renderer $renderer, $seq) { 1514 $originalslot = $this->get_original_slot($slot); 1515 $number = $this->get_question_number($originalslot); 1516 $displayoptions = $this->get_display_options_with_edit_link($reviewing, $slot, $thispageurl); 1517 1518 if ($slot != $originalslot) { 1519 $originalmaxmark = $this->get_question_attempt($slot)->get_max_mark(); 1520 $this->get_question_attempt($slot)->set_max_mark($this->get_question_attempt($originalslot)->get_max_mark()); 1521 } 1522 1523 if ($this->can_question_be_redone_now($slot)) { 1524 $displayoptions->extrainfocontent = $renderer->redo_question_button( 1525 $slot, $displayoptions->readonly); 1526 } 1527 1528 if ($displayoptions->history && $displayoptions->questionreviewlink) { 1529 $links = $this->links_to_other_redos($slot, $displayoptions->questionreviewlink); 1530 if ($links) { 1531 $displayoptions->extrahistorycontent = html_writer::tag('p', 1532 get_string('redoesofthisquestion', 'quiz', $renderer->render($links))); 1533 } 1534 } 1535 1536 if ($seq === null) { 1537 $output = $this->quba->render_question($slot, $displayoptions, $number); 1538 } else { 1539 $output = $this->quba->render_question_at_step($slot, $seq, $displayoptions, $number); 1540 } 1541 1542 if ($slot != $originalslot) { 1543 $this->get_question_attempt($slot)->set_max_mark($originalmaxmark); 1544 } 1545 1546 return $output; 1547 } 1548 1549 /** 1550 * Create a fake question to be displayed in place of a question that is blocked 1551 * until the previous question has been answered. 1552 * 1553 * @param int $slot int slot number of the question to replace. 1554 * @return question_definition the placeholde question. 1555 */ 1556 protected function make_blocked_question_placeholder($slot) { 1557 $replacedquestion = $this->get_question_attempt($slot)->get_question(); 1558 1559 question_bank::load_question_definition_classes('description'); 1560 $question = new qtype_description_question(); 1561 $question->id = $replacedquestion->id; 1562 $question->category = null; 1563 $question->parent = 0; 1564 $question->qtype = question_bank::get_qtype('description'); 1565 $question->name = ''; 1566 $question->questiontext = get_string('questiondependsonprevious', 'quiz'); 1567 $question->questiontextformat = FORMAT_HTML; 1568 $question->generalfeedback = ''; 1569 $question->defaultmark = $this->quba->get_question_max_mark($slot); 1570 $question->length = $replacedquestion->length; 1571 $question->penalty = 0; 1572 $question->stamp = ''; 1573 $question->version = 0; 1574 $question->hidden = 0; 1575 $question->timecreated = null; 1576 $question->timemodified = null; 1577 $question->createdby = null; 1578 $question->modifiedby = null; 1579 1580 $placeholderqa = new question_attempt($question, $this->quba->get_id(), 1581 null, $this->quba->get_question_max_mark($slot)); 1582 $placeholderqa->set_slot($slot); 1583 $placeholderqa->start($this->get_quiz()->preferredbehaviour, 1); 1584 $placeholderqa->set_flagged($this->is_question_flagged($slot)); 1585 return $placeholderqa; 1586 } 1587 1588 /** 1589 * Like {@link render_question()} but displays the question at the past step 1590 * indicated by $seq, rather than showing the latest step. 1591 * 1592 * @param int $id the id of a question in this quiz attempt. 1593 * @param int $seq the seq number of the past state to display. 1594 * @param bool $reviewing is the being printed on an attempt or a review page. 1595 * @param mod_quiz_renderer $renderer the quiz renderer. 1596 * @param string $thispageurl the URL of the page this question is being printed on. 1597 * @return string HTML for the question in its current state. 1598 */ 1599 public function render_question_at_step($slot, $seq, $reviewing, mod_quiz_renderer $renderer, $thispageurl = '') { 1600 return $this->render_question_helper($slot, $reviewing, $thispageurl, $renderer, $seq); 1601 } 1602 1603 /** 1604 * Wrapper round print_question from lib/questionlib.php. 1605 * 1606 * @param int $id the id of a question in this quiz attempt. 1607 */ 1608 public function render_question_for_commenting($slot) { 1609 $options = $this->get_display_options(true); 1610 $options->hide_all_feedback(); 1611 $options->manualcomment = question_display_options::EDITABLE; 1612 return $this->quba->render_question($slot, $options, 1613 $this->get_question_number($slot)); 1614 } 1615 1616 /** 1617 * Check wheter access should be allowed to a particular file. 1618 * 1619 * @param int $id the id of a question in this quiz attempt. 1620 * @param bool $reviewing is the being printed on an attempt or a review page. 1621 * @param string $thispageurl the URL of the page this question is being printed on. 1622 * @return string HTML for the question in its current state. 1623 */ 1624 public function check_file_access($slot, $reviewing, $contextid, $component, 1625 $filearea, $args, $forcedownload) { 1626 $options = $this->get_display_options($reviewing); 1627 1628 // Check permissions - warning there is similar code in review.php and 1629 // reviewquestion.php. If you change on, change them all. 1630 if ($reviewing && $this->is_own_attempt() && !$options->attempt) { 1631 return false; 1632 } 1633 1634 if ($reviewing && !$this->is_own_attempt() && !$this->is_review_allowed()) { 1635 return false; 1636 } 1637 1638 return $this->quba->check_file_access($slot, $options, 1639 $component, $filearea, $args, $forcedownload); 1640 } 1641 1642 /** 1643 * Get the navigation panel object for this attempt. 1644 * 1645 * @param $panelclass The type of panel, quiz_attempt_nav_panel or quiz_review_nav_panel 1646 * @param $page the current page number. 1647 * @param $showall whether we are showing the whole quiz on one page. (Used by review.php) 1648 * @return quiz_nav_panel_base the requested object. 1649 */ 1650 public function get_navigation_panel(mod_quiz_renderer $output, 1651 $panelclass, $page, $showall = false) { 1652 $panel = new $panelclass($this, $this->get_display_options(true), $page, $showall); 1653 1654 $bc = new block_contents(); 1655 $bc->attributes['id'] = 'mod_quiz_navblock'; 1656 $bc->attributes['role'] = 'navigation'; 1657 $bc->attributes['aria-labelledby'] = 'mod_quiz_navblock_title'; 1658 $bc->title = html_writer::span(get_string('quiznavigation', 'quiz'), '', array('id' => 'mod_quiz_navblock_title')); 1659 $bc->content = $output->navigation_panel($panel); 1660 return $bc; 1661 } 1662 1663 /** 1664 * Return an array of variant URLs to other attempts at this quiz. 1665 * 1666 * The $url passed in must contain an attempt parameter. 1667 * 1668 * The {@link mod_quiz_links_to_other_attempts} object returned contains an 1669 * array with keys that are the attempt number, 1, 2, 3. 1670 * The array values are either a {@link moodle_url} with the attmept parameter 1671 * updated to point to the attempt id of the other attempt, or null corresponding 1672 * to the current attempt number. 1673 * 1674 * @param moodle_url $url a URL. 1675 * @return mod_quiz_links_to_other_attempts containing array int => null|moodle_url. 1676 */ 1677 public function links_to_other_attempts(moodle_url $url) { 1678 $attempts = quiz_get_user_attempts($this->get_quiz()->id, $this->attempt->userid, 'all'); 1679 if (count($attempts) <= 1) { 1680 return false; 1681 } 1682 1683 $links = new mod_quiz_links_to_other_attempts(); 1684 foreach ($attempts as $at) { 1685 if ($at->id == $this->attempt->id) { 1686 $links->links[$at->attempt] = null; 1687 } else { 1688 $links->links[$at->attempt] = new moodle_url($url, array('attempt' => $at->id)); 1689 } 1690 } 1691 return $links; 1692 } 1693 1694 /** 1695 * Return an array of variant URLs to other redos of the question in a particular slot. 1696 * 1697 * The $url passed in must contain a slot parameter. 1698 * 1699 * The {@link mod_quiz_links_to_other_attempts} object returned contains an 1700 * array with keys that are the redo number, 1, 2, 3. 1701 * The array values are either a {@link moodle_url} with the slot parameter 1702 * updated to point to the slot that has that redo of this question; or null 1703 * corresponding to the redo identified by $slot. 1704 * 1705 * @param int $slot identifies a question in this attempt. 1706 * @param moodle_url $baseurl the base URL to modify to generate each link. 1707 * @return mod_quiz_links_to_other_attempts|null containing array int => null|moodle_url, 1708 * or null if the question in this slot has not been redone. 1709 */ 1710 public function links_to_other_redos($slot, moodle_url $baseurl) { 1711 $originalslot = $this->get_original_slot($slot); 1712 1713 $qas = $this->all_question_attempts_originally_in_slot($originalslot); 1714 if (count($qas) <= 1) { 1715 return null; 1716 } 1717 1718 $links = new mod_quiz_links_to_other_attempts(); 1719 $index = 1; 1720 foreach ($qas as $qa) { 1721 if ($qa->get_slot() == $slot) { 1722 $links->links[$index] = null; 1723 } else { 1724 $url = new moodle_url($baseurl, array('slot' => $qa->get_slot())); 1725 $links->links[$index] = new action_link($url, $index, 1726 new popup_action('click', $url, 'reviewquestion', 1727 array('width' => 450, 'height' => 650)), 1728 array('title' => get_string('reviewresponse', 'question'))); 1729 } 1730 $index++; 1731 } 1732 return $links; 1733 } 1734 1735 // Methods for processing ================================================== 1736 1737 /** 1738 * Check this attempt, to see if there are any state transitions that should 1739 * happen automatically. This function will update the attempt checkstatetime. 1740 * @param int $timestamp the timestamp that should be stored as the modifed 1741 * @param bool $studentisonline is the student currently interacting with Moodle? 1742 */ 1743 public function handle_if_time_expired($timestamp, $studentisonline) { 1744 global $DB; 1745 1746 $timeclose = $this->get_access_manager($timestamp)->get_end_time($this->attempt); 1747 1748 if ($timeclose === false || $this->is_preview()) { 1749 $this->update_timecheckstate(null); 1750 return; // No time limit 1751 } 1752 if ($timestamp < $timeclose) { 1753 $this->update_timecheckstate($timeclose); 1754 return; // Time has not yet expired. 1755 } 1756 1757 // If the attempt is already overdue, look to see if it should be abandoned ... 1758 if ($this->attempt->state == self::OVERDUE) { 1759 $timeoverdue = $timestamp - $timeclose; 1760 $graceperiod = $this->quizobj->get_quiz()->graceperiod; 1761 if ($timeoverdue >= $graceperiod) { 1762 $this->process_abandon($timestamp, $studentisonline); 1763 } else { 1764 // Overdue time has not yet expired 1765 $this->update_timecheckstate($timeclose + $graceperiod); 1766 } 1767 return; // ... and we are done. 1768 } 1769 1770 if ($this->attempt->state != self::IN_PROGRESS) { 1771 $this->update_timecheckstate(null); 1772 return; // Attempt is already in a final state. 1773 } 1774 1775 // Otherwise, we were in quiz_attempt::IN_PROGRESS, and time has now expired. 1776 // Transition to the appropriate state. 1777 switch ($this->quizobj->get_quiz()->overduehandling) { 1778 case 'autosubmit': 1779 $this->process_finish($timestamp, false); 1780 return; 1781 1782 case 'graceperiod': 1783 $this->process_going_overdue($timestamp, $studentisonline); 1784 return; 1785 1786 case 'autoabandon': 1787 $this->process_abandon($timestamp, $studentisonline); 1788 return; 1789 } 1790 1791 // This is an overdue attempt with no overdue handling defined, so just abandon. 1792 $this->process_abandon($timestamp, $studentisonline); 1793 return; 1794 } 1795 1796 /** 1797 * Process all the actions that were submitted as part of the current request. 1798 * 1799 * @param int $timestamp the timestamp that should be stored as the modifed 1800 * time in the database for these actions. If null, will use the current time. 1801 * @param bool $becomingoverdue 1802 * @param array|null $simulatedresponses If not null, then we are testing, and this is an array of simulated data, keys are slot 1803 * nos and values are arrays representing student responses which will be passed to 1804 * question_definition::prepare_simulated_post_data method and then have the 1805 * appropriate prefix added. 1806 */ 1807 public function process_submitted_actions($timestamp, $becomingoverdue = false, $simulatedresponses = null) { 1808 global $DB; 1809 1810 $transaction = $DB->start_delegated_transaction(); 1811 1812 if ($simulatedresponses !== null) { 1813 $simulatedpostdata = $this->quba->prepare_simulated_post_data($simulatedresponses); 1814 } else { 1815 $simulatedpostdata = null; 1816 } 1817 1818 $this->quba->process_all_actions($timestamp, $simulatedpostdata); 1819 question_engine::save_questions_usage_by_activity($this->quba); 1820 1821 $this->attempt->timemodified = $timestamp; 1822 if ($this->attempt->state == self::FINISHED) { 1823 $this->attempt->sumgrades = $this->quba->get_total_mark(); 1824 } 1825 if ($becomingoverdue) { 1826 $this->process_going_overdue($timestamp, true); 1827 } else { 1828 $DB->update_record('quiz_attempts', $this->attempt); 1829 } 1830 1831 if (!$this->is_preview() && $this->attempt->state == self::FINISHED) { 1832 quiz_save_best_grade($this->get_quiz(), $this->get_userid()); 1833 } 1834 1835 $transaction->allow_commit(); 1836 } 1837 1838 /** 1839 * Replace a question in an attempt with a new attempt at the same qestion. 1840 * @param int $slot the questoin to restart. 1841 * @param int $timestamp the timestamp to record for this action. 1842 */ 1843 public function process_redo_question($slot, $timestamp) { 1844 global $DB; 1845 1846 if (!$this->can_question_be_redone_now($slot)) { 1847 throw new coding_exception('Attempt to restart the question in slot ' . $slot . 1848 ' when it is not in a state to be restarted.'); 1849 } 1850 1851 $qubaids = new \mod_quiz\question\qubaids_for_users_attempts( 1852 $this->get_quizid(), $this->get_userid()); 1853 1854 $transaction = $DB->start_delegated_transaction(); 1855 1856 // Choose the replacement question. 1857 $questiondata = $DB->get_record('question', 1858 array('id' => $this->slots[$slot]->questionid)); 1859 if ($questiondata->qtype != 'random') { 1860 $newqusetionid = $questiondata->id; 1861 } else { 1862 $randomloader = new \core_question\bank\random_question_loader($qubaids, array()); 1863 $newqusetionid = $randomloader->get_next_question_id($questiondata->category, 1864 (bool) $questiondata->questiontext); 1865 if ($newqusetionid === null) { 1866 throw new moodle_exception('notenoughrandomquestions', 'quiz', 1867 $quizobj->view_url(), $questiondata); 1868 } 1869 } 1870 1871 // Add the question to the usage. It is important we do this before we choose a variant. 1872 $newquestion = question_bank::load_question($newqusetionid); 1873 $newslot = $this->quba->add_question_in_place_of_other($slot, $newquestion); 1874 1875 // Choose the variant. 1876 if ($newquestion->get_num_variants() == 1) { 1877 $variant = 1; 1878 } else { 1879 $variantstrategy = new core_question\engine\variants\least_used_strategy( 1880 $this->quba, $qubaids); 1881 $variant = $variantstrategy->choose_variant($newquestion->get_num_variants(), 1882 $newquestion->get_variants_selection_seed()); 1883 } 1884 1885 // Start the question. 1886 $this->quba->start_question($slot, $variant); 1887 $this->quba->set_max_mark($newslot, 0); 1888 $this->quba->set_question_attempt_metadata($newslot, 'originalslot', $slot); 1889 question_engine::save_questions_usage_by_activity($this->quba); 1890 1891 $transaction->allow_commit(); 1892 } 1893 1894 /** 1895 * Process all the autosaved data that was part of the current request. 1896 * 1897 * @param int $timestamp the timestamp that should be stored as the modifed 1898 * time in the database for these actions. If null, will use the current time. 1899 */ 1900 public function process_auto_save($timestamp) { 1901 global $DB; 1902 1903 $transaction = $DB->start_delegated_transaction(); 1904 1905 $this->quba->process_all_autosaves($timestamp); 1906 question_engine::save_questions_usage_by_activity($this->quba); 1907 1908 $transaction->allow_commit(); 1909 } 1910 1911 /** 1912 * Update the flagged state for all question_attempts in this usage, if their 1913 * flagged state was changed in the request. 1914 */ 1915 public function save_question_flags() { 1916 global $DB; 1917 1918 $transaction = $DB->start_delegated_transaction(); 1919 $this->quba->update_question_flags(); 1920 question_engine::save_questions_usage_by_activity($this->quba); 1921 $transaction->allow_commit(); 1922 } 1923 1924 public function process_finish($timestamp, $processsubmitted) { 1925 global $DB; 1926 1927 $transaction = $DB->start_delegated_transaction(); 1928 1929 if ($processsubmitted) { 1930 $this->quba->process_all_actions($timestamp); 1931 } 1932 $this->quba->finish_all_questions($timestamp); 1933 1934 question_engine::save_questions_usage_by_activity($this->quba); 1935 1936 $this->attempt->timemodified = $timestamp; 1937 $this->attempt->timefinish = $timestamp; 1938 $this->attempt->sumgrades = $this->quba->get_total_mark(); 1939 $this->attempt->state = self::FINISHED; 1940 $this->attempt->timecheckstate = null; 1941 $DB->update_record('quiz_attempts', $this->attempt); 1942 1943 if (!$this->is_preview()) { 1944 quiz_save_best_grade($this->get_quiz(), $this->attempt->userid); 1945 1946 // Trigger event. 1947 $this->fire_state_transition_event('\mod_quiz\event\attempt_submitted', $timestamp); 1948 1949 // Tell any access rules that care that the attempt is over. 1950 $this->get_access_manager($timestamp)->current_attempt_finished(); 1951 } 1952 1953 $transaction->allow_commit(); 1954 } 1955 1956 /** 1957 * Update this attempt timecheckstate if necessary. 1958 * @param int|null the timecheckstate 1959 */ 1960 public function update_timecheckstate($time) { 1961 global $DB; 1962 if ($this->attempt->timecheckstate !== $time) { 1963 $this->attempt->timecheckstate = $time; 1964 $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id' => $this->attempt->id)); 1965 } 1966 } 1967 1968 /** 1969 * Mark this attempt as now overdue. 1970 * @param int $timestamp the time to deem as now. 1971 * @param bool $studentisonline is the student currently interacting with Moodle? 1972 */ 1973 public function process_going_overdue($timestamp, $studentisonline) { 1974 global $DB; 1975 1976 $transaction = $DB->start_delegated_transaction(); 1977 $this->attempt->timemodified = $timestamp; 1978 $this->attempt->state = self::OVERDUE; 1979 // If we knew the attempt close time, we could compute when the graceperiod ends. 1980 // Instead we'll just fix it up through cron. 1981 $this->attempt->timecheckstate = $timestamp; 1982 $DB->update_record('quiz_attempts', $this->attempt); 1983 1984 $this->fire_state_transition_event('\mod_quiz\event\attempt_becameoverdue', $timestamp); 1985 1986 $transaction->allow_commit(); 1987 1988 quiz_send_overdue_message($this); 1989 } 1990 1991 /** 1992 * Mark this attempt as abandoned. 1993 * @param int $timestamp the time to deem as now. 1994 * @param bool $studentisonline is the student currently interacting with Moodle? 1995 */ 1996 public function process_abandon($timestamp, $studentisonline) { 1997 global $DB; 1998 1999 $transaction = $DB->start_delegated_transaction(); 2000 $this->attempt->timemodified = $timestamp; 2001 $this->attempt->state = self::ABANDONED; 2002 $this->attempt->timecheckstate = null; 2003 $DB->update_record('quiz_attempts', $this->attempt); 2004 2005 $this->fire_state_transition_event('\mod_quiz\event\attempt_abandoned', $timestamp); 2006 2007 $transaction->allow_commit(); 2008 } 2009 2010 /** 2011 * Fire a state transition event. 2012 * the same event information. 2013 * @param string $eventclass the event class name. 2014 * @param int $timestamp the timestamp to include in the event. 2015 * @return void 2016 */ 2017 protected function fire_state_transition_event($eventclass, $timestamp) { 2018 global $USER; 2019 $quizrecord = $this->get_quiz(); 2020 $params = array( 2021 'context' => $this->get_quizobj()->get_context(), 2022 'courseid' => $this->get_courseid(), 2023 'objectid' => $this->attempt->id, 2024 'relateduserid' => $this->attempt->userid, 2025 'other' => array( 2026 'submitterid' => CLI_SCRIPT ? null : $USER->id, 2027 'quizid' => $quizrecord->id 2028 ) 2029 ); 2030 2031 $event = $eventclass::create($params); 2032 $event->add_record_snapshot('quiz', $this->get_quiz()); 2033 $event->add_record_snapshot('quiz_attempts', $this->get_attempt()); 2034 $event->trigger(); 2035 } 2036 2037 // Private methods ========================================================= 2038 2039 /** 2040 * Get a URL for a particular question on a particular page of the quiz. 2041 * Used by {@link attempt_url()} and {@link review_url()}. 2042 * 2043 * @param string $script. Used in the URL like /mod/quiz/$script.php 2044 * @param int $slot identifies the specific question on the page to jump to. 2045 * 0 to just use the $page parameter. 2046 * @param int $page -1 to look up the page number from the slot, otherwise 2047 * the page number to go to. 2048 * @param bool|null $showall if true, return a URL with showall=1, and not page number. 2049 * if null, then an intelligent default will be chosen. 2050 * @param int $thispage the page we are currently on. Links to questions on this 2051 * page will just be a fragment #q123. -1 to disable this. 2052 * @return The requested URL. 2053 */ 2054 protected function page_and_question_url($script, $slot, $page, $showall, $thispage) { 2055 2056 $defaultshowall = $this->get_default_show_all($script); 2057 if ($showall === null && ($page == 0 || $page == -1)) { 2058 $showall = $defaultshowall; 2059 } 2060 2061 // Fix up $page. 2062 if ($page == -1) { 2063 if ($slot !== null && !$showall) { 2064 $page = $this->get_question_page($slot); 2065 } else { 2066 $page = 0; 2067 } 2068 } 2069 2070 if ($showall) { 2071 $page = 0; 2072 } 2073 2074 // Add a fragment to scroll down to the question. 2075 $fragment = ''; 2076 if ($slot !== null) { 2077 if ($slot == reset($this->pagelayout[$page])) { 2078 // First question on page, go to top. 2079 $fragment = '#'; 2080 } else { 2081 $fragment = '#q' . $slot; 2082 } 2083 } 2084 2085 // Work out the correct start to the URL. 2086 if ($thispage == $page) { 2087 return new moodle_url($fragment); 2088 2089 } else { 2090 $url = new moodle_url('/mod/quiz/' . $script . '.php' . $fragment, 2091 array('attempt' => $this->attempt->id)); 2092 if ($page == 0 && $showall != $defaultshowall) { 2093 $url->param('showall', (int) $showall); 2094 } else if ($page > 0) { 2095 $url->param('page', $page); 2096 } 2097 return $url; 2098 } 2099 } 2100 2101 /** 2102 * Process responses during an attempt at a quiz. 2103 * 2104 * @param int $timenow time when the processing started 2105 * @param bool $finishattempt whether to finish the attempt or not 2106 * @param bool $timeup true if form was submitted by timer 2107 * @param int $thispage current page number 2108 * @return string the attempt state once the data has been processed 2109 * @since Moodle 3.1 2110 * @throws moodle_exception 2111 */ 2112 public function process_attempt($timenow, $finishattempt, $timeup, $thispage) { 2113 global $DB; 2114 2115 $transaction = $DB->start_delegated_transaction(); 2116 2117 // If there is only a very small amount of time left, there is no point trying 2118 // to show the student another page of the quiz. Just finish now. 2119 $graceperiodmin = null; 2120 $accessmanager = $this->get_access_manager($timenow); 2121 $timeclose = $accessmanager->get_end_time($this->get_attempt()); 2122 2123 // Don't enforce timeclose for previews. 2124 if ($this->is_preview()) { 2125 $timeclose = false; 2126 } 2127 $toolate = false; 2128 if ($timeclose !== false && $timenow > $timeclose - QUIZ_MIN_TIME_TO_CONTINUE) { 2129 $timeup = true; 2130 $graceperiodmin = get_config('quiz', 'graceperiodmin'); 2131 if ($timenow > $timeclose + $graceperiodmin) { 2132 $toolate = true; 2133 } 2134 } 2135 2136 // If time is running out, trigger the appropriate action. 2137 $becomingoverdue = false; 2138 $becomingabandoned = false; 2139 if ($timeup) { 2140 if ($this->get_quiz()->overduehandling == 'graceperiod') { 2141 if (is_null($graceperiodmin)) { 2142 $graceperiodmin = get_config('quiz', 'graceperiodmin'); 2143 } 2144 if ($timenow > $timeclose + $this->get_quiz()->graceperiod + $graceperiodmin) { 2145 // Grace period has run out. 2146 $finishattempt = true; 2147 $becomingabandoned = true; 2148 } else { 2149 $becomingoverdue = true; 2150 } 2151 } else { 2152 $finishattempt = true; 2153 } 2154 } 2155 2156 // Don't log - we will end with a redirect to a page that is logged. 2157 2158 if (!$finishattempt) { 2159 // Just process the responses for this page and go to the next page. 2160 if (!$toolate) { 2161 try { 2162 $this->process_submitted_actions($timenow, $becomingoverdue); 2163 2164 } catch (question_out_of_sequence_exception $e) { 2165 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question', 2166 $this->attempt_url(null, $thispage)); 2167 2168 } catch (Exception $e) { 2169 // This sucks, if we display our own custom error message, there is no way 2170 // to display the original stack trace. 2171 $debuginfo = ''; 2172 if (!empty($e->debuginfo)) { 2173 $debuginfo = $e->debuginfo; 2174 } 2175 throw new moodle_exception('errorprocessingresponses', 'question', 2176 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo); 2177 } 2178 2179 if (!$becomingoverdue) { 2180 foreach ($this->get_slots() as $slot) { 2181 if (optional_param('redoslot' . $slot, false, PARAM_BOOL)) { 2182 $this->process_redo_question($slot, $timenow); 2183 } 2184 } 2185 } 2186 2187 } else { 2188 // The student is too late. 2189 $this->process_going_overdue($timenow, true); 2190 } 2191 2192 $transaction->allow_commit(); 2193 2194 return $becomingoverdue ? self::OVERDUE : self::IN_PROGRESS; 2195 } 2196 2197 // Update the quiz attempt record. 2198 try { 2199 if ($becomingabandoned) { 2200 $this->process_abandon($timenow, true); 2201 } else { 2202 $this->process_finish($timenow, !$toolate); 2203 } 2204 2205 } catch (question_out_of_sequence_exception $e) { 2206 throw new moodle_exception('submissionoutofsequencefriendlymessage', 'question', 2207 $this->attempt_url(null, $thispage)); 2208 2209 } catch (Exception $e) { 2210 // This sucks, if we display our own custom error message, there is no way 2211 // to display the original stack trace. 2212 $debuginfo = ''; 2213 if (!empty($e->debuginfo)) { 2214 $debuginfo = $e->debuginfo; 2215 } 2216 throw new moodle_exception('errorprocessingresponses', 'question', 2217 $this->attempt_url(null, $thispage), $e->getMessage(), $debuginfo); 2218 } 2219 2220 // Send the user to the review page. 2221 $transaction->allow_commit(); 2222 2223 return $becomingabandoned ? self::ABANDONED : self::FINISHED; 2224 } 2225 2226 /** 2227 * Check a page access to see if is an out of sequence access. 2228 * 2229 * @param int $page page number 2230 * @return boolean false is is an out of sequence access, true otherwise. 2231 * @since Moodle 3.1 2232 */ 2233 public function check_page_access($page) { 2234 global $DB; 2235 2236 if ($this->get_currentpage() != $page) { 2237 if ($this->get_navigation_method() == QUIZ_NAVMETHOD_SEQ && $this->get_currentpage() > $page) { 2238 return false; 2239 } 2240 } 2241 return true; 2242 } 2243 2244 /** 2245 * Update attempt page. 2246 * 2247 * @param int $page page number 2248 * @return boolean true if everything was ok, false otherwise (out of sequence access). 2249 * @since Moodle 3.1 2250 */ 2251 public function set_currentpage($page) { 2252 global $DB; 2253 2254 if ($this->check_page_access($page)) { 2255 $DB->set_field('quiz_attempts', 'currentpage', $page, array('id' => $this->get_attemptid())); 2256 return true; 2257 } 2258 return false; 2259 } 2260 2261 /** 2262 * Trigger the attempt_viewed event. 2263 * 2264 * @since Moodle 3.1 2265 */ 2266 public function fire_attempt_viewed_event() { 2267 $params = array( 2268 'objectid' => $this->get_attemptid(), 2269 'relateduserid' => $this->get_userid(), 2270 'courseid' => $this->get_courseid(), 2271 'context' => context_module::instance($this->get_cmid()), 2272 'other' => array( 2273 'quizid' => $this->get_quizid() 2274 ) 2275 ); 2276 $event = \mod_quiz\event\attempt_viewed::create($params); 2277 $event->add_record_snapshot('quiz_attempts', $this->get_attempt()); 2278 $event->trigger(); 2279 } 2280 2281 /** 2282 * Trigger the attempt_summary_viewed event. 2283 * 2284 * @since Moodle 3.1 2285 */ 2286 public function fire_attempt_summary_viewed_event() { 2287 2288 $params = array( 2289 'objectid' => $this->get_attemptid(), 2290 'relateduserid' => $this->get_userid(), 2291 'courseid' => $this->get_courseid(), 2292 'context' => context_module::instance($this->get_cmid()), 2293 'other' => array( 2294 'quizid' => $this->get_quizid() 2295 ) 2296 ); 2297 $event = \mod_quiz\event\attempt_summary_viewed::create($params); 2298 $event->add_record_snapshot('quiz_attempts', $this->get_attempt()); 2299 $event->trigger(); 2300 } 2301 2302 /** 2303 * Trigger the attempt_reviewed event. 2304 * 2305 * @since Moodle 3.1 2306 */ 2307 public function fire_attempt_reviewed_event() { 2308 2309 $params = array( 2310 'objectid' => $this->get_attemptid(), 2311 'relateduserid' => $this->get_userid(), 2312 'courseid' => $this->get_courseid(), 2313 'context' => context_module::instance($this->get_cmid()), 2314 'other' => array( 2315 'quizid' => $this->get_quizid() 2316 ) 2317 ); 2318 $event = \mod_quiz\event\attempt_reviewed::create($params); 2319 $event->add_record_snapshot('quiz_attempts', $this->get_attempt()); 2320 $event->trigger(); 2321 } 2322 2323 } 2324 2325 2326 /** 2327 * Represents a heading in the navigation panel. 2328 * 2329 * @copyright 2015 The Open University 2330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2331 * @since Moodle 2.9 2332 */ 2333 class quiz_nav_section_heading implements renderable { 2334 /** @var string the heading text. */ 2335 public $heading; 2336 2337 /** 2338 * Constructor. 2339 * @param string $heading the heading text 2340 */ 2341 public function __construct($heading) { 2342 $this->heading = $heading; 2343 } 2344 } 2345 2346 2347 /** 2348 * Represents a single link in the navigation panel. 2349 * 2350 * @copyright 2011 The Open University 2351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2352 * @since Moodle 2.1 2353 */ 2354 class quiz_nav_question_button implements renderable { 2355 /** @var string id="..." to add to the HTML for this button. */ 2356 public $id; 2357 /** @var string number to display in this button. Either the question number of 'i'. */ 2358 public $number; 2359 /** @var string class to add to the class="" attribute to represnt the question state. */ 2360 public $stateclass; 2361 /** @var string Textual description of the question state, e.g. to use as a tool tip. */ 2362 public $statestring; 2363 /** @var int the page number this question is on. */ 2364 public $page; 2365 /** @var bool true if this question is on the current page. */ 2366 public $currentpage; 2367 /** @var bool true if this question has been flagged. */ 2368 public $flagged; 2369 /** @var moodle_url the link this button goes to, or null if there should not be a link. */ 2370 public $url; 2371 } 2372 2373 2374 /** 2375 * Represents the navigation panel, and builds a {@link block_contents} to allow 2376 * it to be output. 2377 * 2378 * @copyright 2008 Tim Hunt 2379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2380 * @since Moodle 2.0 2381 */ 2382 abstract class quiz_nav_panel_base { 2383 /** @var quiz_attempt */ 2384 protected $attemptobj; 2385 /** @var question_display_options */ 2386 protected $options; 2387 /** @var integer */ 2388 protected $page; 2389 /** @var boolean */ 2390 protected $showall; 2391 2392 public function __construct(quiz_attempt $attemptobj, 2393 question_display_options $options, $page, $showall) { 2394 $this->attemptobj = $attemptobj; 2395 $this->options = $options; 2396 $this->page = $page; 2397 $this->showall = $showall; 2398 } 2399 2400 /** 2401 * Get the buttons and section headings to go in the quiz navigation block. 2402 * @return renderable[] the buttons, possibly interleaved with section headings. 2403 */ 2404 public function get_question_buttons() { 2405 $buttons = array(); 2406 foreach ($this->attemptobj->get_slots() as $slot) { 2407 if ($heading = $this->attemptobj->get_heading_before_slot($slot)) { 2408 $buttons[] = new quiz_nav_section_heading(format_string($heading)); 2409 } 2410 2411 $qa = $this->attemptobj->get_question_attempt($slot); 2412 $showcorrectness = $this->options->correctness && $qa->has_marks(); 2413 2414 $button = new quiz_nav_question_button(); 2415 $button->id = 'quiznavbutton' . $slot; 2416 $button->number = $this->attemptobj->get_question_number($slot); 2417 $button->stateclass = $qa->get_state_class($showcorrectness); 2418 $button->navmethod = $this->attemptobj->get_navigation_method(); 2419 if (!$showcorrectness && $button->stateclass == 'notanswered') { 2420 $button->stateclass = 'complete'; 2421 } 2422 $button->statestring = $this->get_state_string($qa, $showcorrectness); 2423 $button->page = $this->attemptobj->get_question_page($slot); 2424 $button->currentpage = $this->showall || $button->page == $this->page; 2425 $button->flagged = $qa->is_flagged(); 2426 $button->url = $this->get_question_url($slot); 2427 if ($this->attemptobj->is_blocked_by_previous_question($slot)) { 2428 $button->url = null; 2429 $button->stateclass = 'blocked'; 2430 $button->statestring = get_string('questiondependsonprevious', 'quiz'); 2431 } 2432 $buttons[] = $button; 2433 } 2434 2435 return $buttons; 2436 } 2437 2438 protected function get_state_string(question_attempt $qa, $showcorrectness) { 2439 if ($qa->get_question()->length > 0) { 2440 return $qa->get_state_string($showcorrectness); 2441 } 2442 2443 // Special case handling for 'information' items. 2444 if ($qa->get_state() == question_state::$todo) { 2445 return get_string('notyetviewed', 'quiz'); 2446 } else { 2447 return get_string('viewed', 'quiz'); 2448 } 2449 } 2450 2451 public function render_before_button_bits(mod_quiz_renderer $output) { 2452 return ''; 2453 } 2454 2455 abstract public function render_end_bits(mod_quiz_renderer $output); 2456 2457 protected function render_restart_preview_link($output) { 2458 if (!$this->attemptobj->is_own_preview()) { 2459 return ''; 2460 } 2461 return $output->restart_preview_button(new moodle_url( 2462 $this->attemptobj->start_attempt_url(), array('forcenew' => true))); 2463 } 2464 2465 protected abstract function get_question_url($slot); 2466 2467 public function user_picture() { 2468 global $DB; 2469 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_NONE) { 2470 return null; 2471 } 2472 $user = $DB->get_record('user', array('id' => $this->attemptobj->get_userid())); 2473 $userpicture = new user_picture($user); 2474 $userpicture->courseid = $this->attemptobj->get_courseid(); 2475 if ($this->attemptobj->get_quiz()->showuserpicture == QUIZ_SHOWIMAGE_LARGE) { 2476 $userpicture->size = true; 2477 } 2478 return $userpicture; 2479 } 2480 2481 /** 2482 * Return 'allquestionsononepage' as CSS class name when $showall is set, 2483 * otherwise, return 'multipages' as CSS class name. 2484 * @return string, CSS class name 2485 */ 2486 public function get_button_container_class() { 2487 // Quiz navigation is set on 'Show all questions on one page'. 2488 if ($this->showall) { 2489 return 'allquestionsononepage'; 2490 } 2491 // Quiz navigation is set on 'Show one page at a time'. 2492 return 'multipages'; 2493 } 2494 } 2495 2496 2497 /** 2498 * Specialisation of {@link quiz_nav_panel_base} for the attempt quiz page. 2499 * 2500 * @copyright 2008 Tim Hunt 2501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2502 * @since Moodle 2.0 2503 */ 2504 class quiz_attempt_nav_panel extends quiz_nav_panel_base { 2505 public function get_question_url($slot) { 2506 if ($this->attemptobj->can_navigate_to($slot)) { 2507 return $this->attemptobj->attempt_url($slot, -1, $this->page); 2508 } else { 2509 return null; 2510 } 2511 } 2512 2513 public function render_before_button_bits(mod_quiz_renderer $output) { 2514 return html_writer::tag('div', get_string('navnojswarning', 'quiz'), 2515 array('id' => 'quiznojswarning')); 2516 } 2517 2518 public function render_end_bits(mod_quiz_renderer $output) { 2519 return html_writer::link($this->attemptobj->summary_url(), 2520 get_string('endtest', 'quiz'), array('class' => 'endtestlink')) . 2521 $output->countdown_timer($this->attemptobj, time()) . 2522 $this->render_restart_preview_link($output); 2523 } 2524 } 2525 2526 2527 /** 2528 * Specialisation of {@link quiz_nav_panel_base} for the review quiz page. 2529 * 2530 * @copyright 2008 Tim Hunt 2531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2532 * @since Moodle 2.0 2533 */ 2534 class quiz_review_nav_panel extends quiz_nav_panel_base { 2535 public function get_question_url($slot) { 2536 return $this->attemptobj->review_url($slot, -1, $this->showall, $this->page); 2537 } 2538 2539 public function render_end_bits(mod_quiz_renderer $output) { 2540 $html = ''; 2541 if ($this->attemptobj->get_num_pages() > 1) { 2542 if ($this->showall) { 2543 $html .= html_writer::link($this->attemptobj->review_url(null, 0, false), 2544 get_string('showeachpage', 'quiz')); 2545 } else { 2546 $html .= html_writer::link($this->attemptobj->review_url(null, 0, true), 2547 get_string('showall', 'quiz')); 2548 } 2549 } 2550 $html .= $output->finish_review_link($this->attemptobj); 2551 $html .= $this->render_restart_preview_link($output); 2552 return $html; 2553 } 2554 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Thu Aug 11 10:00:09 2016 | Cross-referenced by PHPXref 0.7.1 |