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