MDL-11543 Printing nice list of categories for parent category drop-down
[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)
9376f5a6 287 or has_capability('moodle/grade:manageletters', $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 }
284abb09 320
9376f5a6 321 if (has_capability('moodle/grade:manage', $context) or has_capability('moodle/grade:manageletters', $context)) {
284abb09 322 $url = 'edit/letter/index.php?id='.$courseid;
323 if ($active_type == 'edit' and $active_plugin == 'letter' ) {
324 $active = $url;
325 }
326 $menu[$url] = get_string('letters', 'grades');
327 }
328
e0724506 329 if (has_capability('moodle/grade:manage', $context)) {
330 $url = 'edit/settings/index.php?id='.$courseid;
331 if ($active_type == 'edit' and $active_plugin == 'settings' ) {
332 $active = $url;
333 }
334 $menu[$url] = get_string('coursesettings', 'grades');
335 }
336
281ffa4a 337 }
338
3af29899 339/// finally print/return the popup form
0c811aa7 340 return popup_form($CFG->wwwroot.'/grade/', $menu, 'choosepluginreport', $active, 'choose', '', '', $return, 'self', get_string('view'));
cbff94ba 341}
342
0610812a 343/**
7a6b7acf 344 * Utility class used for return tracking when using edit and other forms in grade plugins
0610812a 345 */
3af29899 346class grade_plugin_return {
347 var $type;
348 var $plugin;
349 var $courseid;
350 var $userid;
351 var $page;
281ffa4a 352
0610812a 353 /**
354 * Constructor
355 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
356 */
3af29899 357 function grade_plugin_return ($params=null) {
358 if (empty($params)) {
359 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
360 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
361 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
362 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
363 $this->page = optional_param('gpr_page', null, PARAM_INT);
a983b6ec 364
a983b6ec 365 } else {
3af29899 366 foreach ($params as $key=>$value) {
367 if (array_key_exists($key, $this)) {
368 $this->$key = $value;
369 }
cbff94ba 370 }
371 }
6cd8c592 372 }
373
0610812a 374 /**
375 * Returns return parameters as options array suitable for buttons.
376 * @return array options
377 */
3af29899 378 function get_options() {
7a6b7acf 379 if (empty($this->type)) {
3af29899 380 return array();
865e9a82 381 }
6cd8c592 382
3af29899 383 $params = array();
6cd8c592 384
7a6b7acf 385 if (!empty($this->plugin)) {
386 $params['plugin'] = $this->plugin;
387 }
6cd8c592 388
3af29899 389 if (!empty($this->courseid)) {
390 $params['id'] = $this->courseid;
6cd8c592 391 }
9c61ba4d 392
3af29899 393 if (!empty($this->userid)) {
394 $params['userid'] = $this->userid;
9c61ba4d 395 }
9c61ba4d 396
3af29899 397 if (!empty($this->page)) {
398 $params['page'] = $this->page;
cbff94ba 399 }
865e9a82 400
3af29899 401 return $params;
cbff94ba 402 }
cbff94ba 403
0610812a 404 /**
405 * Returns return url
406 * @param string $default default url when params not set
407 * @return string url
408 */
65dd61bd 409 function get_return_url($default, $extras=null) {
3af29899 410 global $CFG;
cbff94ba 411
3af29899 412 if (empty($this->type) or empty($this->plugin)) {
413 return $default;
cbff94ba 414 }
415
65dd61bd 416 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
417 $glue = '?';
cbff94ba 418
3af29899 419 if (!empty($this->courseid)) {
420 $url .= $glue.'id='.$this->courseid;
421 $glue = '&amp;';
cbff94ba 422 }
cbff94ba 423
3af29899 424 if (!empty($this->userid)) {
425 $url .= $glue.'userid='.$this->userid;
426 $glue = '&amp;';
cbff94ba 427 }
7e2d7c92 428
3af29899 429 if (!empty($this->page)) {
430 $url .= $glue.'page='.$this->page;
65dd61bd 431 $glue = '&amp;';
432 }
433
434 if (!empty($extras)) {
435 foreach($extras as $key=>$value) {
436 $url .= $glue.$key.'='.$value;
437 $glue = '&amp;';
7a6b7acf 438 }
cbff94ba 439 }
cbff94ba 440
3af29899 441 return $url;
cbff94ba 442 }
cbff94ba 443
0610812a 444 /**
445 * Returns string with hidden return tracking form elements.
446 * @return string
447 */
3af29899 448 function get_form_fields() {
7a6b7acf 449 if (empty($this->type)) {
3af29899 450 return '';
cbff94ba 451 }
cbff94ba 452
3af29899 453 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 454
455 if (!empty($this->plugin)) {
456 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
457 }
0ca5abd6 458
3af29899 459 if (!empty($this->courseid)) {
460 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 461 }
cbff94ba 462
3af29899 463 if (!empty($this->userid)) {
464 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 465 }
cbff94ba 466
3af29899 467 if (!empty($this->page)) {
468 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 469 }
470 }
cbff94ba 471
0610812a 472 /**
473 * Add hidden elements into mform
474 * @param object $mform moodle form object
475 * @return void
476 */
3af29899 477 function add_mform_elements(&$mform) {
7a6b7acf 478 if (empty($this->type)) {
3af29899 479 return;
cbff94ba 480 }
cbff94ba 481
3af29899 482 $mform->addElement('hidden', 'gpr_type', $this->type);
483 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 484
7a6b7acf 485 if (!empty($this->plugin)) {
486 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
487 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
488 }
97033c86 489
3af29899 490 if (!empty($this->courseid)) {
491 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
492 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 493 }
cbff94ba 494
3af29899 495 if (!empty($this->userid)) {
496 $mform->addElement('hidden', 'gpr_userid', $this->userid);
497 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 498 }
cbff94ba 499
3af29899 500 if (!empty($this->page)) {
501 $mform->addElement('hidden', 'gpr_page', $this->page);
502 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 503 }
504 }
281ffa4a 505
0610812a 506 /**
507 * Add return tracking params into url
508 * @param string $url
509 * @return string $url with erturn tracking params
510 */
3af29899 511 function add_url_params($url) {
7a6b7acf 512 if (empty($this->type)) {
3af29899 513 return $url;
cbff94ba 514 }
5609f9e6 515
3af29899 516 if (strpos($url, '?') === false) {
517 $url .= '?gpr_type='.$this->type;
518 } else {
519 $url .= '&amp;gpr_type='.$this->type;
cbff94ba 520 }
cbff94ba 521
7a6b7acf 522 if (!empty($this->plugin)) {
523 $url .= '&amp;gpr_plugin='.$this->plugin;
524 }
cbff94ba 525
3af29899 526 if (!empty($this->courseid)) {
527 $url .= '&amp;gpr_courseid='.$this->courseid;
cbff94ba 528 }
cbff94ba 529
3af29899 530 if (!empty($this->userid)) {
531 $url .= '&amp;gpr_userid='.$this->userid;
cbff94ba 532 }
0a8a95c9 533
3af29899 534 if (!empty($this->page)) {
535 $url .= '&amp;gpr_page='.$this->page;
0a8a95c9 536 }
5a412dbf 537
3af29899 538 return $url;
5a412dbf 539 }
5a412dbf 540}
7a6b7acf 541
826c5f86 542/**
543 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
544 * @param string $path The path of the calling script (using __FILE__?)
545 * @param string $pagename The language string to use as the last part of the navigation (non-link)
546 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
547 * @return string
548 */
549function grade_build_nav($path, $pagename=null, $id=null) {
550 global $CFG, $COURSE;
551
552 $strgrades = get_string('grades', 'grades');
553
554 // Parse the path and build navlinks from its elements
555 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
556 $path = substr($path, $dirroot_length);
557 $path = str_replace('\\', '/', $path);
558
559 $path_elements = explode('/', $path);
560
561 $path_elements_count = count($path_elements);
562
826c5f86 563 // First link is always 'grade'
564 $navlinks = array();
565 $navlinks[] = array('name' => $strgrades,
566 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
567 'type' => 'misc');
568
569 $link = '';
570 $numberofelements = 3;
571
572 // Prepare URL params string
573 $id_string = '?';
574 if (!is_null($id)) {
575 if (is_array($id)) {
576 foreach ($id as $idkey => $idvalue) {
577 $id_string .= "$idkey=$idvalue&amp;";
578 }
579 } else {
580 $id_string .= "id=$id";
581 }
582 }
583
584 $navlink4 = null;
585
0f78c4de 586 // Remove file extensions from filenames
587 foreach ($path_elements as $key => $filename) {
588 $path_elements[$key] = str_replace('.php', '', $filename);
589 }
590
826c5f86 591 // Second level links
592 switch ($path_elements[1]) {
593 case 'edit': // No link
594 if ($path_elements[3] != 'index.php') {
595 $numberofelements = 4;
596 }
597 break;
598 case 'import': // No link
599 break;
600 case 'export': // No link
601 break;
602 case 'report':
603 // $id is required for this link. Do not print it if $id isn't given
604 if (!is_null($id)) {
605 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
606 }
607
608 if ($path_elements[2] == 'grader') {
609 $numberofelements = 4;
610 }
611 break;
612
613 default:
614 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
615 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
616 return false;
617 }
618
619 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
620
621 // Third level links
622 if (empty($pagename)) {
623 $pagename = get_string($path_elements[2], 'grades');
624 }
625
626 switch ($numberofelements) {
627 case 3:
628 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
629 break;
630 case 4:
631
632 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
3cf6a6d5 633 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
826c5f86 634 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
635 'type' => 'misc');
636 }
637 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
638 break;
639 }
640 $navigation = build_navigation($navlinks);
641
642 return $navigation;
d4795a07 643}
7a6b7acf 644
66ef0471 645/**
646 * Computes then returns the percentage value of the grade value within the given range.
647 * @param float $gradeval
648 * @param float $grademin
649 * @param float $grademx
650 * @return float $percentage
651 */
652function grade_to_percentage($gradeval, $grademin, $grademax) {
653 if ($grademin >= $grademax) {
654 debugging("The minimum grade ($grademin) was higher than or equal to the maximum grade ($grademax)!!! Cannot proceed with computation.");
655 }
33a34cd4 656
657 // If given gradevalue is lower than grademin, adjust it to grademin
658 if ($gradeval < $grademin || empty($gradeval)) {
659 $gradeval = $grademin;
660 }
661
66ef0471 662 $offset_value = $gradeval - $grademin;
663 $offset_max = $grademax - $grademin;
664 $factor = 100 / $offset_max;
665 $percentage = $offset_value * $factor;
666 return $percentage;
667}
668
e98871a2 669/**
670 * Flat structure similar to grade tree.
671 */
672class grade_seq {
673
674 /**
675 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
676 * @var string $commonvars
677 */
678 var $commonvars;
679
680 /**
681 * 1D array of grade items only
682 */
683 var $items;
684
685 /**
686 * Course context
687 */
688 var $context;
689
690 /**
691 * Constructor, retrieves and stores array of all grade_category and grade_item
692 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
693 * @param int $courseid
694 * @param boolean $category_grade_last category grade item is the last child
695 * @param array $collapsed array of collapsed categories
696 */
697 function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
698 global $USER, $CFG;
699
700 $this->courseid = $courseid;
701 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
702 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
703
704 // get course grade tree
705 $top_element = grade_category::fetch_course_tree($courseid, true);
706
707 $this->items = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
708 }
709
710 /**
711 * Static recursive helper - makes the grade_item for category the last children
712 * @static
713 * @param array $element The seed of the recursion
714 * @return void
715 */
716 function flatten(&$element, $category_grade_last, $nooutcomes) {
717 if (empty($element['children'])) {
718 return array();
719 }
720 $children = array();
721
722 foreach ($element['children'] as $sortorder=>$unused) {
723 if ($nooutcomes and $element['type'] != 'category' and $element['children'][$sortorder]['object']->is_outcome_item()) {
724 continue;
725 }
726 $children[] = $element['children'][$sortorder];
727 }
728 unset($element['children']);
729
730 if ($category_grade_last and count($children) > 1) {
731 $cat_item = array_shift($children);
732 array_push($children, $cat_item);
733 }
734
735 $result = array();
736 foreach ($children as $child) {
e0724506 737 if ($child['type'] == 'category') {
e98871a2 738 $result = array_merge($result, grade_seq::flatten($child, $category_grade_last, $nooutcomes));
739 } else {
740 $child['eid'] = 'i'.$child['object']->id;
741 $result[] = $child;
742 }
743 }
744
745 return $result;
746 }
747
748 /**
749 * Parses the array in search of a given eid and returns a element object with
750 * information about the element it has found.
751 * @param int $eid
752 * @return object element
753 */
754 function locate_element($eid) {
755 // it is a grade - construct a new object
756 if (strpos($eid, 'n') === 0) {
757 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
758 return null;
759 }
760
761 $itemid = $matches[1];
762 $userid = $matches[2];
763
764 //extra security check - the grade item must be in this tree
765 if (!$item_el = $this->locate_element('i'.$itemid)) {
766 return null;
767 }
768
769 // $gradea->id may be null - means does not exist yet
770 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
771
772 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
773 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
774
775 } else if (strpos($eid, 'g') === 0) {
776 $id = (int)substr($eid, 1);
777 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
778 return null;
779 }
780 //extra security check - the grade item must be in this tree
781 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
782 return null;
783 }
784 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
785 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
786 }
787
788 // it is a category or item
789 foreach ($this->items as $element) {
790 if ($element['eid'] == $eid) {
791 return $element;
792 }
793 }
794
795 return null;
796 }
797
798 /**
799 * Returns the grade eid - the grade may not exist yet.
800 * @param $grade_grade object
801 * @return string eid
802 */
803 function get_grade_eid($grade_grade) {
804 if (empty($grade_grade->id)) {
805 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
806 } else {
807 return 'g'.$grade_grade->id;
808 }
809 }
810
811}
812
7a6b7acf 813/**
814 * This class represents a complete tree of categories, grade_items and final grades,
815 * organises as an array primarily, but which can also be converted to other formats.
816 * It has simple method calls with complex implementations, allowing for easy insertion,
817 * deletion and moving of items and categories within the tree.
818 */
819class grade_tree {
820
821 /**
822 * The basic representation of the tree as a hierarchical, 3-tiered array.
823 * @var object $top_element
824 */
825 var $top_element;
826
827 /**
828 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
829 * @var string $commonvars
830 */
831 var $commonvars;
832
833 /**
834 * 2D array of grade items and categories
835 */
836 var $levels;
837
2cc773f5 838 /**
839 * Course context
840 */
841 var $context;
842
7a6b7acf 843 /**
844 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 845 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
7a6b7acf 846 * @param int $courseid
847 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
848 * @param boolean $category_grade_last category grade item is the last child
4faf5f99 849 * @param array $collapsed array of collapsed categories
7a6b7acf 850 */
aea4df41 851 function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
7a6b7acf 852 global $USER, $CFG;
853
854 $this->courseid = $courseid;
855 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
856 $this->levels = array();
2cc773f5 857 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
7a6b7acf 858
859 // get course grade tree
860 $this->top_element = grade_category::fetch_course_tree($courseid, true);
861
4faf5f99 862 // collapse the categories if requested
863 if (!empty($collapsed)) {
864 grade_tree::category_collapse($this->top_element, $collapsed);
865 }
866
aea4df41 867 // no otucomes if requested
868 if (!empty($nooutcomes)) {
869 grade_tree::no_outcomes($this->top_element);
870 }
871
4faf5f99 872 // move category item to last position in category
7a6b7acf 873 if ($category_grade_last) {
874 grade_tree::category_grade_last($this->top_element);
875 }
876
877 if ($fillers) {
878 // inject fake categories == fillers
879 grade_tree::inject_fillers($this->top_element, 0);
880 // add colspans to categories and fillers
881 grade_tree::inject_colspans($this->top_element);
882 }
883
884 grade_tree::fill_levels($this->levels, $this->top_element, 0);
885 }
886
4faf5f99 887 /**
888 * Static recursive helper - removes items from collapsed categories
889 * @static
890 * @param array $element The seed of the recursion
891 * @param array $collapsed array of collapsed categories
892 * @return void
893 */
894 function category_collapse(&$element, $collapsed) {
895 if ($element['type'] != 'category') {
896 return;
897 }
898 if (empty($element['children']) or count($element['children']) < 2) {
899 return;
900 }
901
384960dd 902 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 903 $category_item = reset($element['children']); //keep only category item
904 $element['children'] = array(key($element['children'])=>$category_item);
905
906 } else {
384960dd 907 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
908 reset($element['children']);
909 $first_key = key($element['children']);
910 unset($element['children'][$first_key]);
911 }
912 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 913 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
914 }
915 }
916 }
7a6b7acf 917
aea4df41 918 /**
919 * Static recursive helper - removes all outcomes
920 * @static
921 * @param array $element The seed of the recursion
922 * @return void
923 */
924 function no_outcomes(&$element) {
925 if ($element['type'] != 'category') {
926 return;
927 }
928 foreach ($element['children'] as $sortorder=>$child) {
929 if ($element['children'][$sortorder]['type'] == 'item'
930 and $element['children'][$sortorder]['object']->is_outcome_item()) {
931 unset($element['children'][$sortorder]);
932
d4795a07 933 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 934 grade_tree::no_outcomes($element['children'][$sortorder]);
935 }
936 }
937 }
938
7a6b7acf 939 /**
940 * Static recursive helper - makes the grade_item for category the last children
941 * @static
942 * @param array $element The seed of the recursion
943 * @return void
944 */
945 function category_grade_last(&$element) {
946 if (empty($element['children'])) {
947 return;
948 }
949 if (count($element['children']) < 2) {
950 return;
951 }
3e0e2436 952 $first_item = reset($element['children']);
4a3dfd9a 953 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 954 // the category item might have been already removed
955 $order = key($element['children']);
956 unset($element['children'][$order]);
957 $element['children'][$order] =& $first_item;
958 }
206f9953 959 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 960 grade_tree::category_grade_last($element['children'][$sortorder]);
961 }
962 }
963
964 /**
965 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
966 * @static
967 * @param int $levels
968 * @param array $element The seed of the recursion
969 * @param int $depth
970 * @return void
971 */
972 function fill_levels(&$levels, &$element, $depth) {
973 if (!array_key_exists($depth, $levels)) {
974 $levels[$depth] = array();
975 }
976
977 // prepare unique identifier
978 if ($element['type'] == 'category') {
979 $element['eid'] = 'c'.$element['object']->id;
980 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
981 $element['eid'] = 'i'.$element['object']->id;
982 }
983
984 $levels[$depth][] =& $element;
985 $depth++;
986 if (empty($element['children'])) {
987 return;
988 }
989 $prev = 0;
990 foreach ($element['children'] as $sortorder=>$child) {
991 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
992 $element['children'][$sortorder]['prev'] = $prev;
993 $element['children'][$sortorder]['next'] = 0;
994 if ($prev) {
995 $element['children'][$prev]['next'] = $sortorder;
996 }
997 $prev = $sortorder;
998 }
999 }
1000
1001 /**
1002 * Static recursive helper - makes full tree (all leafes are at the same level)
1003 */
1004 function inject_fillers(&$element, $depth) {
1005 $depth++;
1006
1007 if (empty($element['children'])) {
1008 return $depth;
1009 }
1010 $chdepths = array();
1011 $chids = array_keys($element['children']);
1012 $last_child = end($chids);
1013 $first_child = reset($chids);
1014
1015 foreach ($chids as $chid) {
1016 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1017 }
1018 arsort($chdepths);
1019
1020 $maxdepth = reset($chdepths);
1021 foreach ($chdepths as $chid=>$chd) {
1022 if ($chd == $maxdepth) {
1023 continue;
1024 }
1025 for ($i=0; $i < $maxdepth-$chd; $i++) {
1026 if ($chid == $first_child) {
1027 $type = 'fillerfirst';
1028 } else if ($chid == $last_child) {
1029 $type = 'fillerlast';
1030 } else {
1031 $type = 'filler';
1032 }
1033 $oldchild =& $element['children'][$chid];
1034 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
1035 }
1036 }
1037
1038 return $maxdepth;
1039 }
1040
1041 /**
1042 * Static recursive helper - add colspan information into categories
1043 */
1044 function inject_colspans(&$element) {
1045 if (empty($element['children'])) {
1046 return 1;
1047 }
1048 $count = 0;
1049 foreach ($element['children'] as $key=>$child) {
1050 $count += grade_tree::inject_colspans($element['children'][$key]);
1051 }
1052 $element['colspan'] = $count;
1053 return $count;
1054 }
1055
1056 /**
1057 * Parses the array in search of a given eid and returns a element object with
1058 * information about the element it has found.
1059 * @param int $eid
1060 * @return object element
1061 */
1062 function locate_element($eid) {
d3c3da1b 1063 // it is a grade - construct a new object
1064 if (strpos($eid, 'n') === 0) {
1065 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1066 return null;
1067 }
1068
1069 $itemid = $matches[1];
1070 $userid = $matches[2];
1071
1072 //extra security check - the grade item must be in this tree
1073 if (!$item_el = $this->locate_element('i'.$itemid)) {
1074 return null;
1075 }
1076
1077 // $gradea->id may be null - means does not exist yet
1078 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1079
1080 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1081 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1082
1083 } else if (strpos($eid, 'g') === 0) {
7a6b7acf 1084 $id = (int)substr($eid, 1);
1085 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1086 return null;
1087 }
1088 //extra security check - the grade item must be in this tree
1089 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1090 return null;
1091 }
1092 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1093 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1094 }
1095
1096 // it is a category or item
1097 foreach ($this->levels as $row) {
1098 foreach ($row as $element) {
1099 if ($element['type'] == 'filler') {
1100 continue;
1101 }
1102 if ($element['eid'] == $eid) {
1103 return $element;
1104 }
1105 }
1106 }
1107
1108 return null;
1109 }
1110
d3c3da1b 1111 /**
1112 * Returns the grade eid - the grade may not exist yet.
1113 * @param $grade_grade object
1114 * @return string eid
1115 */
1116 function get_grade_eid($grade_grade) {
1117 if (empty($grade_grade->id)) {
1118 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1119 } else {
1120 return 'g'.$grade_grade->id;
1121 }
1122 }
1123
7a6b7acf 1124 /**
1125 * Return edit icon for give element
1126 * @param object $element
1127 * @return string
1128 */
1129 function get_edit_icon($element, $gpr) {
1130 global $CFG;
1131
2cc773f5 1132 if (!has_capability('moodle/grade:manage', $this->context)) {
a5b8be62 1133 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
27b1735b 1134 // oki - let them override grade
1135 } else {
1136 return '';
1137 }
7a6b7acf 1138 }
1139
2cc773f5 1140 static $stredit = null;
1141 if (is_null($stredit)) {
1142 $stredit = get_string('edit');
1143 }
1144
7a6b7acf 1145 $object = $element['object'];
2cc773f5 1146 $overlib = '';
7a6b7acf 1147
1148 switch ($element['type']) {
1149 case 'item':
1150 case 'categoryitem':
1151 case 'courseitem':
9988d1b7 1152 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
78ad5f3f 1153 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
f10fac96 1154 } else {
78ad5f3f 1155 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
f10fac96 1156 }
7a6b7acf 1157 $url = $gpr->add_url_params($url);
1158 break;
1159
1160 case 'category':
78ad5f3f 1161 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
7a6b7acf 1162 $url = $gpr->add_url_params($url);
1163 break;
1164
1165 case 'grade':
d3c3da1b 1166 if (empty($object->id)) {
1167 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
1168 } else {
1169 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1170 }
7a6b7acf 1171 $url = $gpr->add_url_params($url);
2cc773f5 1172 if (!empty($object->feedback)) {
1173 $feedback = format_text($object->feedback, $object->feedbackformat);
1174 $function = "return overlib('".s(ltrim($object->feedback)."', FULLHTML);");
1175 $overlib = 'onmouseover="'.$function.'" onmouseout="return nd();"';
1176 }
7a6b7acf 1177 break;
1178
1179 default:
1180 $url = null;
1181 }
1182
1183 if ($url) {
2cc773f5 1184 return '<a href="'.$url.'"><img '.$overlib.' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$stredit.'" title="'.$stredit.'"/></a>';
7a6b7acf 1185
1186 } else {
1187 return '';
1188 }
1189 }
1190
1191 /**
1192 * Return hiding icon for give element
1193 * @param object $element
1194 * @return string
1195 */
1196 function get_hiding_icon($element, $gpr) {
1197 global $CFG;
1198
2cc773f5 1199 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
7a6b7acf 1200 return '';
1201 }
1202
2cc773f5 1203 static $strshow = null;
1204 static $strhide = null;
1205 if (is_null($strshow)) {
7a6b7acf 1206 $strshow = get_string('show');
2cc773f5 1207 $strhide = get_string('hide');
1208 }
1209
1210 if ($element['object']->is_hidden()) {
d4795a07 1211 $icon = 'show';
9a9b5011 1212 $tooltip = $strshow;
d4795a07 1213
f60c61b1 1214 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
d4795a07 1215 $icon = 'hiddenuntil';
c30fafbf 1216 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
d4795a07 1217 }
1218
1219 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1220 . '&amp;eid='.$element['eid'];
7a6b7acf 1221 $url = $gpr->add_url_params($url);
9a9b5011 1222 $action = '<a href="'.$url.'"><img alt="'.$strshow.'" src="'.$CFG->pixpath.'/t/'.$icon.'.gif" class="iconsmall" title="'.$tooltip.'"/></a>';
7a6b7acf 1223
1224 } else {
d4795a07 1225 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1226 . '&amp;eid='.$element['eid'];
7a6b7acf 1227 $url = $gpr->add_url_params($url);
1228 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.$strhide.'" title="'.$strhide.'"/></a>';
1229 }
1230 return $action;
1231 }
1232
1233 /**
1234 * Return locking icon for give element
1235 * @param object $element
1236 * @return string
1237 */
1238 function get_locking_icon($element, $gpr) {
1239 global $CFG;
1240
2cc773f5 1241 static $strunlock = null;
1242 static $strlock = null;
1243 if (is_null($strunlock)) {
1244 $strunlock = get_string('unlock', 'grades');
1245 $strlock = get_string('lock', 'grades');
1246 }
7a6b7acf 1247
1248 if ($element['object']->is_locked()) {
d4795a07 1249 $icon = 'unlock';
9a9b5011 1250 $tooltip = $strunlock;
d4795a07 1251
fb0e3570 1252 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
d4795a07 1253 $icon = 'locktime';
c30fafbf 1254 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
d4795a07 1255 }
1256
2cc773f5 1257 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
7a6b7acf 1258 return '';
1259 }
d4795a07 1260 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1261 . '&amp;eid='.$element['eid'];
7a6b7acf 1262 $url = $gpr->add_url_params($url);
9a9b5011 1263 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/'.$icon.'.gif" alt="'.$strunlock.'" class="iconsmall" title="'.$tooltip.'"/></a>';
7a6b7acf 1264
1265 } else {
2cc773f5 1266 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
7a6b7acf 1267 return '';
1268 }
d4795a07 1269 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1270 . '&amp;eid='.$element['eid'];
7a6b7acf 1271 $url = $gpr->add_url_params($url);
d4795a07 1272 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.$strlock.'" title="'
1273 . $strlock.'"/></a>';
7a6b7acf 1274 }
1275 return $action;
1276 }
1277
2cc773f5 1278 /**
1279 * Return calculation icon for given element
1280 * @param object $element
1281 * @return string
1282 */
1283 function get_calculation_icon($element, $gpr) {
1284 global $CFG;
1285 if (!has_capability('moodle/grade:manage', $this->context)) {
1286 return '';
1287 }
1288
1289 $calculation_icon = '';
1290
1291 $type = $element['type'];
1292 $object = $element['object'];
1293
1294 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1295 $streditcalculation = get_string('editcalculation', 'grades');
1296
1297 // show calculation icon only when calculation possible
9127bc5d 1298 if ((!$object->is_normal_item() or $object->is_outcome_item())
1299 and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
78ad5f3f 1300 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
2cc773f5 1301 $url = $gpr->add_url_params($url);
1302 $calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/calc.gif" class="iconsmall" alt="'
1303 . $streditcalculation.'" title="'.$streditcalculation.'" /></a>'. "\n";
1304 }
1305 }
1306
1307 return $calculation_icon;
1308 }
7a6b7acf 1309}
1310
e2008be2 1311?>