MDL-20138 - convert & to ampersand symbol in Grades tooltip (for simple and full...
[moodle.git] / grade / lib.php
blob558c2f669741c356b4a497950e13d61e0771344a
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 require_once $CFG->libdir.'/gradelib.php';
20 /**
21 * This class iterates over all users that are graded in a course.
22 * Returns detailed info about users and their grades.
24 class graded_users_iterator {
25 var $course;
26 var $grade_items;
27 var $groupid;
28 var $users_rs;
29 var $grades_rs;
30 var $gradestack;
31 var $sortfield1;
32 var $sortorder1;
33 var $sortfield2;
34 var $sortorder2;
36 /**
37 * Constructor
38 * @param $course object
39 * @param array grade_items array of grade items, if not specified only user info returned
40 * @param int $groupid iterate only group users if present
41 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
42 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
43 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
44 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
46 function graded_users_iterator($course, $grade_items=null, $groupid=0, $sortfield1='lastname', $sortorder1='ASC', $sortfield2='firstname', $sortorder2='ASC') {
47 $this->course = $course;
48 $this->grade_items = $grade_items;
49 $this->groupid = $groupid;
50 $this->sortfield1 = $sortfield1;
51 $this->sortorder1 = $sortorder1;
52 $this->sortfield2 = $sortfield2;
53 $this->sortorder2 = $sortorder2;
55 $this->gradestack = array();
58 /**
59 * Initialise the iterator
60 * @return boolean success
62 function init() {
63 global $CFG;
65 $this->close();
67 grade_regrade_final_grades($this->course->id);
68 $course_item = grade_item::fetch_course_item($this->course->id);
69 if ($course_item->needsupdate) {
70 // can not calculate all final grades - sorry
71 return false;
74 if (strpos($CFG->gradebookroles, ',') === false) {
75 $gradebookroles = " = {$CFG->gradebookroles}";
76 } else {
77 $gradebookroles = " IN ({$CFG->gradebookroles})";
80 $relatedcontexts = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $this->course->id));
82 if ($this->groupid) {
83 $groupsql = "INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id";
84 $groupwheresql = "AND gm.groupid = {$this->groupid}";
85 } else {
86 $groupsql = "";
87 $groupwheresql = "";
90 if (empty($this->sortfield1)) {
91 // we must do some sorting even if not specified
92 $ofields = ", u.id AS usrt";
93 $order = "usrt ASC";
95 } else {
96 $ofields = ", u.$this->sortfield1 AS usrt1";
97 $order = "usrt1 $this->sortorder1";
98 if (!empty($this->sortfield2)) {
99 $ofields .= ", u.$this->sortfield2 AS usrt2";
100 $order .= ", usrt2 $this->sortorder2";
102 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
103 // user order MUST be the same in both queries, must include the only unique user->id if not already present
104 $ofields .= ", u.id AS usrt";
105 $order .= ", usrt ASC";
109 $users_sql = "SELECT u.* $ofields
110 FROM {$CFG->prefix}user u
111 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
112 $groupsql
113 WHERE ra.roleid $gradebookroles
114 AND ra.contextid $relatedcontexts
115 $groupwheresql
116 ORDER BY $order";
118 $this->users_rs = get_recordset_sql($users_sql);
120 if (!empty($this->grade_items)) {
121 $itemids = array_keys($this->grade_items);
122 $itemids = implode(',', $itemids);
124 $grades_sql = "SELECT g.* $ofields
125 FROM {$CFG->prefix}grade_grades g
126 INNER JOIN {$CFG->prefix}user u ON g.userid = u.id
127 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
128 $groupsql
129 WHERE ra.roleid $gradebookroles
130 AND ra.contextid $relatedcontexts
131 AND g.itemid IN ($itemids)
132 $groupwheresql
133 ORDER BY $order, g.itemid ASC";
134 $this->grades_rs = get_recordset_sql($grades_sql);
135 } else {
136 $this->grades_rs = false;
139 return true;
143 * Returns information about the next user
144 * @return mixed array of user info, all grades and feedback or null when no more users found
146 function next_user() {
147 if (!$this->users_rs) {
148 return false; // no users present
151 if (!$user = rs_fetch_next_record($this->users_rs)) {
152 if ($current = $this->_pop()) {
153 // this is not good - user or grades updated between the two reads above :-(
156 return false; // no more users
159 // find grades of this user
160 $grade_records = array();
161 while (true) {
162 if (!$current = $this->_pop()) {
163 break; // no more grades
166 if ($current->userid != $user->id) {
167 // grade of the next user, we have all for this user
168 $this->_push($current);
169 break;
172 $grade_records[$current->itemid] = $current;
175 $grades = array();
176 $feedbacks = array();
178 if (!empty($this->grade_items)) {
179 foreach ($this->grade_items as $grade_item) {
180 if (array_key_exists($grade_item->id, $grade_records)) {
181 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
182 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
183 unset($grade_records[$grade_item->id]->feedback);
184 unset($grade_records[$grade_item->id]->feedbackformat);
185 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
186 } else {
187 $feedbacks[$grade_item->id]->feedback = '';
188 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
189 $grades[$grade_item->id] = new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
194 $result = new object();
195 $result->user = $user;
196 $result->grades = $grades;
197 $result->feedbacks = $feedbacks;
199 return $result;
203 * Close the iterator, do not forget to call this function.
204 * @return void
206 function close() {
207 if ($this->users_rs) {
208 rs_close($this->users_rs);
209 $this->users_rs = null;
211 if ($this->grades_rs) {
212 rs_close($this->grades_rs);
213 $this->grades_rs = null;
215 $this->gradestack = array();
219 * Internal function
221 function _push($grade) {
222 array_push($this->gradestack, $grade);
226 * Internal function
228 function _pop() {
229 if (empty($this->gradestack)) {
230 if (!$this->grades_rs) {
231 return NULL; // no grades present
234 if (!$grade = rs_fetch_next_record($this->grades_rs)) {
235 return NULL; // no more grades
238 return $grade;
239 } else {
240 return array_pop($this->gradestack);
246 * Print a selection popup form of the graded users in a course.
248 * @param int $courseid id of the course
249 * @param string $actionpage The page receiving the data from the popoup form
250 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
251 * @param int $groupid id of requested group, 0 means all
252 * @param int $includeall bool include all option
253 * @param bool $return If true, will return the HTML, otherwise, will print directly
254 * @return null
256 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
257 global $CFG, $USER;
259 if (is_null($userid)) {
260 $userid = $USER->id;
263 $context = get_context_instance(CONTEXT_COURSE, $course->id);
265 $menu = array(); // Will be a list of userid => user name
267 $gui = new graded_users_iterator($course, null, $groupid);
268 $gui->init();
271 $label = get_string('selectauser', 'grades');
272 if ($includeall) {
273 $menu[0] = get_string('allusers', 'grades');
274 $label = get_string('selectalloroneuser', 'grades');
277 while ($userdata = $gui->next_user()) {
278 $user = $userdata->user;
279 $menu[$user->id] = fullname($user);
282 $gui->close();
284 if ($includeall) {
285 $menu[0] .= " (" . (count($menu) - 1) . ")";
288 return popup_form($CFG->wwwroot.'/grade/' . $actionpage . '&amp;userid=', $menu, 'choosegradeduser', $userid, 'choose', '', '',
289 $return, 'self', $label);
293 * Print grading plugin selection popup form.
295 * @param int $courseid id of course
296 * @param string $active_type type of plugin on current page - import, export, report or edit
297 * @param string $active_plugin active plugin type - grader, user, cvs, ...
298 * @param boolean $return return as string
299 * @return nothing or string if $return true
301 function print_grade_plugin_selector($plugin_info, $return=false) {
302 global $CFG;
304 $menu = array();
305 $count = 0;
306 $active = '';
308 foreach ($plugin_info as $plugin_type => $plugins) {
309 if ($plugin_type == 'strings') {
310 continue;
313 $first_plugin = reset($plugins);
315 $menu[$first_plugin['link'].'&amp;'] = '--'.$plugin_info['strings'][$plugin_type];
317 if (empty($plugins['id'])) {
318 foreach ($plugins as $plugin) {
319 $menu[$plugin['link']] = $plugin['string'];
320 $count++;
325 /// finally print/return the popup form
326 if ($count > 1) {
327 $select = popup_form('', $menu, 'choosepluginreport', '', get_string('chooseaction', 'grades'), '', '', true, 'self');
328 if ($return) {
329 return $select;
330 } else {
331 echo $select;
333 } else {
334 // only one option - no plugin selector needed
335 return '';
340 * Print grading plugin selection tab-based navigation.
342 * @param int $courseid id of course
343 * @param string $active_type type of plugin on current page - import, export, report or edit
344 * @param string $active_plugin active plugin type - grader, user, cvs, ...
345 * @param boolean $return return as string
346 * @return nothing or string if $return true
348 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
349 global $CFG, $COURSE;
351 if (!isset($currenttab)) {
352 $currenttab = '';
355 $tabs = array();
356 $top_row = array();
357 $bottom_row = array();
358 $inactive = array($active_plugin);
359 $activated = array();
361 $count = 0;
362 $active = '';
364 foreach ($plugin_info as $plugin_type => $plugins) {
365 if ($plugin_type == 'strings') {
366 continue;
369 // If $plugins is actually the definition of a child-less parent link:
370 if (!empty($plugins['id'])) {
371 $string = $plugins['string'];
372 if (!empty($plugin_info[$active_type]['parent'])) {
373 $string = $plugin_info[$active_type]['parent']['string'];
376 $top_row[] = new tabobject($plugin_type, $plugins['link'], $string);
377 continue;
380 $first_plugin = reset($plugins);
381 $url = $first_plugin['link'];
383 if ($plugin_type == 'report') {
384 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
387 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
389 if ($active_type == $plugin_type) {
390 foreach ($plugins as $plugin) {
391 $bottom_row[] = new tabobject($plugin['id'], $plugin['link'], $plugin['string']);
392 if ($plugin['id'] == $active_plugin) {
393 $inactive = array($plugin['id']);
399 $tabs[] = $top_row;
400 $tabs[] = $bottom_row;
402 if ($return) {
403 return print_tabs($tabs, $active_type, $inactive, $activated, true);
404 } else {
405 print_tabs($tabs, $active_type, $inactive, $activated);
409 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
410 global $CFG;
412 $context = get_context_instance(CONTEXT_COURSE, $courseid);
414 $plugin_info = array();
415 $count = 0;
416 $active = '';
417 $url_prefix = $CFG->wwwroot . '/grade/';
419 // Language strings
420 $plugin_info['strings'] = array(
421 'report' => get_string('view'),
422 'edittree' => get_string('edittree', 'grades'),
423 'scale' => get_string('scales'),
424 'outcome' => get_string('outcomes', 'grades'),
425 'letter' => get_string('letters', 'grades'),
426 'export' => get_string('export', 'grades'),
427 'import' => get_string('import'),
428 'preferences' => get_string('mypreferences', 'grades'),
429 'settings' => get_string('settings'));
431 // Settings tab first
432 if (has_capability('moodle/course:update', $context)) {
433 $url = $url_prefix.'edit/settings/index.php?id='.$courseid;
435 if ($active_type == 'settings' and $active_plugin == 'course') {
436 $active = $url;
439 $plugin_info['settings'] = array();
440 $plugin_info['settings']['course'] = array('id' => 'coursesettings', 'link' => $url, 'string' => get_string('course'));
441 $count++;
445 /// report plugins with its special structure
446 if ($reports = get_list_of_plugins('grade/report', 'CVS')) { // Get all installed reports
447 foreach ($reports as $key => $plugin) { // Remove ones we can't see
448 // Outcomes are a special core plugin depending on $CFG->enableoutcomes
449 if ($plugin == 'outcomes' && empty($CFG->enableoutcomes)) {
450 unset($reports[$key]);
452 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
453 unset($reports[$key]);
458 $reportnames = array();
460 if (!empty($reports)) {
461 foreach ($reports as $plugin) {
462 $url = $url_prefix.'report/'.$plugin.'/index.php?id='.$courseid;
463 if ($active_type == 'report' and $active_plugin == $plugin ) {
464 $active = $url;
466 $reportnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradereport_'.$plugin));
468 // Add link to preferences tab if such a page exists
469 if (file_exists($CFG->dirroot . '/grade/report/'.$plugin.'/preferences.php')) {
470 $pref_url = $url_prefix.'report/'.$plugin.'/preferences.php?id='.$courseid;
471 $plugin_info['preferences'][$plugin] = array('id' => $plugin, 'link' => $pref_url, 'string' => get_string('modulename', 'gradereport_'.$plugin));
474 $count++;
476 asort($reportnames);
478 if (!empty($reportnames)) {
479 $plugin_info['report']=$reportnames;
482 /// editing scripts - not real plugins
483 if (has_capability('moodle/grade:manage', $context)
484 or has_capability('moodle/grade:manageletters', $context)
485 or has_capability('moodle/course:managescales', $context)
486 or has_capability('moodle/course:update', $context)) {
488 if (has_capability('moodle/grade:manage', $context)) {
489 $url = $url_prefix.'edit/tree/index.php?sesskey='.sesskey().'&amp;showadvanced=0&amp;id='.$courseid;
490 $url_adv = $url_prefix.'edit/tree/index.php?sesskey='.sesskey().'&amp;showadvanced=1&amp;id='.$courseid;
492 if ($active_type == 'edittree' and $active_plugin == 'simpleview') {
493 $active = $url;
494 } elseif ($active_type == 'edittree' and $active_plugin == 'fullview') {
495 $active = $url_adv;
498 $plugin_info['edittree'] = array();
499 $plugin_info['edittree']['simpleview'] = array('id' => 'simpleview', 'link' => $url, 'string' => get_string('simpleview', 'grades'));
500 $plugin_info['edittree']['fullview'] = array('id' => 'fullview', 'link' => $url_adv, 'string' => get_string('fullview', 'grades'));
501 $count++;
504 if (has_capability('moodle/course:managescales', $context)) {
505 $url = $url_prefix.'edit/scale/index.php?id='.$courseid;
507 if ($active_type == 'scale' and is_null($active_plugin)) {
508 $active = $url;
511 $plugin_info['scale'] = array();
513 if ($active_type == 'scale' and $active_plugin == 'edit') {
514 $edit_url = $url_prefix.'edit/scale/edit.php?courseid='.$courseid.'&amp;id='.optional_param('id', 0, PARAM_INT);
515 $active = $edit_url;
516 $plugin_info['scale']['view'] = array('id' => 'edit', 'link' => $edit_url, 'string' => get_string('edit'),
517 'parent' => array('id' => 'scale', 'link' => $url, 'string' => get_string('scales')));
518 } else {
519 $plugin_info['scale']['view'] = array('id' => 'scale', 'link' => $url, 'string' => get_string('view'));
522 $count++;
525 if (!empty($CFG->enableoutcomes) && (has_capability('moodle/grade:manage', $context) or
526 has_capability('moodle/course:update', $context))) {
528 $url_course = $url_prefix.'edit/outcome/course.php?id='.$courseid;
529 $url_edit = $url_prefix.'edit/outcome/index.php?id='.$courseid;
531 $plugin_info['outcome'] = array();
533 if (has_capability('moodle/course:update', $context)) { // Default to course assignment
534 $plugin_info['outcome']['course'] = array('id' => 'course', 'link' => $url_course, 'string' => get_string('outcomescourse', 'grades'));
535 $plugin_info['outcome']['edit'] = array('id' => 'edit', 'link' => $url_edit, 'string' => get_string('editoutcomes', 'grades'));
536 } else {
537 $plugin_info['outcome'] = array('id' => 'edit', 'link' => $url_course, 'string' => get_string('outcomescourse', 'grades'));
540 if ($active_type == 'outcome' and is_null($active_plugin)) {
541 $active = $url_edit;
542 } elseif ($active_type == 'outcome' and $active_plugin == 'course' ) {
543 $active = $url_course;
544 } elseif ($active_type == 'outcome' and $active_plugin == 'edit' ) {
545 $active = $url_edit;
546 } elseif ($active_type == 'outcome' and $active_plugin == 'import') {
547 $plugin_info['outcome']['import'] = array('id' => 'import', 'link' => null, 'string' => get_string('importoutcomes', 'grades'));
550 $count++;
553 if (has_capability('moodle/grade:manage', $context) or has_capability('moodle/grade:manageletters', $context)) {
554 $course_context = get_context_instance(CONTEXT_COURSE, $courseid);
555 $url = $url_prefix.'edit/letter/index.php?id='.$courseid;
556 $url_edit = $url_prefix.'edit/letter/edit.php?id='.$course_context->id;
558 if ($active_type == 'letter' and $active_plugin == 'view' ) {
559 $active = $url;
560 } elseif ($active_type == 'letter' and $active_plugin == 'edit' ) {
561 $active = $url_edit;
564 $plugin_info['letter'] = array();
565 $plugin_info['letter']['view'] = array('id' => 'view', 'link' => $url, 'string' => get_string('view'));
566 $plugin_info['letter']['edit'] = array('id' => 'edit', 'link' => $url_edit, 'string' => get_string('edit'));
567 $count++;
571 /// standard import plugins
572 if ($imports = get_list_of_plugins('grade/import', 'CVS')) { // Get all installed import plugins
573 foreach ($imports as $key => $plugin) { // Remove ones we can't see
574 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
575 unset($imports[$key]);
579 $importnames = array();
580 if (!empty($imports)) {
581 foreach ($imports as $plugin) {
582 $url = $url_prefix.'import/'.$plugin.'/index.php?id='.$courseid;
583 if ($active_type == 'import' and $active_plugin == $plugin ) {
584 $active = $url;
586 $importnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradeimport_'.$plugin));
587 $count++;
589 asort($importnames);
591 if (!empty($importnames)) {
592 $plugin_info['import']=$importnames;
595 /// standard export plugins
596 if ($exports = get_list_of_plugins('grade/export', 'CVS')) { // Get all installed export plugins
597 foreach ($exports as $key => $plugin) { // Remove ones we can't see
598 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
599 unset($exports[$key]);
603 $exportnames = array();
604 if (!empty($exports)) {
605 foreach ($exports as $plugin) {
606 $url = $url_prefix.'export/'.$plugin.'/index.php?id='.$courseid;
607 if ($active_type == 'export' and $active_plugin == $plugin ) {
608 $active = $url;
610 $exportnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradeexport_'.$plugin));
611 $count++;
613 asort($exportnames);
616 if (!empty($exportnames)) {
617 $plugin_info['export']=$exportnames;
620 // Key managers
621 if ($CFG->gradepublishing) {
622 $keymanager_url = $url_prefix.'export/keymanager.php?id='.$courseid;
623 $plugin_info['export']['keymanager'] = array('id' => 'keymanager', 'link' => $keymanager_url, 'string' => get_string('keymanager', 'grades'));
624 if ($active_type == 'export' and $active_plugin == 'keymanager' ) {
625 $active = $keymanager_url;
627 $count++;
629 $keymanager_url = $url_prefix.'import/keymanager.php?id='.$courseid;
630 $plugin_info['import']['keymanager'] = array('id' => 'keymanager', 'link' => $keymanager_url, 'string' => get_string('keymanager', 'grades'));
631 if ($active_type == 'import' and $active_plugin == 'keymanager' ) {
632 $active = $keymanager_url;
634 $count++;
638 foreach ($plugin_info as $plugin_type => $plugins) {
639 if (!empty($plugins['id']) && $active_plugin == $plugins['id']) {
640 $plugin_info['strings']['active_plugin_str'] = $plugins['string'];
641 break;
643 foreach ($plugins as $plugin) {
644 if ($active_plugin == $plugin['id']) {
645 $plugin_info['strings']['active_plugin_str'] = $plugin['string'];
650 // Put settings last
651 if (!empty($plugin_info['settings'])) {
652 $settings = $plugin_info['settings'];
653 unset($plugin_info['settings']);
654 $plugin_info['settings'] = $settings;
657 // Put preferences last
658 if (!empty($plugin_info['preferences'])) {
659 $prefs = $plugin_info['preferences'];
660 unset($plugin_info['preferences']);
661 $plugin_info['preferences'] = $prefs;
664 // Check import and export caps
665 if (!has_capability('moodle/grade:export', $context)) {
666 unset($plugin_info['export']);
668 if (!has_capability('moodle/grade:import', $context)) {
669 unset($plugin_info['import']);
671 return $plugin_info;
675 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
676 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
677 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
678 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
679 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
681 * @param int $courseid
682 * @param string $active_type The type of the current page (report, settings, import, export, scales, outcomes, letters)
683 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
684 * @param string $heading The heading of the page. Tries to guess if none is given
685 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
686 * @param string $bodytags Additional attributes that will be added to the <body> tag
687 * @param string $buttons Additional buttons to display on the page
689 * @return string HTML code or nothing if $return == false
691 function print_grade_page_head($courseid, $active_type, $active_plugin=null, $heading = false, $return=false, $bodytags='', $buttons=false, $extracss=array()) {
692 global $CFG, $COURSE;
693 $strgrades = get_string('grades');
694 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
696 // Determine the string of the active plugin
697 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
698 $stractive_type = $plugin_info['strings'][$active_type];
700 $navlinks = array();
701 $first_link = '';
703 if ($active_type == 'settings' && $active_plugin != 'coursesettings') {
704 $first_link = $plugin_info['report'][$active_plugin]['link'];
705 } elseif ($active_type != 'report') {
706 $first_link = $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id;
709 if ($active_type == 'preferences') {
710 $CFG->stylesheets[] = $CFG->wwwroot . '/grade/report/styles.css';
713 foreach ($extracss as $css_url) {
714 $CFG->stylesheets[] = $css_url;
717 $navlinks[] = array('name' => $strgrades,
718 'link' => $first_link,
719 'type' => 'misc');
721 $active_type_link = '';
723 if (!empty($plugin_info[$active_type]['link']) && $plugin_info[$active_type]['link'] != qualified_me()) {
724 $active_type_link = $plugin_info[$active_type]['link'];
727 if (!empty($plugin_info[$active_type]['parent']['link'])) {
728 $active_type_link = $plugin_info[$active_type]['parent']['link'];
729 $navlinks[] = array('name' => $stractive_type, 'link' => $active_type_link, 'type' => 'misc');
732 if (empty($plugin_info[$active_type]['id'])) {
733 $navlinks[] = array('name' => $stractive_type, 'link' => $active_type_link, 'type' => 'misc');
736 $navlinks[] = array('name' => $stractive_plugin, 'link' => null, 'type' => 'misc');
738 $navigation = build_navigation($navlinks);
740 $title = ': ' . $stractive_plugin;
741 if (empty($plugin_info[$active_type]['id']) || !empty($plugin_info[$active_type]['parent'])) {
742 $title = ': ' . $stractive_type . ': ' . $stractive_plugin;
745 $returnval = print_header_simple($strgrades . ': ' . $stractive_type, $title, $navigation, '',
746 $bodytags, true, $buttons, navmenu($COURSE), false, '', $return);
748 // Guess heading if not given explicitly
749 if (!$heading) {
750 $heading = $stractive_plugin;
753 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
754 $returnval .= print_grade_plugin_selector($plugin_info, $return);
756 $returnval .= print_heading($heading);
758 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
759 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
762 if ($return) {
763 return $returnval;
768 * Utility class used for return tracking when using edit and other forms in grade plugins
770 class grade_plugin_return {
771 var $type;
772 var $plugin;
773 var $courseid;
774 var $userid;
775 var $page;
778 * Constructor
779 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
781 function grade_plugin_return ($params=null) {
782 if (empty($params)) {
783 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
784 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
785 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
786 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
787 $this->page = optional_param('gpr_page', null, PARAM_INT);
789 } else {
790 foreach ($params as $key=>$value) {
791 if (array_key_exists($key, $this)) {
792 $this->$key = $value;
799 * Returns return parameters as options array suitable for buttons.
800 * @return array options
802 function get_options() {
803 if (empty($this->type)) {
804 return array();
807 $params = array();
809 if (!empty($this->plugin)) {
810 $params['plugin'] = $this->plugin;
813 if (!empty($this->courseid)) {
814 $params['id'] = $this->courseid;
817 if (!empty($this->userid)) {
818 $params['userid'] = $this->userid;
821 if (!empty($this->page)) {
822 $params['page'] = $this->page;
825 return $params;
829 * Returns return url
830 * @param string $default default url when params not set
831 * @return string url
833 function get_return_url($default, $extras=null) {
834 global $CFG;
836 if (empty($this->type) or empty($this->plugin)) {
837 return $default;
840 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
841 $glue = '?';
843 if (!empty($this->courseid)) {
844 $url .= $glue.'id='.$this->courseid;
845 $glue = '&amp;';
848 if (!empty($this->userid)) {
849 $url .= $glue.'userid='.$this->userid;
850 $glue = '&amp;';
853 if (!empty($this->page)) {
854 $url .= $glue.'page='.$this->page;
855 $glue = '&amp;';
858 if (!empty($extras)) {
859 foreach($extras as $key=>$value) {
860 $url .= $glue.$key.'='.$value;
861 $glue = '&amp;';
865 return $url;
869 * Returns string with hidden return tracking form elements.
870 * @return string
872 function get_form_fields() {
873 if (empty($this->type)) {
874 return '';
877 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
879 if (!empty($this->plugin)) {
880 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
883 if (!empty($this->courseid)) {
884 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
887 if (!empty($this->userid)) {
888 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
891 if (!empty($this->page)) {
892 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
897 * Add hidden elements into mform
898 * @param object $mform moodle form object
899 * @return void
901 function add_mform_elements(&$mform) {
902 if (empty($this->type)) {
903 return;
906 $mform->addElement('hidden', 'gpr_type', $this->type);
907 $mform->setType('gpr_type', PARAM_SAFEDIR);
909 if (!empty($this->plugin)) {
910 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
911 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
914 if (!empty($this->courseid)) {
915 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
916 $mform->setType('gpr_courseid', PARAM_INT);
919 if (!empty($this->userid)) {
920 $mform->addElement('hidden', 'gpr_userid', $this->userid);
921 $mform->setType('gpr_userid', PARAM_INT);
924 if (!empty($this->page)) {
925 $mform->addElement('hidden', 'gpr_page', $this->page);
926 $mform->setType('gpr_page', PARAM_INT);
931 * Add return tracking params into url
932 * @param string $url
933 * @return string $url with erturn tracking params
935 function add_url_params($url) {
936 if (empty($this->type)) {
937 return $url;
940 if (strpos($url, '?') === false) {
941 $url .= '?gpr_type='.$this->type;
942 } else {
943 $url .= '&amp;gpr_type='.$this->type;
946 if (!empty($this->plugin)) {
947 $url .= '&amp;gpr_plugin='.$this->plugin;
950 if (!empty($this->courseid)) {
951 $url .= '&amp;gpr_courseid='.$this->courseid;
954 if (!empty($this->userid)) {
955 $url .= '&amp;gpr_userid='.$this->userid;
958 if (!empty($this->page)) {
959 $url .= '&amp;gpr_page='.$this->page;
962 return $url;
967 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
968 * @param string $path The path of the calling script (using __FILE__?)
969 * @param string $pagename The language string to use as the last part of the navigation (non-link)
970 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
971 * @return string
973 function grade_build_nav($path, $pagename=null, $id=null) {
974 global $CFG, $COURSE;
976 $strgrades = get_string('grades', 'grades');
978 // Parse the path and build navlinks from its elements
979 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
980 $path = substr($path, $dirroot_length);
981 $path = str_replace('\\', '/', $path);
983 $path_elements = explode('/', $path);
985 $path_elements_count = count($path_elements);
987 // First link is always 'grade'
988 $navlinks = array();
989 $navlinks[] = array('name' => $strgrades,
990 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
991 'type' => 'misc');
993 $link = '';
994 $numberofelements = 3;
996 // Prepare URL params string
997 $id_string = '?';
998 if (!is_null($id)) {
999 if (is_array($id)) {
1000 foreach ($id as $idkey => $idvalue) {
1001 $id_string .= "$idkey=$idvalue&amp;";
1003 } else {
1004 $id_string .= "id=$id";
1008 $navlink4 = null;
1010 // Remove file extensions from filenames
1011 foreach ($path_elements as $key => $filename) {
1012 $path_elements[$key] = str_replace('.php', '', $filename);
1015 // Second level links
1016 switch ($path_elements[1]) {
1017 case 'edit': // No link
1018 if ($path_elements[3] != 'index.php') {
1019 $numberofelements = 4;
1021 break;
1022 case 'import': // No link
1023 break;
1024 case 'export': // No link
1025 break;
1026 case 'report':
1027 // $id is required for this link. Do not print it if $id isn't given
1028 if (!is_null($id)) {
1029 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
1032 if ($path_elements[2] == 'grader') {
1033 $numberofelements = 4;
1035 break;
1037 default:
1038 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1039 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
1040 return false;
1043 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
1045 // Third level links
1046 if (empty($pagename)) {
1047 $pagename = get_string($path_elements[2], 'grades');
1050 switch ($numberofelements) {
1051 case 3:
1052 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
1053 break;
1054 case 4:
1056 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1057 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
1058 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
1059 'type' => 'misc');
1061 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
1062 break;
1064 $navigation = build_navigation($navlinks);
1066 return $navigation;
1070 * General structure representing grade items in course
1072 class grade_structure {
1073 var $context;
1075 var $courseid;
1078 * 1D array of grade items only
1080 var $items;
1083 * Returns icon of element
1084 * @param object $element
1085 * @param bool $spacerifnone return spacer if no icon found
1086 * @return string icon or spacer
1088 function get_element_icon(&$element, $spacerifnone=false) {
1089 global $CFG;
1091 switch ($element['type']) {
1092 case 'item':
1093 case 'courseitem':
1094 case 'categoryitem':
1095 if ($element['object']->is_calculated()) {
1096 $strcalc = get_string('calculatedgrade', 'grades');
1097 return '<img src="'.$CFG->pixpath.'/i/calc.gif" class="icon itemicon" title="'.s($strcalc).'" alt="'.s($strcalc).'"/>';
1099 } else if (($element['object']->is_course_item() or $element['object']->is_category_item())
1100 and ($element['object']->gradetype == GRADE_TYPE_SCALE or $element['object']->gradetype == GRADE_TYPE_VALUE)) {
1101 if ($category = $element['object']->get_item_category()) {
1102 switch ($category->aggregation) {
1103 case GRADE_AGGREGATE_MEDIAN:
1104 case GRADE_AGGREGATE_MEDIAN:
1105 return '<img src="'.$CFG->pixpath.'/i/agg_sum.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1106 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1107 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1108 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1109 return '<img src="'.$CFG->pixpath.'/i/agg_mean.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1110 case GRADE_AGGREGATE_SUM:
1111 return '<img src="'.$CFG->pixpath.'/i/agg_sum.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1115 } else if ($element['object']->itemtype == 'mod') {
1116 $strmodname = get_string('modulename', $element['object']->itemmodule);
1117 return '<img src="'.$CFG->modpixpath.'/'.$element['object']->itemmodule.'/icon.gif" class="icon itemicon" title="' .s($strmodname).'" alt="' .s($strmodname).'"/>';
1119 } else if ($element['object']->itemtype == 'manual') {
1120 if ($element['object']->is_outcome_item()) {
1121 $stroutcome = get_string('outcome', 'grades');
1122 return '<img src="'.$CFG->pixpath.'/i/outcomes.gif" class="icon itemicon" title="'.s($stroutcome).'" alt="'.s($stroutcome).'"/>';
1123 } else {
1124 $strmanual = get_string('manualitem', 'grades');
1125 return '<img src="'.$CFG->pixpath.'/t/manual_item.gif" class="icon itemicon" title="'.s($strmanual).'" alt="'.s($strmanual).'"/>';
1128 break;
1130 case 'category':
1131 $strcat = get_string('category', 'grades');
1132 return '<img src="'.$CFG->pixpath.'/f/folder.gif" class="icon itemicon" title="'.s($strcat).'" alt="'.s($strcat).'" />';
1135 if ($spacerifnone) {
1136 return '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="icon itemicon" alt=""/>';
1137 } else {
1138 return '';
1143 * Returns name of element optionally with icon and link
1144 * @param object $element
1145 * @param bool $withlinks
1146 * @param bool $icons
1147 * @param bool $spacerifnone return spacer if no icon found
1148 * @return header string
1150 function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1151 global $CFG;
1153 $header = '';
1155 if ($icon) {
1156 $header .= $this->get_element_icon($element, $spacerifnone);
1159 $header .= $element['object']->get_name();
1161 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and $element['type'] != 'courseitem') {
1162 return $header;
1165 $itemtype = $element['object']->itemtype;
1166 $itemmodule = $element['object']->itemmodule;
1167 $iteminstance = $element['object']->iteminstance;
1169 if ($withlink and $itemtype=='mod' and $iteminstance and $itemmodule) {
1170 if ($cm = get_coursemodule_from_instance($itemmodule, $iteminstance, $this->courseid)) {
1172 $a->name = get_string('modulename', $element['object']->itemmodule);
1173 $title = get_string('linktoactivity', 'grades', $a);
1174 $dir = $CFG->dirroot.'/mod/'.$itemmodule;
1176 if (file_exists($dir.'/grade.php')) {
1177 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/grade.php?id='.$cm->id;
1178 } else {
1179 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/view.php?id='.$cm->id;
1182 $header = '<a href="'.$url.'" title="'.s($title).'">'.$header.'</a>';
1186 return $header;
1190 * Returns the grade eid - the grade may not exist yet.
1191 * @param $grade_grade object
1192 * @return string eid
1194 function get_grade_eid($grade_grade) {
1195 if (empty($grade_grade->id)) {
1196 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1197 } else {
1198 return 'g'.$grade_grade->id;
1203 * Returns the grade_item eid
1204 * @param $grade_item object
1205 * @return string eid
1207 function get_item_eid($grade_item) {
1208 return 'i'.$grade_item->id;
1211 function get_params_for_iconstr($element) {
1212 $strparams = new stdClass();
1213 $strparams->category = '';
1214 $strparams->itemname = '';
1215 $strparams->itemmodule = '';
1216 if (!method_exists($element['object'], 'get_name')) {
1217 return $strparams;
1220 $strparams->itemname = html_to_text($element['object']->get_name());
1222 // If element name is categorytotal, get the name of the parent category
1223 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1224 $parent = $element['object']->get_parent_category();
1225 $strparams->category = $parent->get_name() . ' ';
1226 } else {
1227 $strparams->category = '';
1230 $strparams->itemmodule = null;
1231 if (isset($element['object']->itemmodule)) {
1232 $strparams->itemmodule = $element['object']->itemmodule;
1234 return $strparams;
1238 * Return edit icon for give element
1239 * @param object $element
1240 * @return string
1242 function get_edit_icon($element, $gpr) {
1243 global $CFG;
1245 if (!has_capability('moodle/grade:manage', $this->context)) {
1246 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1247 // oki - let them override grade
1248 } else {
1249 return '';
1253 static $strfeedback = null;
1254 static $streditgrade = null;
1255 if (is_null($streditgrade)) {
1256 $streditgrade = get_string('editgrade', 'grades');
1257 $strfeedback = get_string('feedback');
1260 $strparams = $this->get_params_for_iconstr($element);
1261 if ($element['type'] == 'item' or $element['type'] == 'category') {
1264 $object = $element['object'];
1266 switch ($element['type']) {
1267 case 'item':
1268 case 'categoryitem':
1269 case 'courseitem':
1270 $stredit = get_string('editverbose', 'grades', $strparams);
1271 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1272 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1273 } else {
1274 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1276 $url = $gpr->add_url_params($url);
1277 break;
1279 case 'category':
1280 $stredit = get_string('editverbose', 'grades', $strparams);
1281 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1282 $url = $gpr->add_url_params($url);
1283 break;
1285 case 'grade':
1286 $stredit = $streditgrade;
1287 if (empty($object->id)) {
1288 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
1289 } else {
1290 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1292 $url = $gpr->add_url_params($url);
1293 if (!empty($object->feedback)) {
1294 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1296 break;
1298 default:
1299 $url = null;
1302 if ($url) {
1303 return '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.s($stredit).'" title="'.s($stredit).'"/></a>';
1305 } else {
1306 return '';
1311 * Return hiding icon for give element
1312 * @param object $element
1313 * @return string
1315 function get_hiding_icon($element, $gpr) {
1316 global $CFG;
1318 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
1319 return '';
1322 $strparams = $this->get_params_for_iconstr($element);
1323 $strshow = get_string('showverbose', 'grades', $strparams);
1324 $strhide = get_string('hideverbose', 'grades', $strparams);
1326 if ($element['object']->is_hidden()) {
1327 $icon = 'show';
1328 $tooltip = $strshow;
1330 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
1331 $icon = 'hiddenuntil';
1332 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
1335 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1336 . '&amp;eid='.$element['eid'];
1337 $url = $gpr->add_url_params($url);
1338 $action = '<a href="'.$url.'"><img alt="'.$strshow.'" src="'.$CFG->pixpath.'/t/'.$icon.'.gif" class="iconsmall" title="'.s($tooltip).'"/></a>';
1340 } else {
1341 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1342 . '&amp;eid='.$element['eid'];
1343 $url = $gpr->add_url_params($url);
1344 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.s($strhide).'" title="'.s($strhide).'"/></a>';
1346 return $action;
1350 * Return locking icon for given element
1351 * @param object $element
1352 * @return string
1354 function get_locking_icon($element, $gpr) {
1355 global $CFG;
1357 $strparams = $this->get_params_for_iconstr($element);
1358 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1359 $strlock = get_string('lockverbose', 'grades', $strparams);
1361 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1362 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1363 $strparamobj = new stdClass();
1364 $strparamobj->itemname = $element['object']->grade_item->itemname;
1365 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1366 $action = '<img src="'.$CFG->pixpath.'/t/unlock_gray.gif" alt="'.s($strnonunlockable).'" class="iconsmall" title="'.s($strnonunlockable).'"/>';
1367 } elseif ($element['object']->is_locked()) {
1368 $icon = 'unlock';
1369 $tooltip = $strunlock;
1371 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
1372 $icon = 'locktime';
1373 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
1376 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1377 return '';
1379 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1380 . '&amp;eid='.$element['eid'];
1381 $url = $gpr->add_url_params($url);
1382 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/'.$icon.'.gif" alt="'.s($strunlock).'" class="iconsmall" title="'.s($tooltip).'"/></a>';
1384 } else {
1385 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1386 return '';
1388 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1389 . '&amp;eid='.$element['eid'];
1390 $url = $gpr->add_url_params($url);
1391 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.s($strlock).'" title="'
1392 . s($strlock).'"/></a>';
1394 return $action;
1398 * Return calculation icon for given element
1399 * @param object $element
1400 * @return string
1402 function get_calculation_icon($element, $gpr) {
1403 global $CFG;
1404 if (!has_capability('moodle/grade:manage', $this->context)) {
1405 return '';
1408 $calculation_icon = '';
1410 $type = $element['type'];
1411 $object = $element['object'];
1414 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1415 $strparams = $this->get_params_for_iconstr($element);
1416 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1418 // show calculation icon only when calculation possible
1419 if (!$object->is_external_item() and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
1420 if ($object->is_calculated()) {
1421 $icon = 'calc.gif';
1422 } else {
1423 $icon = 'calc_off.gif';
1425 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1426 $url = $gpr->add_url_params($url);
1427 $calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/'.$icon.'" class="iconsmall" alt="'
1428 . s($streditcalculation).'" title="'.s($streditcalculation).'" /></a>'. "\n";
1432 return $calculation_icon;
1437 * Flat structure similar to grade tree.
1439 class grade_seq extends grade_structure {
1442 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1443 * @var string $commonvars
1445 var $commonvars;
1448 * 1D array of elements
1450 var $elements;
1453 * Constructor, retrieves and stores array of all grade_category and grade_item
1454 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1455 * @param int $courseid
1456 * @param boolean $category_grade_last category grade item is the last child
1457 * @param array $collapsed array of collapsed categories
1459 function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1460 global $USER, $CFG;
1462 $this->courseid = $courseid;
1463 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
1464 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1466 // get course grade tree
1467 $top_element = grade_category::fetch_course_tree($courseid, true);
1469 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1471 foreach ($this->elements as $key=>$unused) {
1472 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1477 * Static recursive helper - makes the grade_item for category the last children
1478 * @static
1479 * @param array $element The seed of the recursion
1480 * @return void
1482 function flatten(&$element, $category_grade_last, $nooutcomes) {
1483 if (empty($element['children'])) {
1484 return array();
1486 $children = array();
1488 foreach ($element['children'] as $sortorder=>$unused) {
1489 if ($nooutcomes and $element['type'] != 'category' and $element['children'][$sortorder]['object']->is_outcome_item()) {
1490 continue;
1492 $children[] = $element['children'][$sortorder];
1494 unset($element['children']);
1496 if ($category_grade_last and count($children) > 1) {
1497 $cat_item = array_shift($children);
1498 array_push($children, $cat_item);
1501 $result = array();
1502 foreach ($children as $child) {
1503 if ($child['type'] == 'category') {
1504 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1505 } else {
1506 $child['eid'] = 'i'.$child['object']->id;
1507 $result[$child['object']->id] = $child;
1511 return $result;
1515 * Parses the array in search of a given eid and returns a element object with
1516 * information about the element it has found.
1517 * @param int $eid
1518 * @return object element
1520 function locate_element($eid) {
1521 // it is a grade - construct a new object
1522 if (strpos($eid, 'n') === 0) {
1523 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1524 return null;
1527 $itemid = $matches[1];
1528 $userid = $matches[2];
1530 //extra security check - the grade item must be in this tree
1531 if (!$item_el = $this->locate_element('i'.$itemid)) {
1532 return null;
1535 // $gradea->id may be null - means does not exist yet
1536 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1538 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1539 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1541 } else if (strpos($eid, 'g') === 0) {
1542 $id = (int)substr($eid, 1);
1543 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1544 return null;
1546 //extra security check - the grade item must be in this tree
1547 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1548 return null;
1550 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1551 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1554 // it is a category or item
1555 foreach ($this->elements as $element) {
1556 if ($element['eid'] == $eid) {
1557 return $element;
1561 return null;
1566 * This class represents a complete tree of categories, grade_items and final grades,
1567 * organises as an array primarily, but which can also be converted to other formats.
1568 * It has simple method calls with complex implementations, allowing for easy insertion,
1569 * deletion and moving of items and categories within the tree.
1571 class grade_tree extends grade_structure {
1574 * The basic representation of the tree as a hierarchical, 3-tiered array.
1575 * @var object $top_element
1577 var $top_element;
1580 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1581 * @var string $commonvars
1583 var $commonvars;
1586 * 2D array of grade items and categories
1588 var $levels;
1591 * Grade items
1593 var $items;
1596 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1597 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1598 * @param int $courseid
1599 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
1600 * @param boolean $category_grade_last category grade item is the last child
1601 * @param array $collapsed array of collapsed categories
1603 function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
1604 global $USER, $CFG;
1606 $this->courseid = $courseid;
1607 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
1608 $this->levels = array();
1609 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1611 // get course grade tree
1612 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1614 // collapse the categories if requested
1615 if (!empty($collapsed)) {
1616 grade_tree::category_collapse($this->top_element, $collapsed);
1619 // no otucomes if requested
1620 if (!empty($nooutcomes)) {
1621 grade_tree::no_outcomes($this->top_element);
1624 // move category item to last position in category
1625 if ($category_grade_last) {
1626 grade_tree::category_grade_last($this->top_element);
1629 if ($fillers) {
1630 // inject fake categories == fillers
1631 grade_tree::inject_fillers($this->top_element, 0);
1632 // add colspans to categories and fillers
1633 grade_tree::inject_colspans($this->top_element);
1636 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1641 * Static recursive helper - removes items from collapsed categories
1642 * @static
1643 * @param array $element The seed of the recursion
1644 * @param array $collapsed array of collapsed categories
1645 * @return void
1647 function category_collapse(&$element, $collapsed) {
1648 if ($element['type'] != 'category') {
1649 return;
1651 if (empty($element['children']) or count($element['children']) < 2) {
1652 return;
1655 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1656 $category_item = reset($element['children']); //keep only category item
1657 $element['children'] = array(key($element['children'])=>$category_item);
1659 } else {
1660 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1661 reset($element['children']);
1662 $first_key = key($element['children']);
1663 unset($element['children'][$first_key]);
1665 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1666 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1672 * Static recursive helper - removes all outcomes
1673 * @static
1674 * @param array $element The seed of the recursion
1675 * @return void
1677 function no_outcomes(&$element) {
1678 if ($element['type'] != 'category') {
1679 return;
1681 foreach ($element['children'] as $sortorder=>$child) {
1682 if ($element['children'][$sortorder]['type'] == 'item'
1683 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1684 unset($element['children'][$sortorder]);
1686 } else if ($element['children'][$sortorder]['type'] == 'category') {
1687 grade_tree::no_outcomes($element['children'][$sortorder]);
1693 * Static recursive helper - makes the grade_item for category the last children
1694 * @static
1695 * @param array $element The seed of the recursion
1696 * @return void
1698 function category_grade_last(&$element) {
1699 if (empty($element['children'])) {
1700 return;
1702 if (count($element['children']) < 2) {
1703 return;
1705 $first_item = reset($element['children']);
1706 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1707 // the category item might have been already removed
1708 $order = key($element['children']);
1709 unset($element['children'][$order]);
1710 $element['children'][$order] =& $first_item;
1712 foreach ($element['children'] as $sortorder => $child) {
1713 grade_tree::category_grade_last($element['children'][$sortorder]);
1718 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1719 * @static
1720 * @param int $levels
1721 * @param array $element The seed of the recursion
1722 * @param int $depth
1723 * @return void
1725 function fill_levels(&$levels, &$element, $depth) {
1726 if (!array_key_exists($depth, $levels)) {
1727 $levels[$depth] = array();
1730 // prepare unique identifier
1731 if ($element['type'] == 'category') {
1732 $element['eid'] = 'c'.$element['object']->id;
1733 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1734 $element['eid'] = 'i'.$element['object']->id;
1735 $this->items[$element['object']->id] =& $element['object'];
1738 $levels[$depth][] =& $element;
1739 $depth++;
1740 if (empty($element['children'])) {
1741 return;
1743 $prev = 0;
1744 foreach ($element['children'] as $sortorder=>$child) {
1745 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1746 $element['children'][$sortorder]['prev'] = $prev;
1747 $element['children'][$sortorder]['next'] = 0;
1748 if ($prev) {
1749 $element['children'][$prev]['next'] = $sortorder;
1751 $prev = $sortorder;
1756 * Static recursive helper - makes full tree (all leafes are at the same level)
1758 function inject_fillers(&$element, $depth) {
1759 $depth++;
1761 if (empty($element['children'])) {
1762 return $depth;
1764 $chdepths = array();
1765 $chids = array_keys($element['children']);
1766 $last_child = end($chids);
1767 $first_child = reset($chids);
1769 foreach ($chids as $chid) {
1770 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1772 arsort($chdepths);
1774 $maxdepth = reset($chdepths);
1775 foreach ($chdepths as $chid=>$chd) {
1776 if ($chd == $maxdepth) {
1777 continue;
1779 for ($i=0; $i < $maxdepth-$chd; $i++) {
1780 if ($chid == $first_child) {
1781 $type = 'fillerfirst';
1782 } else if ($chid == $last_child) {
1783 $type = 'fillerlast';
1784 } else {
1785 $type = 'filler';
1787 $oldchild =& $element['children'][$chid];
1788 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
1792 return $maxdepth;
1796 * Static recursive helper - add colspan information into categories
1798 function inject_colspans(&$element) {
1799 if (empty($element['children'])) {
1800 return 1;
1802 $count = 0;
1803 foreach ($element['children'] as $key=>$child) {
1804 $count += grade_tree::inject_colspans($element['children'][$key]);
1806 $element['colspan'] = $count;
1807 return $count;
1811 * Parses the array in search of a given eid and returns a element object with
1812 * information about the element it has found.
1813 * @param int $eid
1814 * @return object element
1816 function locate_element($eid) {
1817 // it is a grade - construct a new object
1818 if (strpos($eid, 'n') === 0) {
1819 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1820 return null;
1823 $itemid = $matches[1];
1824 $userid = $matches[2];
1826 //extra security check - the grade item must be in this tree
1827 if (!$item_el = $this->locate_element('i'.$itemid)) {
1828 return null;
1831 // $gradea->id may be null - means does not exist yet
1832 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1834 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1835 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1837 } else if (strpos($eid, 'g') === 0) {
1838 $id = (int)substr($eid, 1);
1839 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1840 return null;
1842 //extra security check - the grade item must be in this tree
1843 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1844 return null;
1846 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1847 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1850 // it is a category or item
1851 foreach ($this->levels as $row) {
1852 foreach ($row as $element) {
1853 if ($element['type'] == 'filler') {
1854 continue;
1856 if ($element['eid'] == $eid) {
1857 return $element;
1862 return null;