calendar/lib: calendar_set_filters() use pre-fetched context and course recs
[moodle-pu.git] / grade / lib.php
blob34f5d9b1e801bdd4a2e4d02a2afd5437dc7b6c6e
1 <?php //$Id$
3 require_once $CFG->libdir.'/gradelib.php';
6 /**
7 * This class iterates over all users that are graded in a course.
8 * Returns fetailed info about users and their grades.
9 */
10 class graded_users_iterator {
11 var $course;
12 var $grade_items;
13 var $groupid;
14 var $users_rs;
15 var $grades_rs;
16 var $gradestack;
18 /**
19 * Constructor
20 * @param $coruse object
21 * @param array grade_items array of grade items, if not specified only user info returned
22 * @param int $groupid iterate only group users if present
24 function graded_users_iterator($course, $grade_items=null, $groupid=0) {
25 $this->course = $course;
26 $this->grade_items = $grade_items;
27 $this->groupid = $groupid;
29 $this->gradestack = array();
32 /**
33 * Initialise the iterator
34 * @return boolean success
36 function init() {
37 global $CFG;
39 $this->close();
41 grade_regrade_final_grades($this->course->id);
42 $course_item = grade_item::fetch_course_item($this->course->id);
43 if ($course_item->needsupdate) {
44 // can not calculate all final grades - sorry
45 return false;
48 if (strpos($CFG->gradebookroles, ',') !== false) {
49 $gradebookroles = " = {$CFG->gradebookroles}";
50 } else {
51 $gradebookroles = " IN ({$CFG->gradebookroles})";
54 $relatedcontexts = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $this->course->id));
56 if ($this->groupid) {
57 $groupsql = "INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id";
58 $groupwheresql = "AND gm.groupid = {$this->groupid}";
59 } else {
60 $groupsql = "";
61 $groupwheresql = "";
64 $users_sql = "SELECT u.*
65 FROM {$CFG->prefix}user u
66 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
67 $groupsql
68 WHERE ra.roleid $gradebookroles
69 AND ra.contextid $relatedcontexts
70 $groupwheresql
71 ORDER BY u.id ASC";
72 $this->users_rs = get_recordset_sql($users_sql);
74 if (!empty($this->grade_items)) {
75 $itemids = array_keys($this->grade_items);
76 $itemids = implode(',', $itemids);
78 $grades_sql = "SELECT g.*, gt.feedback, gt.feedbackformat
79 FROM {$CFG->prefix}grade_grades g
80 LEFT JOIN {$CFG->prefix}grade_grades_text gt ON gt.gradeid = g.id
81 INNER JOIN {$CFG->prefix}user u ON g.userid = u.id
82 INNER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
83 $groupsql
84 WHERE ra.roleid $gradebookroles
85 AND ra.contextid $relatedcontexts
86 AND g.itemid IN ($itemids)
87 $groupwheresql
88 ORDER BY g.userid ASC, g.itemid ASC";
89 $this->grades_rs = get_recordset_sql($grades_sql);
92 return true;
95 /**
96 * Returns information about the next user
97 * @return mixed array of user info, all grades and feedback or null when no more users found
99 function next_user() {
100 if (!$this->users_rs or !$this->users_rs->RecordCount()) {
101 return false; // no users present
104 if (!$user = rs_fetch_next_record($this->users_rs)) {
105 return false; // no more users
108 //find the first grade of this user
109 $grade_records = array();
110 while (true) {
111 if (!$current = $this->_pop()) {
112 break; // no more grades
115 if ($current->userid < $user->id) {
116 // this should not happen, could be caused by concurrent updates - skip this record
117 continue;
119 } else if ($current->userid > $user->id) {
120 // this user does not have any more grades
121 $this->_push($current);
122 break;
125 $grade_records[$current->itemid] = $current;
128 $grades = array();
129 $feedbacks = array();
131 foreach ($this->grade_items as $grade_item) {
132 if (array_key_exists($grade_item->id, $grade_records)) {
133 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
134 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
135 unset($grade_records[$grade_item->id]->feedback);
136 unset($grade_records[$grade_item->id]->feedbackformat);
137 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
138 } else {
139 $feedbacks[$grade_item->id]->feedback = '';
140 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
141 $grades[$grade_item->id] = new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
145 $result = new object();
146 $result->user = $user;
147 $result->grades = $grades;
148 $result->feedbacks = $feedbacks;
150 return $result;
154 * Close the iterator, do not forget to call this function.
155 * @return void
157 function close() {
158 if ($this->users_rs) {
159 rs_close($this->users_rs);
160 $this->users_rs = null;
162 if ($this->grades_rs) {
163 rs_close($this->grades_rs);
164 $this->grades_rs = null;
166 $this->gradestack = array();
170 * Internal function
172 function _push($grade) {
173 array_push($this->gradestack, $grade);
177 * Internal function
179 function _pop() {
180 if (empty($this->gradestack)) {
181 if (!$this->grades_rs or !$this->grades_rs->RecordCount()) {
182 return NULL; // no grades present
185 if (!$grade = rs_fetch_next_record($this->grades_rs)) {
186 return NULL; // no more grades
189 return $grade;
190 } else {
191 return array_pop($this->gradestack);
197 * Print grading plugin selection popup form.
199 * @param int $courseid id of course
200 * @param string $active_type type of plugin on current page - import, export, report or edit
201 * @param string $active_plugin active plugin type - grader, user, cvs, ...
202 * @param boolean $return return as string
203 * @return nothing or string if $return true
205 function print_grade_plugin_selector($courseid, $active_type, $active_plugin, $return=false) {
206 global $CFG;
208 $context = get_context_instance(CONTEXT_COURSE, $courseid);
210 $menu = array();
212 $active = '';
214 /// report plugins with its special structure
215 if ($reports = get_list_of_plugins('grade/report', 'CVS')) { // Get all installed reports
216 foreach ($reports as $key => $plugin) { // Remove ones we can't see
217 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
218 unset($reports[$key]);
222 $reportnames = array();
223 if (!empty($reports)) {
224 foreach ($reports as $plugin) {
225 $url = 'report/'.$plugin.'/index.php?id='.$courseid;
226 if ($active_type == 'report' and $active_plugin == $plugin ) {
227 $active = $url;
229 $reportnames[$url] = get_string('modulename', 'gradereport_'.$plugin, NULL, $CFG->dirroot.'/grade/report/'.$plugin.'/lang/');
231 asort($reportnames);
233 if (!empty($reportnames)) {
234 $menu['reportgroup']='--'.get_string('reportplugins', 'grades');
235 $menu = $menu+$reportnames;
238 /// standard import plugins
239 if ($imports = get_list_of_plugins('grade/import', 'CVS')) { // Get all installed import plugins
240 foreach ($imports as $key => $plugin) { // Remove ones we can't see
241 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
242 unset($imports[$key]);
246 $importnames = array();
247 if (!empty($imports)) {
248 foreach ($imports as $plugin) {
249 $url = 'import/'.$plugin.'/index.php?id='.$courseid;
250 if ($active_type == 'import' and $active_plugin == $plugin ) {
251 $active = $url;
253 $importnames[$url] = get_string('modulename', 'gradeimport_'.$plugin, NULL, $CFG->dirroot.'/grade/import/'.$plugin.'/lang/');
255 asort($importnames);
257 if (!empty($importnames)) {
258 $menu['importgroup']='--'.get_string('importplugins', 'grades');
259 $menu = $menu+$importnames;
262 /// standard export plugins
263 if ($exports = get_list_of_plugins('grade/export', 'CVS')) { // Get all installed export plugins
264 foreach ($exports as $key => $plugin) { // Remove ones we can't see
265 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
266 unset($exports[$key]);
270 $exportnames = array();
271 if (!empty($exports)) {
272 foreach ($exports as $plugin) {
273 $url = 'export/'.$plugin.'/index.php?id='.$courseid;
274 if ($active_type == 'export' and $active_plugin == $plugin ) {
275 $active = $url;
277 $exportnames[$url] = get_string('modulename', 'gradeexport_'.$plugin, NULL, $CFG->dirroot.'/grade/export/'.$plugin.'/lang/');
279 asort($exportnames);
281 if (!empty($exportnames)) {
282 $menu['exportgroup']='--'.get_string('exportplugins', 'grades');
283 $menu = $menu+$exportnames;
286 /// editing scripts - not real plugins
287 if (has_capability('moodle/grade:manage', $context)
288 or has_capability('moodle/course:managescales', $context)
289 or has_capability('moodle/course:update', $context)) {
290 $menu['edit']='--'.get_string('edit');
292 if (has_capability('moodle/grade:manage', $context)) {
293 $url = 'edit/tree/index.php?id='.$courseid;
294 if ($active_type == 'edit' and $active_plugin == 'tree' ) {
295 $active = $url;
297 $menu[$url] = get_string('edittree', 'grades');
300 if (has_capability('moodle/course:managescales', $context)) {
301 $url = 'edit/scale/index.php?id='.$courseid;
302 if ($active_type == 'edit' and $active_plugin == 'scale' ) {
303 $active = $url;
305 $menu[$url] = get_string('scales');
308 if (!empty($CFG->enableoutcomes) && (has_capability('moodle/grade:manage', $context) or
309 has_capability('moodle/course:update', $context))) {
310 if (has_capability('moodle/course:update', $context)) { // Default to course assignment
311 $url = 'edit/outcome/course.php?id='.$courseid;
312 } else {
313 $url = 'edit/outcome/index.php?id='.$courseid;
315 if ($active_type == 'edit' and $active_plugin == 'outcome' ) {
316 $active = $url;
318 $menu[$url] = get_string('outcomes', 'grades');
322 /// finally print/return the popup form
323 return popup_form($CFG->wwwroot.'/grade/', $menu, 'choosepluginreport', $active, 'choose', '', '', $return, 'self', get_string('view'));
327 * Utility class used for return tracking when using edit and other forms in grade plugins
329 class grade_plugin_return {
330 var $type;
331 var $plugin;
332 var $courseid;
333 var $userid;
334 var $page;
337 * Constructor
338 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
340 function grade_plugin_return ($params=null) {
341 if (empty($params)) {
342 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
343 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
344 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
345 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
346 $this->page = optional_param('gpr_page', null, PARAM_INT);
348 } else {
349 foreach ($params as $key=>$value) {
350 if (array_key_exists($key, $this)) {
351 $this->$key = $value;
358 * Returns return parameters as options array suitable for buttons.
359 * @return array options
361 function get_options() {
362 if (empty($this->type)) {
363 return array();
366 $params = array();
368 if (!empty($this->plugin)) {
369 $params['plugin'] = $this->plugin;
372 if (!empty($this->courseid)) {
373 $params['id'] = $this->courseid;
376 if (!empty($this->userid)) {
377 $params['userid'] = $this->userid;
380 if (!empty($this->page)) {
381 $params['page'] = $this->page;
384 return $params;
388 * Returns return url
389 * @param string $default default url when params not set
390 * @return string url
392 function get_return_url($default, $extras=null) {
393 global $CFG;
395 if (empty($this->type) or empty($this->plugin)) {
396 return $default;
399 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
400 $glue = '?';
402 if (!empty($this->courseid)) {
403 $url .= $glue.'id='.$this->courseid;
404 $glue = '&amp;';
407 if (!empty($this->userid)) {
408 $url .= $glue.'userid='.$this->userid;
409 $glue = '&amp;';
412 if (!empty($this->page)) {
413 $url .= $glue.'page='.$this->page;
414 $glue = '&amp;';
417 if (!empty($extras)) {
418 foreach($extras as $key=>$value) {
419 $url .= $glue.$key.'='.$value;
420 $glue = '&amp;';
424 return $url;
428 * Returns string with hidden return tracking form elements.
429 * @return string
431 function get_form_fields() {
432 if (empty($this->type)) {
433 return '';
436 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
438 if (!empty($this->plugin)) {
439 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
442 if (!empty($this->courseid)) {
443 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
446 if (!empty($this->userid)) {
447 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
450 if (!empty($this->page)) {
451 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
456 * Add hidden elements into mform
457 * @param object $mform moodle form object
458 * @return void
460 function add_mform_elements(&$mform) {
461 if (empty($this->type)) {
462 return;
465 $mform->addElement('hidden', 'gpr_type', $this->type);
466 $mform->setType('gpr_type', PARAM_SAFEDIR);
468 if (!empty($this->plugin)) {
469 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
470 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
473 if (!empty($this->courseid)) {
474 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
475 $mform->setType('gpr_courseid', PARAM_INT);
478 if (!empty($this->userid)) {
479 $mform->addElement('hidden', 'gpr_userid', $this->userid);
480 $mform->setType('gpr_userid', PARAM_INT);
483 if (!empty($this->page)) {
484 $mform->addElement('hidden', 'gpr_page', $this->page);
485 $mform->setType('gpr_page', PARAM_INT);
490 * Add return tracking params into url
491 * @param string $url
492 * @return string $url with erturn tracking params
494 function add_url_params($url) {
495 if (empty($this->type)) {
496 return $url;
499 if (strpos($url, '?') === false) {
500 $url .= '?gpr_type='.$this->type;
501 } else {
502 $url .= '&amp;gpr_type='.$this->type;
505 if (!empty($this->plugin)) {
506 $url .= '&amp;gpr_plugin='.$this->plugin;
509 if (!empty($this->courseid)) {
510 $url .= '&amp;gpr_courseid='.$this->courseid;
513 if (!empty($this->userid)) {
514 $url .= '&amp;gpr_userid='.$this->userid;
517 if (!empty($this->page)) {
518 $url .= '&amp;gpr_page='.$this->page;
521 return $url;
526 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
527 * @param string $path The path of the calling script (using __FILE__?)
528 * @param string $pagename The language string to use as the last part of the navigation (non-link)
529 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
530 * @return string
532 function grade_build_nav($path, $pagename=null, $id=null) {
533 global $CFG, $COURSE;
535 $strgrades = get_string('grades', 'grades');
537 // Parse the path and build navlinks from its elements
538 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
539 $path = substr($path, $dirroot_length);
540 $path = str_replace('\\', '/', $path);
542 $path_elements = explode('/', $path);
544 $path_elements_count = count($path_elements);
546 // First link is always 'grade'
547 $navlinks = array();
548 $navlinks[] = array('name' => $strgrades,
549 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
550 'type' => 'misc');
552 $link = '';
553 $numberofelements = 3;
555 // Prepare URL params string
556 $id_string = '?';
557 if (!is_null($id)) {
558 if (is_array($id)) {
559 foreach ($id as $idkey => $idvalue) {
560 $id_string .= "$idkey=$idvalue&amp;";
562 } else {
563 $id_string .= "id=$id";
567 $navlink4 = null;
569 // Remove file extensions from filenames
570 foreach ($path_elements as $key => $filename) {
571 $path_elements[$key] = str_replace('.php', '', $filename);
574 // Second level links
575 switch ($path_elements[1]) {
576 case 'edit': // No link
577 if ($path_elements[3] != 'index.php') {
578 $numberofelements = 4;
580 break;
581 case 'import': // No link
582 break;
583 case 'export': // No link
584 break;
585 case 'report':
586 // $id is required for this link. Do not print it if $id isn't given
587 if (!is_null($id)) {
588 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
591 if ($path_elements[2] == 'grader') {
592 $numberofelements = 4;
594 break;
596 default:
597 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
598 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
599 return false;
602 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
604 // Third level links
605 if (empty($pagename)) {
606 $pagename = get_string($path_elements[2], 'grades');
609 switch ($numberofelements) {
610 case 3:
611 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
612 break;
613 case 4:
615 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
616 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
617 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
618 'type' => 'misc');
620 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
621 break;
623 $navigation = build_navigation($navlinks);
625 return $navigation;
629 * Computes then returns the percentage value of the grade value within the given range.
630 * @param float $gradeval
631 * @param float $grademin
632 * @param float $grademx
633 * @return float $percentage
635 function grade_to_percentage($gradeval, $grademin, $grademax) {
636 if ($grademin >= $grademax) {
637 debugging("The minimum grade ($grademin) was higher than or equal to the maximum grade ($grademax)!!! Cannot proceed with computation.");
640 // If given gradevalue is lower than grademin, adjust it to grademin
641 if ($gradeval < $grademin || empty($gradeval)) {
642 $gradeval = $grademin;
645 $offset_value = $gradeval - $grademin;
646 $offset_max = $grademax - $grademin;
647 $factor = 100 / $offset_max;
648 $percentage = $offset_value * $factor;
649 return $percentage;
653 * This class represents a complete tree of categories, grade_items and final grades,
654 * organises as an array primarily, but which can also be converted to other formats.
655 * It has simple method calls with complex implementations, allowing for easy insertion,
656 * deletion and moving of items and categories within the tree.
658 class grade_tree {
661 * The basic representation of the tree as a hierarchical, 3-tiered array.
662 * @var object $top_element
664 var $top_element;
667 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
668 * @var string $commonvars
670 var $commonvars;
673 * 2D array of grade items and categories
675 var $levels;
678 * Course context
680 var $context;
683 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
684 * objects for the given courseid. Full objects are instantiated.
685 * and renumbering.
686 * @param int $courseid
687 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
688 * @param boolean $category_grade_last category grade item is the last child
689 * @param array $collapsed array of collapsed categories
691 function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
692 global $USER, $CFG;
694 $this->courseid = $courseid;
695 $this->commonvars = "&amp;sesskey=$USER->sesskey&amp;id=$this->courseid";
696 $this->levels = array();
697 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
699 // get course grade tree
700 $this->top_element = grade_category::fetch_course_tree($courseid, true);
702 // collapse the categories if requested
703 if (!empty($collapsed)) {
704 grade_tree::category_collapse($this->top_element, $collapsed);
707 // no otucomes if requested
708 if (!empty($nooutcomes)) {
709 grade_tree::no_outcomes($this->top_element);
712 // move category item to last position in category
713 if ($category_grade_last) {
714 grade_tree::category_grade_last($this->top_element);
717 if ($fillers) {
718 // inject fake categories == fillers
719 grade_tree::inject_fillers($this->top_element, 0);
720 // add colspans to categories and fillers
721 grade_tree::inject_colspans($this->top_element);
724 grade_tree::fill_levels($this->levels, $this->top_element, 0);
728 * Static recursive helper - removes items from collapsed categories
729 * @static
730 * @param array $element The seed of the recursion
731 * @param array $collapsed array of collapsed categories
732 * @return void
734 function category_collapse(&$element, $collapsed) {
735 if ($element['type'] != 'category') {
736 return;
738 if (empty($element['children']) or count($element['children']) < 2) {
739 return;
742 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
743 $category_item = reset($element['children']); //keep only category item
744 $element['children'] = array(key($element['children'])=>$category_item);
746 } else {
747 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
748 reset($element['children']);
749 $first_key = key($element['children']);
750 unset($element['children'][$first_key]);
752 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
753 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
759 * Static recursive helper - removes all outcomes
760 * @static
761 * @param array $element The seed of the recursion
762 * @return void
764 function no_outcomes(&$element) {
765 if ($element['type'] != 'category') {
766 return;
768 foreach ($element['children'] as $sortorder=>$child) {
769 if ($element['children'][$sortorder]['type'] == 'item'
770 and $element['children'][$sortorder]['object']->is_outcome_item()) {
771 unset($element['children'][$sortorder]);
773 } else if ($element['children'][$sortorder]['type'] == 'category') {
774 grade_tree::no_outcomes($element['children'][$sortorder]);
780 * Static recursive helper - makes the grade_item for category the last children
781 * @static
782 * @param array $element The seed of the recursion
783 * @return void
785 function category_grade_last(&$element) {
786 if (empty($element['children'])) {
787 return;
789 if (count($element['children']) < 2) {
790 return;
792 $category_item = reset($element['children']);
793 $order = key($element['children']);
794 unset($element['children'][$order]);
795 $element['children'][$order] =& $category_item;
796 foreach ($element['children'] as $sortorder=>$child) {
797 grade_tree::category_grade_last($element['children'][$sortorder]);
802 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
803 * @static
804 * @param int $levels
805 * @param array $element The seed of the recursion
806 * @param int $depth
807 * @return void
809 function fill_levels(&$levels, &$element, $depth) {
810 if (!array_key_exists($depth, $levels)) {
811 $levels[$depth] = array();
814 // prepare unique identifier
815 if ($element['type'] == 'category') {
816 $element['eid'] = 'c'.$element['object']->id;
817 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
818 $element['eid'] = 'i'.$element['object']->id;
821 $levels[$depth][] =& $element;
822 $depth++;
823 if (empty($element['children'])) {
824 return;
826 $prev = 0;
827 foreach ($element['children'] as $sortorder=>$child) {
828 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
829 $element['children'][$sortorder]['prev'] = $prev;
830 $element['children'][$sortorder]['next'] = 0;
831 if ($prev) {
832 $element['children'][$prev]['next'] = $sortorder;
834 $prev = $sortorder;
839 * Static recursive helper - makes full tree (all leafes are at the same level)
841 function inject_fillers(&$element, $depth) {
842 $depth++;
844 if (empty($element['children'])) {
845 return $depth;
847 $chdepths = array();
848 $chids = array_keys($element['children']);
849 $last_child = end($chids);
850 $first_child = reset($chids);
852 foreach ($chids as $chid) {
853 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
855 arsort($chdepths);
857 $maxdepth = reset($chdepths);
858 foreach ($chdepths as $chid=>$chd) {
859 if ($chd == $maxdepth) {
860 continue;
862 for ($i=0; $i < $maxdepth-$chd; $i++) {
863 if ($chid == $first_child) {
864 $type = 'fillerfirst';
865 } else if ($chid == $last_child) {
866 $type = 'fillerlast';
867 } else {
868 $type = 'filler';
870 $oldchild =& $element['children'][$chid];
871 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
875 return $maxdepth;
879 * Static recursive helper - add colspan information into categories
881 function inject_colspans(&$element) {
882 if (empty($element['children'])) {
883 return 1;
885 $count = 0;
886 foreach ($element['children'] as $key=>$child) {
887 $count += grade_tree::inject_colspans($element['children'][$key]);
889 $element['colspan'] = $count;
890 return $count;
894 * Parses the array in search of a given eid and returns a element object with
895 * information about the element it has found.
896 * @param int $eid
897 * @return object element
899 function locate_element($eid) {
900 // it is a grade - construct a new object
901 if (strpos($eid, 'n') === 0) {
902 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
903 return null;
906 $itemid = $matches[1];
907 $userid = $matches[2];
909 //extra security check - the grade item must be in this tree
910 if (!$item_el = $this->locate_element('i'.$itemid)) {
911 return null;
914 // $gradea->id may be null - means does not exist yet
915 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
917 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
918 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
920 } else if (strpos($eid, 'g') === 0) {
921 $id = (int)substr($eid, 1);
922 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
923 return null;
925 //extra security check - the grade item must be in this tree
926 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
927 return null;
929 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
930 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
933 // it is a category or item
934 foreach ($this->levels as $row) {
935 foreach ($row as $element) {
936 if ($element['type'] == 'filler') {
937 continue;
939 if ($element['eid'] == $eid) {
940 return $element;
945 return null;
949 * Returns the grade eid - the grade may not exist yet.
950 * @param $grade_grade object
951 * @return string eid
953 function get_grade_eid($grade_grade) {
954 if (empty($grade_grade->id)) {
955 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
956 } else {
957 return 'g'.$grade_grade->id;
962 * Return edit icon for give element
963 * @param object $element
964 * @return string
966 function get_edit_icon($element, $gpr) {
967 global $CFG;
969 if (!has_capability('moodle/grade:manage', $this->context)) {
970 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
971 // oki - let them override grade
972 } else {
973 return '';
977 static $stredit = null;
978 if (is_null($stredit)) {
979 $stredit = get_string('edit');
982 $object = $element['object'];
983 $overlib = '';
985 switch ($element['type']) {
986 case 'item':
987 case 'categoryitem':
988 case 'courseitem':
989 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
990 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
991 } else {
992 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
994 $url = $gpr->add_url_params($url);
995 break;
997 case 'category':
998 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
999 $url = $gpr->add_url_params($url);
1000 break;
1002 case 'grade':
1003 if (empty($object->id)) {
1004 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
1005 } else {
1006 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1008 $url = $gpr->add_url_params($url);
1009 if (!empty($object->feedback)) {
1010 $feedback = format_text($object->feedback, $object->feedbackformat);
1011 $function = "return overlib('".s(ltrim($object->feedback)."', FULLHTML);");
1012 $overlib = 'onmouseover="'.$function.'" onmouseout="return nd();"';
1014 break;
1016 default:
1017 $url = null;
1020 if ($url) {
1021 return '<a href="'.$url.'"><img '.$overlib.' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$stredit.'" title="'.$stredit.'"/></a>';
1023 } else {
1024 return '';
1029 * Return hiding icon for give element
1030 * @param object $element
1031 * @return string
1033 function get_hiding_icon($element, $gpr) {
1034 global $CFG;
1036 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
1037 return '';
1040 static $strshow = null;
1041 static $strhide = null;
1042 if (is_null($strshow)) {
1043 $strshow = get_string('show');
1044 $strhide = get_string('hide');
1047 if ($element['object']->is_hidden()) {
1048 $icon = 'show';
1049 $tooltip = '';
1051 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
1052 $icon = 'hiddenuntil';
1053 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
1056 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1057 . '&amp;eid='.$element['eid'];
1058 $url = $gpr->add_url_params($url);
1059 $action = '<a href="'.$url.'"><img title="' . $tooltip . '" src="'.$CFG->pixpath.'/t/' . $icon . '.gif" class="iconsmall" alt="'
1060 . $strshow.'" title="'.$strshow.'"/></a>';
1062 } else {
1063 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1064 . '&amp;eid='.$element['eid'];
1065 $url = $gpr->add_url_params($url);
1066 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.$strhide.'" title="'.$strhide.'"/></a>';
1068 return $action;
1072 * Return locking icon for give element
1073 * @param object $element
1074 * @return string
1076 function get_locking_icon($element, $gpr) {
1077 global $CFG;
1079 static $strunlock = null;
1080 static $strlock = null;
1081 if (is_null($strunlock)) {
1082 $strunlock = get_string('unlock', 'grades');
1083 $strlock = get_string('lock', 'grades');
1086 if ($element['object']->is_locked()) {
1087 $icon = 'unlock';
1088 $tooltip = '';
1090 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
1091 $icon = 'locktime';
1092 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
1095 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1096 return '';
1098 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1099 . '&amp;eid='.$element['eid'];
1100 $url = $gpr->add_url_params($url);
1101 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/' . $icon . '.gif" title="' . $tooltip
1102 . '" class="iconsmall" alt="'.$strunlock
1103 . '" title="'.$strunlock.'"/></a>';
1105 } else {
1106 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1107 return '';
1109 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1110 . '&amp;eid='.$element['eid'];
1111 $url = $gpr->add_url_params($url);
1112 $action = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.$strlock.'" title="'
1113 . $strlock.'"/></a>';
1115 return $action;
1119 * Return calculation icon for given element
1120 * @param object $element
1121 * @return string
1123 function get_calculation_icon($element, $gpr) {
1124 global $CFG;
1125 if (!has_capability('moodle/grade:manage', $this->context)) {
1126 return '';
1129 $calculation_icon = '';
1131 $type = $element['type'];
1132 $object = $element['object'];
1134 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1135 $streditcalculation = get_string('editcalculation', 'grades');
1137 // show calculation icon only when calculation possible
1138 if ((!$object->is_normal_item() or $object->is_outcome_item())
1139 and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
1140 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1141 $url = $gpr->add_url_params($url);
1142 $calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/calc.gif" class="iconsmall" alt="'
1143 . $streditcalculation.'" title="'.$streditcalculation.'" /></a>'. "\n";
1147 return $calculation_icon;