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