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