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