MDL-16553 Assignment, student view: whitespace fix
[moodle.git] / grade / lib.php
blob5e7986cd1108e07410a639c51a1c86f1bcd8ac4e
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 $groupsql
112 JOIN (
113 SELECT DISTINCT ra.userid
114 FROM {$CFG->prefix}role_assignments ra
115 WHERE ra.roleid $gradebookroles
116 AND ra.contextid $relatedcontexts
117 ) rainner ON rainner.userid = u.id
118 WHERE u.deleted = 0
119 $groupwheresql
120 ORDER BY $order";
122 $this->users_rs = get_recordset_sql($users_sql);
124 if (!empty($this->grade_items)) {
125 $itemids = array_keys($this->grade_items);
126 $itemids = implode(',', $itemids);
128 $grades_sql = "SELECT g.* $ofields
129 FROM {$CFG->prefix}grade_grades g
130 JOIN {$CFG->prefix}user u ON g.userid = u.id
131 $groupsql
132 JOIN (
133 SELECT DISTINCT ra.userid
134 FROM {$CFG->prefix}role_assignments ra
135 WHERE ra.roleid $gradebookroles
136 AND ra.contextid $relatedcontexts
137 ) rainner ON rainner.userid = u.id
138 WHERE u.deleted = 0
139 AND g.itemid IN ($itemids)
140 $groupwheresql
141 ORDER BY $order, g.itemid ASC";
142 $this->grades_rs = get_recordset_sql($grades_sql);
143 } else {
144 $this->grades_rs = false;
147 return true;
151 * Returns information about the next user
152 * @return mixed array of user info, all grades and feedback or null when no more users found
154 function next_user() {
155 if (!$this->users_rs) {
156 return false; // no users present
159 if (!$user = rs_fetch_next_record($this->users_rs)) {
160 if ($current = $this->_pop()) {
161 // this is not good - user or grades updated between the two reads above :-(
164 return false; // no more users
167 // find grades of this user
168 $grade_records = array();
169 while (true) {
170 if (!$current = $this->_pop()) {
171 break; // no more grades
174 if ($current->userid != $user->id) {
175 // grade of the next user, we have all for this user
176 $this->_push($current);
177 break;
180 $grade_records[$current->itemid] = $current;
183 $grades = array();
184 $feedbacks = array();
186 if (!empty($this->grade_items)) {
187 foreach ($this->grade_items as $grade_item) {
188 if (array_key_exists($grade_item->id, $grade_records)) {
189 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
190 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
191 unset($grade_records[$grade_item->id]->feedback);
192 unset($grade_records[$grade_item->id]->feedbackformat);
193 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
194 } else {
195 $feedbacks[$grade_item->id]->feedback = '';
196 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
197 $grades[$grade_item->id] = new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
202 $result = new object();
203 $result->user = $user;
204 $result->grades = $grades;
205 $result->feedbacks = $feedbacks;
207 return $result;
211 * Close the iterator, do not forget to call this function.
212 * @return void
214 function close() {
215 if ($this->users_rs) {
216 rs_close($this->users_rs);
217 $this->users_rs = null;
219 if ($this->grades_rs) {
220 rs_close($this->grades_rs);
221 $this->grades_rs = null;
223 $this->gradestack = array();
227 * Internal function
229 function _push($grade) {
230 array_push($this->gradestack, $grade);
234 * Internal function
236 function _pop() {
237 if (empty($this->gradestack)) {
238 if (!$this->grades_rs) {
239 return NULL; // no grades present
242 if (!$grade = rs_fetch_next_record($this->grades_rs)) {
243 return NULL; // no more grades
246 return $grade;
247 } else {
248 return array_pop($this->gradestack);
254 * Print a selection popup form of the graded users in a course.
256 * @param int $courseid id of the course
257 * @param string $actionpage The page receiving the data from the popoup form
258 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
259 * @param int $groupid id of requested group, 0 means all
260 * @param int $includeall bool include all option
261 * @param bool $return If true, will return the HTML, otherwise, will print directly
262 * @return null
264 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
265 global $CFG, $USER;
267 if (is_null($userid)) {
268 $userid = $USER->id;
271 $context = get_context_instance(CONTEXT_COURSE, $course->id);
273 $menu = array(); // Will be a list of userid => user name
275 $gui = new graded_users_iterator($course, null, $groupid);
276 $gui->init();
279 $label = get_string('selectauser', 'grades');
280 if ($includeall) {
281 $menu[0] = get_string('allusers', 'grades');
282 $label = get_string('selectalloroneuser', 'grades');
285 while ($userdata = $gui->next_user()) {
286 $user = $userdata->user;
287 $menu[$user->id] = fullname($user);
290 $gui->close();
292 if ($includeall) {
293 $menu[0] .= " (" . (count($menu) - 1) . ")";
296 return popup_form($CFG->wwwroot.'/grade/' . $actionpage . '&amp;userid=', $menu, 'choosegradeduser', $userid, 'choose', '', '',
297 $return, 'self', $label);
301 * Print grading plugin selection popup form.
303 * @param int $courseid id of course
304 * @param string $active_type type of plugin on current page - import, export, report or edit
305 * @param string $active_plugin active plugin type - grader, user, cvs, ...
306 * @param boolean $return return as string
307 * @return nothing or string if $return true
309 function print_grade_plugin_selector($plugin_info, $return=false) {
310 global $CFG;
312 $menu = array();
313 $count = 0;
314 $active = '';
316 foreach ($plugin_info as $plugin_type => $plugins) {
317 if ($plugin_type == 'strings') {
318 continue;
321 $first_plugin = reset($plugins);
323 $menu[$first_plugin['link'].'&amp;'] = '--'.$plugin_info['strings'][$plugin_type];
325 if (empty($plugins['id'])) {
326 foreach ($plugins as $plugin) {
327 $menu[$plugin['link']] = $plugin['string'];
328 $count++;
333 /// finally print/return the popup form
334 if ($count > 1) {
335 $select = popup_form('', $menu, 'choosepluginreport', '', get_string('chooseaction', 'grades'), '', '', true, 'self');
336 if ($return) {
337 return $select;
338 } else {
339 echo $select;
341 } else {
342 // only one option - no plugin selector needed
343 return '';
348 * Print grading plugin selection tab-based navigation.
350 * @param int $courseid id of course
351 * @param string $active_type type of plugin on current page - import, export, report or edit
352 * @param string $active_plugin active plugin type - grader, user, cvs, ...
353 * @param boolean $return return as string
354 * @return nothing or string if $return true
356 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
357 global $CFG, $COURSE;
359 if (!isset($currenttab)) {
360 $currenttab = '';
363 $tabs = array();
364 $top_row = array();
365 $bottom_row = array();
366 $inactive = array($active_plugin);
367 $activated = array();
369 $count = 0;
370 $active = '';
372 foreach ($plugin_info as $plugin_type => $plugins) {
373 if ($plugin_type == 'strings') {
374 continue;
377 // If $plugins is actually the definition of a child-less parent link:
378 if (!empty($plugins['id'])) {
379 $string = $plugins['string'];
380 if (!empty($plugin_info[$active_type]['parent'])) {
381 $string = $plugin_info[$active_type]['parent']['string'];
384 $top_row[] = new tabobject($plugin_type, $plugins['link'], $string);
385 continue;
388 $first_plugin = reset($plugins);
389 $url = $first_plugin['link'];
391 if ($plugin_type == 'report') {
392 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
395 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
397 if ($active_type == $plugin_type) {
398 foreach ($plugins as $plugin) {
399 $bottom_row[] = new tabobject($plugin['id'], $plugin['link'], $plugin['string']);
400 if ($plugin['id'] == $active_plugin) {
401 $inactive = array($plugin['id']);
407 $tabs[] = $top_row;
408 $tabs[] = $bottom_row;
410 if ($return) {
411 return print_tabs($tabs, $active_type, $inactive, $activated, true);
412 } else {
413 print_tabs($tabs, $active_type, $inactive, $activated);
417 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
418 global $CFG;
420 $context = get_context_instance(CONTEXT_COURSE, $courseid);
422 $plugin_info = array();
423 $count = 0;
424 $active = '';
425 $url_prefix = $CFG->wwwroot . '/grade/';
427 // Language strings
428 $plugin_info['strings'] = array(
429 'report' => get_string('view'),
430 'edittree' => get_string('edittree', 'grades'),
431 'scale' => get_string('scales'),
432 'outcome' => get_string('outcomes', 'grades'),
433 'letter' => get_string('letters', 'grades'),
434 'export' => get_string('export', 'grades'),
435 'import' => get_string('import'),
436 'preferences' => get_string('mypreferences', 'grades'),
437 'settings' => get_string('settings'));
439 // Settings tab first
440 if (has_capability('moodle/course:update', $context)) {
441 $url = $url_prefix.'edit/settings/index.php?id='.$courseid;
443 if ($active_type == 'settings' and $active_plugin == 'course') {
444 $active = $url;
447 $plugin_info['settings'] = array();
448 $plugin_info['settings']['course'] = array('id' => 'coursesettings', 'link' => $url, 'string' => get_string('course'));
449 $count++;
453 /// report plugins with its special structure
454 if ($reports = get_list_of_plugins('grade/report', 'CVS')) { // Get all installed reports
455 foreach ($reports as $key => $plugin) { // Remove ones we can't see
456 // Outcomes are a special core plugin depending on $CFG->enableoutcomes
457 if ($plugin == 'outcomes' && empty($CFG->enableoutcomes)) {
458 unset($reports[$key]);
460 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
461 unset($reports[$key]);
466 $reportnames = array();
468 if (!empty($reports)) {
469 foreach ($reports as $plugin) {
470 $url = $url_prefix.'report/'.$plugin.'/index.php?id='.$courseid;
471 if ($active_type == 'report' and $active_plugin == $plugin ) {
472 $active = $url;
474 $reportnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradereport_'.$plugin));
476 // Add link to preferences tab if such a page exists
477 if (file_exists($CFG->dirroot . '/grade/report/'.$plugin.'/preferences.php')) {
478 $pref_url = $url_prefix.'report/'.$plugin.'/preferences.php?id='.$courseid;
479 $plugin_info['preferences'][$plugin] = array('id' => $plugin, 'link' => $pref_url, 'string' => get_string('modulename', 'gradereport_'.$plugin));
482 $count++;
484 asort($reportnames);
486 if (!empty($reportnames)) {
487 $plugin_info['report']=$reportnames;
490 /// editing scripts - not real plugins
491 if (has_capability('moodle/grade:manage', $context)
492 or has_capability('moodle/grade:manageletters', $context)
493 or has_capability('moodle/course:managescales', $context)
494 or has_capability('moodle/course:update', $context)) {
496 if (has_capability('moodle/grade:manage', $context)) {
497 $url = $url_prefix.'edit/tree/index.php?sesskey='.sesskey().'&amp;showadvanced=0&amp;id='.$courseid;
498 $url_adv = $url_prefix.'edit/tree/index.php?sesskey='.sesskey().'&amp;showadvanced=1&amp;id='.$courseid;
500 if ($active_type == 'edittree' and $active_plugin == 'simpleview') {
501 $active = $url;
502 } elseif ($active_type == 'edittree' and $active_plugin == 'fullview') {
503 $active = $url_adv;
506 $plugin_info['edittree'] = array();
507 $plugin_info['edittree']['simpleview'] = array('id' => 'simpleview', 'link' => $url, 'string' => get_string('simpleview', 'grades'));
508 $plugin_info['edittree']['fullview'] = array('id' => 'fullview', 'link' => $url_adv, 'string' => get_string('fullview', 'grades'));
509 $count++;
512 if (has_capability('moodle/course:managescales', $context)) {
513 $url = $url_prefix.'edit/scale/index.php?id='.$courseid;
515 if ($active_type == 'scale' and is_null($active_plugin)) {
516 $active = $url;
519 $plugin_info['scale'] = array();
521 if ($active_type == 'scale' and $active_plugin == 'edit') {
522 $edit_url = $url_prefix.'edit/scale/edit.php?courseid='.$courseid.'&amp;id='.optional_param('id', 0, PARAM_INT);
523 $active = $edit_url;
524 $plugin_info['scale']['view'] = array('id' => 'edit', 'link' => $edit_url, 'string' => get_string('edit'),
525 'parent' => array('id' => 'scale', 'link' => $url, 'string' => get_string('scales')));
526 } else {
527 $plugin_info['scale']['view'] = array('id' => 'scale', 'link' => $url, 'string' => get_string('view'));
530 $count++;
533 if (!empty($CFG->enableoutcomes) && (has_capability('moodle/grade:manage', $context) or
534 has_capability('moodle/course:update', $context))) {
536 $url_course = $url_prefix.'edit/outcome/course.php?id='.$courseid;
537 $url_edit = $url_prefix.'edit/outcome/index.php?id='.$courseid;
539 $plugin_info['outcome'] = array();
541 if (has_capability('moodle/course:update', $context)) { // Default to course assignment
542 $plugin_info['outcome']['course'] = array('id' => 'course', 'link' => $url_course, 'string' => get_string('outcomescourse', 'grades'));
543 $plugin_info['outcome']['edit'] = array('id' => 'edit', 'link' => $url_edit, 'string' => get_string('editoutcomes', 'grades'));
544 } else {
545 $plugin_info['outcome'] = array('id' => 'edit', 'link' => $url_course, 'string' => get_string('outcomescourse', 'grades'));
548 if ($active_type == 'outcome' and is_null($active_plugin)) {
549 $active = $url_edit;
550 } elseif ($active_type == 'outcome' and $active_plugin == 'course' ) {
551 $active = $url_course;
552 } elseif ($active_type == 'outcome' and $active_plugin == 'edit' ) {
553 $active = $url_edit;
554 } elseif ($active_type == 'outcome' and $active_plugin == 'import') {
555 $plugin_info['outcome']['import'] = array('id' => 'import', 'link' => null, 'string' => get_string('importoutcomes', 'grades'));
558 $count++;
561 if (has_capability('moodle/grade:manage', $context) or has_capability('moodle/grade:manageletters', $context)) {
562 $course_context = get_context_instance(CONTEXT_COURSE, $courseid);
563 $url = $url_prefix.'edit/letter/index.php?id='.$courseid;
564 $url_edit = $url_prefix.'edit/letter/edit.php?id='.$course_context->id;
566 if ($active_type == 'letter' and $active_plugin == 'view' ) {
567 $active = $url;
568 } elseif ($active_type == 'letter' and $active_plugin == 'edit' ) {
569 $active = $url_edit;
572 $plugin_info['letter'] = array();
573 $plugin_info['letter']['view'] = array('id' => 'view', 'link' => $url, 'string' => get_string('view'));
574 $plugin_info['letter']['edit'] = array('id' => 'edit', 'link' => $url_edit, 'string' => get_string('edit'));
575 $count++;
579 /// standard import plugins
580 if ($imports = get_list_of_plugins('grade/import', 'CVS')) { // Get all installed import plugins
581 foreach ($imports as $key => $plugin) { // Remove ones we can't see
582 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
583 unset($imports[$key]);
587 $importnames = array();
588 if (!empty($imports)) {
589 foreach ($imports as $plugin) {
590 $url = $url_prefix.'import/'.$plugin.'/index.php?id='.$courseid;
591 if ($active_type == 'import' and $active_plugin == $plugin ) {
592 $active = $url;
594 $importnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradeimport_'.$plugin));
595 $count++;
597 asort($importnames);
599 if (!empty($importnames)) {
600 $plugin_info['import']=$importnames;
603 /// standard export plugins
604 if ($exports = get_list_of_plugins('grade/export', 'CVS')) { // Get all installed export plugins
605 foreach ($exports as $key => $plugin) { // Remove ones we can't see
606 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
607 unset($exports[$key]);
611 $exportnames = array();
612 if (!empty($exports)) {
613 foreach ($exports as $plugin) {
614 $url = $url_prefix.'export/'.$plugin.'/index.php?id='.$courseid;
615 if ($active_type == 'export' and $active_plugin == $plugin ) {
616 $active = $url;
618 $exportnames[$plugin] = array('id' => $plugin, 'link' => $url, 'string' => get_string('modulename', 'gradeexport_'.$plugin));
619 $count++;
621 asort($exportnames);
624 if (!empty($exportnames)) {
625 $plugin_info['export']=$exportnames;
628 // Key managers
629 if ($CFG->gradepublishing) {
630 $keymanager_url = $url_prefix.'export/keymanager.php?id='.$courseid;
631 $plugin_info['export']['keymanager'] = array('id' => 'keymanager', 'link' => $keymanager_url, 'string' => get_string('keymanager', 'grades'));
632 if ($active_type == 'export' and $active_plugin == 'keymanager' ) {
633 $active = $keymanager_url;
635 $count++;
637 $keymanager_url = $url_prefix.'import/keymanager.php?id='.$courseid;
638 $plugin_info['import']['keymanager'] = array('id' => 'keymanager', 'link' => $keymanager_url, 'string' => get_string('keymanager', 'grades'));
639 if ($active_type == 'import' and $active_plugin == 'keymanager' ) {
640 $active = $keymanager_url;
642 $count++;
646 foreach ($plugin_info as $plugin_type => $plugins) {
647 if (!empty($plugins['id']) && $active_plugin == $plugins['id']) {
648 $plugin_info['strings']['active_plugin_str'] = $plugins['string'];
649 break;
651 foreach ($plugins as $plugin) {
652 if ($active_plugin == $plugin['id']) {
653 $plugin_info['strings']['active_plugin_str'] = $plugin['string'];
658 // Put settings last
659 if (!empty($plugin_info['settings'])) {
660 $settings = $plugin_info['settings'];
661 unset($plugin_info['settings']);
662 $plugin_info['settings'] = $settings;
665 // Put preferences last
666 if (!empty($plugin_info['preferences'])) {
667 $prefs = $plugin_info['preferences'];
668 unset($plugin_info['preferences']);
669 $plugin_info['preferences'] = $prefs;
672 // Check import and export caps
673 if (!has_capability('moodle/grade:export', $context)) {
674 unset($plugin_info['export']);
676 if (!has_capability('moodle/grade:import', $context)) {
677 unset($plugin_info['import']);
679 return $plugin_info;
683 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
684 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
685 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
686 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
687 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
689 * @param int $courseid
690 * @param string $active_type The type of the current page (report, settings, import, export, scales, outcomes, letters)
691 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
692 * @param string $heading The heading of the page. Tries to guess if none is given
693 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
694 * @param string $bodytags Additional attributes that will be added to the <body> tag
695 * @param string $buttons Additional buttons to display on the page
697 * @return string HTML code or nothing if $return == false
699 function print_grade_page_head($courseid, $active_type, $active_plugin=null, $heading = false, $return=false, $bodytags='', $buttons=false, $extracss=array()) {
700 global $CFG, $COURSE;
701 $strgrades = get_string('grades');
702 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
704 // Determine the string of the active plugin
705 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
706 $stractive_type = $plugin_info['strings'][$active_type];
708 $navlinks = array();
709 $first_link = '';
711 if ($active_type == 'settings' && $active_plugin != 'coursesettings') {
712 $first_link = $plugin_info['report'][$active_plugin]['link'];
713 } elseif ($active_type != 'report') {
714 $first_link = $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id;
717 if ($active_type == 'preferences') {
718 $CFG->stylesheets[] = $CFG->wwwroot . '/grade/report/styles.css';
721 foreach ($extracss as $css_url) {
722 $CFG->stylesheets[] = $css_url;
725 $navlinks[] = array('name' => $strgrades,
726 'link' => $first_link,
727 'type' => 'misc');
729 $active_type_link = '';
731 if (!empty($plugin_info[$active_type]['link']) && $plugin_info[$active_type]['link'] != qualified_me()) {
732 $active_type_link = $plugin_info[$active_type]['link'];
735 if (!empty($plugin_info[$active_type]['parent']['link'])) {
736 $active_type_link = $plugin_info[$active_type]['parent']['link'];
737 $navlinks[] = array('name' => $stractive_type, 'link' => $active_type_link, 'type' => 'misc');
740 if (empty($plugin_info[$active_type]['id'])) {
741 $navlinks[] = array('name' => $stractive_type, 'link' => $active_type_link, 'type' => 'misc');
744 $navlinks[] = array('name' => $stractive_plugin, 'link' => null, 'type' => 'misc');
746 $navigation = build_navigation($navlinks);
748 $title = ': ' . $stractive_plugin;
749 if (empty($plugin_info[$active_type]['id']) || !empty($plugin_info[$active_type]['parent'])) {
750 $title = ': ' . $stractive_type . ': ' . $stractive_plugin;
753 $returnval = print_header_simple($strgrades . ': ' . $stractive_type, $title, $navigation, '',
754 $bodytags, true, $buttons, navmenu($COURSE), false, '', $return);
756 // Guess heading if not given explicitly
757 if (!$heading) {
758 $heading = $stractive_plugin;
761 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
762 $returnval .= print_grade_plugin_selector($plugin_info, $return);
764 $returnval .= print_heading($heading);
766 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
767 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
770 if ($return) {
771 return $returnval;
776 * Utility class used for return tracking when using edit and other forms in grade plugins
778 class grade_plugin_return {
779 var $type;
780 var $plugin;
781 var $courseid;
782 var $userid;
783 var $page;
786 * Constructor
787 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
789 function grade_plugin_return ($params=null) {
790 if (empty($params)) {
791 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
792 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
793 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
794 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
795 $this->page = optional_param('gpr_page', null, PARAM_INT);
797 } else {
798 foreach ($params as $key=>$value) {
799 if (array_key_exists($key, $this)) {
800 $this->$key = $value;
807 * Returns return parameters as options array suitable for buttons.
808 * @return array options
810 function get_options() {
811 if (empty($this->type)) {
812 return array();
815 $params = array();
817 if (!empty($this->plugin)) {
818 $params['plugin'] = $this->plugin;
821 if (!empty($this->courseid)) {
822 $params['id'] = $this->courseid;
825 if (!empty($this->userid)) {
826 $params['userid'] = $this->userid;
829 if (!empty($this->page)) {
830 $params['page'] = $this->page;
833 return $params;
837 * Returns return url
838 * @param string $default default url when params not set
839 * @return string url
841 function get_return_url($default, $extras=null) {
842 global $CFG;
844 if (empty($this->type) or empty($this->plugin)) {
845 return $default;
848 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
849 $glue = '?';
851 if (!empty($this->courseid)) {
852 $url .= $glue.'id='.$this->courseid;
853 $glue = '&amp;';
856 if (!empty($this->userid)) {
857 $url .= $glue.'userid='.$this->userid;
858 $glue = '&amp;';
861 if (!empty($this->page)) {
862 $url .= $glue.'page='.$this->page;
863 $glue = '&amp;';
866 if (!empty($extras)) {
867 foreach($extras as $key=>$value) {
868 $url .= $glue.$key.'='.$value;
869 $glue = '&amp;';
873 return $url;
877 * Returns string with hidden return tracking form elements.
878 * @return string
880 function get_form_fields() {
881 if (empty($this->type)) {
882 return '';
885 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
887 if (!empty($this->plugin)) {
888 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
891 if (!empty($this->courseid)) {
892 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
895 if (!empty($this->userid)) {
896 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
899 if (!empty($this->page)) {
900 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
905 * Add hidden elements into mform
906 * @param object $mform moodle form object
907 * @return void
909 function add_mform_elements(&$mform) {
910 if (empty($this->type)) {
911 return;
914 $mform->addElement('hidden', 'gpr_type', $this->type);
915 $mform->setType('gpr_type', PARAM_SAFEDIR);
917 if (!empty($this->plugin)) {
918 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
919 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
922 if (!empty($this->courseid)) {
923 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
924 $mform->setType('gpr_courseid', PARAM_INT);
927 if (!empty($this->userid)) {
928 $mform->addElement('hidden', 'gpr_userid', $this->userid);
929 $mform->setType('gpr_userid', PARAM_INT);
932 if (!empty($this->page)) {
933 $mform->addElement('hidden', 'gpr_page', $this->page);
934 $mform->setType('gpr_page', PARAM_INT);
939 * Add return tracking params into url
940 * @param string $url
941 * @return string $url with erturn tracking params
943 function add_url_params($url) {
944 if (empty($this->type)) {
945 return $url;
948 if (strpos($url, '?') === false) {
949 $url .= '?gpr_type='.$this->type;
950 } else {
951 $url .= '&amp;gpr_type='.$this->type;
954 if (!empty($this->plugin)) {
955 $url .= '&amp;gpr_plugin='.$this->plugin;
958 if (!empty($this->courseid)) {
959 $url .= '&amp;gpr_courseid='.$this->courseid;
962 if (!empty($this->userid)) {
963 $url .= '&amp;gpr_userid='.$this->userid;
966 if (!empty($this->page)) {
967 $url .= '&amp;gpr_page='.$this->page;
970 return $url;
975 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
976 * @param string $path The path of the calling script (using __FILE__?)
977 * @param string $pagename The language string to use as the last part of the navigation (non-link)
978 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
979 * @return string
981 function grade_build_nav($path, $pagename=null, $id=null) {
982 global $CFG, $COURSE;
984 $strgrades = get_string('grades', 'grades');
986 // Parse the path and build navlinks from its elements
987 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
988 $path = substr($path, $dirroot_length);
989 $path = str_replace('\\', '/', $path);
991 $path_elements = explode('/', $path);
993 $path_elements_count = count($path_elements);
995 // First link is always 'grade'
996 $navlinks = array();
997 $navlinks[] = array('name' => $strgrades,
998 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
999 'type' => 'misc');
1001 $link = '';
1002 $numberofelements = 3;
1004 // Prepare URL params string
1005 $id_string = '?';
1006 if (!is_null($id)) {
1007 if (is_array($id)) {
1008 foreach ($id as $idkey => $idvalue) {
1009 $id_string .= "$idkey=$idvalue&amp;";
1011 } else {
1012 $id_string .= "id=$id";
1016 $navlink4 = null;
1018 // Remove file extensions from filenames
1019 foreach ($path_elements as $key => $filename) {
1020 $path_elements[$key] = str_replace('.php', '', $filename);
1023 // Second level links
1024 switch ($path_elements[1]) {
1025 case 'edit': // No link
1026 if ($path_elements[3] != 'index.php') {
1027 $numberofelements = 4;
1029 break;
1030 case 'import': // No link
1031 break;
1032 case 'export': // No link
1033 break;
1034 case 'report':
1035 // $id is required for this link. Do not print it if $id isn't given
1036 if (!is_null($id)) {
1037 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
1040 if ($path_elements[2] == 'grader') {
1041 $numberofelements = 4;
1043 break;
1045 default:
1046 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1047 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
1048 return false;
1051 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
1053 // Third level links
1054 if (empty($pagename)) {
1055 $pagename = get_string($path_elements[2], 'grades');
1058 switch ($numberofelements) {
1059 case 3:
1060 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
1061 break;
1062 case 4:
1064 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1065 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
1066 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
1067 'type' => 'misc');
1069 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
1070 break;
1072 $navigation = build_navigation($navlinks);
1074 return $navigation;
1078 * General structure representing grade items in course
1080 class grade_structure {
1081 var $context;
1083 var $courseid;
1086 * 1D array of grade items only
1088 var $items;
1091 * Returns icon of element
1092 * @param object $element
1093 * @param bool $spacerifnone return spacer if no icon found
1094 * @return string icon or spacer
1096 function get_element_icon(&$element, $spacerifnone=false) {
1097 global $CFG;
1099 switch ($element['type']) {
1100 case 'item':
1101 case 'courseitem':
1102 case 'categoryitem':
1103 if ($element['object']->is_calculated()) {
1104 $strcalc = get_string('calculatedgrade', 'grades');
1105 return '<img src="'.$CFG->pixpath.'/i/calc.gif" class="icon itemicon" title="'.s($strcalc).'" alt="'.s($strcalc).'"/>';
1107 } else if (($element['object']->is_course_item() or $element['object']->is_category_item())
1108 and ($element['object']->gradetype == GRADE_TYPE_SCALE or $element['object']->gradetype == GRADE_TYPE_VALUE)) {
1109 if ($category = $element['object']->get_item_category()) {
1110 switch ($category->aggregation) {
1111 case GRADE_AGGREGATE_MEDIAN:
1112 case GRADE_AGGREGATE_MEDIAN:
1113 return '<img src="'.$CFG->pixpath.'/i/agg_sum.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1114 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1115 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1116 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1117 return '<img src="'.$CFG->pixpath.'/i/agg_mean.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1118 case GRADE_AGGREGATE_SUM:
1119 return '<img src="'.$CFG->pixpath.'/i/agg_sum.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
1123 } else if ($element['object']->itemtype == 'mod') {
1124 $strmodname = get_string('modulename', $element['object']->itemmodule);
1125 return '<img src="'.$CFG->modpixpath.'/'.$element['object']->itemmodule.'/icon.gif" class="icon itemicon" title="' .s($strmodname).'" alt="' .s($strmodname).'"/>';
1127 } else if ($element['object']->itemtype == 'manual') {
1128 if ($element['object']->is_outcome_item()) {
1129 $stroutcome = get_string('outcome', 'grades');
1130 return '<img src="'.$CFG->pixpath.'/i/outcomes.gif" class="icon itemicon" title="'.s($stroutcome).'" alt="'.s($stroutcome).'"/>';
1131 } else {
1132 $strmanual = get_string('manualitem', 'grades');
1133 return '<img src="'.$CFG->pixpath.'/t/manual_item.gif" class="icon itemicon" title="'.s($strmanual).'" alt="'.s($strmanual).'"/>';
1136 break;
1138 case 'category':
1139 $strcat = get_string('category', 'grades');
1140 return '<img src="'.$CFG->pixpath.'/f/folder.gif" class="icon itemicon" title="'.s($strcat).'" alt="'.s($strcat).'" />';
1143 if ($spacerifnone) {
1144 return '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="icon itemicon" alt=""/>';
1145 } else {
1146 return '';
1151 * Returns name of element optionally with icon and link
1152 * @param object $element
1153 * @param bool $withlinks
1154 * @param bool $icons
1155 * @param bool $spacerifnone return spacer if no icon found
1156 * @return header string
1158 function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1159 global $CFG;
1161 $header = '';
1163 if ($icon) {
1164 $header .= $this->get_element_icon($element, $spacerifnone);
1167 $header .= $element['object']->get_name();
1169 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and $element['type'] != 'courseitem') {
1170 return $header;
1173 $itemtype = $element['object']->itemtype;
1174 $itemmodule = $element['object']->itemmodule;
1175 $iteminstance = $element['object']->iteminstance;
1177 if ($withlink and $itemtype=='mod' and $iteminstance and $itemmodule) {
1178 if ($cm = get_coursemodule_from_instance($itemmodule, $iteminstance, $this->courseid)) {
1180 $a->name = get_string('modulename', $element['object']->itemmodule);
1181 $title = get_string('linktoactivity', 'grades', $a);
1182 $dir = $CFG->dirroot.'/mod/'.$itemmodule;
1184 if (file_exists($dir.'/grade.php')) {
1185 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/grade.php?id='.$cm->id;
1186 } else {
1187 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/view.php?id='.$cm->id;
1190 $header = '<a href="'.$url.'" title="'.s($title).'">'.$header.'</a>';
1194 return $header;
1198 * Returns the grade eid - the grade may not exist yet.
1199 * @param $grade_grade object
1200 * @return string eid
1202 function get_grade_eid($grade_grade) {
1203 if (empty($grade_grade->id)) {
1204 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1205 } else {
1206 return 'g'.$grade_grade->id;
1211 * Returns the grade_item eid
1212 * @param $grade_item object
1213 * @return string eid
1215 function get_item_eid($grade_item) {
1216 return 'i'.$grade_item->id;
1219 function get_params_for_iconstr($element) {
1220 $strparams = new stdClass();
1221 $strparams->category = '';
1222 $strparams->itemname = '';
1223 $strparams->itemmodule = '';
1224 if (!method_exists($element['object'], 'get_name')) {
1225 return $strparams;
1228 $strparams->itemname = html_to_text($element['object']->get_name());
1230 // If element name is categorytotal, get the name of the parent category
1231 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1232 $parent = $element['object']->get_parent_category();
1233 $strparams->category = $parent->get_name() . ' ';
1234 } else {
1235 $strparams->category = '';
1238 $strparams->itemmodule = null;
1239 if (isset($element['object']->itemmodule)) {
1240 $strparams->itemmodule = $element['object']->itemmodule;
1242 return $strparams;
1246 * Return edit icon for give element
1247 * @param object $element
1248 * @return string
1250 function get_edit_icon($element, $gpr) {
1251 global $CFG;
1253 if (!has_capability('moodle/grade:manage', $this->context)) {
1254 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1255 // oki - let them override grade
1256 } else {
1257 return '';
1261 static $strfeedback = null;
1262 static $streditgrade = null;
1263 if (is_null($streditgrade)) {
1264 $streditgrade = get_string('editgrade', 'grades');
1265 $strfeedback = get_string('feedback');
1268 $strparams = $this->get_params_for_iconstr($element);
1269 if ($element['type'] == 'item' or $element['type'] == 'category') {
1272 $object = $element['object'];
1274 switch ($element['type']) {
1275 case 'item':
1276 case 'categoryitem':
1277 case 'courseitem':
1278 $stredit = get_string('editverbose', 'grades', $strparams);
1279 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1280 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1281 } else {
1282 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1284 $url = $gpr->add_url_params($url);
1285 break;
1287 case 'category':
1288 $stredit = get_string('editverbose', 'grades', $strparams);
1289 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1290 $url = $gpr->add_url_params($url);
1291 break;
1293 case 'grade':
1294 $stredit = $streditgrade;
1295 if (empty($object->id)) {
1296 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
1297 } else {
1298 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1300 $url = $gpr->add_url_params($url);
1301 if (!empty($object->feedback)) {
1302 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1304 break;
1306 default:
1307 $url = null;
1310 if ($url) {
1311 return '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.s($stredit).'" title="'.s($stredit).'"/></a>';
1313 } else {
1314 return '';
1319 * Return hiding icon for give element
1320 * @param object $element
1321 * @return string
1323 function get_hiding_icon($element, $gpr) {
1324 global $CFG;
1326 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
1327 return '';
1330 $strparams = $this->get_params_for_iconstr($element);
1331 $strshow = get_string('showverbose', 'grades', $strparams);
1332 $strhide = get_string('hideverbose', 'grades', $strparams);
1334 if ($element['object']->is_hidden()) {
1335 $icon = 'show';
1336 $tooltip = $strshow;
1338 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
1339 $icon = 'hiddenuntil';
1340 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
1343 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1344 . '&amp;eid='.$element['eid'];
1345 $url = $gpr->add_url_params($url);
1346 $action = '<a href="'.$url.'"><img alt="'.$strshow.'" src="'.$CFG->pixpath.'/t/'.$icon.'.gif" class="iconsmall" title="'.s($tooltip).'"/></a>';
1348 } else {
1349 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1350 . '&amp;eid='.$element['eid'];
1351 $url = $gpr->add_url_params($url);
1352 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.s($strhide).'" title="'.s($strhide).'"/></a>';
1354 return $action;
1358 * Return locking icon for given element
1359 * @param object $element
1360 * @return string
1362 function get_locking_icon($element, $gpr) {
1363 global $CFG;
1365 $strparams = $this->get_params_for_iconstr($element);
1366 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1367 $strlock = get_string('lockverbose', 'grades', $strparams);
1369 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1370 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1371 $strparamobj = new stdClass();
1372 $strparamobj->itemname = $element['object']->grade_item->itemname;
1373 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1374 $action = '<img src="'.$CFG->pixpath.'/t/unlock_gray.gif" alt="'.s($strnonunlockable).'" class="iconsmall" title="'.s($strnonunlockable).'"/>';
1375 } elseif ($element['object']->is_locked()) {
1376 $icon = 'unlock';
1377 $tooltip = $strunlock;
1379 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
1380 $icon = 'locktime';
1381 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
1384 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1385 return '';
1387 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1388 . '&amp;eid='.$element['eid'];
1389 $url = $gpr->add_url_params($url);
1390 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/'.$icon.'.gif" alt="'.s($strunlock).'" class="iconsmall" title="'.s($tooltip).'"/></a>';
1392 } else {
1393 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1394 return '';
1396 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1397 . '&amp;eid='.$element['eid'];
1398 $url = $gpr->add_url_params($url);
1399 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.s($strlock).'" title="'
1400 . s($strlock).'"/></a>';
1402 return $action;
1406 * Return calculation icon for given element
1407 * @param object $element
1408 * @return string
1410 function get_calculation_icon($element, $gpr) {
1411 global $CFG;
1412 if (!has_capability('moodle/grade:manage', $this->context)) {
1413 return '';
1416 $calculation_icon = '';
1418 $type = $element['type'];
1419 $object = $element['object'];
1422 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1423 $strparams = $this->get_params_for_iconstr($element);
1424 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1426 // show calculation icon only when calculation possible
1427 if (!$object->is_external_item() and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
1428 if ($object->is_calculated()) {
1429 $icon = 'calc.gif';
1430 } else {
1431 $icon = 'calc_off.gif';
1433 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1434 $url = $gpr->add_url_params($url);
1435 $calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/'.$icon.'" class="iconsmall" alt="'
1436 . s($streditcalculation).'" title="'.s($streditcalculation).'" /></a>'. "\n";
1440 return $calculation_icon;
1445 * Flat structure similar to grade tree.
1447 class grade_seq extends grade_structure {
1450 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1451 * @var string $commonvars
1453 var $commonvars;
1456 * 1D array of elements
1458 var $elements;
1461 * Constructor, retrieves and stores array of all grade_category and grade_item
1462 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1463 * @param int $courseid
1464 * @param boolean $category_grade_last category grade item is the last child
1465 * @param array $collapsed array of collapsed categories
1467 function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1468 global $USER, $CFG;
1470 $this->courseid = $courseid;
1471 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
1472 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1474 // get course grade tree
1475 $top_element = grade_category::fetch_course_tree($courseid, true);
1477 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1479 foreach ($this->elements as $key=>$unused) {
1480 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
1485 * Static recursive helper - makes the grade_item for category the last children
1486 * @static
1487 * @param array $element The seed of the recursion
1488 * @return void
1490 function flatten(&$element, $category_grade_last, $nooutcomes) {
1491 if (empty($element['children'])) {
1492 return array();
1494 $children = array();
1496 foreach ($element['children'] as $sortorder=>$unused) {
1497 if ($nooutcomes and $element['type'] != 'category' and $element['children'][$sortorder]['object']->is_outcome_item()) {
1498 continue;
1500 $children[] = $element['children'][$sortorder];
1502 unset($element['children']);
1504 if ($category_grade_last and count($children) > 1) {
1505 $cat_item = array_shift($children);
1506 array_push($children, $cat_item);
1509 $result = array();
1510 foreach ($children as $child) {
1511 if ($child['type'] == 'category') {
1512 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
1513 } else {
1514 $child['eid'] = 'i'.$child['object']->id;
1515 $result[$child['object']->id] = $child;
1519 return $result;
1523 * Parses the array in search of a given eid and returns a element object with
1524 * information about the element it has found.
1525 * @param int $eid
1526 * @return object element
1528 function locate_element($eid) {
1529 // it is a grade - construct a new object
1530 if (strpos($eid, 'n') === 0) {
1531 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1532 return null;
1535 $itemid = $matches[1];
1536 $userid = $matches[2];
1538 //extra security check - the grade item must be in this tree
1539 if (!$item_el = $this->locate_element('i'.$itemid)) {
1540 return null;
1543 // $gradea->id may be null - means does not exist yet
1544 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1546 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1547 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1549 } else if (strpos($eid, 'g') === 0) {
1550 $id = (int)substr($eid, 1);
1551 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1552 return null;
1554 //extra security check - the grade item must be in this tree
1555 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1556 return null;
1558 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1559 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1562 // it is a category or item
1563 foreach ($this->elements as $element) {
1564 if ($element['eid'] == $eid) {
1565 return $element;
1569 return null;
1574 * This class represents a complete tree of categories, grade_items and final grades,
1575 * organises as an array primarily, but which can also be converted to other formats.
1576 * It has simple method calls with complex implementations, allowing for easy insertion,
1577 * deletion and moving of items and categories within the tree.
1579 class grade_tree extends grade_structure {
1582 * The basic representation of the tree as a hierarchical, 3-tiered array.
1583 * @var object $top_element
1585 var $top_element;
1588 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1589 * @var string $commonvars
1591 var $commonvars;
1594 * 2D array of grade items and categories
1596 var $levels;
1599 * Grade items
1601 var $items;
1604 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1605 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1606 * @param int $courseid
1607 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
1608 * @param boolean $category_grade_last category grade item is the last child
1609 * @param array $collapsed array of collapsed categories
1611 function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
1612 global $USER, $CFG;
1614 $this->courseid = $courseid;
1615 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
1616 $this->levels = array();
1617 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1619 // get course grade tree
1620 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1622 // collapse the categories if requested
1623 if (!empty($collapsed)) {
1624 grade_tree::category_collapse($this->top_element, $collapsed);
1627 // no otucomes if requested
1628 if (!empty($nooutcomes)) {
1629 grade_tree::no_outcomes($this->top_element);
1632 // move category item to last position in category
1633 if ($category_grade_last) {
1634 grade_tree::category_grade_last($this->top_element);
1637 if ($fillers) {
1638 // inject fake categories == fillers
1639 grade_tree::inject_fillers($this->top_element, 0);
1640 // add colspans to categories and fillers
1641 grade_tree::inject_colspans($this->top_element);
1644 grade_tree::fill_levels($this->levels, $this->top_element, 0);
1649 * Static recursive helper - removes items from collapsed categories
1650 * @static
1651 * @param array $element The seed of the recursion
1652 * @param array $collapsed array of collapsed categories
1653 * @return void
1655 function category_collapse(&$element, $collapsed) {
1656 if ($element['type'] != 'category') {
1657 return;
1659 if (empty($element['children']) or count($element['children']) < 2) {
1660 return;
1663 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
1664 $category_item = reset($element['children']); //keep only category item
1665 $element['children'] = array(key($element['children'])=>$category_item);
1667 } else {
1668 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1669 reset($element['children']);
1670 $first_key = key($element['children']);
1671 unset($element['children'][$first_key]);
1673 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1674 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1680 * Static recursive helper - removes all outcomes
1681 * @static
1682 * @param array $element The seed of the recursion
1683 * @return void
1685 function no_outcomes(&$element) {
1686 if ($element['type'] != 'category') {
1687 return;
1689 foreach ($element['children'] as $sortorder=>$child) {
1690 if ($element['children'][$sortorder]['type'] == 'item'
1691 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1692 unset($element['children'][$sortorder]);
1694 } else if ($element['children'][$sortorder]['type'] == 'category') {
1695 grade_tree::no_outcomes($element['children'][$sortorder]);
1701 * Static recursive helper - makes the grade_item for category the last children
1702 * @static
1703 * @param array $element The seed of the recursion
1704 * @return void
1706 function category_grade_last(&$element) {
1707 if (empty($element['children'])) {
1708 return;
1710 if (count($element['children']) < 2) {
1711 return;
1713 $first_item = reset($element['children']);
1714 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1715 // the category item might have been already removed
1716 $order = key($element['children']);
1717 unset($element['children'][$order]);
1718 $element['children'][$order] =& $first_item;
1720 foreach ($element['children'] as $sortorder => $child) {
1721 grade_tree::category_grade_last($element['children'][$sortorder]);
1726 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1727 * @static
1728 * @param int $levels
1729 * @param array $element The seed of the recursion
1730 * @param int $depth
1731 * @return void
1733 function fill_levels(&$levels, &$element, $depth) {
1734 if (!array_key_exists($depth, $levels)) {
1735 $levels[$depth] = array();
1738 // prepare unique identifier
1739 if ($element['type'] == 'category') {
1740 $element['eid'] = 'c'.$element['object']->id;
1741 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1742 $element['eid'] = 'i'.$element['object']->id;
1743 $this->items[$element['object']->id] =& $element['object'];
1746 $levels[$depth][] =& $element;
1747 $depth++;
1748 if (empty($element['children'])) {
1749 return;
1751 $prev = 0;
1752 foreach ($element['children'] as $sortorder=>$child) {
1753 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1754 $element['children'][$sortorder]['prev'] = $prev;
1755 $element['children'][$sortorder]['next'] = 0;
1756 if ($prev) {
1757 $element['children'][$prev]['next'] = $sortorder;
1759 $prev = $sortorder;
1764 * Static recursive helper - makes full tree (all leafes are at the same level)
1766 function inject_fillers(&$element, $depth) {
1767 $depth++;
1769 if (empty($element['children'])) {
1770 return $depth;
1772 $chdepths = array();
1773 $chids = array_keys($element['children']);
1774 $last_child = end($chids);
1775 $first_child = reset($chids);
1777 foreach ($chids as $chid) {
1778 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1780 arsort($chdepths);
1782 $maxdepth = reset($chdepths);
1783 foreach ($chdepths as $chid=>$chd) {
1784 if ($chd == $maxdepth) {
1785 continue;
1787 for ($i=0; $i < $maxdepth-$chd; $i++) {
1788 if ($chid == $first_child) {
1789 $type = 'fillerfirst';
1790 } else if ($chid == $last_child) {
1791 $type = 'fillerlast';
1792 } else {
1793 $type = 'filler';
1795 $oldchild =& $element['children'][$chid];
1796 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
1800 return $maxdepth;
1804 * Static recursive helper - add colspan information into categories
1806 function inject_colspans(&$element) {
1807 if (empty($element['children'])) {
1808 return 1;
1810 $count = 0;
1811 foreach ($element['children'] as $key=>$child) {
1812 $count += grade_tree::inject_colspans($element['children'][$key]);
1814 $element['colspan'] = $count;
1815 return $count;
1819 * Parses the array in search of a given eid and returns a element object with
1820 * information about the element it has found.
1821 * @param int $eid
1822 * @return object element
1824 function locate_element($eid) {
1825 // it is a grade - construct a new object
1826 if (strpos($eid, 'n') === 0) {
1827 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1828 return null;
1831 $itemid = $matches[1];
1832 $userid = $matches[2];
1834 //extra security check - the grade item must be in this tree
1835 if (!$item_el = $this->locate_element('i'.$itemid)) {
1836 return null;
1839 // $gradea->id may be null - means does not exist yet
1840 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1842 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1843 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1845 } else if (strpos($eid, 'g') === 0) {
1846 $id = (int)substr($eid, 1);
1847 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1848 return null;
1850 //extra security check - the grade item must be in this tree
1851 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1852 return null;
1854 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1855 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1858 // it is a category or item
1859 foreach ($this->levels as $row) {
1860 foreach ($row as $element) {
1861 if ($element['type'] == 'filler') {
1862 continue;
1864 if ($element['eid'] == $eid) {
1865 return $element;
1870 return null;