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