.
/**
* Library of functions for the quiz module.
*
* This contains functions that are called also from outside the quiz module
* Functions that are only called by the quiz module itself are in {@link locallib.php}
*
* @package mod_quiz
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/eventslib.php');
require_once($CFG->dirroot . '/calendar/lib.php');
/**#@+
* Option controlling what options are offered on the quiz settings form.
*/
define('QUIZ_MAX_ATTEMPT_OPTION', 10);
define('QUIZ_MAX_QPP_OPTION', 50);
define('QUIZ_MAX_DECIMAL_OPTION', 5);
define('QUIZ_MAX_Q_DECIMAL_OPTION', 7);
/**#@-*/
/**#@+
* Options determining how the grades from individual attempts are combined to give
* the overall grade for a user
*/
define('QUIZ_GRADEHIGHEST', '1');
define('QUIZ_GRADEAVERAGE', '2');
define('QUIZ_ATTEMPTFIRST', '3');
define('QUIZ_ATTEMPTLAST', '4');
/**#@-*/
/**
* @var int If start and end date for the quiz are more than this many seconds apart
* they will be represented by two separate events in the calendar
*/
define('QUIZ_MAX_EVENT_LENGTH', 5*24*60*60); // 5 days.
/**#@+
* Options for navigation method within quizzes.
*/
define('QUIZ_NAVMETHOD_FREE', 'free');
define('QUIZ_NAVMETHOD_SEQ', 'sequential');
/**#@-*/
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will create a new instance and return the id number
* of the new instance.
*
* @param object $quiz the data that came from the form.
* @return mixed the id of the new instance on success,
* false or a string error message on failure.
*/
function quiz_add_instance($quiz) {
global $DB;
$cmid = $quiz->coursemodule;
// Process the options from the form.
$quiz->created = time();
$result = quiz_process_options($quiz);
if ($result && is_string($result)) {
return $result;
}
// Try to store it in the database.
$quiz->id = $DB->insert_record('quiz', $quiz);
// Create the first section for this quiz.
$DB->insert_record('quiz_sections', array('quizid' => $quiz->id,
'firstslot' => 1, 'heading' => '', 'shufflequestions' => 0));
// Do the processing required after an add or an update.
quiz_after_add_or_update($quiz);
return $quiz->id;
}
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @param object $quiz the data that came from the form.
* @return mixed true on success, false or a string error message on failure.
*/
function quiz_update_instance($quiz, $mform) {
global $CFG, $DB;
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
// Process the options from the form.
$result = quiz_process_options($quiz);
if ($result && is_string($result)) {
return $result;
}
// Get the current value, so we can see what changed.
$oldquiz = $DB->get_record('quiz', array('id' => $quiz->instance));
// We need two values from the existing DB record that are not in the form,
// in some of the function calls below.
$quiz->sumgrades = $oldquiz->sumgrades;
$quiz->grade = $oldquiz->grade;
// Update the database.
$quiz->id = $quiz->instance;
$DB->update_record('quiz', $quiz);
// Do the processing required after an add or an update.
quiz_after_add_or_update($quiz);
if ($oldquiz->grademethod != $quiz->grademethod) {
quiz_update_all_final_grades($quiz);
quiz_update_grades($quiz);
}
$quizdateschanged = $oldquiz->timelimit != $quiz->timelimit
|| $oldquiz->timeclose != $quiz->timeclose
|| $oldquiz->graceperiod != $quiz->graceperiod;
if ($quizdateschanged) {
quiz_update_open_attempts(array('quizid' => $quiz->id));
}
// Delete any previous preview attempts.
quiz_delete_previews($quiz);
// Repaginate, if asked to.
if (!empty($quiz->repaginatenow)) {
quiz_repaginate_questions($quiz->id, $quiz->questionsperpage);
}
return true;
}
/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @param int $id the id of the quiz to delete.
* @return bool success or failure.
*/
function quiz_delete_instance($id) {
global $DB;
$quiz = $DB->get_record('quiz', array('id' => $id), '*', MUST_EXIST);
quiz_delete_all_attempts($quiz);
quiz_delete_all_overrides($quiz);
// Look for random questions that may no longer be used when this quiz is gone.
$sql = "SELECT q.id
FROM {quiz_slots} slot
JOIN {question} q ON q.id = slot.questionid
WHERE slot.quizid = ? AND q.qtype = ?";
$questionids = $DB->get_fieldset_sql($sql, array($quiz->id, 'random'));
// We need to do this before we try and delete randoms, otherwise they would still be 'in use'.
$DB->delete_records('quiz_slots', array('quizid' => $quiz->id));
$DB->delete_records('quiz_sections', array('quizid' => $quiz->id));
foreach ($questionids as $questionid) {
question_delete_question($questionid);
}
$DB->delete_records('quiz_feedback', array('quizid' => $quiz->id));
quiz_access_manager::delete_settings($quiz);
$events = $DB->get_records('event', array('modulename' => 'quiz', 'instance' => $quiz->id));
foreach ($events as $event) {
$event = calendar_event::load($event);
$event->delete();
}
quiz_grade_item_delete($quiz);
$DB->delete_records('quiz', array('id' => $quiz->id));
return true;
}
/**
* Deletes a quiz override from the database and clears any corresponding calendar events
*
* @param object $quiz The quiz object.
* @param int $overrideid The id of the override being deleted
* @return bool true on success
*/
function quiz_delete_override($quiz, $overrideid) {
global $DB;
if (!isset($quiz->cmid)) {
$cm = get_coursemodule_from_instance('quiz', $quiz->id, $quiz->course);
$quiz->cmid = $cm->id;
}
$override = $DB->get_record('quiz_overrides', array('id' => $overrideid), '*', MUST_EXIST);
// Delete the events.
$events = $DB->get_records('event', array('modulename' => 'quiz',
'instance' => $quiz->id, 'groupid' => (int)$override->groupid,
'userid' => (int)$override->userid));
foreach ($events as $event) {
$eventold = calendar_event::load($event);
$eventold->delete();
}
$DB->delete_records('quiz_overrides', array('id' => $overrideid));
// Set the common parameters for one of the events we will be triggering.
$params = array(
'objectid' => $override->id,
'context' => context_module::instance($quiz->cmid),
'other' => array(
'quizid' => $override->quiz
)
);
// Determine which override deleted event to fire.
if (!empty($override->userid)) {
$params['relateduserid'] = $override->userid;
$event = \mod_quiz\event\user_override_deleted::create($params);
} else {
$params['other']['groupid'] = $override->groupid;
$event = \mod_quiz\event\group_override_deleted::create($params);
}
// Trigger the override deleted event.
$event->add_record_snapshot('quiz_overrides', $override);
$event->trigger();
return true;
}
/**
* Deletes all quiz overrides from the database and clears any corresponding calendar events
*
* @param object $quiz The quiz object.
*/
function quiz_delete_all_overrides($quiz) {
global $DB;
$overrides = $DB->get_records('quiz_overrides', array('quiz' => $quiz->id), 'id');
foreach ($overrides as $override) {
quiz_delete_override($quiz, $override->id);
}
}
/**
* Updates a quiz object with override information for a user.
*
* Algorithm: For each quiz setting, if there is a matching user-specific override,
* then use that otherwise, if there are group-specific overrides, return the most
* lenient combination of them. If neither applies, leave the quiz setting unchanged.
*
* Special case: if there is more than one password that applies to the user, then
* quiz->extrapasswords will contain an array of strings giving the remaining
* passwords.
*
* @param object $quiz The quiz object.
* @param int $userid The userid.
* @return object $quiz The updated quiz object.
*/
function quiz_update_effective_access($quiz, $userid) {
global $DB;
// Check for user override.
$override = $DB->get_record('quiz_overrides', array('quiz' => $quiz->id, 'userid' => $userid));
if (!$override) {
$override = new stdClass();
$override->timeopen = null;
$override->timeclose = null;
$override->timelimit = null;
$override->attempts = null;
$override->password = null;
}
// Check for group overrides.
$groupings = groups_get_user_groups($quiz->course, $userid);
if (!empty($groupings[0])) {
// Select all overrides that apply to the User's groups.
list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
$sql = "SELECT * FROM {quiz_overrides}
WHERE groupid $extra AND quiz = ?";
$params[] = $quiz->id;
$records = $DB->get_records_sql($sql, $params);
// Combine the overrides.
$opens = array();
$closes = array();
$limits = array();
$attempts = array();
$passwords = array();
foreach ($records as $gpoverride) {
if (isset($gpoverride->timeopen)) {
$opens[] = $gpoverride->timeopen;
}
if (isset($gpoverride->timeclose)) {
$closes[] = $gpoverride->timeclose;
}
if (isset($gpoverride->timelimit)) {
$limits[] = $gpoverride->timelimit;
}
if (isset($gpoverride->attempts)) {
$attempts[] = $gpoverride->attempts;
}
if (isset($gpoverride->password)) {
$passwords[] = $gpoverride->password;
}
}
// If there is a user override for a setting, ignore the group override.
if (is_null($override->timeopen) && count($opens)) {
$override->timeopen = min($opens);
}
if (is_null($override->timeclose) && count($closes)) {
if (in_array(0, $closes)) {
$override->timeclose = 0;
} else {
$override->timeclose = max($closes);
}
}
if (is_null($override->timelimit) && count($limits)) {
if (in_array(0, $limits)) {
$override->timelimit = 0;
} else {
$override->timelimit = max($limits);
}
}
if (is_null($override->attempts) && count($attempts)) {
if (in_array(0, $attempts)) {
$override->attempts = 0;
} else {
$override->attempts = max($attempts);
}
}
if (is_null($override->password) && count($passwords)) {
$override->password = array_shift($passwords);
if (count($passwords)) {
$override->extrapasswords = $passwords;
}
}
}
// Merge with quiz defaults.
$keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password', 'extrapasswords');
foreach ($keys as $key) {
if (isset($override->{$key})) {
$quiz->{$key} = $override->{$key};
}
}
return $quiz;
}
/**
* Delete all the attempts belonging to a quiz.
*
* @param object $quiz The quiz object.
*/
function quiz_delete_all_attempts($quiz) {
global $CFG, $DB;
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
question_engine::delete_questions_usage_by_activities(new qubaids_for_quiz($quiz->id));
$DB->delete_records('quiz_attempts', array('quiz' => $quiz->id));
$DB->delete_records('quiz_grades', array('quiz' => $quiz->id));
}
/**
* Get the best current grade for a particular user in a quiz.
*
* @param object $quiz the quiz settings.
* @param int $userid the id of the user.
* @return float the user's current grade for this quiz, or null if this user does
* not have a grade on this quiz.
*/
function quiz_get_best_grade($quiz, $userid) {
global $DB;
$grade = $DB->get_field('quiz_grades', 'grade',
array('quiz' => $quiz->id, 'userid' => $userid));
// Need to detect errors/no result, without catching 0 grades.
if ($grade === false) {
return null;
}
return $grade + 0; // Convert to number.
}
/**
* Is this a graded quiz? If this method returns true, you can assume that
* $quiz->grade and $quiz->sumgrades are non-zero (for example, if you want to
* divide by them).
*
* @param object $quiz a row from the quiz table.
* @return bool whether this is a graded quiz.
*/
function quiz_has_grades($quiz) {
return $quiz->grade >= 0.000005 && $quiz->sumgrades >= 0.000005;
}
/**
* Does this quiz allow multiple tries?
*
* @return bool
*/
function quiz_allows_multiple_tries($quiz) {
$bt = question_engine::get_behaviour_type($quiz->preferredbehaviour);
return $bt->allows_multiple_submitted_responses();
}
/**
* Return a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
* $return->time = the time they did it
* $return->info = a short text description
*
* @param object $course
* @param object $user
* @param object $mod
* @param object $quiz
* @return object|null
*/
function quiz_user_outline($course, $user, $mod, $quiz) {
global $DB, $CFG;
require_once($CFG->libdir . '/gradelib.php');
$grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
if (empty($grades->items[0]->grades)) {
return null;
} else {
$grade = reset($grades->items[0]->grades);
}
$result = new stdClass();
$result->info = get_string('grade') . ': ' . $grade->str_long_grade;
// Datesubmitted == time created. dategraded == time modified or time overridden
// if grade was last modified by the user themselves use date graded. Otherwise use
// date submitted.
// TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
$result->time = $grade->dategraded;
} else {
$result->time = $grade->datesubmitted;
}
return $result;
}
/**
* Print a detailed representation of what a user has done with
* a given particular instance of this module, for user activity reports.
*
* @param object $course
* @param object $user
* @param object $mod
* @param object $quiz
* @return bool
*/
function quiz_user_complete($course, $user, $mod, $quiz) {
global $DB, $CFG, $OUTPUT;
require_once($CFG->libdir . '/gradelib.php');
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
$grades = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $user->id);
if (!empty($grades->items[0]->grades)) {
$grade = reset($grades->items[0]->grades);
echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
if ($grade->str_feedback) {
echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
}
}
if ($attempts = $DB->get_records('quiz_attempts',
array('userid' => $user->id, 'quiz' => $quiz->id), 'attempt')) {
foreach ($attempts as $attempt) {
echo get_string('attempt', 'quiz', $attempt->attempt) . ': ';
if ($attempt->state != quiz_attempt::FINISHED) {
echo quiz_attempt_state_name($attempt->state);
} else {
echo quiz_format_grade($quiz, $attempt->sumgrades) . '/' .
quiz_format_grade($quiz, $quiz->sumgrades);
}
echo ' - '.userdate($attempt->timemodified).'
';
}
} else {
print_string('noattempts', 'quiz');
}
return true;
}
/**
* Quiz periodic clean-up tasks.
*/
function quiz_cron() {
global $CFG;
require_once($CFG->dirroot . '/mod/quiz/cronlib.php');
mtrace('');
$timenow = time();
$overduehander = new mod_quiz_overdue_attempt_updater();
$processto = $timenow - get_config('quiz', 'graceperiodmin');
mtrace(' Looking for quiz overdue quiz attempts...');
list($count, $quizcount) = $overduehander->update_overdue_attempts($timenow, $processto);
mtrace(' Considered ' . $count . ' attempts in ' . $quizcount . ' quizzes.');
// Run cron for our sub-plugin types.
cron_execute_plugin_type('quiz', 'quiz reports');
cron_execute_plugin_type('quizaccess', 'quiz access rules');
return true;
}
/**
* @param int $quizid the quiz id.
* @param int $userid the userid.
* @param string $status 'all', 'finished' or 'unfinished' to control
* @param bool $includepreviews
* @return an array of all the user's attempts at this quiz. Returns an empty
* array if there are none.
*/
function quiz_get_user_attempts($quizid, $userid, $status = 'finished', $includepreviews = false) {
global $DB, $CFG;
// TODO MDL-33071 it is very annoying to have to included all of locallib.php
// just to get the quiz_attempt::FINISHED constants, but I will try to sort
// that out properly for Moodle 2.4. For now, I will just do a quick fix for
// MDL-33048.
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
$params = array();
switch ($status) {
case 'all':
$statuscondition = '';
break;
case 'finished':
$statuscondition = ' AND state IN (:state1, :state2)';
$params['state1'] = quiz_attempt::FINISHED;
$params['state2'] = quiz_attempt::ABANDONED;
break;
case 'unfinished':
$statuscondition = ' AND state IN (:state1, :state2)';
$params['state1'] = quiz_attempt::IN_PROGRESS;
$params['state2'] = quiz_attempt::OVERDUE;
break;
}
$previewclause = '';
if (!$includepreviews) {
$previewclause = ' AND preview = 0';
}
$params['quizid'] = $quizid;
$params['userid'] = $userid;
return $DB->get_records_select('quiz_attempts',
'quiz = :quizid AND userid = :userid' . $previewclause . $statuscondition,
$params, 'attempt ASC');
}
/**
* Return grade for given user or all users.
*
* @param int $quizid id of quiz
* @param int $userid optional user id, 0 means all users
* @return array array of grades, false if none. These are raw grades. They should
* be processed with quiz_format_grade for display.
*/
function quiz_get_user_grades($quiz, $userid = 0) {
global $CFG, $DB;
$params = array($quiz->id);
$usertest = '';
if ($userid) {
$params[] = $userid;
$usertest = 'AND u.id = ?';
}
return $DB->get_records_sql("
SELECT
u.id,
u.id AS userid,
qg.grade AS rawgrade,
qg.timemodified AS dategraded,
MAX(qa.timefinish) AS datesubmitted
FROM {user} u
JOIN {quiz_grades} qg ON u.id = qg.userid
JOIN {quiz_attempts} qa ON qa.quiz = qg.quiz AND qa.userid = u.id
WHERE qg.quiz = ?
$usertest
GROUP BY u.id, qg.grade, qg.timemodified", $params);
}
/**
* Round a grade to to the correct number of decimal places, and format it for display.
*
* @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
* @param float $grade The grade to round.
* @return float
*/
function quiz_format_grade($quiz, $grade) {
if (is_null($grade)) {
return get_string('notyetgraded', 'quiz');
}
return format_float($grade, $quiz->decimalpoints);
}
/**
* Determine the correct number of decimal places required to format a grade.
*
* @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
* @return integer
*/
function quiz_get_grade_format($quiz) {
if (empty($quiz->questiondecimalpoints)) {
$quiz->questiondecimalpoints = -1;
}
if ($quiz->questiondecimalpoints == -1) {
return $quiz->decimalpoints;
}
return $quiz->questiondecimalpoints;
}
/**
* Round a grade to the correct number of decimal places, and format it for display.
*
* @param object $quiz The quiz table row, only $quiz->decimalpoints is used.
* @param float $grade The grade to round.
* @return float
*/
function quiz_format_question_grade($quiz, $grade) {
return format_float($grade, quiz_get_grade_format($quiz));
}
/**
* Update grades in central gradebook
*
* @category grade
* @param object $quiz the quiz settings.
* @param int $userid specific user only, 0 means all users.
* @param bool $nullifnone If a single user is specified and $nullifnone is true a grade item with a null rawgrade will be inserted
*/
function quiz_update_grades($quiz, $userid = 0, $nullifnone = true) {
global $CFG, $DB;
require_once($CFG->libdir . '/gradelib.php');
if ($quiz->grade == 0) {
quiz_grade_item_update($quiz);
} else if ($grades = quiz_get_user_grades($quiz, $userid)) {
quiz_grade_item_update($quiz, $grades);
} else if ($userid && $nullifnone) {
$grade = new stdClass();
$grade->userid = $userid;
$grade->rawgrade = null;
quiz_grade_item_update($quiz, $grade);
} else {
quiz_grade_item_update($quiz);
}
}
/**
* Create or update the grade item for given quiz
*
* @category grade
* @param object $quiz object with extra cmidnumber
* @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
* @return int 0 if ok, error code otherwise
*/
function quiz_grade_item_update($quiz, $grades = null) {
global $CFG, $OUTPUT;
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
require_once($CFG->libdir . '/gradelib.php');
if (array_key_exists('cmidnumber', $quiz)) { // May not be always present.
$params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
} else {
$params = array('itemname' => $quiz->name);
}
if ($quiz->grade > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $quiz->grade;
$params['grademin'] = 0;
} else {
$params['gradetype'] = GRADE_TYPE_NONE;
}
// What this is trying to do:
// 1. If the quiz is set to not show grades while the quiz is still open,
// and is set to show grades after the quiz is closed, then create the
// grade_item with a show-after date that is the quiz close date.
// 2. If the quiz is set to not show grades at either of those times,
// create the grade_item as hidden.
// 3. If the quiz is set to show grades, create the grade_item visible.
$openreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
mod_quiz_display_options::LATER_WHILE_OPEN);
$closedreviewoptions = mod_quiz_display_options::make_from_quiz($quiz,
mod_quiz_display_options::AFTER_CLOSE);
if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
$closedreviewoptions->marks < question_display_options::MARK_AND_MAX) {
$params['hidden'] = 1;
} else if ($openreviewoptions->marks < question_display_options::MARK_AND_MAX &&
$closedreviewoptions->marks >= question_display_options::MARK_AND_MAX) {
if ($quiz->timeclose) {
$params['hidden'] = $quiz->timeclose;
} else {
$params['hidden'] = 1;
}
} else {
// Either
// a) both open and closed enabled
// b) open enabled, closed disabled - we can not "hide after",
// grades are kept visible even after closing.
$params['hidden'] = 0;
}
if (!$params['hidden']) {
// If the grade item is not hidden by the quiz logic, then we need to
// hide it if the quiz is hidden from students.
if (property_exists($quiz, 'visible')) {
// Saving the quiz form, and cm not yet updated in the database.
$params['hidden'] = !$quiz->visible;
} else {
$cm = get_coursemodule_from_instance('quiz', $quiz->id);
$params['hidden'] = !$cm->visible;
}
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = null;
}
$gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
if (!empty($gradebook_grades->items)) {
$grade_item = $gradebook_grades->items[0];
if ($grade_item->locked) {
// NOTE: this is an extremely nasty hack! It is not a bug if this confirmation fails badly. --skodak.
$confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
if (!$confirm_regrade) {
if (!AJAX_SCRIPT) {
$message = get_string('gradeitemislocked', 'grades');
$back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id .
'&mode=overview';
$regrade_link = qualified_me() . '&confirm_regrade=1';
echo $OUTPUT->box_start('generalbox', 'notice');
echo '
'. $message .'
'; echo $OUTPUT->container_start('buttons'); echo $OUTPUT->single_button($regrade_link, get_string('regradeanyway', 'grades')); echo $OUTPUT->single_button($back_link, get_string('cancel')); echo $OUTPUT->container_end(); echo $OUTPUT->box_end(); } return GRADE_UPDATE_ITEM_LOCKED; } } } return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params); } /** * Delete grade item for given quiz * * @category grade * @param object $quiz object * @return object quiz */ function quiz_grade_item_delete($quiz) { global $CFG; require_once($CFG->libdir . '/gradelib.php'); return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, null, array('deleted' => 1)); } /** * This standard function will check all instances of this module * and make sure there are up-to-date events created for each of them. * If courseid = 0, then every quiz event in the site is checked, else * only quiz events belonging to the course specified are checked. * This function is used, in its new format, by restore_refresh_events() * * @param int $courseid * @return bool */ function quiz_refresh_events($courseid = 0) { global $DB; if ($courseid == 0) { if (!$quizzes = $DB->get_records('quiz')) { return true; } } else { if (!$quizzes = $DB->get_records('quiz', array('course' => $courseid))) { return true; } } foreach ($quizzes as $quiz) { quiz_update_events($quiz); } return true; } /** * Returns all quiz graded users since a given time for specified quiz */ function quiz_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0) { global $CFG, $USER, $DB; require_once($CFG->dirroot . '/mod/quiz/locallib.php'); $course = get_course($courseid); $modinfo = get_fast_modinfo($course); $cm = $modinfo->cms[$cmid]; $quiz = $DB->get_record('quiz', array('id' => $cm->instance)); if ($userid) { $userselect = "AND u.id = :userid"; $params['userid'] = $userid; } else { $userselect = ''; } if ($groupid) { $groupselect = 'AND gm.groupid = :groupid'; $groupjoin = 'JOIN {groups_members} gm ON gm.userid=u.id'; $params['groupid'] = $groupid; } else { $groupselect = ''; $groupjoin = ''; } $params['timestart'] = $timestart; $params['quizid'] = $quiz->id; $ufields = user_picture::fields('u', null, 'useridagain'); if (!$attempts = $DB->get_records_sql(" SELECT qa.*, {$ufields} FROM {quiz_attempts} qa JOIN {user} u ON u.id = qa.userid $groupjoin WHERE qa.timefinish > :timestart AND qa.quiz = :quizid AND qa.preview = 0 $userselect $groupselect ORDER BY qa.timefinish ASC", $params)) { return; } $context = context_module::instance($cm->id); $accessallgroups = has_capability('moodle/site:accessallgroups', $context); $viewfullnames = has_capability('moodle/site:viewfullnames', $context); $grader = has_capability('mod/quiz:viewreports', $context); $groupmode = groups_get_activity_groupmode($cm, $course); $usersgroups = null; $aname = format_string($cm->name, true); foreach ($attempts as $attempt) { if ($attempt->userid != $USER->id) { if (!$grader) { // Grade permission required. continue; } if ($groupmode == SEPARATEGROUPS and !$accessallgroups) { $usersgroups = groups_get_all_groups($course->id, $attempt->userid, $cm->groupingid); $usersgroups = array_keys($usersgroups); if (!array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid))) { continue; } } } $options = quiz_get_review_options($quiz, $attempt, $context); $tmpactivity = new stdClass(); $tmpactivity->type = 'quiz'; $tmpactivity->cmid = $cm->id; $tmpactivity->name = $aname; $tmpactivity->sectionnum = $cm->sectionnum; $tmpactivity->timestamp = $attempt->timefinish; $tmpactivity->content = new stdClass(); $tmpactivity->content->attemptid = $attempt->id; $tmpactivity->content->attempt = $attempt->attempt; if (quiz_has_grades($quiz) && $options->marks >= question_display_options::MARK_AND_MAX) { $tmpactivity->content->sumgrades = quiz_format_grade($quiz, $attempt->sumgrades); $tmpactivity->content->maxgrade = quiz_format_grade($quiz, $quiz->sumgrades); } else { $tmpactivity->content->sumgrades = null; $tmpactivity->content->maxgrade = null; } $tmpactivity->user = user_picture::unalias($attempt, null, 'useridagain'); $tmpactivity->user->fullname = fullname($tmpactivity->user, $viewfullnames); $activities[$index++] = $tmpactivity; } } function quiz_print_recent_mod_activity($activity, $courseid, $detail, $modnames) { global $CFG, $OUTPUT; echo ''; echo $OUTPUT->user_picture($activity->user, array('courseid' => $courseid)); echo ' | ';
if ($detail) {
$modname = $modnames[$activity->type];
echo ' ';
echo '';
echo '' . $activity->name . '';
echo ' ';
}
echo '';
echo get_string('attempt', 'quiz', $activity->content->attempt);
if (isset($activity->content->maxgrade)) {
$grades = $activity->content->sumgrades . ' / ' . $activity->content->maxgrade;
echo ': (' . $grades . ')';
}
echo ' ';
echo '';
echo '' . $activity->user->fullname .
' - ' . userdate($activity->timestamp);
echo ' ';
echo ' |