Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]
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 * Library of functions for the quiz module. 19 * 20 * This contains functions that are called also from outside the quiz module 21 * Functions that are only called by the quiz module itself are in {@link locallib.php} 22 * 23 * @package mod_quiz 24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 26 */ 27 28 29 defined('MOODLE_INTERNAL') || die(); 30 31 use mod_quiz\access_manager; 32 use mod_quiz\form\add_random_form; 33 use mod_quiz\grade_calculator; 34 use mod_quiz\question\bank\custom_view; 35 use mod_quiz\question\bank\qbank_helper; 36 use mod_quiz\question\display_options; 37 use mod_quiz\question\qubaids_for_quiz; 38 use mod_quiz\question\qubaids_for_users_attempts; 39 use core_question\statistics\questions\all_calculated_for_qubaid_condition; 40 use mod_quiz\quiz_attempt; 41 use mod_quiz\quiz_settings; 42 43 require_once($CFG->dirroot . '/calendar/lib.php'); 44 45 /**#@+ 46 * Option controlling what options are offered on the quiz settings form. 47 */ 48 define('QUIZ_MAX_ATTEMPT_OPTION', 10); 49 define('QUIZ_MAX_QPP_OPTION', 50); 50 define('QUIZ_MAX_DECIMAL_OPTION', 5); 51 define('QUIZ_MAX_Q_DECIMAL_OPTION', 7); 52 /**#@-*/ 53 54 /**#@+ 55 * Options determining how the grades from individual attempts are combined to give 56 * the overall grade for a user 57 */ 58 define('QUIZ_GRADEHIGHEST', '1'); 59 define('QUIZ_GRADEAVERAGE', '2'); 60 define('QUIZ_ATTEMPTFIRST', '3'); 61 define('QUIZ_ATTEMPTLAST', '4'); 62 /**#@-*/ 63 64 /** 65 * @var int If start and end date for the quiz are more than this many seconds apart 66 * they will be represented by two separate events in the calendar 67 */ 68 define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days. 69 70 /**#@+ 71 * Options for navigation method within quizzes. 72 */ 73 define('QUIZ_NAVMETHOD_FREE', 'free'); 74 define('QUIZ_NAVMETHOD_SEQ', 'sequential'); 75 /**#@-*/ 76 77 /** 78 * Event types. 79 */ 80 define('QUIZ_EVENT_TYPE_OPEN', 'open'); 81 define('QUIZ_EVENT_TYPE_CLOSE', 'close'); 82 83 require_once (__DIR__ . '/deprecatedlib.php'); 84 85 /** 86 * Given an object containing all the necessary data, 87 * (defined by the form in mod_form.php) this function 88 * will create a new instance and return the id number 89 * of the new instance. 90 * 91 * @param stdClass $quiz the data that came from the form. 92 * @return mixed the id of the new instance on success, 93 * false or a string error message on failure. 94 */ 95 function quiz_add_instance($quiz) { 96 global $DB; 97 $cmid = $quiz->coursemodule; 98 99 // Process the options from the form. 100 $quiz->timecreated = time(); 101 $result = quiz_process_options($quiz); 102 if ($result && is_string($result)) { 103 return $result; 104 } 105 106 // Try to store it in the database. 107 $quiz->id = $DB->insert_record('quiz', $quiz); 108 109 // Create the first section for this quiz. 110 $DB->insert_record('quiz_sections', ['quizid' => $quiz->id, 111 'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0]); 112 113 // Do the processing required after an add or an update. 114 quiz_after_add_or_update($quiz); 115 116 return $quiz->id; 117 } 118 119 /** 120 * Given an object containing all the necessary data, 121 * (defined by the form in mod_form.php) this function 122 * will update an existing instance with new data. 123 * 124 * @param stdClass $quiz the data that came from the form. 125 * @param stdClass $mform no longer used. 126 * @return mixed true on success, false or a string error message on failure. 127 */ 128 function quiz_update_instance($quiz, $mform) { 129 global $CFG, $DB; 130 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 131 132 // Process the options from the form. 133 $result = quiz_process_options($quiz); 134 if ($result && is_string($result)) { 135 return $result; 136 } 137 138 // Get the current value, so we can see what changed. 139 $oldquiz = $DB->get_record('quiz', ['id' => $quiz->instance]); 140 141 // We need two values from the existing DB record that are not in the form, 142 // in some of the function calls below. 143 $quiz->sumgrades = $oldquiz->sumgrades; 144 $quiz->grade = $oldquiz->grade; 145 146 // Update the database. 147 $quiz->id = $quiz->instance; 148 $DB->update_record('quiz', $quiz); 149 150 // Do the processing required after an add or an update. 151 quiz_after_add_or_update($quiz); 152 153 if ($oldquiz->grademethod != $quiz->grademethod) { 154 $gradecalculator = quiz_settings::create($quiz->id)->get_grade_calculator(); 155 $gradecalculator->recompute_all_final_grades(); 156 quiz_update_grades($quiz); 157 } 158 159 $quizdateschanged = $oldquiz->timelimit != $quiz->timelimit 160 || $oldquiz->timeclose != $quiz->timeclose 161 || $oldquiz->graceperiod != $quiz->graceperiod; 162 if ($quizdateschanged) { 163 quiz_update_open_attempts(['quizid' => $quiz->id]); 164 } 165 166 // Delete any previous preview attempts. 167 quiz_delete_previews($quiz); 168 169 // Repaginate, if asked to. 170 if (!empty($quiz->repaginatenow) && !quiz_has_attempts($quiz->id)) { 171 quiz_repaginate_questions($quiz->id, $quiz->questionsperpage); 172 } 173 174 return true; 175 } 176 177 /** 178 * Given an ID of an instance of this module, 179 * this function will permanently delete the instance 180 * and any data that depends on it. 181 * 182 * @param int $id the id of the quiz to delete. 183 * @return bool success or failure. 184 */ 185 function quiz_delete_instance($id) { 186 global $DB; 187 188 $quiz = $DB->get_record('quiz', ['id' => $id], '*', MUST_EXIST); 189 190 quiz_delete_all_attempts($quiz); 191 quiz_delete_all_overrides($quiz); 192 quiz_delete_references($quiz->id); 193 194 // We need to do the following deletes before we try and delete randoms, otherwise they would still be 'in use'. 195 $DB->delete_records('quiz_slots', ['quizid' => $quiz->id]); 196 $DB->delete_records('quiz_sections', ['quizid' => $quiz->id]); 197 198 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]); 199 200 access_manager::delete_settings($quiz); 201 202 $events = $DB->get_records('event', ['modulename' => 'quiz', 'instance' => $quiz->id]); 203 foreach ($events as $event) { 204 $event = calendar_event::load($event); 205 $event->delete(); 206 } 207 208 quiz_grade_item_delete($quiz); 209 // We must delete the module record after we delete the grade item. 210 $DB->delete_records('quiz', ['id' => $quiz->id]); 211 212 return true; 213 } 214 215 /** 216 * Deletes a quiz override from the database and clears any corresponding calendar events 217 * 218 * @param stdClass $quiz The quiz object. 219 * @param int $overrideid The id of the override being deleted 220 * @param bool $log Whether to trigger logs. 221 * @return bool true on success 222 */ 223 function quiz_delete_override($quiz, $overrideid, $log = true) { 224 global $DB; 225 226 if (!isset($quiz->cmid)) { 227 $cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course); 228 $quiz->cmid = $cm->id; 229 } 230 231 $override = $DB->get_record('quiz_overrides', ['id' => $overrideid], '*', MUST_EXIST); 232 233 // Delete the events. 234 if (isset($override->groupid)) { 235 // Create the search array for a group override. 236 $eventsearcharray = ['modulename' => 'quiz', 237 'instance' => $quiz->id, 'groupid' => (int)$override->groupid]; 238 $cachekey = "{$quiz->id}_g_{$override->groupid}"; 239 } else { 240 // Create the search array for a user override. 241 $eventsearcharray = ['modulename' => 'quiz', 242 'instance' => $quiz->id, 'userid' => (int)$override->userid]; 243 $cachekey = "{$quiz->id}_u_{$override->userid}"; 244 } 245 $events = $DB->get_records('event', $eventsearcharray); 246 foreach ($events as $event) { 247 $eventold = calendar_event::load($event); 248 $eventold->delete(); 249 } 250 251 $DB->delete_records('quiz_overrides', ['id' => $overrideid]); 252 cache::make('mod_quiz', 'overrides')->delete($cachekey); 253 254 if ($log) { 255 // Set the common parameters for one of the events we will be triggering. 256 $params = [ 257 'objectid' => $override->id, 258 'context' => context_module::instance($quiz->cmid), 259 'other' => [ 260 'quizid' => $override->quiz 261 ] 262 ]; 263 // Determine which override deleted event to fire. 264 if (!empty($override->userid)) { 265 $params['relateduserid'] = $override->userid; 266 $event = \mod_quiz\event\user_override_deleted::create($params); 267 } else { 268 $params['other']['groupid'] = $override->groupid; 269 $event = \mod_quiz\event\group_override_deleted::create($params); 270 } 271 272 // Trigger the override deleted event. 273 $event->add_record_snapshot('quiz_overrides', $override); 274 $event->trigger(); 275 } 276 277 return true; 278 } 279 280 /** 281 * Deletes all quiz overrides from the database and clears any corresponding calendar events 282 * 283 * @param stdClass $quiz The quiz object. 284 * @param bool $log Whether to trigger logs. 285 */ 286 function quiz_delete_all_overrides($quiz, $log = true) { 287 global $DB; 288 289 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id'); 290 foreach ($overrides as $override) { 291 quiz_delete_override($quiz, $override->id, $log); 292 } 293 } 294 295 /** 296 * Updates a quiz object with override information for a user. 297 * 298 * Algorithm: For each quiz setting, if there is a matching user-specific override, 299 * then use that otherwise, if there are group-specific overrides, return the most 300 * lenient combination of them. If neither applies, leave the quiz setting unchanged. 301 * 302 * Special case: if there is more than one password that applies to the user, then 303 * quiz->extrapasswords will contain an array of strings giving the remaining 304 * passwords. 305 * 306 * @param stdClass $quiz The quiz object. 307 * @param int $userid The userid. 308 * @return stdClass $quiz The updated quiz object. 309 */ 310 function quiz_update_effective_access($quiz, $userid) { 311 global $DB; 312 313 // Check for user override. 314 $override = $DB->get_record('quiz_overrides', ['quiz' => $quiz->id, 'userid' => $userid]); 315 316 if (!$override) { 317 $override = new stdClass(); 318 $override->timeopen = null; 319 $override->timeclose = null; 320 $override->timelimit = null; 321 $override->attempts = null; 322 $override->password = null; 323 } 324 325 // Check for group overrides. 326 $groupings = groups_get_user_groups($quiz->course, $userid); 327 328 if (!empty($groupings[0])) { 329 // Select all overrides that apply to the User's groups. 330 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0])); 331 $sql = "SELECT * FROM {quiz_overrides} 332 WHERE groupid $extra AND quiz = ?"; 333 $params[] = $quiz->id; 334 $records = $DB->get_records_sql($sql, $params); 335 336 // Combine the overrides. 337 $opens = []; 338 $closes = []; 339 $limits = []; 340 $attempts = []; 341 $passwords = []; 342 343 foreach ($records as $gpoverride) { 344 if (isset($gpoverride->timeopen)) { 345 $opens[] = $gpoverride->timeopen; 346 } 347 if (isset($gpoverride->timeclose)) { 348 $closes[] = $gpoverride->timeclose; 349 } 350 if (isset($gpoverride->timelimit)) { 351 $limits[] = $gpoverride->timelimit; 352 } 353 if (isset($gpoverride->attempts)) { 354 $attempts[] = $gpoverride->attempts; 355 } 356 if (isset($gpoverride->password)) { 357 $passwords[] = $gpoverride->password; 358 } 359 } 360 // If there is a user override for a setting, ignore the group override. 361 if (is_null($override->timeopen) && count($opens)) { 362 $override->timeopen = min($opens); 363 } 364 if (is_null($override->timeclose) && count($closes)) { 365 if (in_array(0, $closes)) { 366 $override->timeclose = 0; 367 } else { 368 $override->timeclose = max($closes); 369 } 370 } 371 if (is_null($override->timelimit) && count($limits)) { 372 if (in_array(0, $limits)) { 373 $override->timelimit = 0; 374 } else { 375 $override->timelimit = max($limits); 376 } 377 } 378 if (is_null($override->attempts) && count($attempts)) { 379 if (in_array(0, $attempts)) { 380 $override->attempts = 0; 381 } else { 382 $override->attempts = max($attempts); 383 } 384 } 385 if (is_null($override->password) && count($passwords)) { 386 $override->password = array_shift($passwords); 387 if (count($passwords)) { 388 $override->extrapasswords = $passwords; 389 } 390 } 391 392 } 393 394 // Merge with quiz defaults. 395 $keys = ['timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords']; 396 foreach ($keys as $key) { 397 if (isset($override->{$key})) { 398 $quiz->{$key} = $override->{$key}; 399 } 400 } 401 402 return $quiz; 403 } 404 405 /** 406 * Delete all the attempts belonging to a quiz. 407 * 408 * @param stdClass $quiz The quiz object. 409 */ 410 function quiz_delete_all_attempts($quiz) { 411 global $CFG, $DB; 412 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 413 question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id)); 414 $DB->delete_records('quiz_attempts', ['quiz' => $quiz->id]); 415 $DB->delete_records('quiz_grades', ['quiz' => $quiz->id]); 416 } 417 418 /** 419 * Delete all the attempts belonging to a user in a particular quiz. 420 * 421 * @param \mod_quiz\quiz_settings $quiz The quiz object. 422 * @param stdClass $user The user object. 423 */ 424 function quiz_delete_user_attempts($quiz, $user) { 425 global $CFG, $DB; 426 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 427 question_engine::delete_questions_usage_by_activities(new qubaids_for_users_attempts( 428 $quiz->get_quizid(), $user->id, 'all')); 429 $params = [ 430 'quiz' => $quiz->get_quizid(), 431 'userid' => $user->id, 432 ]; 433 $DB->delete_records('quiz_attempts', $params); 434 $DB->delete_records('quiz_grades', $params); 435 } 436 437 /** 438 * Get the best current grade for a particular user in a quiz. 439 * 440 * @param stdClass $quiz the quiz settings. 441 * @param int $userid the id of the user. 442 * @return float the user's current grade for this quiz, or null if this user does 443 * not have a grade on this quiz. 444 */ 445 function quiz_get_best_grade($quiz, $userid) { 446 global $DB; 447 $grade = $DB->get_field('quiz_grades', 'grade', 448 ['quiz' => $quiz->id, 'userid' => $userid]); 449 450 // Need to detect errors/no result, without catching 0 grades. 451 if ($grade === false) { 452 return null; 453 } 454 455 return $grade + 0; // Convert to number. 456 } 457 458 /** 459 * Is this a graded quiz? If this method returns true, you can assume that 460 * $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to 461 * divide by them). 462 * 463 * @param stdClass $quiz a row from the quiz table. 464 * @return bool whether this is a graded quiz. 465 */ 466 function quiz_has_grades($quiz) { 467 return $quiz->grade >= grade_calculator::ALMOST_ZERO && $quiz->sumgrades >= grade_calculator::ALMOST_ZERO; 468 } 469 470 /** 471 * Does this quiz allow multiple tries? 472 * 473 * @return bool 474 */ 475 function quiz_allows_multiple_tries($quiz) { 476 $bt = question_engine::get_behaviour_type($quiz->preferredbehaviour); 477 return $bt->allows_multiple_submitted_responses(); 478 } 479 480 /** 481 * Return a small object with summary information about what a 482 * user has done with a given particular instance of this module 483 * Used for user activity reports. 484 * $return->time = the time they did it 485 * $return->info = a short text description 486 * 487 * @param stdClass $course 488 * @param stdClass $user 489 * @param stdClass $mod 490 * @param stdClass $quiz 491 * @return stdClass|null 492 */ 493 function quiz_user_outline($course, $user, $mod, $quiz) { 494 global $DB, $CFG; 495 require_once($CFG->libdir . '/gradelib.php'); 496 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id); 497 498 if (empty($grades->items[0]->grades)) { 499 return null; 500 } else { 501 $grade = reset($grades->items[0]->grades); 502 } 503 504 $result = new stdClass(); 505 // If the user can't see hidden grades, don't return that information. 506 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]); 507 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 508 $result->info = get_string('gradenoun') . ': ' . $grade->str_long_grade; 509 } else { 510 $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades'); 511 } 512 513 $result->time = grade_get_date_for_user_grade($grade, $user); 514 515 return $result; 516 } 517 518 /** 519 * Print a detailed representation of what a user has done with 520 * a given particular instance of this module, for user activity reports. 521 * 522 * @param stdClass $course 523 * @param stdClass $user 524 * @param stdClass $mod 525 * @param stdClass $quiz 526 * @return bool 527 */ 528 function quiz_user_complete($course, $user, $mod, $quiz) { 529 global $DB, $CFG, $OUTPUT; 530 require_once($CFG->libdir . '/gradelib.php'); 531 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 532 533 $grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id); 534 if (!empty($grades->items[0]->grades)) { 535 $grade = reset($grades->items[0]->grades); 536 // If the user can't see hidden grades, don't return that information. 537 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]); 538 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 539 echo $OUTPUT->container(get_string('gradenoun').': '.$grade->str_long_grade); 540 if ($grade->str_feedback) { 541 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback); 542 } 543 } else { 544 echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades')); 545 if ($grade->str_feedback) { 546 echo $OUTPUT->container(get_string('feedback').': '.get_string('hidden', 'grades')); 547 } 548 } 549 } 550 551 if ($attempts = $DB->get_records('quiz_attempts', 552 ['userid' => $user->id, 'quiz' => $quiz->id], 'attempt')) { 553 foreach ($attempts as $attempt) { 554 echo get_string('attempt', 'quiz', $attempt->attempt) . ': '; 555 if ($attempt->state != quiz_attempt::FINISHED) { 556 echo quiz_attempt_state_name($attempt->state); 557 } else { 558 if (!isset($gitem)) { 559 if (!empty($grades->items[0]->grades)) { 560 $gitem = grade_item::fetch(['id' => $grades->items[0]->id]); 561 } else { 562 $gitem = new stdClass(); 563 $gitem->hidden = true; 564 } 565 } 566 if (!$gitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 567 echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' . quiz_format_grade($quiz, $quiz->sumgrades); 568 } else { 569 echo get_string('hidden', 'grades'); 570 } 571 echo ' - '.userdate($attempt->timefinish).'<br />'; 572 } 573 } 574 } else { 575 print_string('noattempts', 'quiz'); 576 } 577 578 return true; 579 } 580 581 582 /** 583 * @param int|array $quizids A quiz ID, or an array of quiz IDs. 584 * @param int $userid the userid. 585 * @param string $status 'all', 'finished' or 'unfinished' to control 586 * @param bool $includepreviews 587 * @return array of all the user's attempts at this quiz. Returns an empty 588 * array if there are none. 589 */ 590 function quiz_get_user_attempts($quizids, $userid, $status = 'finished', $includepreviews = false) { 591 global $DB; 592 593 $params = []; 594 switch ($status) { 595 case 'all': 596 $statuscondition = ''; 597 break; 598 599 case 'finished': 600 $statuscondition = ' AND state IN (:state1, :state2)'; 601 $params['state1'] = quiz_attempt::FINISHED; 602 $params['state2'] = quiz_attempt::ABANDONED; 603 break; 604 605 case 'unfinished': 606 $statuscondition = ' AND state IN (:state1, :state2)'; 607 $params['state1'] = quiz_attempt::IN_PROGRESS; 608 $params['state2'] = quiz_attempt::OVERDUE; 609 break; 610 } 611 612 $quizids = (array) $quizids; 613 list($insql, $inparams) = $DB->get_in_or_equal($quizids, SQL_PARAMS_NAMED); 614 $params += $inparams; 615 $params['userid'] = $userid; 616 617 $previewclause = ''; 618 if (!$includepreviews) { 619 $previewclause = ' AND preview = 0'; 620 } 621 622 return $DB->get_records_select('quiz_attempts', 623 "quiz $insql AND userid = :userid" . $previewclause . $statuscondition, 624 $params, 'quiz, attempt ASC'); 625 } 626 627 /** 628 * Return grade for given user or all users. 629 * 630 * @param int $quizid id of quiz 631 * @param int $userid optional user id, 0 means all users 632 * @return array array of grades, false if none. These are raw grades. They should 633 * be processed with quiz_format_grade for display. 634 */ 635 function quiz_get_user_grades($quiz, $userid = 0) { 636 global $CFG, $DB; 637 638 $params = [$quiz->id]; 639 $usertest = ''; 640 if ($userid) { 641 $params[] = $userid; 642 $usertest = 'AND u.id = ?'; 643 } 644 return $DB->get_records_sql(" 645 SELECT 646 u.id, 647 u.id AS userid, 648 qg.grade AS rawgrade, 649 qg.timemodified AS dategraded, 650 MAX(qa.timefinish) AS datesubmitted 651 652 FROM {user} u 653 JOIN {quiz_grades} qg ON u.id = qg.userid 654 JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id 655 656 WHERE qg.quiz = ? 657 $usertest 658 GROUP BY u.id, qg.grade, qg.timemodified", $params); 659 } 660 661 /** 662 * Round a grade to the correct number of decimal places, and format it for display. 663 * 664 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used. 665 * @param float $grade The grade to round. 666 * @return string 667 */ 668 function quiz_format_grade($quiz, $grade) { 669 if (is_null($grade)) { 670 return get_string('notyetgraded', 'quiz'); 671 } 672 return format_float($grade, $quiz->decimalpoints); 673 } 674 675 /** 676 * Determine the correct number of decimal places required to format a grade. 677 * 678 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints and 679 * ->questiondecimalpoints are used. 680 * @return integer 681 */ 682 function quiz_get_grade_format($quiz) { 683 if (empty($quiz->questiondecimalpoints)) { 684 $quiz->questiondecimalpoints = -1; 685 } 686 687 if ($quiz->questiondecimalpoints == -1) { 688 return $quiz->decimalpoints; 689 } 690 691 return $quiz->questiondecimalpoints; 692 } 693 694 /** 695 * Round a grade to the correct number of decimal places, and format it for display. 696 * 697 * @param stdClass $quiz The quiz table row, only $quiz->decimalpoints is used. 698 * @param float $grade The grade to round. 699 * @return string 700 */ 701 function quiz_format_question_grade($quiz, $grade) { 702 return format_float($grade, quiz_get_grade_format($quiz)); 703 } 704 705 /** 706 * Update grades in central gradebook 707 * 708 * @category grade 709 * @param stdClass $quiz the quiz settings. 710 * @param int $userid specific user only, 0 means all users. 711 * @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted 712 */ 713 function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) { 714 global $CFG, $DB; 715 require_once($CFG->libdir . '/gradelib.php'); 716 717 if ($quiz->grade == 0) { 718 quiz_grade_item_update($quiz); 719 720 } else if ($grades = quiz_get_user_grades($quiz, $userid)) { 721 quiz_grade_item_update($quiz, $grades); 722 723 } else if ($userid && $nullifnone) { 724 $grade = new stdClass(); 725 $grade->userid = $userid; 726 $grade->rawgrade = null; 727 quiz_grade_item_update($quiz, $grade); 728 729 } else { 730 quiz_grade_item_update($quiz); 731 } 732 } 733 734 /** 735 * Create or update the grade item for given quiz 736 * 737 * @category grade 738 * @param stdClass $quiz object with extra cmidnumber 739 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook 740 * @return int 0 if ok, error code otherwise 741 */ 742 function quiz_grade_item_update($quiz, $grades = null) { 743 global $CFG, $OUTPUT; 744 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 745 require_once($CFG->libdir . '/gradelib.php'); 746 747 if (property_exists($quiz, 'cmidnumber')) { // May not be always present. 748 $params = ['itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber]; 749 } else { 750 $params = ['itemname' => $quiz->name]; 751 } 752 753 if ($quiz->grade > 0) { 754 $params['gradetype'] = GRADE_TYPE_VALUE; 755 $params['grademax'] = $quiz->grade; 756 $params['grademin'] = 0; 757 758 } else { 759 $params['gradetype'] = GRADE_TYPE_NONE; 760 } 761 762 // What this is trying to do: 763 // 1. If the quiz is set to not show grades while the quiz is still open, 764 // and is set to show grades after the quiz is closed, then create the 765 // grade_item with a show-after date that is the quiz close date. 766 // 2. If the quiz is set to not show grades at either of those times, 767 // create the grade_item as hidden. 768 // 3. If the quiz is set to show grades, create the grade_item visible. 769 $openreviewoptions = display_options::make_from_quiz($quiz, 770 display_options::LATER_WHILE_OPEN); 771 $closedreviewoptions = display_options::make_from_quiz($quiz, 772 display_options::AFTER_CLOSE); 773 if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX && 774 $closedreviewoptions->marks < question_display_options::MARK_AND_MAX) { 775 $params['hidden'] = 1; 776 777 } else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX && 778 $closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) { 779 if ($quiz->timeclose) { 780 $params['hidden'] = $quiz->timeclose; 781 } else { 782 $params['hidden'] = 1; 783 } 784 785 } else { 786 // Either 787 // a) both open and closed enabled 788 // b) open enabled, closed disabled - we can not "hide after", 789 // grades are kept visible even after closing. 790 $params['hidden'] = 0; 791 } 792 793 if (!$params['hidden']) { 794 // If the grade item is not hidden by the quiz logic, then we need to 795 // hide it if the quiz is hidden from students. 796 if (property_exists($quiz, 'visible')) { 797 // Saving the quiz form, and cm not yet updated in the database. 798 $params['hidden'] = !$quiz->visible; 799 } else { 800 $cm = get_coursemodule_from_instance('quiz', $quiz->id); 801 $params['hidden'] = !$cm->visible; 802 } 803 } 804 805 if ($grades === 'reset') { 806 $params['reset'] = true; 807 $grades = null; 808 } 809 810 $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id); 811 if (!empty($gradebook_grades->items)) { 812 $grade_item = $gradebook_grades->items[0]; 813 if ($grade_item->locked) { 814 // NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak. 815 $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT); 816 if (!$confirm_regrade) { 817 if (!AJAX_SCRIPT) { 818 $message = get_string('gradeitemislocked', 'grades'); 819 $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id . 820 '&mode=overview'; 821 $regrade_link = qualified_me() . '&confirm_regrade=1'; 822 echo $OUTPUT->box_start('generalbox', 'notice'); 823 echo '<p>'. $message .'</p>'; 824 echo $OUTPUT->container_start('buttons'); 825 echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades')); 826 echo $OUTPUT->single_button($back_link, get_string('cancel')); 827 echo $OUTPUT->container_end(); 828 echo $OUTPUT->box_end(); 829 } 830 return GRADE_UPDATE_ITEM_LOCKED; 831 } 832 } 833 } 834 835 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params); 836 } 837 838 /** 839 * Delete grade item for given quiz 840 * 841 * @category grade 842 * @param stdClass $quiz object 843 * @return int 844 */ 845 function quiz_grade_item_delete($quiz) { 846 global $CFG; 847 require_once($CFG->libdir . '/gradelib.php'); 848 849 return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, 850 null, ['deleted' => 1]); 851 } 852 853 /** 854 * This standard function will check all instances of this module 855 * and make sure there are up-to-date events created for each of them. 856 * If courseid = 0, then every quiz event in the site is checked, else 857 * only quiz events belonging to the course specified are checked. 858 * This function is used, in its new format, by restore_refresh_events() 859 * 860 * @param int $courseid 861 * @param int|stdClass $instance Quiz module instance or ID. 862 * @param int|stdClass $cm Course module object or ID (not used in this module). 863 * @return bool 864 */ 865 function quiz_refresh_events($courseid = 0, $instance = null, $cm = null) { 866 global $DB; 867 868 // If we have instance information then we can just update the one event instead of updating all events. 869 if (isset($instance)) { 870 if (!is_object($instance)) { 871 $instance = $DB->get_record('quiz', ['id' => $instance], '*', MUST_EXIST); 872 } 873 quiz_update_events($instance); 874 return true; 875 } 876 877 if ($courseid == 0) { 878 if (!$quizzes = $DB->get_records('quiz')) { 879 return true; 880 } 881 } else { 882 if (!$quizzes = $DB->get_records('quiz', ['course' => $courseid])) { 883 return true; 884 } 885 } 886 887 foreach ($quizzes as $quiz) { 888 quiz_update_events($quiz); 889 } 890 891 return true; 892 } 893 894 /** 895 * Returns all quiz graded users since a given time for specified quiz 896 */ 897 function quiz_get_recent_mod_activity(&$activities, &$index, $timestart, 898 $courseid, $cmid, $userid = 0, $groupid = 0) { 899 global $CFG, $USER, $DB; 900 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 901 902 $course = get_course($courseid); 903 $modinfo = get_fast_modinfo($course); 904 905 $cm = $modinfo->cms[$cmid]; 906 $quiz = $DB->get_record('quiz', ['id' => $cm->instance]); 907 908 if ($userid) { 909 $userselect = "AND u.id = :userid"; 910 $params['userid'] = $userid; 911 } else { 912 $userselect = ''; 913 } 914 915 if ($groupid) { 916 $groupselect = 'AND gm.groupid = :groupid'; 917 $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id'; 918 $params['groupid'] = $groupid; 919 } else { 920 $groupselect = ''; 921 $groupjoin = ''; 922 } 923 924 $params['timestart'] = $timestart; 925 $params['quizid'] = $quiz->id; 926 927 $userfieldsapi = \core_user\fields::for_userpic(); 928 $ufields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects; 929 if (!$attempts = $DB->get_records_sql(" 930 SELECT qa.*, 931 {$ufields} 932 FROM {quiz_attempts} qa 933 JOIN {user} u ON u.id = qa.userid 934 $groupjoin 935 WHERE qa.timefinish > :timestart 936 AND qa.quiz = :quizid 937 AND qa.preview = 0 938 $userselect 939 $groupselect 940 ORDER BY qa.timefinish ASC", $params)) { 941 return; 942 } 943 944 $context = context_module::instance($cm->id); 945 $accessallgroups = has_capability('moodle/site:accessallgroups', $context); 946 $viewfullnames = has_capability('moodle/site:viewfullnames', $context); 947 $grader = has_capability('mod/quiz:viewreports', $context); 948 $groupmode = groups_get_activity_groupmode($cm, $course); 949 950 $usersgroups = null; 951 $aname = format_string($cm->name, true); 952 foreach ($attempts as $attempt) { 953 if ($attempt->userid != $USER->id) { 954 if (!$grader) { 955 // Grade permission required. 956 continue; 957 } 958 959 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) { 960 $usersgroups = groups_get_all_groups($course->id, 961 $attempt->userid, $cm->groupingid); 962 $usersgroups = array_keys($usersgroups); 963 if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) { 964 continue; 965 } 966 } 967 } 968 969 $options = quiz_get_review_options($quiz, $attempt, $context); 970 971 $tmpactivity = new stdClass(); 972 973 $tmpactivity->type = 'quiz'; 974 $tmpactivity->cmid = $cm->id; 975 $tmpactivity->name = $aname; 976 $tmpactivity->sectionnum = $cm->sectionnum; 977 $tmpactivity->timestamp = $attempt->timefinish; 978 979 $tmpactivity->content = new stdClass(); 980 $tmpactivity->content->attemptid = $attempt->id; 981 $tmpactivity->content->attempt = $attempt->attempt; 982 if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) { 983 $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades); 984 $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades); 985 } else { 986 $tmpactivity->content->sumgrades = null; 987 $tmpactivity->content->maxgrade = null; 988 } 989 990 $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain'); 991 $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames); 992 993 $activities[$index++] = $tmpactivity; 994 } 995 } 996 997 function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) { 998 global $CFG, $OUTPUT; 999 1000 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">'; 1001 1002 echo '<tr><td class="userpicture" valign="top">'; 1003 echo $OUTPUT->user_picture($activity->user, ['courseid' => $courseid]); 1004 echo '</td><td>'; 1005 1006 if ($detail) { 1007 $modname = $modnames[$activity->type]; 1008 echo '<div class="title">'; 1009 echo $OUTPUT->image_icon('monologo', $modname, $activity->type); 1010 echo '<a href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' . 1011 $activity->cmid . '">' . $activity->name . '</a>'; 1012 echo '</div>'; 1013 } 1014 1015 echo '<div class="grade">'; 1016 echo get_string('attempt', 'quiz', $activity->content->attempt); 1017 if (isset($activity->content->maxgrade)) { 1018 $grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade; 1019 echo ': (<a href="' . $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . 1020 $activity->content->attemptid . '">' . $grades . '</a>)'; 1021 } 1022 echo '</div>'; 1023 1024 echo '<div class="user">'; 1025 echo '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $activity->user->id . 1026 '&course=' . $courseid . '">' . $activity->user->fullname . 1027 '</a> - ' . userdate($activity->timestamp); 1028 echo '</div>'; 1029 1030 echo '</td></tr></table>'; 1031 1032 return; 1033 } 1034 1035 /** 1036 * Pre-process the quiz options form data, making any necessary adjustments. 1037 * Called by add/update instance in this file. 1038 * 1039 * @param stdClass $quiz The variables set on the form. 1040 */ 1041 function quiz_process_options($quiz) { 1042 global $CFG; 1043 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 1044 require_once($CFG->libdir . '/questionlib.php'); 1045 1046 $quiz->timemodified = time(); 1047 1048 // Quiz name. 1049 if (!empty($quiz->name)) { 1050 $quiz->name = trim($quiz->name); 1051 } 1052 1053 // Password field - different in form to stop browsers that remember passwords 1054 // getting confused. 1055 $quiz->password = $quiz->quizpassword; 1056 unset($quiz->quizpassword); 1057 1058 // Quiz feedback. 1059 if (isset($quiz->feedbacktext)) { 1060 // Clean up the boundary text. 1061 for ($i = 0; $i < count($quiz->feedbacktext); $i += 1) { 1062 if (empty($quiz->feedbacktext[$i]['text'])) { 1063 $quiz->feedbacktext[$i]['text'] = ''; 1064 } else { 1065 $quiz->feedbacktext[$i]['text'] = trim($quiz->feedbacktext[$i]['text']); 1066 } 1067 } 1068 1069 // Check the boundary value is a number or a percentage, and in range. 1070 $i = 0; 1071 while (!empty($quiz->feedbackboundaries[$i])) { 1072 $boundary = trim($quiz->feedbackboundaries[$i]); 1073 if (!is_numeric($boundary)) { 1074 if (strlen($boundary) > 0 && $boundary[strlen($boundary) - 1] == '%') { 1075 $boundary = trim(substr($boundary, 0, -1)); 1076 if (is_numeric($boundary)) { 1077 $boundary = $boundary * $quiz->grade / 100.0; 1078 } else { 1079 return get_string('feedbackerrorboundaryformat', 'quiz', $i + 1); 1080 } 1081 } 1082 } 1083 if ($boundary <= 0 || $boundary >= $quiz->grade) { 1084 return get_string('feedbackerrorboundaryoutofrange', 'quiz', $i + 1); 1085 } 1086 if ($i > 0 && $boundary >= $quiz->feedbackboundaries[$i - 1]) { 1087 return get_string('feedbackerrororder', 'quiz', $i + 1); 1088 } 1089 $quiz->feedbackboundaries[$i] = $boundary; 1090 $i += 1; 1091 } 1092 $numboundaries = $i; 1093 1094 // Check there is nothing in the remaining unused fields. 1095 if (!empty($quiz->feedbackboundaries)) { 1096 for ($i = $numboundaries; $i < count($quiz->feedbackboundaries); $i += 1) { 1097 if (!empty($quiz->feedbackboundaries[$i]) && 1098 trim($quiz->feedbackboundaries[$i]) != '') { 1099 return get_string('feedbackerrorjunkinboundary', 'quiz', $i + 1); 1100 } 1101 } 1102 } 1103 for ($i = $numboundaries + 1; $i < count($quiz->feedbacktext); $i += 1) { 1104 if (!empty($quiz->feedbacktext[$i]['text']) && 1105 trim($quiz->feedbacktext[$i]['text']) != '') { 1106 return get_string('feedbackerrorjunkinfeedback', 'quiz', $i + 1); 1107 } 1108 } 1109 // Needs to be bigger than $quiz->grade because of '<' test in quiz_feedback_for_grade(). 1110 $quiz->feedbackboundaries[-1] = $quiz->grade + 1; 1111 $quiz->feedbackboundaries[$numboundaries] = 0; 1112 $quiz->feedbackboundarycount = $numboundaries; 1113 } else { 1114 $quiz->feedbackboundarycount = -1; 1115 } 1116 1117 // Combing the individual settings into the review columns. 1118 $quiz->reviewattempt = quiz_review_option_form_to_db($quiz, 'attempt'); 1119 $quiz->reviewcorrectness = quiz_review_option_form_to_db($quiz, 'correctness'); 1120 $quiz->reviewmarks = quiz_review_option_form_to_db($quiz, 'marks'); 1121 $quiz->reviewspecificfeedback = quiz_review_option_form_to_db($quiz, 'specificfeedback'); 1122 $quiz->reviewgeneralfeedback = quiz_review_option_form_to_db($quiz, 'generalfeedback'); 1123 $quiz->reviewrightanswer = quiz_review_option_form_to_db($quiz, 'rightanswer'); 1124 $quiz->reviewoverallfeedback = quiz_review_option_form_to_db($quiz, 'overallfeedback'); 1125 $quiz->reviewattempt |= display_options::DURING; 1126 $quiz->reviewoverallfeedback &= ~display_options::DURING; 1127 1128 // Ensure that disabled checkboxes in completion settings are set to 0. 1129 // But only if the completion settinsg are unlocked. 1130 if (!empty($quiz->completionunlocked)) { 1131 if (empty($quiz->completionusegrade)) { 1132 $quiz->completionpassgrade = 0; 1133 } 1134 if (empty($quiz->completionpassgrade)) { 1135 $quiz->completionattemptsexhausted = 0; 1136 } 1137 if (empty($quiz->completionminattemptsenabled)) { 1138 $quiz->completionminattempts = 0; 1139 } 1140 } 1141 } 1142 1143 /** 1144 * Helper function for {@link quiz_process_options()}. 1145 * @param stdClass $fromform the sumbitted form date. 1146 * @param string $field one of the review option field names. 1147 */ 1148 function quiz_review_option_form_to_db($fromform, $field) { 1149 static $times = [ 1150 'during' => display_options::DURING, 1151 'immediately' => display_options::IMMEDIATELY_AFTER, 1152 'open' => display_options::LATER_WHILE_OPEN, 1153 'closed' => display_options::AFTER_CLOSE, 1154 ]; 1155 1156 $review = 0; 1157 foreach ($times as $whenname => $when) { 1158 $fieldname = $field . $whenname; 1159 if (!empty($fromform->$fieldname)) { 1160 $review |= $when; 1161 unset($fromform->$fieldname); 1162 } 1163 } 1164 1165 return $review; 1166 } 1167 1168 /** 1169 * In place editable callback for slot displaynumber. 1170 * 1171 * @param string $itemtype slotdisplarnumber 1172 * @param int $itemid the id of the slot in the quiz_slots table 1173 * @param string $newvalue the new value for displaynumber field for a given slot in the quiz_slots table 1174 * @return \core\output\inplace_editable|void 1175 */ 1176 function mod_quiz_inplace_editable(string $itemtype, int $itemid, string $newvalue): \core\output\inplace_editable { 1177 global $DB; 1178 1179 if ($itemtype === 'slotdisplaynumber') { 1180 // Work out which quiz and slot this is. 1181 $slot = $DB->get_record('quiz_slots', ['id' => $itemid], '*', MUST_EXIST); 1182 $quizobj = quiz_settings::create($slot->quizid); 1183 1184 // Validate the context, and check the required capability. 1185 $context = $quizobj->get_context(); 1186 \core_external\external_api::validate_context($context); 1187 require_capability('mod/quiz:manage', $context); 1188 1189 // Update the value - truncating the size of the DB column. 1190 $structure = $quizobj->get_structure(); 1191 $structure->update_slot_display_number($itemid, core_text::substr($newvalue, 0, 16)); 1192 1193 // Prepare the element for the output. 1194 return $structure->make_slot_display_number_in_place_editable($itemid, $context); 1195 } 1196 } 1197 1198 /** 1199 * This function is called at the end of quiz_add_instance 1200 * and quiz_update_instance, to do the common processing. 1201 * 1202 * @param stdClass $quiz the quiz object. 1203 */ 1204 function quiz_after_add_or_update($quiz) { 1205 global $DB; 1206 $cmid = $quiz->coursemodule; 1207 1208 // We need to use context now, so we need to make sure all needed info is already in db. 1209 $DB->set_field('course_modules', 'instance', $quiz->id, ['id' => $cmid]); 1210 $context = context_module::instance($cmid); 1211 1212 // Save the feedback. 1213 $DB->delete_records('quiz_feedback', ['quizid' => $quiz->id]); 1214 1215 for ($i = 0; $i <= $quiz->feedbackboundarycount; $i++) { 1216 $feedback = new stdClass(); 1217 $feedback->quizid = $quiz->id; 1218 $feedback->feedbacktext = $quiz->feedbacktext[$i]['text']; 1219 $feedback->feedbacktextformat = $quiz->feedbacktext[$i]['format']; 1220 $feedback->mingrade = $quiz->feedbackboundaries[$i]; 1221 $feedback->maxgrade = $quiz->feedbackboundaries[$i - 1]; 1222 $feedback->id = $DB->insert_record('quiz_feedback', $feedback); 1223 $feedbacktext = file_save_draft_area_files((int)$quiz->feedbacktext[$i]['itemid'], 1224 $context->id, 'mod_quiz', 'feedback', $feedback->id, 1225 ['subdirs' => false, 'maxfiles' => -1, 'maxbytes' => 0], 1226 $quiz->feedbacktext[$i]['text']); 1227 $DB->set_field('quiz_feedback', 'feedbacktext', $feedbacktext, 1228 ['id' => $feedback->id]); 1229 } 1230 1231 // Store any settings belonging to the access rules. 1232 access_manager::save_settings($quiz); 1233 1234 // Update the events relating to this quiz. 1235 quiz_update_events($quiz); 1236 $completionexpected = (!empty($quiz->completionexpected)) ? $quiz->completionexpected : null; 1237 \core_completion\api::update_completion_date_event($quiz->coursemodule, 'quiz', $quiz->id, $completionexpected); 1238 1239 // Update related grade item. 1240 quiz_grade_item_update($quiz); 1241 } 1242 1243 /** 1244 * This function updates the events associated to the quiz. 1245 * If $override is non-zero, then it updates only the events 1246 * associated with the specified override. 1247 * 1248 * @param stdClass $quiz the quiz object. 1249 * @param stdClass|null $override limit to a specific override 1250 */ 1251 function quiz_update_events($quiz, $override = null) { 1252 global $DB; 1253 1254 // Load the old events relating to this quiz. 1255 $conds = ['modulename' => 'quiz', 1256 'instance' => $quiz->id]; 1257 if (!empty($override)) { 1258 // Only load events for this override. 1259 if (isset($override->userid)) { 1260 $conds['userid'] = $override->userid; 1261 } else { 1262 $conds['groupid'] = $override->groupid; 1263 } 1264 } 1265 $oldevents = $DB->get_records('event', $conds, 'id ASC'); 1266 1267 // Now make a to-do list of all that needs to be updated. 1268 if (empty($override)) { 1269 // We are updating the primary settings for the quiz, so we need to add all the overrides. 1270 $overrides = $DB->get_records('quiz_overrides', ['quiz' => $quiz->id], 'id ASC'); 1271 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents 1272 // list contains the original (non-override) event for the module. If this is not included 1273 // the logic below will end up updating the wrong row when we try to reconcile this $overrides 1274 // list against the $oldevents list. 1275 array_unshift($overrides, new stdClass()); 1276 } else { 1277 // Just do the one override. 1278 $overrides = [$override]; 1279 } 1280 1281 // Get group override priorities. 1282 $grouppriorities = quiz_get_group_override_priorities($quiz->id); 1283 1284 foreach ($overrides as $current) { 1285 $groupid = isset($current->groupid)? $current->groupid : 0; 1286 $userid = isset($current->userid)? $current->userid : 0; 1287 $timeopen = isset($current->timeopen)? $current->timeopen : $quiz->timeopen; 1288 $timeclose = isset($current->timeclose)? $current->timeclose : $quiz->timeclose; 1289 1290 // Only add open/close events for an override if they differ from the quiz default. 1291 $addopen = empty($current->id) || !empty($current->timeopen); 1292 $addclose = empty($current->id) || !empty($current->timeclose); 1293 1294 if (!empty($quiz->coursemodule)) { 1295 $cmid = $quiz->coursemodule; 1296 } else { 1297 $cmid = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course)->id; 1298 } 1299 1300 $event = new stdClass(); 1301 $event->type = !$timeclose ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD; 1302 $event->description = format_module_intro('quiz', $quiz, $cmid, false); 1303 $event->format = FORMAT_HTML; 1304 // Events module won't show user events when the courseid is nonzero. 1305 $event->courseid = ($userid) ? 0 : $quiz->course; 1306 $event->groupid = $groupid; 1307 $event->userid = $userid; 1308 $event->modulename = 'quiz'; 1309 $event->instance = $quiz->id; 1310 $event->timestart = $timeopen; 1311 $event->timeduration = max($timeclose - $timeopen, 0); 1312 $event->timesort = $timeopen; 1313 $event->visible = instance_is_visible('quiz', $quiz); 1314 $event->eventtype = QUIZ_EVENT_TYPE_OPEN; 1315 $event->priority = null; 1316 1317 // Determine the event name and priority. 1318 if ($groupid) { 1319 // Group override event. 1320 $params = new stdClass(); 1321 $params->quiz = $quiz->name; 1322 $params->group = groups_get_group_name($groupid); 1323 if ($params->group === false) { 1324 // Group doesn't exist, just skip it. 1325 continue; 1326 } 1327 $eventname = get_string('overridegroupeventname', 'quiz', $params); 1328 // Set group override priority. 1329 if ($grouppriorities !== null) { 1330 $openpriorities = $grouppriorities['open']; 1331 if (isset($openpriorities[$timeopen])) { 1332 $event->priority = $openpriorities[$timeopen]; 1333 } 1334 } 1335 } else if ($userid) { 1336 // User override event. 1337 $params = new stdClass(); 1338 $params->quiz = $quiz->name; 1339 $eventname = get_string('overrideusereventname', 'quiz', $params); 1340 // Set user override priority. 1341 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY; 1342 } else { 1343 // The parent event. 1344 $eventname = $quiz->name; 1345 } 1346 1347 if ($addopen or $addclose) { 1348 // Separate start and end events. 1349 $event->timeduration = 0; 1350 if ($timeopen && $addopen) { 1351 if ($oldevent = array_shift($oldevents)) { 1352 $event->id = $oldevent->id; 1353 } else { 1354 unset($event->id); 1355 } 1356 $event->name = get_string('quizeventopens', 'quiz', $eventname); 1357 // The method calendar_event::create will reuse a db record if the id field is set. 1358 calendar_event::create($event, false); 1359 } 1360 if ($timeclose && $addclose) { 1361 if ($oldevent = array_shift($oldevents)) { 1362 $event->id = $oldevent->id; 1363 } else { 1364 unset($event->id); 1365 } 1366 $event->type = CALENDAR_EVENT_TYPE_ACTION; 1367 $event->name = get_string('quizeventcloses', 'quiz', $eventname); 1368 $event->timestart = $timeclose; 1369 $event->timesort = $timeclose; 1370 $event->eventtype = QUIZ_EVENT_TYPE_CLOSE; 1371 if ($groupid && $grouppriorities !== null) { 1372 $closepriorities = $grouppriorities['close']; 1373 if (isset($closepriorities[$timeclose])) { 1374 $event->priority = $closepriorities[$timeclose]; 1375 } 1376 } 1377 calendar_event::create($event, false); 1378 } 1379 } 1380 } 1381 1382 // Delete any leftover events. 1383 foreach ($oldevents as $badevent) { 1384 $badevent = calendar_event::load($badevent); 1385 $badevent->delete(); 1386 } 1387 } 1388 1389 /** 1390 * Calculates the priorities of timeopen and timeclose values for group overrides for a quiz. 1391 * 1392 * @param int $quizid The quiz ID. 1393 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides. 1394 */ 1395 function quiz_get_group_override_priorities($quizid) { 1396 global $DB; 1397 1398 // Fetch group overrides. 1399 $where = 'quiz = :quiz AND groupid IS NOT NULL'; 1400 $params = ['quiz' => $quizid]; 1401 $overrides = $DB->get_records_select('quiz_overrides', $where, $params, '', 'id, timeopen, timeclose'); 1402 if (!$overrides) { 1403 return null; 1404 } 1405 1406 $grouptimeopen = []; 1407 $grouptimeclose = []; 1408 foreach ($overrides as $override) { 1409 if ($override->timeopen !== null && !in_array($override->timeopen, $grouptimeopen)) { 1410 $grouptimeopen[] = $override->timeopen; 1411 } 1412 if ($override->timeclose !== null && !in_array($override->timeclose, $grouptimeclose)) { 1413 $grouptimeclose[] = $override->timeclose; 1414 } 1415 } 1416 1417 // Sort open times in ascending manner. The earlier open time gets higher priority. 1418 sort($grouptimeopen); 1419 // Set priorities. 1420 $opengrouppriorities = []; 1421 $openpriority = 1; 1422 foreach ($grouptimeopen as $timeopen) { 1423 $opengrouppriorities[$timeopen] = $openpriority++; 1424 } 1425 1426 // Sort close times in descending manner. The later close time gets higher priority. 1427 rsort($grouptimeclose); 1428 // Set priorities. 1429 $closegrouppriorities = []; 1430 $closepriority = 1; 1431 foreach ($grouptimeclose as $timeclose) { 1432 $closegrouppriorities[$timeclose] = $closepriority++; 1433 } 1434 1435 return [ 1436 'open' => $opengrouppriorities, 1437 'close' => $closegrouppriorities 1438 ]; 1439 } 1440 1441 /** 1442 * List the actions that correspond to a view of this module. 1443 * This is used by the participation report. 1444 * 1445 * Note: This is not used by new logging system. Event with 1446 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will 1447 * be considered as view action. 1448 * 1449 * @return array 1450 */ 1451 function quiz_get_view_actions() { 1452 return ['view', 'view all', 'report', 'review']; 1453 } 1454 1455 /** 1456 * List the actions that correspond to a post of this module. 1457 * This is used by the participation report. 1458 * 1459 * Note: This is not used by new logging system. Event with 1460 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING 1461 * will be considered as post action. 1462 * 1463 * @return array 1464 */ 1465 function quiz_get_post_actions() { 1466 return ['attempt', 'close attempt', 'preview', 'editquestions', 1467 'delete attempt', 'manualgrade']; 1468 } 1469 1470 /** 1471 * Standard callback used by questions_in_use. 1472 * 1473 * @param array $questionids of question ids. 1474 * @return bool whether any of these questions are used by any instance of this module. 1475 */ 1476 function quiz_questions_in_use($questionids) { 1477 return question_engine::questions_in_use($questionids, 1478 new qubaid_join('{quiz_attempts} quiza', 'quiza.uniqueid', 1479 'quiza.preview = 0')); 1480 } 1481 1482 /** 1483 * Implementation of the function for printing the form elements that control 1484 * whether the course reset functionality affects the quiz. 1485 * 1486 * @param MoodleQuickForm $mform the course reset form that is being built. 1487 */ 1488 function quiz_reset_course_form_definition($mform) { 1489 $mform->addElement('header', 'quizheader', get_string('modulenameplural', 'quiz')); 1490 $mform->addElement('advcheckbox', 'reset_quiz_attempts', 1491 get_string('removeallquizattempts', 'quiz')); 1492 $mform->addElement('advcheckbox', 'reset_quiz_user_overrides', 1493 get_string('removealluseroverrides', 'quiz')); 1494 $mform->addElement('advcheckbox', 'reset_quiz_group_overrides', 1495 get_string('removeallgroupoverrides', 'quiz')); 1496 } 1497 1498 /** 1499 * Course reset form defaults. 1500 * @return array the defaults. 1501 */ 1502 function quiz_reset_course_form_defaults($course) { 1503 return ['reset_quiz_attempts' => 1, 1504 'reset_quiz_group_overrides' => 1, 1505 'reset_quiz_user_overrides' => 1]; 1506 } 1507 1508 /** 1509 * Removes all grades from gradebook 1510 * 1511 * @param int $courseid 1512 * @param string optional type 1513 */ 1514 function quiz_reset_gradebook($courseid, $type='') { 1515 global $CFG, $DB; 1516 1517 $quizzes = $DB->get_records_sql(" 1518 SELECT q.*, cm.idnumber as cmidnumber, q.course as courseid 1519 FROM {modules} m 1520 JOIN {course_modules} cm ON m.id = cm.module 1521 JOIN {quiz} q ON cm.instance = q.id 1522 WHERE m.name = 'quiz' AND cm.course = ?", [$courseid]); 1523 1524 foreach ($quizzes as $quiz) { 1525 quiz_grade_item_update($quiz, 'reset'); 1526 } 1527 } 1528 1529 /** 1530 * Actual implementation of the reset course functionality, delete all the 1531 * quiz attempts for course $data->courseid, if $data->reset_quiz_attempts is 1532 * set and true. 1533 * 1534 * Also, move the quiz open and close dates, if the course start date is changing. 1535 * 1536 * @param stdClass $data the data submitted from the reset course. 1537 * @return array status array 1538 */ 1539 function quiz_reset_userdata($data) { 1540 global $CFG, $DB; 1541 require_once($CFG->libdir . '/questionlib.php'); 1542 1543 $componentstr = get_string('modulenameplural', 'quiz'); 1544 $status = []; 1545 1546 // Delete attempts. 1547 if (!empty($data->reset_quiz_attempts)) { 1548 question_engine::delete_questions_usage_by_activities(new qubaid_join( 1549 '{quiz_attempts} quiza JOIN {quiz} quiz ON quiza.quiz = quiz.id', 1550 'quiza.uniqueid', 'quiz.course = :quizcourseid', 1551 ['quizcourseid' => $data->courseid])); 1552 1553 $DB->delete_records_select('quiz_attempts', 1554 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]); 1555 $status[] = [ 1556 'component' => $componentstr, 1557 'item' => get_string('attemptsdeleted', 'quiz'), 1558 'error' => false]; 1559 1560 // Remove all grades from gradebook. 1561 $DB->delete_records_select('quiz_grades', 1562 'quiz IN (SELECT id FROM {quiz} WHERE course = ?)', [$data->courseid]); 1563 if (empty($data->reset_gradebook_grades)) { 1564 quiz_reset_gradebook($data->courseid); 1565 } 1566 $status[] = [ 1567 'component' => $componentstr, 1568 'item' => get_string('gradesdeleted', 'quiz'), 1569 'error' => false]; 1570 } 1571 1572 $purgeoverrides = false; 1573 1574 // Remove user overrides. 1575 if (!empty($data->reset_quiz_user_overrides)) { 1576 $DB->delete_records_select('quiz_overrides', 1577 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid]); 1578 $status[] = [ 1579 'component' => $componentstr, 1580 'item' => get_string('useroverridesdeleted', 'quiz'), 1581 'error' => false]; 1582 $purgeoverrides = true; 1583 } 1584 // Remove group overrides. 1585 if (!empty($data->reset_quiz_group_overrides)) { 1586 $DB->delete_records_select('quiz_overrides', 1587 'quiz IN (SELECT id FROM {quiz} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid]); 1588 $status[] = [ 1589 'component' => $componentstr, 1590 'item' => get_string('groupoverridesdeleted', 'quiz'), 1591 'error' => false]; 1592 $purgeoverrides = true; 1593 } 1594 1595 // Updating dates - shift may be negative too. 1596 if ($data->timeshift) { 1597 $DB->execute("UPDATE {quiz_overrides} 1598 SET timeopen = timeopen + ? 1599 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?) 1600 AND timeopen <> 0", [$data->timeshift, $data->courseid]); 1601 $DB->execute("UPDATE {quiz_overrides} 1602 SET timeclose = timeclose + ? 1603 WHERE quiz IN (SELECT id FROM {quiz} WHERE course = ?) 1604 AND timeclose <> 0", [$data->timeshift, $data->courseid]); 1605 1606 $purgeoverrides = true; 1607 1608 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset. 1609 // See MDL-9367. 1610 shift_course_mod_dates('quiz', ['timeopen', 'timeclose'], 1611 $data->timeshift, $data->courseid); 1612 1613 $status[] = [ 1614 'component' => $componentstr, 1615 'item' => get_string('openclosedatesupdated', 'quiz'), 1616 'error' => false]; 1617 } 1618 1619 if ($purgeoverrides) { 1620 cache::make('mod_quiz', 'overrides')->purge(); 1621 } 1622 1623 return $status; 1624 } 1625 1626 /** 1627 * Return a textual summary of the number of attempts that have been made at a particular quiz, 1628 * returns '' if no attempts have been made yet, unless $returnzero is passed as true. 1629 * 1630 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment. 1631 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and 1632 * $cm->groupingid fields are used at the moment. 1633 * @param bool $returnzero if false (default), when no attempts have been 1634 * made '' is returned instead of 'Attempts: 0'. 1635 * @param int $currentgroup if there is a concept of current group where this method is being called 1636 * (e.g. a report) pass it in here. Default 0 which means no current group. 1637 * @return string a string like "Attempts: 123", "Attemtps 123 (45 from your groups)" or 1638 * "Attemtps 123 (45 from this group)". 1639 */ 1640 function quiz_num_attempt_summary($quiz, $cm, $returnzero = false, $currentgroup = 0) { 1641 global $DB, $USER; 1642 $numattempts = $DB->count_records('quiz_attempts', ['quiz' => $quiz->id, 'preview' => 0]); 1643 if ($numattempts || $returnzero) { 1644 if (groups_get_activity_groupmode($cm)) { 1645 $a = new stdClass(); 1646 $a->total = $numattempts; 1647 if ($currentgroup) { 1648 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' . 1649 '{quiz_attempts} qa JOIN ' . 1650 '{groups_members} gm ON qa.userid = gm.userid ' . 1651 'WHERE quiz = ? AND preview = 0 AND groupid = ?', 1652 [$quiz->id, $currentgroup]); 1653 return get_string('attemptsnumthisgroup', 'quiz', $a); 1654 } else if ($groups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid)) { 1655 list($usql, $params) = $DB->get_in_or_equal(array_keys($groups)); 1656 $a->group = $DB->count_records_sql('SELECT COUNT(DISTINCT qa.id) FROM ' . 1657 '{quiz_attempts} qa JOIN ' . 1658 '{groups_members} gm ON qa.userid = gm.userid ' . 1659 'WHERE quiz = ? AND preview = 0 AND ' . 1660 "groupid $usql", array_merge([$quiz->id], $params)); 1661 return get_string('attemptsnumyourgroups', 'quiz', $a); 1662 } 1663 } 1664 return get_string('attemptsnum', 'quiz', $numattempts); 1665 } 1666 return ''; 1667 } 1668 1669 /** 1670 * Returns the same as {@link quiz_num_attempt_summary()} but wrapped in a link 1671 * to the quiz reports. 1672 * 1673 * @param stdClass $quiz the quiz object. Only $quiz->id is used at the moment. 1674 * @param stdClass $cm the cm object. Only $cm->course, $cm->groupmode and 1675 * $cm->groupingid fields are used at the moment. 1676 * @param stdClass $context the quiz context. 1677 * @param bool $returnzero if false (default), when no attempts have been made 1678 * '' is returned instead of 'Attempts: 0'. 1679 * @param int $currentgroup if there is a concept of current group where this method is being called 1680 * (e.g. a report) pass it in here. Default 0 which means no current group. 1681 * @return string HTML fragment for the link. 1682 */ 1683 function quiz_attempt_summary_link_to_reports($quiz, $cm, $context, $returnzero = false, 1684 $currentgroup = 0) { 1685 global $PAGE; 1686 1687 return $PAGE->get_renderer('mod_quiz')->quiz_attempt_summary_link_to_reports( 1688 $quiz, $cm, $context, $returnzero, $currentgroup); 1689 } 1690 1691 /** 1692 * @param string $feature FEATURE_xx constant for requested feature 1693 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose. 1694 */ 1695 function quiz_supports($feature) { 1696 switch($feature) { 1697 case FEATURE_GROUPS: return true; 1698 case FEATURE_GROUPINGS: return true; 1699 case FEATURE_MOD_INTRO: return true; 1700 case FEATURE_COMPLETION_TRACKS_VIEWS: return true; 1701 case FEATURE_COMPLETION_HAS_RULES: return true; 1702 case FEATURE_GRADE_HAS_GRADE: return true; 1703 case FEATURE_GRADE_OUTCOMES: return true; 1704 case FEATURE_BACKUP_MOODLE2: return true; 1705 case FEATURE_SHOW_DESCRIPTION: return true; 1706 case FEATURE_CONTROLS_GRADE_VISIBILITY: return true; 1707 case FEATURE_USES_QUESTIONS: return true; 1708 case FEATURE_PLAGIARISM: return true; 1709 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_ASSESSMENT; 1710 1711 default: return null; 1712 } 1713 } 1714 1715 /** 1716 * @return array all other caps used in module 1717 */ 1718 function quiz_get_extra_capabilities() { 1719 global $CFG; 1720 require_once($CFG->libdir . '/questionlib.php'); 1721 return question_get_all_capabilities(); 1722 } 1723 1724 /** 1725 * This function extends the settings navigation block for the site. 1726 * 1727 * It is safe to rely on PAGE here as we will only ever be within the module 1728 * context when this is called 1729 * 1730 * @param settings_navigation $settings 1731 * @param navigation_node $quiznode 1732 * @return void 1733 */ 1734 function quiz_extend_settings_navigation(settings_navigation $settings, navigation_node $quiznode) { 1735 global $CFG; 1736 1737 // Require {@link questionlib.php} 1738 // Included here as we only ever want to include this file if we really need to. 1739 require_once($CFG->libdir . '/questionlib.php'); 1740 1741 // We want to add these new nodes after the Edit settings node, and before the 1742 // Locally assigned roles node. Of course, both of those are controlled by capabilities. 1743 $keys = $quiznode->get_children_key_list(); 1744 $beforekey = null; 1745 $i = array_search('modedit', $keys); 1746 if ($i === false and array_key_exists(0, $keys)) { 1747 $beforekey = $keys[0]; 1748 } else if (array_key_exists($i + 1, $keys)) { 1749 $beforekey = $keys[$i + 1]; 1750 } 1751 1752 if (has_any_capability(['mod/quiz:manageoverrides', 'mod/quiz:viewoverrides'], $settings->get_page()->cm->context)) { 1753 $url = new moodle_url('/mod/quiz/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']); 1754 $node = navigation_node::create(get_string('overrides', 'quiz'), 1755 $url, navigation_node::TYPE_SETTING, null, 'mod_quiz_useroverrides'); 1756 $settingsoverride = $quiznode->add_node($node, $beforekey); 1757 } 1758 1759 if (has_capability('mod/quiz:manage', $settings->get_page()->cm->context)) { 1760 $node = navigation_node::create(get_string('questions', 'quiz'), 1761 new moodle_url('/mod/quiz/edit.php', ['cmid' => $settings->get_page()->cm->id]), 1762 navigation_node::TYPE_SETTING, null, 'mod_quiz_edit', new pix_icon('t/edit', '')); 1763 $quiznode->add_node($node, $beforekey); 1764 } 1765 1766 if (has_capability('mod/quiz:preview', $settings->get_page()->cm->context)) { 1767 $url = new moodle_url('/mod/quiz/startattempt.php', 1768 ['cmid' => $settings->get_page()->cm->id, 'sesskey' => sesskey()]); 1769 $node = navigation_node::create(get_string('preview', 'quiz'), $url, 1770 navigation_node::TYPE_SETTING, null, 'mod_quiz_preview', 1771 new pix_icon('i/preview', '')); 1772 $previewnode = $quiznode->add_node($node, $beforekey); 1773 $previewnode->set_show_in_secondary_navigation(false); 1774 } 1775 1776 question_extend_settings_navigation($quiznode, $settings->get_page()->cm->context)->trim_if_empty(); 1777 1778 if (has_any_capability(['mod/quiz:viewreports', 'mod/quiz:grade'], $settings->get_page()->cm->context)) { 1779 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php'); 1780 $reportlist = quiz_report_list($settings->get_page()->cm->context); 1781 1782 $url = new moodle_url('/mod/quiz/report.php', 1783 ['id' => $settings->get_page()->cm->id, 'mode' => reset($reportlist)]); 1784 $reportnode = $quiznode->add_node(navigation_node::create(get_string('results', 'quiz'), $url, 1785 navigation_node::TYPE_SETTING, 1786 null, 'quiz_report', new pix_icon('i/report', ''))); 1787 1788 foreach ($reportlist as $report) { 1789 $url = new moodle_url('/mod/quiz/report.php', ['id' => $settings->get_page()->cm->id, 'mode' => $report]); 1790 $reportnode->add_node(navigation_node::create(get_string($report, 'quiz_'.$report), $url, 1791 navigation_node::TYPE_SETTING, 1792 null, 'quiz_report_' . $report, new pix_icon('i/item', ''))); 1793 } 1794 } 1795 } 1796 1797 /** 1798 * Serves the quiz files. 1799 * 1800 * @package mod_quiz 1801 * @category files 1802 * @param stdClass $course course object 1803 * @param stdClass $cm course module object 1804 * @param stdClass $context context object 1805 * @param string $filearea file area 1806 * @param array $args extra arguments 1807 * @param bool $forcedownload whether or not force download 1808 * @param array $options additional options affecting the file serving 1809 * @return bool false if file not found, does not return if found - justsend the file 1810 */ 1811 function quiz_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options= []) { 1812 global $CFG, $DB; 1813 1814 if ($context->contextlevel != CONTEXT_MODULE) { 1815 return false; 1816 } 1817 1818 require_login($course, false, $cm); 1819 1820 if (!$quiz = $DB->get_record('quiz', ['id' => $cm->instance])) { 1821 return false; 1822 } 1823 1824 // The 'intro' area is served by pluginfile.php. 1825 $fileareas = ['feedback']; 1826 if (!in_array($filearea, $fileareas)) { 1827 return false; 1828 } 1829 1830 $feedbackid = (int)array_shift($args); 1831 if (!$feedback = $DB->get_record('quiz_feedback', ['id' => $feedbackid])) { 1832 return false; 1833 } 1834 1835 $fs = get_file_storage(); 1836 $relativepath = implode('/', $args); 1837 $fullpath = "/$context->id/mod_quiz/$filearea/$feedbackid/$relativepath"; 1838 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { 1839 return false; 1840 } 1841 send_stored_file($file, 0, 0, true, $options); 1842 } 1843 1844 /** 1845 * Called via pluginfile.php -> question_pluginfile to serve files belonging to 1846 * a question in a question_attempt when that attempt is a quiz attempt. 1847 * 1848 * @package mod_quiz 1849 * @category files 1850 * @param stdClass $course course settings object 1851 * @param stdClass $context context object 1852 * @param string $component the name of the component we are serving files for. 1853 * @param string $filearea the name of the file area. 1854 * @param int $qubaid the attempt usage id. 1855 * @param int $slot the id of a question in this quiz attempt. 1856 * @param array $args the remaining bits of the file path. 1857 * @param bool $forcedownload whether the user must be forced to download the file. 1858 * @param array $options additional options affecting the file serving 1859 * @return bool false if file not found, does not return if found - justsend the file 1860 */ 1861 function quiz_question_pluginfile($course, $context, $component, 1862 $filearea, $qubaid, $slot, $args, $forcedownload, array $options= []) { 1863 global $CFG; 1864 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 1865 1866 $attemptobj = quiz_attempt::create_from_usage_id($qubaid); 1867 require_login($attemptobj->get_course(), false, $attemptobj->get_cm()); 1868 1869 if ($attemptobj->is_own_attempt() && !$attemptobj->is_finished()) { 1870 // In the middle of an attempt. 1871 if (!$attemptobj->is_preview_user()) { 1872 $attemptobj->require_capability('mod/quiz:attempt'); 1873 } 1874 $isreviewing = false; 1875 1876 } else { 1877 // Reviewing an attempt. 1878 $attemptobj->check_review_capability(); 1879 $isreviewing = true; 1880 } 1881 1882 if (!$attemptobj->check_file_access($slot, $isreviewing, $context->id, 1883 $component, $filearea, $args, $forcedownload)) { 1884 send_file_not_found(); 1885 } 1886 1887 $fs = get_file_storage(); 1888 $relativepath = implode('/', $args); 1889 $fullpath = "/$context->id/$component/$filearea/$relativepath"; 1890 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { 1891 send_file_not_found(); 1892 } 1893 1894 send_stored_file($file, 0, 0, $forcedownload, $options); 1895 } 1896 1897 /** 1898 * Return a list of page types 1899 * @param string $pagetype current page type 1900 * @param stdClass $parentcontext Block's parent context 1901 * @param stdClass $currentcontext Current context of block 1902 */ 1903 function quiz_page_type_list($pagetype, $parentcontext, $currentcontext) { 1904 $modulepagetype = [ 1905 'mod-quiz-*' => get_string('page-mod-quiz-x', 'quiz'), 1906 'mod-quiz-view' => get_string('page-mod-quiz-view', 'quiz'), 1907 'mod-quiz-attempt' => get_string('page-mod-quiz-attempt', 'quiz'), 1908 'mod-quiz-summary' => get_string('page-mod-quiz-summary', 'quiz'), 1909 'mod-quiz-review' => get_string('page-mod-quiz-review', 'quiz'), 1910 'mod-quiz-edit' => get_string('page-mod-quiz-edit', 'quiz'), 1911 'mod-quiz-report' => get_string('page-mod-quiz-report', 'quiz'), 1912 ]; 1913 return $modulepagetype; 1914 } 1915 1916 /** 1917 * @return the options for quiz navigation. 1918 */ 1919 function quiz_get_navigation_options() { 1920 return [ 1921 QUIZ_NAVMETHOD_FREE => get_string('navmethod_free', 'quiz'), 1922 QUIZ_NAVMETHOD_SEQ => get_string('navmethod_seq', 'quiz') 1923 ]; 1924 } 1925 1926 /** 1927 * Check if the module has any update that affects the current user since a given time. 1928 * 1929 * @param cm_info $cm course module data 1930 * @param int $from the time to check updates from 1931 * @param array $filter if we need to check only specific updates 1932 * @return stdClass an object with the different type of areas indicating if they were updated or not 1933 * @since Moodle 3.2 1934 */ 1935 function quiz_check_updates_since(cm_info $cm, $from, $filter = []) { 1936 global $DB, $USER, $CFG; 1937 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 1938 1939 $updates = course_check_module_updates_since($cm, $from, [], $filter); 1940 1941 // Check if questions were updated. 1942 $updates->questions = (object) ['updated' => false]; 1943 $quizobj = quiz_settings::create($cm->instance, $USER->id); 1944 $quizobj->preload_questions(); 1945 $quizobj->load_questions(); 1946 $questionids = array_keys($quizobj->get_questions()); 1947 if (!empty($questionids)) { 1948 list($questionsql, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED); 1949 $select = 'id ' . $questionsql . ' AND (timemodified > :time1 OR timecreated > :time2)'; 1950 $params['time1'] = $from; 1951 $params['time2'] = $from; 1952 $questions = $DB->get_records_select('question', $select, $params, '', 'id'); 1953 if (!empty($questions)) { 1954 $updates->questions->updated = true; 1955 $updates->questions->itemids = array_keys($questions); 1956 } 1957 } 1958 1959 // Check for new attempts or grades. 1960 $updates->attempts = (object) ['updated' => false]; 1961 $updates->grades = (object) ['updated' => false]; 1962 $select = 'quiz = ? AND userid = ? AND timemodified > ?'; 1963 $params = [$cm->instance, $USER->id, $from]; 1964 1965 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id'); 1966 if (!empty($attempts)) { 1967 $updates->attempts->updated = true; 1968 $updates->attempts->itemids = array_keys($attempts); 1969 } 1970 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id'); 1971 if (!empty($grades)) { 1972 $updates->grades->updated = true; 1973 $updates->grades->itemids = array_keys($grades); 1974 } 1975 1976 // Now, teachers should see other students updates. 1977 if (has_capability('mod/quiz:viewreports', $cm->context)) { 1978 $select = 'quiz = ? AND timemodified > ?'; 1979 $params = [$cm->instance, $from]; 1980 1981 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) { 1982 $groupusers = array_keys(groups_get_activity_shared_group_members($cm)); 1983 if (empty($groupusers)) { 1984 return $updates; 1985 } 1986 list($insql, $inparams) = $DB->get_in_or_equal($groupusers); 1987 $select .= ' AND userid ' . $insql; 1988 $params = array_merge($params, $inparams); 1989 } 1990 1991 $updates->userattempts = (object) ['updated' => false]; 1992 $attempts = $DB->get_records_select('quiz_attempts', $select, $params, '', 'id'); 1993 if (!empty($attempts)) { 1994 $updates->userattempts->updated = true; 1995 $updates->userattempts->itemids = array_keys($attempts); 1996 } 1997 1998 $updates->usergrades = (object) ['updated' => false]; 1999 $grades = $DB->get_records_select('quiz_grades', $select, $params, '', 'id'); 2000 if (!empty($grades)) { 2001 $updates->usergrades->updated = true; 2002 $updates->usergrades->itemids = array_keys($grades); 2003 } 2004 } 2005 return $updates; 2006 } 2007 2008 /** 2009 * Get icon mapping for font-awesome. 2010 */ 2011 function mod_quiz_get_fontawesome_icon_map() { 2012 return [ 2013 'mod_quiz:navflagged' => 'fa-flag', 2014 ]; 2015 } 2016 2017 /** 2018 * This function receives a calendar event and returns the action associated with it, or null if there is none. 2019 * 2020 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event 2021 * is not displayed on the block. 2022 * 2023 * @param calendar_event $event 2024 * @param \core_calendar\action_factory $factory 2025 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default). 2026 * @return \core_calendar\local\event\entities\action_interface|null 2027 */ 2028 function mod_quiz_core_calendar_provide_event_action(calendar_event $event, 2029 \core_calendar\action_factory $factory, 2030 int $userid = 0) { 2031 global $CFG, $USER; 2032 2033 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 2034 2035 if (empty($userid)) { 2036 $userid = $USER->id; 2037 } 2038 2039 $cm = get_fast_modinfo($event->courseid, $userid)->instances['quiz'][$event->instance]; 2040 $quizobj = quiz_settings::create($cm->instance, $userid); 2041 $quiz = $quizobj->get_quiz(); 2042 2043 // Check they have capabilities allowing them to view the quiz. 2044 if (!has_any_capability(['mod/quiz:reviewmyattempts', 'mod/quiz:attempt'], $quizobj->get_context(), $userid)) { 2045 return null; 2046 } 2047 2048 $completion = new \completion_info($cm->get_course()); 2049 2050 $completiondata = $completion->get_data($cm, false, $userid); 2051 2052 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) { 2053 return null; 2054 } 2055 2056 quiz_update_effective_access($quiz, $userid); 2057 2058 // Check if quiz is closed, if so don't display it. 2059 if (!empty($quiz->timeclose) && $quiz->timeclose <= time()) { 2060 return null; 2061 } 2062 2063 if (!$quizobj->is_participant($userid)) { 2064 // If the user is not a participant then they have 2065 // no action to take. This will filter out the events for teachers. 2066 return null; 2067 } 2068 2069 $attempts = quiz_get_user_attempts($quizobj->get_quizid(), $userid); 2070 if (!empty($attempts)) { 2071 // The student's last attempt is finished. 2072 return null; 2073 } 2074 2075 $name = get_string('attemptquiznow', 'quiz'); 2076 $url = new \moodle_url('/mod/quiz/view.php', [ 2077 'id' => $cm->id 2078 ]); 2079 $itemcount = 1; 2080 $actionable = true; 2081 2082 // Check if the quiz is not currently actionable. 2083 if (!empty($quiz->timeopen) && $quiz->timeopen > time()) { 2084 $actionable = false; 2085 } 2086 2087 return $factory->create_instance( 2088 $name, 2089 $url, 2090 $itemcount, 2091 $actionable 2092 ); 2093 } 2094 2095 /** 2096 * Add a get_coursemodule_info function in case any quiz type wants to add 'extra' information 2097 * for the course (see resource). 2098 * 2099 * Given a course_module object, this function returns any "extra" information that may be needed 2100 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php. 2101 * 2102 * @param stdClass $coursemodule The coursemodule object (record). 2103 * @return cached_cm_info|false An object on information that the courses 2104 * will know about (most noticeably, an icon). 2105 */ 2106 function quiz_get_coursemodule_info($coursemodule) { 2107 global $DB; 2108 2109 $dbparams = ['id' => $coursemodule->instance]; 2110 $fields = 'id, name, intro, introformat, completionattemptsexhausted, completionminattempts, 2111 timeopen, timeclose'; 2112 if (!$quiz = $DB->get_record('quiz', $dbparams, $fields)) { 2113 return false; 2114 } 2115 2116 $result = new cached_cm_info(); 2117 $result->name = $quiz->name; 2118 2119 if ($coursemodule->showdescription) { 2120 // Convert intro to html. Do not filter cached version, filters run at display time. 2121 $result->content = format_module_intro('quiz', $quiz, $coursemodule->id, false); 2122 } 2123 2124 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'. 2125 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) { 2126 if ($quiz->completionattemptsexhausted) { 2127 $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = [ 2128 'completionpassgrade' => $coursemodule->completionpassgrade, 2129 'completionattemptsexhausted' => $quiz->completionattemptsexhausted, 2130 ]; 2131 } else { 2132 $result->customdata['customcompletionrules']['completionpassorattemptsexhausted'] = []; 2133 } 2134 2135 $result->customdata['customcompletionrules']['completionminattempts'] = $quiz->completionminattempts; 2136 } 2137 2138 // Populate some other values that can be used in calendar or on dashboard. 2139 if ($quiz->timeopen) { 2140 $result->customdata['timeopen'] = $quiz->timeopen; 2141 } 2142 if ($quiz->timeclose) { 2143 $result->customdata['timeclose'] = $quiz->timeclose; 2144 } 2145 2146 return $result; 2147 } 2148 2149 /** 2150 * Sets dynamic information about a course module 2151 * 2152 * This function is called from cm_info when displaying the module 2153 * 2154 * @param cm_info $cm 2155 */ 2156 function mod_quiz_cm_info_dynamic(cm_info $cm) { 2157 global $USER; 2158 2159 $cache = cache::make('mod_quiz', 'overrides'); 2160 $override = $cache->get("{$cm->instance}_u_{$USER->id}"); 2161 2162 if (!$override) { 2163 $override = (object) [ 2164 'timeopen' => null, 2165 'timeclose' => null, 2166 ]; 2167 } 2168 2169 // No need to look for group overrides if there are user overrides for both timeopen and timeclose. 2170 if (is_null($override->timeopen) || is_null($override->timeclose)) { 2171 $opens = []; 2172 $closes = []; 2173 $groupings = groups_get_user_groups($cm->course, $USER->id); 2174 foreach ($groupings[0] as $groupid) { 2175 $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}"); 2176 if (isset($groupoverride->timeopen)) { 2177 $opens[] = $groupoverride->timeopen; 2178 } 2179 if (isset($groupoverride->timeclose)) { 2180 $closes[] = $groupoverride->timeclose; 2181 } 2182 } 2183 // If there is a user override for a setting, ignore the group override. 2184 if (is_null($override->timeopen) && count($opens)) { 2185 $override->timeopen = min($opens); 2186 } 2187 if (is_null($override->timeclose) && count($closes)) { 2188 if (in_array(0, $closes)) { 2189 $override->timeclose = 0; 2190 } else { 2191 $override->timeclose = max($closes); 2192 } 2193 } 2194 } 2195 2196 // Populate some other values that can be used in calendar or on dashboard. 2197 if (!is_null($override->timeopen)) { 2198 $cm->override_customdata('timeopen', $override->timeopen); 2199 } 2200 if (!is_null($override->timeclose)) { 2201 $cm->override_customdata('timeclose', $override->timeclose); 2202 } 2203 } 2204 2205 /** 2206 * Callback which returns human-readable strings describing the active completion custom rules for the module instance. 2207 * 2208 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules'] 2209 * @return array $descriptions the array of descriptions for the custom rules. 2210 */ 2211 function mod_quiz_get_completion_active_rule_descriptions($cm) { 2212 // Values will be present in cm_info, and we assume these are up to date. 2213 if (empty($cm->customdata['customcompletionrules']) 2214 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) { 2215 return []; 2216 } 2217 2218 $descriptions = []; 2219 $rules = $cm->customdata['customcompletionrules']; 2220 2221 if (!empty($rules['completionpassorattemptsexhausted'])) { 2222 if (!empty($rules['completionpassorattemptsexhausted']['completionattemptsexhausted'])) { 2223 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz'); 2224 } 2225 } else { 2226 // Fallback. 2227 if (!empty($rules['completionattemptsexhausted'])) { 2228 $descriptions[] = get_string('completionpassorattemptsexhausteddesc', 'quiz'); 2229 } 2230 } 2231 2232 if (!empty($rules['completionminattempts'])) { 2233 $descriptions[] = get_string('completionminattemptsdesc', 'quiz', $rules['completionminattempts']); 2234 } 2235 2236 return $descriptions; 2237 } 2238 2239 /** 2240 * Returns the min and max values for the timestart property of a quiz 2241 * activity event. 2242 * 2243 * The min and max values will be the timeopen and timeclose properties 2244 * of the quiz, respectively, if they are set. 2245 * 2246 * If either value isn't set then null will be returned instead to 2247 * indicate that there is no cutoff for that value. 2248 * 2249 * If the vent has no valid timestart range then [false, false] will 2250 * be returned. This is the case for overriden events. 2251 * 2252 * A minimum and maximum cutoff return value will look like: 2253 * [ 2254 * [1505704373, 'The date must be after this date'], 2255 * [1506741172, 'The date must be before this date'] 2256 * ] 2257 * 2258 * @throws \moodle_exception 2259 * @param \calendar_event $event The calendar event to get the time range for 2260 * @param stdClass $quiz The module instance to get the range from 2261 * @return array 2262 */ 2263 function mod_quiz_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $quiz) { 2264 global $CFG, $DB; 2265 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 2266 2267 // Overrides do not have a valid timestart range. 2268 if (quiz_is_overriden_calendar_event($event)) { 2269 return [false, false]; 2270 } 2271 2272 $mindate = null; 2273 $maxdate = null; 2274 2275 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) { 2276 if (!empty($quiz->timeclose)) { 2277 $maxdate = [ 2278 $quiz->timeclose, 2279 get_string('openafterclose', 'quiz') 2280 ]; 2281 } 2282 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) { 2283 if (!empty($quiz->timeopen)) { 2284 $mindate = [ 2285 $quiz->timeopen, 2286 get_string('closebeforeopen', 'quiz') 2287 ]; 2288 } 2289 } 2290 2291 return [$mindate, $maxdate]; 2292 } 2293 2294 /** 2295 * This function will update the quiz module according to the 2296 * event that has been modified. 2297 * 2298 * It will set the timeopen or timeclose value of the quiz instance 2299 * according to the type of event provided. 2300 * 2301 * @throws \moodle_exception 2302 * @param \calendar_event $event A quiz activity calendar event 2303 * @param \stdClass $quiz A quiz activity instance 2304 */ 2305 function mod_quiz_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $quiz) { 2306 global $CFG, $DB; 2307 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 2308 2309 if (!in_array($event->eventtype, [QUIZ_EVENT_TYPE_OPEN, QUIZ_EVENT_TYPE_CLOSE])) { 2310 // This isn't an event that we care about so we can ignore it. 2311 return; 2312 } 2313 2314 $courseid = $event->courseid; 2315 $modulename = $event->modulename; 2316 $instanceid = $event->instance; 2317 $modified = false; 2318 $closedatechanged = false; 2319 2320 // Something weird going on. The event is for a different module so 2321 // we should ignore it. 2322 if ($modulename != 'quiz') { 2323 return; 2324 } 2325 2326 if ($quiz->id != $instanceid) { 2327 // The provided quiz instance doesn't match the event so 2328 // there is nothing to do here. 2329 return; 2330 } 2331 2332 // We don't update the activity if it's an override event that has 2333 // been modified. 2334 if (quiz_is_overriden_calendar_event($event)) { 2335 return; 2336 } 2337 2338 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid]; 2339 $context = context_module::instance($coursemodule->id); 2340 2341 // The user does not have the capability to modify this activity. 2342 if (!has_capability('moodle/course:manageactivities', $context)) { 2343 return; 2344 } 2345 2346 if ($event->eventtype == QUIZ_EVENT_TYPE_OPEN) { 2347 // If the event is for the quiz activity opening then we should 2348 // set the start time of the quiz activity to be the new start 2349 // time of the event. 2350 if ($quiz->timeopen != $event->timestart) { 2351 $quiz->timeopen = $event->timestart; 2352 $modified = true; 2353 } 2354 } else if ($event->eventtype == QUIZ_EVENT_TYPE_CLOSE) { 2355 // If the event is for the quiz activity closing then we should 2356 // set the end time of the quiz activity to be the new start 2357 // time of the event. 2358 if ($quiz->timeclose != $event->timestart) { 2359 $quiz->timeclose = $event->timestart; 2360 $modified = true; 2361 $closedatechanged = true; 2362 } 2363 } 2364 2365 if ($modified) { 2366 $quiz->timemodified = time(); 2367 $DB->update_record('quiz', $quiz); 2368 2369 if ($closedatechanged) { 2370 quiz_update_open_attempts(['quizid' => $quiz->id]); 2371 } 2372 2373 // Delete any previous preview attempts. 2374 quiz_delete_previews($quiz); 2375 quiz_update_events($quiz); 2376 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context); 2377 $event->trigger(); 2378 } 2379 } 2380 2381 /** 2382 * Generates the question bank in a fragment output. This allows 2383 * the question bank to be displayed in a modal. 2384 * 2385 * The only expected argument provided in the $args array is 2386 * 'querystring'. The value should be the list of parameters 2387 * URL encoded and used to build the question bank page. 2388 * 2389 * The individual list of parameters expected can be found in 2390 * question_build_edit_resources. 2391 * 2392 * @param array $args The fragment arguments. 2393 * @return string The rendered mform fragment. 2394 */ 2395 function mod_quiz_output_fragment_quiz_question_bank($args) { 2396 global $CFG, $DB, $PAGE; 2397 require_once($CFG->dirroot . '/mod/quiz/locallib.php'); 2398 require_once($CFG->dirroot . '/question/editlib.php'); 2399 2400 $querystring = preg_replace('/^\?/', '', $args['querystring']); 2401 $params = []; 2402 parse_str($querystring, $params); 2403 2404 // Build the required resources. The $params are all cleaned as 2405 // part of this process. 2406 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) = 2407 question_build_edit_resources('editq', '/mod/quiz/edit.php', $params, custom_view::DEFAULT_PAGE_SIZE); 2408 2409 // Get the course object and related bits. 2410 $course = get_course($quiz->course); 2411 require_capability('mod/quiz:manage', $contexts->lowest()); 2412 2413 // Create quiz question bank view. 2414 $questionbank = new custom_view($contexts, $thispageurl, $course, $cm, $quiz); 2415 $questionbank->set_quiz_has_attempts(quiz_has_attempts($quiz->id)); 2416 2417 // Output. 2418 $renderer = $PAGE->get_renderer('mod_quiz', 'edit'); 2419 return $renderer->question_bank_contents($questionbank, $pagevars); 2420 } 2421 2422 /** 2423 * Generates the add random question in a fragment output. This allows the 2424 * form to be rendered in javascript, for example inside a modal. 2425 * 2426 * The required arguments as keys in the $args array are: 2427 * cat {string} The category and category context ids comma separated. 2428 * addonpage {int} The page id to add this question to. 2429 * returnurl {string} URL to return to after form submission. 2430 * cmid {int} The course module id the questions are being added to. 2431 * 2432 * @param array $args The fragment arguments. 2433 * @return string The rendered mform fragment. 2434 */ 2435 function mod_quiz_output_fragment_add_random_question_form($args) { 2436 global $CFG; 2437 2438 $contexts = new \core_question\local\bank\question_edit_contexts($args['context']); 2439 $formoptions = [ 2440 'contexts' => $contexts, 2441 'cat' => $args['cat'] 2442 ]; 2443 $formdata = [ 2444 'category' => $args['cat'], 2445 'addonpage' => $args['addonpage'], 2446 'returnurl' => $args['returnurl'], 2447 'cmid' => $args['cmid'] 2448 ]; 2449 2450 $form = new add_random_form( 2451 new \moodle_url('/mod/quiz/addrandom.php'), 2452 $formoptions, 2453 'post', 2454 '', 2455 null, 2456 true, 2457 $formdata 2458 ); 2459 $form->set_data($formdata); 2460 2461 return $form->render(); 2462 } 2463 2464 /** 2465 * Callback to fetch the activity event type lang string. 2466 * 2467 * @param string $eventtype The event type. 2468 * @return lang_string The event type lang string. 2469 */ 2470 function mod_quiz_core_calendar_get_event_action_string(string $eventtype): string { 2471 $modulename = get_string('modulename', 'quiz'); 2472 2473 switch ($eventtype) { 2474 case QUIZ_EVENT_TYPE_OPEN: 2475 $identifier = 'quizeventopens'; 2476 break; 2477 case QUIZ_EVENT_TYPE_CLOSE: 2478 $identifier = 'quizeventcloses'; 2479 break; 2480 default: 2481 return get_string('requiresaction', 'calendar', $modulename); 2482 } 2483 2484 return get_string($identifier, 'quiz', $modulename); 2485 } 2486 2487 /** 2488 * Delete question reference data. 2489 * 2490 * @param int $quizid The id of quiz. 2491 */ 2492 function quiz_delete_references($quizid): void { 2493 global $DB; 2494 $slots = $DB->get_records('quiz_slots', ['quizid' => $quizid]); 2495 foreach ($slots as $slot) { 2496 $params = [ 2497 'itemid' => $slot->id, 2498 'component' => 'mod_quiz', 2499 'questionarea' => 'slot' 2500 ]; 2501 // Delete any set references. 2502 $DB->delete_records('question_set_references', $params); 2503 // Delete any references. 2504 $DB->delete_records('question_references', $params); 2505 } 2506 } 2507 2508 /** 2509 * Implement the calculate_question_stats callback. 2510 * 2511 * This enables quiz statistics to be shown in statistics columns in the database. 2512 * 2513 * @param context $context return the statistics related to this context (which will be a quiz context). 2514 * @return all_calculated_for_qubaid_condition|null The statistics for this quiz, if available, else null. 2515 */ 2516 function mod_quiz_calculate_question_stats(context $context): ?all_calculated_for_qubaid_condition { 2517 global $CFG; 2518 require_once($CFG->dirroot . '/mod/quiz/report/statistics/report.php'); 2519 $cm = get_coursemodule_from_id('quiz', $context->instanceid); 2520 $report = new quiz_statistics_report(); 2521 return $report->calculate_questions_stats_for_question_bank($cm->instance, false, false); 2522 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body