MDL-34054 quiz reports: missing context.
[moodle.git] / mod / quiz / report / reportlib.php
CommitLineData
f33c438e 1<?php
2709ee45
TH
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 * Helper functions for the quiz reports.
19 *
8d76124c
TH
20 * @package mod_quiz
21 * @copyright 2008 Jamie Pratt
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2709ee45
TH
23 */
24
a17b297d
TH
25
26defined('MOODLE_INTERNAL') || die();
27
530d9866 28require_once($CFG->dirroot . '/mod/quiz/lib.php');
446166a6 29require_once($CFG->libdir . '/filelib.php');
530d9866 30
869309b8 31/**
32 * Takes an array of objects and constructs a multidimensional array keyed by
33 * the keys it finds on the object.
34 * @param array $datum an array of objects with properties on the object
35 * including the keys passed as the next param.
36 * @param array $keys Array of strings with the names of the properties on the
37 * objects in datum that you want to index the multidimensional array by.
f7970e3c 38 * @param bool $keysunique If there is not only one object for each
869309b8 39 * combination of keys you are using you should set $keysunique to true.
40 * Otherwise all the object will be added to a zero based array. So the array
41 * returned will have count($keys) + 1 indexs.
42 * @return array multidimensional array properly indexed.
43 */
2709ee45
TH
44function quiz_report_index_by_keys($datum, $keys, $keysunique = true) {
45 if (!$datum) {
46 return array();
98f38217 47 }
48 $key = array_shift($keys);
49 $datumkeyed = array();
2709ee45
TH
50 foreach ($datum as $data) {
51 if ($keys || !$keysunique) {
98f38217 52 $datumkeyed[$data->{$key}][]= $data;
53 } else {
54 $datumkeyed[$data->{$key}]= $data;
55 }
56 }
2709ee45
TH
57 if ($keys) {
58 foreach ($datumkeyed as $datakey => $datakeyed) {
869309b8 59 $datumkeyed[$datakey] = quiz_report_index_by_keys($datakeyed, $keys, $keysunique);
98f38217 60 }
61 }
62 return $datumkeyed;
63}
2709ee45
TH
64
65function quiz_report_unindex($datum) {
66 if (!$datum) {
869309b8 67 return $datum;
68 }
69 $datumunkeyed = array();
2709ee45
TH
70 foreach ($datum as $value) {
71 if (is_array($value)) {
869309b8 72 $datumunkeyed = array_merge($datumunkeyed, quiz_report_unindex($value));
73 } else {
74 $datumunkeyed[] = $value;
75 }
76 }
77 return $datumunkeyed;
78}
720be6f2 79
2badf2e6 80/**
2709ee45
TH
81 * Get the slots of real questions (not descriptions) in this quiz, in order.
82 * @param object $quiz the quiz.
25a03faa
TH
83 * @return array of slot => $question object with fields
84 * ->slot, ->id, ->maxmark, ->number, ->length.
2badf2e6 85 */
cf3b6568 86function quiz_report_get_significant_questions($quiz) {
2709ee45
TH
87 global $DB;
88
cf3b6568 89 $questionids = quiz_questions_in_quiz($quiz->questions);
3c6185e9
TH
90 if (empty($questionids)) {
91 return array();
92 }
93
cf3b6568 94 list($usql, $params) = $DB->get_in_or_equal(explode(',', $questionids));
9cf4a18b 95 $params[] = $quiz->id;
2709ee45
TH
96 $questions = $DB->get_records_sql("
97SELECT
98 q.id,
99 q.length,
100 qqi.grade AS maxmark
101
102FROM {question} q
103JOIN {quiz_question_instances} qqi ON qqi.question = q.id
104
105WHERE
2709ee45 106 q.id $usql AND
cf3b6568 107 qqi.quiz = ? AND
2709ee45
TH
108 length > 0", $params);
109
110 $qsbyslot = array();
2badf2e6 111 $number = 1;
2709ee45
TH
112 foreach (explode(',', $questionids) as $key => $id) {
113 if (!array_key_exists($id, $questions)) {
114 continue;
2badf2e6 115 }
2709ee45
TH
116
117 $slot = $key + 1;
118 $question = $questions[$id];
119 $question->slot = $slot;
120 $question->number = $number;
121
122 $qsbyslot[$slot] = $question;
123
124 $number += $question->length;
2badf2e6 125 }
2709ee45
TH
126
127 return $qsbyslot;
2badf2e6 128}
2709ee45 129
863872e3
TH
130/**
131 * @param object $quiz the quiz settings.
132 * @return bool whether, for this quiz, it is possible to filter attempts to show
133 * only those that gave the final grade.
134 */
135function quiz_report_can_filter_only_graded($quiz) {
136 return $quiz->attempts != 1 && $quiz->grademethod != QUIZ_GRADEAVERAGE;
137}
138
4469159e 139/**
140 * Given the quiz grading method return sub select sql to find the id of the
9cf4a18b 141 * one attempt that will be graded for each user. Or return
4469159e 142 * empty string if all attempts contribute to final grade.
143 */
2709ee45 144function quiz_report_qm_filter_select($quiz, $quizattemptsalias = 'quiza') {
768a7588
TH
145 if ($quiz->attempts == 1) {
146 // This quiz only allows one attempt.
b621e1a0 147 return '';
148 }
9b40c540 149
b621e1a0 150 switch ($quiz->grademethod) {
25a03faa
TH
151 case QUIZ_GRADEHIGHEST :
152 return "$quizattemptsalias.id = (
153 SELECT MIN(qa2.id)
154 FROM {quiz_attempts} qa2
155 WHERE qa2.quiz = $quizattemptsalias.quiz AND
156 qa2.userid = $quizattemptsalias.userid AND
157 COALESCE(qa2.sumgrades, 0) = (
158 SELECT MAX(COALESCE(qa3.sumgrades, 0))
159 FROM {quiz_attempts} qa3
160 WHERE qa3.quiz = $quizattemptsalias.quiz AND
161 qa3.userid = $quizattemptsalias.userid
162 )
163 )";
164
165 case QUIZ_GRADEAVERAGE :
166 return '';
167
168 case QUIZ_ATTEMPTFIRST :
169 return "$quizattemptsalias.id = (
170 SELECT MIN(qa2.id)
171 FROM {quiz_attempts} qa2
172 WHERE qa2.quiz = $quizattemptsalias.quiz AND
173 qa2.userid = $quizattemptsalias.userid)";
174
175 case QUIZ_ATTEMPTLAST :
176 return "$quizattemptsalias.id = (
177 SELECT MAX(qa2.id)
178 FROM {quiz_attempts} qa2
179 WHERE qa2.quiz = $quizattemptsalias.quiz AND
180 qa2.userid = $quizattemptsalias.userid)";
4469159e 181 }
4469159e 182}
8b87ab00 183
2709ee45
TH
184/**
185 * Get the nuber of students whose score was in a particular band for this quiz.
186 * @param number $bandwidth the width of each band.
f7970e3c
TH
187 * @param int $bands the number of bands
188 * @param int $quizid the quiz id.
2709ee45
TH
189 * @param array $userids list of user ids.
190 * @return array band number => number of users with scores in that band.
191 */
192function quiz_report_grade_bands($bandwidth, $bands, $quizid, $userids = array()) {
446166a6 193 global $DB;
2709ee45
TH
194
195 if ($userids) {
a2ac2349 196 list($usql, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'u');
2709ee45 197 $usql = "qg.userid $usql AND";
8b2f8253 198 } else {
2daffca5 199 $usql = '';
8b2f8253 200 $params = array();
201 }
2709ee45 202 $sql = "
330c1148 203SELECT band, COUNT(1)
2709ee45 204
330c1148
TH
205FROM (
206 SELECT FLOOR(qg.grade / :bandwidth) AS band
207 FROM {quiz_grades} qg
208 WHERE $usql qg.quiz = :quizid
209) subquery
2709ee45
TH
210
211GROUP BY
330c1148 212 band
2709ee45
TH
213
214ORDER BY
215 band";
2daffca5
TH
216
217 $params['quizid'] = $quizid;
330c1148 218 $params['bandwidth'] = $bandwidth;
2709ee45 219
9cf4a18b 220 $data = $DB->get_records_sql_menu($sql, $params);
2709ee45 221
768a7588 222 // We need to create array elements with values 0 at indexes where there is no element.
a5686531 223 $data = $data + array_fill(0, $bands+1, 0);
8b87ab00 224 ksort($data);
2709ee45 225
768a7588
TH
226 // Place the maximum (prefect grade) into the last band i.e. make last
227 // band for example 9 <= g <=10 (where 10 is the perfect grade) rather than
228 // just 9 <= g <10.
2709ee45 229 $data[$bands - 1] += $data[$bands];
a5686531 230 unset($data[$bands]);
2709ee45 231
8b87ab00 232 return $data;
233}
2709ee45
TH
234
235function quiz_report_highlighting_grading_method($quiz, $qmsubselect, $qmfilter) {
236 if ($quiz->attempts == 1) {
237 return '<p>' . get_string('onlyoneattemptallowed', 'quiz_overview') . '</p>';
238
239 } else if (!$qmsubselect) {
240 return '<p>' . get_string('allattemptscontributetograde', 'quiz_overview') . '</p>';
241
242 } else if ($qmfilter) {
243 return '<p>' . get_string('showinggraded', 'quiz_overview') . '</p>';
244
245 } else {
246 return '<p>' . get_string('showinggradedandungraded', 'quiz_overview',
247 '<span class="gradedattempt">' . quiz_get_grading_option_name($quiz->grademethod) .
248 '</span>') . '</p>';
b621e1a0 249 }
250}
aad5b0fc 251
aad5b0fc 252/**
253 * Get the feedback text for a grade on this quiz. The feedback is
254 * processed ready for display.
255 *
256 * @param float $grade a grade on this quiz.
f7970e3c 257 * @param int $quizid the id of the quiz object.
aad5b0fc 258 * @return string the comment that corresponds to this grade (empty string if there is not one.
259 */
8ad67658 260function quiz_report_feedback_for_grade($grade, $quizid, $context) {
446166a6 261 global $DB;
99d19c13 262
aad5b0fc 263 static $feedbackcache = array();
2709ee45
TH
264
265 if (!isset($feedbackcache[$quizid])) {
9cf4a18b 266 $feedbackcache[$quizid] = $DB->get_records('quiz_feedback', array('quizid' => $quizid));
aad5b0fc 267 }
2709ee45 268
b7ab57f3
TH
269 // With CBM etc, it is possible to get -ve grades, which would then not match
270 // any feedback. Therefore, we replace -ve grades with 0.
271 $grade = max($grade, 0);
272
aad5b0fc 273 $feedbacks = $feedbackcache[$quizid];
8ad67658 274 $feedbackid = 0;
aad5b0fc 275 $feedbacktext = '';
8ad67658 276 $feedbacktextformat = FORMAT_MOODLE;
aad5b0fc 277 foreach ($feedbacks as $feedback) {
25a03faa 278 if ($feedback->mingrade <= $grade && $grade < $feedback->maxgrade) {
8ad67658 279 $feedbackid = $feedback->id;
aad5b0fc 280 $feedbacktext = $feedback->feedbacktext;
8ad67658 281 $feedbacktextformat = $feedback->feedbacktextformat;
aad5b0fc 282 break;
283 }
284 }
285
286 // Clean the text, ready for display.
0ff4bd08 287 $formatoptions = new stdClass();
aad5b0fc 288 $formatoptions->noclean = true;
25a03faa
TH
289 $feedbacktext = file_rewrite_pluginfile_urls($feedbacktext, 'pluginfile.php',
290 $context->id, 'mod_quiz', 'feedback', $feedbackid);
8ad67658 291 $feedbacktext = format_text($feedbacktext, $feedbacktextformat, $formatoptions);
aad5b0fc 292
293 return $feedbacktext;
294}
0c1c764e 295
2709ee45
TH
296/**
297 * Format a number as a percentage out of $quiz->sumgrades
298 * @param number $rawgrade the mark to format.
299 * @param object $quiz the quiz settings
f7970e3c 300 * @param bool $round whether to round the results ot $quiz->decimalpoints.
2709ee45
TH
301 */
302function quiz_report_scale_summarks_as_percentage($rawmark, $quiz, $round = true) {
303 if ($quiz->sumgrades == 0) {
869309b8 304 return '';
0c1c764e 305 }
2709ee45
TH
306 if (!is_numeric($rawmark)) {
307 return $rawmark;
308 }
309
310 $mark = $rawmark * 100 / $quiz->sumgrades;
311 if ($round) {
312 $mark = quiz_format_grade($quiz, $mark);
313 }
314 return $mark . '%';
0c1c764e 315}
2709ee45 316
bbf4f440 317/**
318 * Returns an array of reports to which the current user has access to.
2709ee45 319 * @return array reports are ordered as they should be for display in tabs.
bbf4f440 320 */
a49cb927 321function quiz_report_list($context) {
bbf4f440 322 global $DB;
323 static $reportlist = null;
2709ee45 324 if (!is_null($reportlist)) {
bbf4f440 325 return $reportlist;
326 }
2709ee45 327
f2557823 328 $reports = $DB->get_records('quiz_reports', null, 'displayorder DESC', 'name, capability');
a49cb927 329 $reportdirs = get_plugin_list('quiz');
1ddfb914 330
768a7588 331 // Order the reports tab in descending order of displayorder.
bbf4f440 332 $reportcaps = array();
2709ee45
TH
333 foreach ($reports as $key => $report) {
334 if (array_key_exists($report->name, $reportdirs)) {
335 $reportcaps[$report->name] = $report->capability;
bbf4f440 336 }
337 }
338
768a7588 339 // Add any other reports, which are on disc but not in the DB, on the end.
1ddfb914 340 foreach ($reportdirs as $reportname => $notused) {
bbf4f440 341 if (!isset($reportcaps[$reportname])) {
1ddfb914 342 $reportcaps[$reportname] = null;
bbf4f440 343 }
344 }
345 $reportlist = array();
2709ee45
TH
346 foreach ($reportcaps as $name => $capability) {
347 if (empty($capability)) {
bbf4f440 348 $capability = 'mod/quiz:viewreports';
349 }
2709ee45 350 if (has_capability($capability, $context)) {
bbf4f440 351 $reportlist[] = $name;
352 }
353 }
354 return $reportlist;
355}
356
2709ee45
TH
357/**
358 * Create a filename for use when downloading data from a quiz report. It is
359 * expected that this will be passed to flexible_table::is_downloading, which
360 * cleans the filename of bad characters and adds the file extension.
361 * @param string $report the type of report.
362 * @param string $courseshortname the course shortname.
363 * @param string $quizname the quiz name.
364 * @return string the filename.
365 */
366function quiz_report_download_filename($report, $courseshortname, $quizname) {
367 return $courseshortname . '-' . format_string($quizname, true) . '-' . $report;
368}
369
a49cb927
TH
370/**
371 * Get the default report for the current user.
372 * @param object $context the quiz context.
373 */
374function quiz_report_default_report($context) {
6b4e2d76
TH
375 $reports = quiz_report_list($context);
376 return reset($reports);
a49cb927 377}
d755b0f5
TH
378
379/**
380 * Generate a message saying that this quiz has no questions, with a button to
381 * go to the edit page, if the user has the right capability.
382 * @param object $quiz the quiz settings.
383 * @param object $cm the course_module object.
384 * @param object $context the quiz context.
385 * @return string HTML to output.
386 */
387function quiz_no_questions_message($quiz, $cm, $context) {
388 global $OUTPUT;
389
390 $output = '';
391 $output .= $OUTPUT->notification(get_string('noquestions', 'quiz'));
392 if (has_capability('mod/quiz:manage', $context)) {
393 $output .= $OUTPUT->single_button(new moodle_url('/mod/quiz/edit.php',
394 array('cmid' => $cm->id)), get_string('editquiz', 'quiz'), 'get');
395 }
396
397 return $output;
398}
dcd65f1b
TH
399
400/**
401 * Should the grades be displayed in this report. That depends on the quiz
402 * display options, and whether the quiz is graded.
403 * @param object $quiz the quiz settings.
564b8788 404 * @param context $context the quiz context.
dcd65f1b
TH
405 * @return bool
406 */
564b8788 407function quiz_report_should_show_grades($quiz, context $context) {
dcd65f1b
TH
408 if ($quiz->timeclose && time() > $quiz->timeclose) {
409 $when = mod_quiz_display_options::AFTER_CLOSE;
410 } else {
411 $when = mod_quiz_display_options::LATER_WHILE_OPEN;
412 }
413 $reviewoptions = mod_quiz_display_options::make_from_quiz($quiz, $when);
414
415 return quiz_has_grades($quiz) &&
416 ($reviewoptions->marks >= question_display_options::MARK_AND_MAX ||
564b8788 417 has_capability('moodle/grade:viewhidden', $context));
dcd65f1b 418}