MDL-11075 Now saving to temp file, then outputting using filelib's readfile_chunked...
[moodle.git] / grade / lib.php
CommitLineData
3af29899 1<?php //$Id$
cbff94ba 2
7a6b7acf 3require_once $CFG->libdir.'/gradelib.php';
4
0f5660f7 5
6/**
7 * This class iterates over all users that are graded in a course.
8 * Returns fetailed info about users and their grades.
9 */
10class graded_users_iterator {
11 var $course;
12 var $grade_items;
13 var $groupid;
14 var $users_rs;
15 var $grades_rs;
16 var $gradestack;
17
18 /**
19 * Constructor
20 * @param $coruse object
21 * @param array grade_items array of grade items, if not specified only user info returned
22 * @param int $groupid iterate only group users if present
23 */
24 function graded_users_iterator($course, $grade_items=null, $groupid=0) {
25 $this->course = $course;
26 $this->grade_items = $grade_items;
27 $this->groupid = $groupid;
28
29 $this->gradestack = array();
30 }
31
32 /**
33 * Initialise the iterator
34 * @return boolean success
35 */
36 function init() {
37 global $CFG;
38
39 $this->close();
40
41 grade_regrade_final_grades($this->course->id);
42 $course_item = grade_item::fetch_course_item($this->course->id);
43 if ($course_item->needsupdate) {
44 // can not calculate all final grades - sorry
45 return false;
46 }
47
48 if (strpos($CFG->gradebookroles, ',') !== false) {
49 $gradebookroles = " = {$CFG->gradebookroles}";
50 } else {
51 $gradebookroles = " IN ({$CFG->gradebookroles})";
52 }
53
54 $relatedcontexts = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $this->course->id));
55
56 if ($this->groupid) {
57 $groupsql = "INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id";
58 $groupwheresql = "AND gm.groupid = {$this->groupid}";
59 } else {
60 $groupsql = "";
61 $groupwheresql = "";
62 }
63
64 $users_sql = "SELECT u.*
65 FROM {$CFG->prefix}user u
66 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
67 $groupsql
68 WHERE ra.roleid $gradebookroles
69 AND ra.contextid $relatedcontexts
70 $groupwheresql
71 ORDER BY u.id ASC";
72 $this->rs_users = get_recordset_sql($users_sql);
73
74 if (!empty($this->grade_items)) {
75 $itemids = array_keys($this->grade_items);
76 $itemids = implode(',', $itemids);
77
78 $grades_sql = "SELECT g.*, gt.feedback, gt.feedbackformat
79 FROM {$CFG->prefix}grade_grades g
80 LEFT JOIN {$CFG->prefix}grade_grades_text gt ON gt.gradeid = g.id
81 INNER JOIN {$CFG->prefix}user u ON g.userid = u.id
82 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
83 $groupsql
84 WHERE ra.roleid $gradebookroles
85 AND ra.contextid $relatedcontexts
86 AND g.itemid IN ($itemids)
87 $groupwheresql
88 ORDER BY g.userid ASC, g.itemid ASC";
89 $this->rs_grades = get_recordset_sql($grades_sql);
90 }
91
92 return true;
93 }
94
95 /**
96 * Returns information about the next user
97 * @return mixed array of user info, all grades and feedback or null when no more users found
98 */
99 function next_user() {
100 if (!$this->rs_users or !$this->rs_users->RecordCount()) {
101 return false; // no users present
102 }
103
104 if (!$user = rs_fetch_next_record($this->rs_users)) {
105 return false; // no more users
106 }
107
108 //find the first grade of this user
109 $grade_records = array();
110 while (true) {
111 if (!$current = $this->_pop()) {
112 break; // no more grades
113 }
114
115 if ($current->userid < $user->id) {
116 // this should not happen, could be caused by concurrent updates - skip this record
117 continue;
118
119 } else if ($current->userid > $user->id) {
120 // this user does not have any more grades
121 $this->_push($current);
122 break;
123 }
124
125 $grade_records[$current->itemid] = $current;
126 }
127
128 $grades = array();
129 $feedbacks = array();
130
131 foreach ($this->grade_items as $grade_item) {
132 if (array_key_exists($grade_item->id, $grade_records)) {
133 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
134 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
135 unset($grade_records[$grade_item->id]->feedback);
136 unset($grade_records[$grade_item->id]->feedbackformat);
137 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
138 } else {
139 $feedbacks[$grade_item->id]->feedback = '';
140 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
141 $grades[$grade_item->id] = new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
142 }
143 }
144
145 $result = new object();
146 $result->user = $user;
147 $result->grades = $grades;
148 $result->feedbacks = $feedbacks;
149
150 return $result;
151 }
152
153 /**
154 * Close the iterator, do not forget to call this function.
155 * @return void
156 */
157 function close() {
158 if ($this->rs_users) {
159 rs_close($this->rs_users);
160 $this->rs_users = null;
161 }
162 if ($this->rs_grades) {
163 rs_close($this->rs_grades);
164 $this->rs_grades = null;
165 }
166 $this->gradestack = array();
167 }
168
169 /**
170 * Internal function
171 */
172 function _push($grade) {
173 array_push($this->gradestack, $grade);
174 }
175
176 /**
177 * Internal function
178 */
179 function _pop() {
180 if (empty($this->gradestack)) {
181 if (!$this->rs_grades or !$this->rs_grades->RecordCount()) {
182 return NULL; // no grades present
183 }
184
185 if (!$grade = rs_fetch_next_record($this->rs_grades)) {
186 return NULL; // no more grades
187 }
188
189 return $grade;
190 } else {
191 return array_pop($this->gradestack);
192 }
193 }
194}
195
0610812a 196/**
197 * Print grading plugin selection popup form.
198 *
199 * @param int $courseid id of course
200 * @param string $active_type type of plugin on current page - import, export, report or edit
201 * @param string $active_plugin active plugin type - grader, user, cvs, ...
202 * @param boolean $return return as string
203 * @return nothing or string if $return true
204 */
3af29899 205function print_grade_plugin_selector($courseid, $active_type, $active_plugin, $return=false) {
cbff94ba 206 global $CFG;
cbff94ba 207
3af29899 208 $context = get_context_instance(CONTEXT_COURSE, $courseid);
cbff94ba 209
3af29899 210 $menu = array();
cbff94ba 211
3af29899 212 $active = '';
cbff94ba 213
3af29899 214/// report plugins with its special structure
215 if ($reports = get_list_of_plugins('grade/report', 'CVS')) { // Get all installed reports
216 foreach ($reports as $key => $plugin) { // Remove ones we can't see
217 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
218 unset($reports[$key]);
cbff94ba 219 }
220 }
04678d8e 221 }
3af29899 222 $reportnames = array();
223 if (!empty($reports)) {
224 foreach ($reports as $plugin) {
65dd61bd 225 $url = 'report/'.$plugin.'/index.php?id='.$courseid;
3af29899 226 if ($active_type == 'report' and $active_plugin == $plugin ) {
227 $active = $url;
cbff94ba 228 }
3565ff92 229 $reportnames[$url] = get_string('modulename', 'gradereport_'.$plugin, NULL, $CFG->dirroot.'/grade/report/'.$plugin.'/lang/');
cbff94ba 230 }
3af29899 231 asort($reportnames);
cbff94ba 232 }
3af29899 233 if (!empty($reportnames)) {
234 $menu['reportgroup']='--'.get_string('reportplugins', 'grades');
235 $menu = $menu+$reportnames;
cbff94ba 236 }
cbff94ba 237
3af29899 238/// standard import plugins
e2008be2 239 if ($imports = get_list_of_plugins('grade/import', 'CVS')) { // Get all installed import plugins
3af29899 240 foreach ($imports as $key => $plugin) { // Remove ones we can't see
241 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
242 unset($imports[$key]);
cbff94ba 243 }
244 }
245 }
3af29899 246 $importnames = array();
247 if (!empty($imports)) {
248 foreach ($imports as $plugin) {
249 $url = 'import/'.$plugin.'/index.php?id='.$courseid;
65dd61bd 250 if ($active_type == 'import' and $active_plugin == $plugin ) {
3af29899 251 $active = $url;
252 }
3565ff92 253 $importnames[$url] = get_string('modulename', 'gradeimport_'.$plugin, NULL, $CFG->dirroot.'/grade/import/'.$plugin.'/lang/');
281ffa4a 254 }
3af29899 255 asort($importnames);
281ffa4a 256 }
3af29899 257 if (!empty($importnames)) {
258 $menu['importgroup']='--'.get_string('importplugins', 'grades');
259 $menu = $menu+$importnames;
281ffa4a 260 }
281ffa4a 261
3af29899 262/// standard export plugins
e2008be2 263 if ($exports = get_list_of_plugins('grade/export', 'CVS')) { // Get all installed export plugins
3af29899 264 foreach ($exports as $key => $plugin) { // Remove ones we can't see
265 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
266 unset($exports[$key]);
281ffa4a 267 }
268 }
cbff94ba 269 }
3af29899 270 $exportnames = array();
271 if (!empty($exports)) {
272 foreach ($exports as $plugin) {
273 $url = 'export/'.$plugin.'/index.php?id='.$courseid;
65dd61bd 274 if ($active_type == 'export' and $active_plugin == $plugin ) {
3af29899 275 $active = $url;
276 }
3565ff92 277 $exportnames[$url] = get_string('modulename', 'gradeexport_'.$plugin, NULL, $CFG->dirroot.'/grade/export/'.$plugin.'/lang/');
281ffa4a 278 }
3af29899 279 asort($exportnames);
cbff94ba 280 }
3af29899 281 if (!empty($exportnames)) {
282 $menu['exportgroup']='--'.get_string('exportplugins', 'grades');
283 $menu = $menu+$exportnames;
281ffa4a 284 }
cbff94ba 285
3af29899 286/// editing scripts - not real plugins
78ad5f3f 287 if (has_capability('moodle/grade:manage', $context)
04259694 288 or has_capability('moodle/course:managescales', $context)
289 or has_capability('moodle/course:update', $context)) {
3af29899 290 $menu['edit']='--'.get_string('edit');
78ad5f3f 291
292 if (has_capability('moodle/grade:manage', $context)) {
293 $url = 'edit/tree/index.php?id='.$courseid;
294 if ($active_type == 'edit' and $active_plugin == 'tree' ) {
295 $active = $url;
296 }
297 $menu[$url] = get_string('edittree', 'grades');
298 }
299
300 if (has_capability('moodle/course:managescales', $context)) {
301 $url = 'edit/scale/index.php?id='.$courseid;
302 if ($active_type == 'edit' and $active_plugin == 'scale' ) {
303 $active = $url;
304 }
305 $menu[$url] = get_string('scales');
306 }
307
2b0f65e2 308 if (!empty($CFG->enableoutcomes) && (has_capability('moodle/grade:manage', $context) or
2a598439 309 has_capability('moodle/course:update', $context))) {
310 if (has_capability('moodle/course:update', $context)) { // Default to course assignment
04259694 311 $url = 'edit/outcome/course.php?id='.$courseid;
2a598439 312 } else {
313 $url = 'edit/outcome/index.php?id='.$courseid;
04259694 314 }
78ad5f3f 315 if ($active_type == 'edit' and $active_plugin == 'outcome' ) {
316 $active = $url;
317 }
318 $menu[$url] = get_string('outcomes', 'grades');
cbff94ba 319 }
281ffa4a 320 }
321
3af29899 322/// finally print/return the popup form
0c811aa7 323 return popup_form($CFG->wwwroot.'/grade/', $menu, 'choosepluginreport', $active, 'choose', '', '', $return, 'self', get_string('view'));
cbff94ba 324}
325
0610812a 326/**
7a6b7acf 327 * Utility class used for return tracking when using edit and other forms in grade plugins
0610812a 328 */
3af29899 329class grade_plugin_return {
330 var $type;
331 var $plugin;
332 var $courseid;
333 var $userid;
334 var $page;
281ffa4a 335
0610812a 336 /**
337 * Constructor
338 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
339 */
3af29899 340 function grade_plugin_return ($params=null) {
341 if (empty($params)) {
342 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
343 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
344 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
345 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
346 $this->page = optional_param('gpr_page', null, PARAM_INT);
a983b6ec 347
a983b6ec 348 } else {
3af29899 349 foreach ($params as $key=>$value) {
350 if (array_key_exists($key, $this)) {
351 $this->$key = $value;
352 }
cbff94ba 353 }
354 }
6cd8c592 355 }
356
0610812a 357 /**
358 * Returns return parameters as options array suitable for buttons.
359 * @return array options
360 */
3af29899 361 function get_options() {
7a6b7acf 362 if (empty($this->type)) {
3af29899 363 return array();
865e9a82 364 }
6cd8c592 365
3af29899 366 $params = array();
6cd8c592 367
7a6b7acf 368 if (!empty($this->plugin)) {
369 $params['plugin'] = $this->plugin;
370 }
6cd8c592 371
3af29899 372 if (!empty($this->courseid)) {
373 $params['id'] = $this->courseid;
6cd8c592 374 }
9c61ba4d 375
3af29899 376 if (!empty($this->userid)) {
377 $params['userid'] = $this->userid;
9c61ba4d 378 }
9c61ba4d 379
3af29899 380 if (!empty($this->page)) {
381 $params['page'] = $this->page;
cbff94ba 382 }
865e9a82 383
3af29899 384 return $params;
cbff94ba 385 }
cbff94ba 386
0610812a 387 /**
388 * Returns return url
389 * @param string $default default url when params not set
390 * @return string url
391 */
65dd61bd 392 function get_return_url($default, $extras=null) {
3af29899 393 global $CFG;
cbff94ba 394
3af29899 395 if (empty($this->type) or empty($this->plugin)) {
396 return $default;
cbff94ba 397 }
398
65dd61bd 399 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
400 $glue = '?';
cbff94ba 401
3af29899 402 if (!empty($this->courseid)) {
403 $url .= $glue.'id='.$this->courseid;
404 $glue = '&amp;';
cbff94ba 405 }
cbff94ba 406
3af29899 407 if (!empty($this->userid)) {
408 $url .= $glue.'userid='.$this->userid;
409 $glue = '&amp;';
cbff94ba 410 }
7e2d7c92 411
3af29899 412 if (!empty($this->page)) {
413 $url .= $glue.'page='.$this->page;
65dd61bd 414 $glue = '&amp;';
415 }
416
417 if (!empty($extras)) {
418 foreach($extras as $key=>$value) {
419 $url .= $glue.$key.'='.$value;
420 $glue = '&amp;';
7a6b7acf 421 }
cbff94ba 422 }
cbff94ba 423
3af29899 424 return $url;
cbff94ba 425 }
cbff94ba 426
0610812a 427 /**
428 * Returns string with hidden return tracking form elements.
429 * @return string
430 */
3af29899 431 function get_form_fields() {
7a6b7acf 432 if (empty($this->type)) {
3af29899 433 return '';
cbff94ba 434 }
cbff94ba 435
3af29899 436 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 437
438 if (!empty($this->plugin)) {
439 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
440 }
0ca5abd6 441
3af29899 442 if (!empty($this->courseid)) {
443 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 444 }
cbff94ba 445
3af29899 446 if (!empty($this->userid)) {
447 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 448 }
cbff94ba 449
3af29899 450 if (!empty($this->page)) {
451 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 452 }
453 }
cbff94ba 454
0610812a 455 /**
456 * Add hidden elements into mform
457 * @param object $mform moodle form object
458 * @return void
459 */
3af29899 460 function add_mform_elements(&$mform) {
7a6b7acf 461 if (empty($this->type)) {
3af29899 462 return;
cbff94ba 463 }
cbff94ba 464
3af29899 465 $mform->addElement('hidden', 'gpr_type', $this->type);
466 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 467
7a6b7acf 468 if (!empty($this->plugin)) {
469 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
470 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
471 }
97033c86 472
3af29899 473 if (!empty($this->courseid)) {
474 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
475 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 476 }
cbff94ba 477
3af29899 478 if (!empty($this->userid)) {
479 $mform->addElement('hidden', 'gpr_userid', $this->userid);
480 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 481 }
cbff94ba 482
3af29899 483 if (!empty($this->page)) {
484 $mform->addElement('hidden', 'gpr_page', $this->page);
485 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 486 }
487 }
281ffa4a 488
0610812a 489 /**
490 * Add return tracking params into url
491 * @param string $url
492 * @return string $url with erturn tracking params
493 */
3af29899 494 function add_url_params($url) {
7a6b7acf 495 if (empty($this->type)) {
3af29899 496 return $url;
cbff94ba 497 }
5609f9e6 498
3af29899 499 if (strpos($url, '?') === false) {
500 $url .= '?gpr_type='.$this->type;
501 } else {
502 $url .= '&amp;gpr_type='.$this->type;
cbff94ba 503 }
cbff94ba 504
7a6b7acf 505 if (!empty($this->plugin)) {
506 $url .= '&amp;gpr_plugin='.$this->plugin;
507 }
cbff94ba 508
3af29899 509 if (!empty($this->courseid)) {
510 $url .= '&amp;gpr_courseid='.$this->courseid;
cbff94ba 511 }
cbff94ba 512
3af29899 513 if (!empty($this->userid)) {
514 $url .= '&amp;gpr_userid='.$this->userid;
cbff94ba 515 }
0a8a95c9 516
3af29899 517 if (!empty($this->page)) {
518 $url .= '&amp;gpr_page='.$this->page;
0a8a95c9 519 }
5a412dbf 520
3af29899 521 return $url;
5a412dbf 522 }
5a412dbf 523}
7a6b7acf 524
826c5f86 525/**
526 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
527 * @param string $path The path of the calling script (using __FILE__?)
528 * @param string $pagename The language string to use as the last part of the navigation (non-link)
529 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
530 * @return string
531 */
532function grade_build_nav($path, $pagename=null, $id=null) {
533 global $CFG, $COURSE;
534
535 $strgrades = get_string('grades', 'grades');
536
537 // Parse the path and build navlinks from its elements
538 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
539 $path = substr($path, $dirroot_length);
540 $path = str_replace('\\', '/', $path);
541
542 $path_elements = explode('/', $path);
543
544 $path_elements_count = count($path_elements);
545
826c5f86 546 // First link is always 'grade'
547 $navlinks = array();
548 $navlinks[] = array('name' => $strgrades,
549 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
550 'type' => 'misc');
551
552 $link = '';
553 $numberofelements = 3;
554
555 // Prepare URL params string
556 $id_string = '?';
557 if (!is_null($id)) {
558 if (is_array($id)) {
559 foreach ($id as $idkey => $idvalue) {
560 $id_string .= "$idkey=$idvalue&amp;";
561 }
562 } else {
563 $id_string .= "id=$id";
564 }
565 }
566
567 $navlink4 = null;
568
0f78c4de 569 // Remove file extensions from filenames
570 foreach ($path_elements as $key => $filename) {
571 $path_elements[$key] = str_replace('.php', '', $filename);
572 }
573
826c5f86 574 // Second level links
575 switch ($path_elements[1]) {
576 case 'edit': // No link
577 if ($path_elements[3] != 'index.php') {
578 $numberofelements = 4;
579 }
580 break;
581 case 'import': // No link
582 break;
583 case 'export': // No link
584 break;
585 case 'report':
586 // $id is required for this link. Do not print it if $id isn't given
587 if (!is_null($id)) {
588 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
589 }
590
591 if ($path_elements[2] == 'grader') {
592 $numberofelements = 4;
593 }
594 break;
595
596 default:
597 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
598 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
599 return false;
600 }
601
602 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
603
604 // Third level links
605 if (empty($pagename)) {
606 $pagename = get_string($path_elements[2], 'grades');
607 }
608
609 switch ($numberofelements) {
610 case 3:
611 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
612 break;
613 case 4:
614
615 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
3cf6a6d5 616 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
826c5f86 617 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
618 'type' => 'misc');
619 }
620 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
621 break;
622 }
623 $navigation = build_navigation($navlinks);
624
625 return $navigation;
d4795a07 626}
7a6b7acf 627
66ef0471 628/**
629 * Computes then returns the percentage value of the grade value within the given range.
630 * @param float $gradeval
631 * @param float $grademin
632 * @param float $grademx
633 * @return float $percentage
634 */
635function grade_to_percentage($gradeval, $grademin, $grademax) {
636 if ($grademin >= $grademax) {
637 debugging("The minimum grade ($grademin) was higher than or equal to the maximum grade ($grademax)!!! Cannot proceed with computation.");
638 }
33a34cd4 639
640 // If given gradevalue is lower than grademin, adjust it to grademin
641 if ($gradeval < $grademin || empty($gradeval)) {
642 $gradeval = $grademin;
643 }
644
66ef0471 645 $offset_value = $gradeval - $grademin;
646 $offset_max = $grademax - $grademin;
647 $factor = 100 / $offset_max;
648 $percentage = $offset_value * $factor;
649 return $percentage;
650}
651
7a6b7acf 652/**
653 * This class represents a complete tree of categories, grade_items and final grades,
654 * organises as an array primarily, but which can also be converted to other formats.
655 * It has simple method calls with complex implementations, allowing for easy insertion,
656 * deletion and moving of items and categories within the tree.
657 */
658class grade_tree {
659
660 /**
661 * The basic representation of the tree as a hierarchical, 3-tiered array.
662 * @var object $top_element
663 */
664 var $top_element;
665
666 /**
667 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
668 * @var string $commonvars
669 */
670 var $commonvars;
671
672 /**
673 * 2D array of grade items and categories
674 */
675 var $levels;
676
2cc773f5 677 /**
678 * Course context
679 */
680 var $context;
681
7a6b7acf 682 /**
683 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
684 * objects for the given courseid. Full objects are instantiated.
685 * and renumbering.
686 * @param int $courseid
687 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
688 * @param boolean $category_grade_last category grade item is the last child
4faf5f99 689 * @param array $collapsed array of collapsed categories
7a6b7acf 690 */
aea4df41 691 function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
7a6b7acf 692 global $USER, $CFG;
693
694 $this->courseid = $courseid;
695 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
696 $this->levels = array();
2cc773f5 697 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
7a6b7acf 698
699 // get course grade tree
700 $this->top_element = grade_category::fetch_course_tree($courseid, true);
701
4faf5f99 702 // collapse the categories if requested
703 if (!empty($collapsed)) {
704 grade_tree::category_collapse($this->top_element, $collapsed);
705 }
706
aea4df41 707 // no otucomes if requested
708 if (!empty($nooutcomes)) {
709 grade_tree::no_outcomes($this->top_element);
710 }
711
4faf5f99 712 // move category item to last position in category
7a6b7acf 713 if ($category_grade_last) {
714 grade_tree::category_grade_last($this->top_element);
715 }
716
717 if ($fillers) {
718 // inject fake categories == fillers
719 grade_tree::inject_fillers($this->top_element, 0);
720 // add colspans to categories and fillers
721 grade_tree::inject_colspans($this->top_element);
722 }
723
724 grade_tree::fill_levels($this->levels, $this->top_element, 0);
725 }
726
4faf5f99 727 /**
728 * Static recursive helper - removes items from collapsed categories
729 * @static
730 * @param array $element The seed of the recursion
731 * @param array $collapsed array of collapsed categories
732 * @return void
733 */
734 function category_collapse(&$element, $collapsed) {
735 if ($element['type'] != 'category') {
736 return;
737 }
738 if (empty($element['children']) or count($element['children']) < 2) {
739 return;
740 }
741
384960dd 742 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 743 $category_item = reset($element['children']); //keep only category item
744 $element['children'] = array(key($element['children'])=>$category_item);
745
746 } else {
384960dd 747 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
748 reset($element['children']);
749 $first_key = key($element['children']);
750 unset($element['children'][$first_key]);
751 }
752 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 753 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
754 }
755 }
756 }
7a6b7acf 757
aea4df41 758 /**
759 * Static recursive helper - removes all outcomes
760 * @static
761 * @param array $element The seed of the recursion
762 * @return void
763 */
764 function no_outcomes(&$element) {
765 if ($element['type'] != 'category') {
766 return;
767 }
768 foreach ($element['children'] as $sortorder=>$child) {
769 if ($element['children'][$sortorder]['type'] == 'item'
770 and $element['children'][$sortorder]['object']->is_outcome_item()) {
771 unset($element['children'][$sortorder]);
772
d4795a07 773 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 774 grade_tree::no_outcomes($element['children'][$sortorder]);
775 }
776 }
777 }
778
7a6b7acf 779 /**
780 * Static recursive helper - makes the grade_item for category the last children
781 * @static
782 * @param array $element The seed of the recursion
783 * @return void
784 */
785 function category_grade_last(&$element) {
786 if (empty($element['children'])) {
787 return;
788 }
789 if (count($element['children']) < 2) {
790 return;
791 }
792 $category_item = reset($element['children']);
793 $order = key($element['children']);
794 unset($element['children'][$order]);
795 $element['children'][$order] =& $category_item;
796 foreach ($element['children'] as $sortorder=>$child) {
797 grade_tree::category_grade_last($element['children'][$sortorder]);
798 }
799 }
800
801 /**
802 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
803 * @static
804 * @param int $levels
805 * @param array $element The seed of the recursion
806 * @param int $depth
807 * @return void
808 */
809 function fill_levels(&$levels, &$element, $depth) {
810 if (!array_key_exists($depth, $levels)) {
811 $levels[$depth] = array();
812 }
813
814 // prepare unique identifier
815 if ($element['type'] == 'category') {
816 $element['eid'] = 'c'.$element['object']->id;
817 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
818 $element['eid'] = 'i'.$element['object']->id;
819 }
820
821 $levels[$depth][] =& $element;
822 $depth++;
823 if (empty($element['children'])) {
824 return;
825 }
826 $prev = 0;
827 foreach ($element['children'] as $sortorder=>$child) {
828 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
829 $element['children'][$sortorder]['prev'] = $prev;
830 $element['children'][$sortorder]['next'] = 0;
831 if ($prev) {
832 $element['children'][$prev]['next'] = $sortorder;
833 }
834 $prev = $sortorder;
835 }
836 }
837
838 /**
839 * Static recursive helper - makes full tree (all leafes are at the same level)
840 */
841 function inject_fillers(&$element, $depth) {
842 $depth++;
843
844 if (empty($element['children'])) {
845 return $depth;
846 }
847 $chdepths = array();
848 $chids = array_keys($element['children']);
849 $last_child = end($chids);
850 $first_child = reset($chids);
851
852 foreach ($chids as $chid) {
853 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
854 }
855 arsort($chdepths);
856
857 $maxdepth = reset($chdepths);
858 foreach ($chdepths as $chid=>$chd) {
859 if ($chd == $maxdepth) {
860 continue;
861 }
862 for ($i=0; $i < $maxdepth-$chd; $i++) {
863 if ($chid == $first_child) {
864 $type = 'fillerfirst';
865 } else if ($chid == $last_child) {
866 $type = 'fillerlast';
867 } else {
868 $type = 'filler';
869 }
870 $oldchild =& $element['children'][$chid];
871 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
872 }
873 }
874
875 return $maxdepth;
876 }
877
878 /**
879 * Static recursive helper - add colspan information into categories
880 */
881 function inject_colspans(&$element) {
882 if (empty($element['children'])) {
883 return 1;
884 }
885 $count = 0;
886 foreach ($element['children'] as $key=>$child) {
887 $count += grade_tree::inject_colspans($element['children'][$key]);
888 }
889 $element['colspan'] = $count;
890 return $count;
891 }
892
893 /**
894 * Parses the array in search of a given eid and returns a element object with
895 * information about the element it has found.
896 * @param int $eid
897 * @return object element
898 */
899 function locate_element($eid) {
d3c3da1b 900 // it is a grade - construct a new object
901 if (strpos($eid, 'n') === 0) {
902 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
903 return null;
904 }
905
906 $itemid = $matches[1];
907 $userid = $matches[2];
908
909 //extra security check - the grade item must be in this tree
910 if (!$item_el = $this->locate_element('i'.$itemid)) {
911 return null;
912 }
913
914 // $gradea->id may be null - means does not exist yet
915 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
916
917 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
918 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
919
920 } else if (strpos($eid, 'g') === 0) {
7a6b7acf 921 $id = (int)substr($eid, 1);
922 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
923 return null;
924 }
925 //extra security check - the grade item must be in this tree
926 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
927 return null;
928 }
929 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
930 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
931 }
932
933 // it is a category or item
934 foreach ($this->levels as $row) {
935 foreach ($row as $element) {
936 if ($element['type'] == 'filler') {
937 continue;
938 }
939 if ($element['eid'] == $eid) {
940 return $element;
941 }
942 }
943 }
944
945 return null;
946 }
947
d3c3da1b 948 /**
949 * Returns the grade eid - the grade may not exist yet.
950 * @param $grade_grade object
951 * @return string eid
952 */
953 function get_grade_eid($grade_grade) {
954 if (empty($grade_grade->id)) {
955 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
956 } else {
957 return 'g'.$grade_grade->id;
958 }
959 }
960
7a6b7acf 961 /**
962 * Return edit icon for give element
963 * @param object $element
964 * @return string
965 */
966 function get_edit_icon($element, $gpr) {
967 global $CFG;
968
2cc773f5 969 if (!has_capability('moodle/grade:manage', $this->context)) {
27b1735b 970 if ($element['type'] == 'grade' and has_capability('moodle/grade:override', $this->context)) {
971 // oki - let them override grade
972 } else {
973 return '';
974 }
7a6b7acf 975 }
976
2cc773f5 977 static $stredit = null;
978 if (is_null($stredit)) {
979 $stredit = get_string('edit');
980 }
981
7a6b7acf 982 $object = $element['object'];
2cc773f5 983 $overlib = '';
7a6b7acf 984
985 switch ($element['type']) {
986 case 'item':
987 case 'categoryitem':
988 case 'courseitem':
9988d1b7 989 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
78ad5f3f 990 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
f10fac96 991 } else {
78ad5f3f 992 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
f10fac96 993 }
7a6b7acf 994 $url = $gpr->add_url_params($url);
995 break;
996
997 case 'category':
78ad5f3f 998 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
7a6b7acf 999 $url = $gpr->add_url_params($url);
1000 break;
1001
1002 case 'grade':
d3c3da1b 1003 if (empty($object->id)) {
1004 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
1005 } else {
1006 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1007 }
7a6b7acf 1008 $url = $gpr->add_url_params($url);
2cc773f5 1009 if (!empty($object->feedback)) {
1010 $feedback = format_text($object->feedback, $object->feedbackformat);
1011 $function = "return overlib('".s(ltrim($object->feedback)."', FULLHTML);");
1012 $overlib = 'onmouseover="'.$function.'" onmouseout="return nd();"';
1013 }
7a6b7acf 1014 break;
1015
1016 default:
1017 $url = null;
1018 }
1019
1020 if ($url) {
2cc773f5 1021 return '<a href="'.$url.'"><img '.$overlib.' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$stredit.'" title="'.$stredit.'"/></a>';
7a6b7acf 1022
1023 } else {
1024 return '';
1025 }
1026 }
1027
1028 /**
1029 * Return hiding icon for give element
1030 * @param object $element
1031 * @return string
1032 */
1033 function get_hiding_icon($element, $gpr) {
1034 global $CFG;
1035
2cc773f5 1036 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
7a6b7acf 1037 return '';
1038 }
1039
2cc773f5 1040 static $strshow = null;
1041 static $strhide = null;
1042 if (is_null($strshow)) {
7a6b7acf 1043 $strshow = get_string('show');
2cc773f5 1044 $strhide = get_string('hide');
1045 }
1046
1047 if ($element['object']->is_hidden()) {
d4795a07 1048 $icon = 'show';
1049 $tooltip = '';
1050
f60c61b1 1051 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
d4795a07 1052 $icon = 'hiddenuntil';
c30fafbf 1053 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
d4795a07 1054 }
1055
1056 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1057 . '&amp;eid='.$element['eid'];
7a6b7acf 1058 $url = $gpr->add_url_params($url);
d4795a07 1059 $action = '<a href="'.$url.'"><img title="' . $tooltip . '" src="'.$CFG->pixpath.'/t/' . $icon . '.gif" class="iconsmall" alt="'
1060 . $strshow.'" title="'.$strshow.'"/></a>';
7a6b7acf 1061
1062 } else {
d4795a07 1063 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1064 . '&amp;eid='.$element['eid'];
7a6b7acf 1065 $url = $gpr->add_url_params($url);
1066 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.$strhide.'" title="'.$strhide.'"/></a>';
1067 }
1068 return $action;
1069 }
1070
1071 /**
1072 * Return locking icon for give element
1073 * @param object $element
1074 * @return string
1075 */
1076 function get_locking_icon($element, $gpr) {
1077 global $CFG;
1078
2cc773f5 1079 static $strunlock = null;
1080 static $strlock = null;
1081 if (is_null($strunlock)) {
1082 $strunlock = get_string('unlock', 'grades');
1083 $strlock = get_string('lock', 'grades');
1084 }
7a6b7acf 1085
1086 if ($element['object']->is_locked()) {
d4795a07 1087 $icon = 'unlock';
1088 $tooltip = '';
1089
fb0e3570 1090 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
d4795a07 1091 $icon = 'locktime';
c30fafbf 1092 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
d4795a07 1093 }
1094
2cc773f5 1095 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
7a6b7acf 1096 return '';
1097 }
d4795a07 1098 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1099 . '&amp;eid='.$element['eid'];
7a6b7acf 1100 $url = $gpr->add_url_params($url);
d4795a07 1101 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/' . $icon . '.gif" title="' . $tooltip
1102 . '" class="iconsmall" alt="'.$strunlock
1103 . '" title="'.$strunlock.'"/></a>';
7a6b7acf 1104
1105 } else {
2cc773f5 1106 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
7a6b7acf 1107 return '';
1108 }
d4795a07 1109 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1110 . '&amp;eid='.$element['eid'];
7a6b7acf 1111 $url = $gpr->add_url_params($url);
d4795a07 1112 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.$strlock.'" title="'
1113 . $strlock.'"/></a>';
7a6b7acf 1114 }
1115 return $action;
1116 }
1117
2cc773f5 1118 /**
1119 * Return calculation icon for given element
1120 * @param object $element
1121 * @return string
1122 */
1123 function get_calculation_icon($element, $gpr) {
1124 global $CFG;
1125 if (!has_capability('moodle/grade:manage', $this->context)) {
1126 return '';
1127 }
1128
1129 $calculation_icon = '';
1130
1131 $type = $element['type'];
1132 $object = $element['object'];
1133
1134 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1135 $streditcalculation = get_string('editcalculation', 'grades');
1136
1137 // show calculation icon only when calculation possible
9127bc5d 1138 if ((!$object->is_normal_item() or $object->is_outcome_item())
1139 and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
78ad5f3f 1140 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
2cc773f5 1141 $url = $gpr->add_url_params($url);
1142 $calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/calc.gif" class="iconsmall" alt="'
1143 . $streditcalculation.'" title="'.$streditcalculation.'" /></a>'. "\n";
1144 }
1145 }
1146
1147 return $calculation_icon;
1148 }
7a6b7acf 1149}
1150
e2008be2 1151?>