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