2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir
. '/gradelib.php');
26 require_once($CFG->dirroot
. '/grade/export/lib.php');
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator
{
38 * The couse whose users we are interested in
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
48 * The group ID we are interested in. 0 means all groups.
53 * A recordset of graded users
58 * A recordset of user grades (grade_grade instances)
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
101 protected $suspendedusers = array();
106 * @param object $course A course object
107 * @param array $grade_items array of grade items, if not specified only user info returned
108 * @param int $groupid iterate only group users if present
109 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
110 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
111 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
112 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
114 public function __construct($course, $grade_items=null, $groupid=0,
115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
117 $this->course
= $course;
118 $this->grade_items
= $grade_items;
119 $this->groupid
= $groupid;
120 $this->sortfield1
= $sortfield1;
121 $this->sortorder1
= $sortorder1;
122 $this->sortfield2
= $sortfield2;
123 $this->sortorder2
= $sortorder2;
125 $this->gradestack
= array();
129 * Initialise the iterator
131 * @return boolean success
133 public function init() {
138 export_verify_grades($this->course
->id
);
139 $course_item = grade_item
::fetch_course_item($this->course
->id
);
140 if ($course_item->needsupdate
) {
141 // can not calculate all final grades - sorry
145 $coursecontext = context_course
::instance($this->course
->id
);
146 $relatedcontexts = get_related_contexts_string($coursecontext);
148 list($gradebookroles_sql, $params) =
149 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles
), SQL_PARAMS_NAMED
, 'grbr');
150 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive
);
152 $params = array_merge($params, $enrolledparams);
154 if ($this->groupid
) {
155 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
156 $groupwheresql = "AND gm.groupid = :groupid";
157 // $params contents: gradebookroles
158 $params['groupid'] = $this->groupid
;
164 if (empty($this->sortfield1
)) {
165 // we must do some sorting even if not specified
166 $ofields = ", u.id AS usrt";
170 $ofields = ", u.$this->sortfield1 AS usrt1";
171 $order = "usrt1 $this->sortorder1";
172 if (!empty($this->sortfield2
)) {
173 $ofields .= ", u.$this->sortfield2 AS usrt2";
174 $order .= ", usrt2 $this->sortorder2";
176 if ($this->sortfield1
!= 'id' and $this->sortfield2
!= 'id') {
177 // user order MUST be the same in both queries,
178 // must include the only unique user->id if not already present
179 $ofields .= ", u.id AS usrt";
180 $order .= ", usrt ASC";
185 $customfieldssql = '';
186 if ($this->allowusercustomfields
&& !empty($CFG->grade_export_customprofilefields
)) {
187 $customfieldscount = 0;
188 $customfieldsarray = grade_helper
::get_user_profile_fields($this->course
->id
, $this->allowusercustomfields
);
189 foreach ($customfieldsarray as $field) {
190 if (!empty($field->customid
)) {
191 $customfieldssql .= "
192 LEFT JOIN (SELECT * FROM {user_info_data}
193 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
194 ON u.id = cf$customfieldscount.userid";
195 $userfields .= ", cf$customfieldscount.data AS 'customfield_{$field->shortname}'";
196 $params['cf'.$customfieldscount] = $field->customid
;
197 $customfieldscount++
;
202 // $params contents: gradebookroles and groupid (for $groupwheresql)
203 $users_sql = "SELECT $userfields $ofields
205 JOIN ($enrolledsql) je ON je.id = u.id
206 $groupsql $customfieldssql
208 SELECT DISTINCT ra.userid
209 FROM {role_assignments} ra
210 WHERE ra.roleid $gradebookroles_sql
211 AND ra.contextid $relatedcontexts
212 ) rainner ON rainner.userid = u.id
216 $this->users_rs
= $DB->get_recordset_sql($users_sql, $params);
218 if (!$this->onlyactive
) {
219 $context = context_course
::instance($this->course
->id
);
220 $this->suspendedusers
= get_suspended_userids($context);
222 $this->suspendedusers
= array();
225 if (!empty($this->grade_items
)) {
226 $itemids = array_keys($this->grade_items
);
227 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED
, 'items');
228 $params = array_merge($params, $grades_params);
229 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
231 $grades_sql = "SELECT g.* $ofields
232 FROM {grade_grades} g
233 JOIN {user} u ON g.userid = u.id
234 JOIN ($enrolledsql) je ON je.id = u.id
237 SELECT DISTINCT ra.userid
238 FROM {role_assignments} ra
239 WHERE ra.roleid $gradebookroles_sql
240 AND ra.contextid $relatedcontexts
241 ) rainner ON rainner.userid = u.id
243 AND g.itemid $itemidsql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs
= $DB->get_recordset_sql($grades_sql, $params);
248 $this->grades_rs
= false;
255 * Returns information about the next user
256 * @return mixed array of user info, all grades and feedback or null when no more users found
258 public function next_user() {
259 if (!$this->users_rs
) {
260 return false; // no users present
263 if (!$this->users_rs
->valid()) {
264 if ($current = $this->_pop()) {
265 // this is not good - user or grades updated between the two reads above :-(
268 return false; // no more users
270 $user = $this->users_rs
->current();
271 $this->users_rs
->next();
274 // find grades of this user
275 $grade_records = array();
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid
)) {
285 if ($current->userid
!= $user->id
) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
291 $grade_records[$current->itemid
] = $current;
295 $feedbacks = array();
297 if (!empty($this->grade_items
)) {
298 foreach ($this->grade_items
as $grade_item) {
299 if (!isset($feedbacks[$grade_item->id
])) {
300 $feedbacks[$grade_item->id
] = new stdClass();
302 if (array_key_exists($grade_item->id
, $grade_records)) {
303 $feedbacks[$grade_item->id
]->feedback
= $grade_records[$grade_item->id
]->feedback
;
304 $feedbacks[$grade_item->id
]->feedbackformat
= $grade_records[$grade_item->id
]->feedbackformat
;
305 unset($grade_records[$grade_item->id
]->feedback
);
306 unset($grade_records[$grade_item->id
]->feedbackformat
);
307 $grades[$grade_item->id
] = new grade_grade($grade_records[$grade_item->id
], false);
309 $feedbacks[$grade_item->id
]->feedback
= '';
310 $feedbacks[$grade_item->id
]->feedbackformat
= FORMAT_MOODLE
;
311 $grades[$grade_item->id
] =
312 new grade_grade(array('userid'=>$user->id
, 'itemid'=>$grade_item->id
), false);
317 // Set user suspended status.
318 $user->suspendedenrolment
= isset($this->suspendedusers
[$user->id
]);
319 $result = new stdClass();
320 $result->user
= $user;
321 $result->grades
= $grades;
322 $result->feedbacks
= $feedbacks;
327 * Close the iterator, do not forget to call this function
329 public function close() {
330 if ($this->users_rs
) {
331 $this->users_rs
->close();
332 $this->users_rs
= null;
334 if ($this->grades_rs
) {
335 $this->grades_rs
->close();
336 $this->grades_rs
= null;
338 $this->gradestack
= array();
342 * Should all enrolled users be exported or just those with an active enrolment?
344 * @param bool $onlyactive True to limit the export to users with an active enrolment
346 public function require_active_enrolment($onlyactive = true) {
347 if (!empty($this->users_rs
)) {
348 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER
);
350 $this->onlyactive
= $onlyactive;
354 * Allow custom fields to be included
356 * @param bool $allow Whether to allow custom fields or not
359 public function allow_user_custom_fields($allow = true) {
361 $this->allowusercustomfields
= true;
363 $this->allowusercustomfields
= false;
368 * Add a grade_grade instance to the grade stack
370 * @param grade_grade $grade Grade object
374 private function _push($grade) {
375 array_push($this->gradestack
, $grade);
380 * Remove a grade_grade instance from the grade stack
382 * @return grade_grade current grade object
384 private function _pop() {
386 if (empty($this->gradestack
)) {
387 if (empty($this->grades_rs
) ||
!$this->grades_rs
->valid()) {
388 return null; // no grades present
391 $current = $this->grades_rs
->current();
393 $this->grades_rs
->next();
397 return array_pop($this->gradestack
);
403 * Print a selection popup form of the graded users in a course.
405 * @deprecated since 2.0
407 * @param int $course id of the course
408 * @param string $actionpage The page receiving the data from the popoup form
409 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
410 * @param int $groupid id of requested group, 0 means all
411 * @param int $includeall bool include all option
412 * @param bool $return If true, will return the HTML, otherwise, will print directly
415 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
416 global $CFG, $USER, $OUTPUT;
417 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
420 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
423 if (is_null($userid)) {
426 $coursecontext = context_course
::instance($course->id
);
427 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol
);
428 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
429 $showonlyactiveenrol = $showonlyactiveenrol ||
!has_capability('moodle/course:viewsuspendedusers', $coursecontext);
430 $menu = array(); // Will be a list of userid => user name
431 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
432 $gui = new graded_users_iterator($course, null, $groupid);
433 $gui->require_active_enrolment($showonlyactiveenrol);
435 $label = get_string('selectauser', 'grades');
437 $menu[0] = get_string('allusers', 'grades');
438 $label = get_string('selectalloroneuser', 'grades');
440 while ($userdata = $gui->next_user()) {
441 $user = $userdata->user
;
442 $userfullname = fullname($user);
443 if ($user->suspendedenrolment
) {
444 $menususpendedusers[$user->id
] = $userfullname;
446 $menu[$user->id
] = $userfullname;
452 $menu[0] .= " (" . (count($menu) +
count($menususpendedusers) - 1) . ")";
455 if (!empty($menususpendedusers)) {
456 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
458 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id
)), 'userid', $menu, $userid);
459 $select->label
= $label;
460 $select->formid
= 'choosegradeuser';
465 * Print grading plugin selection popup form.
467 * @param array $plugin_info An array of plugins containing information for the selector
468 * @param boolean $return return as string
470 * @return nothing or string if $return true
472 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
473 global $CFG, $OUTPUT, $PAGE;
479 foreach ($plugin_info as $plugin_type => $plugins) {
480 if ($plugin_type == 'strings') {
484 $first_plugin = reset($plugins);
486 $sectionname = $plugin_info['strings'][$plugin_type];
489 foreach ($plugins as $plugin) {
490 $link = $plugin->link
->out(false);
491 $section[$link] = $plugin->string;
493 if ($plugin_type === $active_type and $plugin->id
=== $active_plugin) {
499 $menu[] = array($sectionname=>$section);
503 // finally print/return the popup form
505 $select = new url_select($menu, $active, null, 'choosepluginreport');
506 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
508 return $OUTPUT->render($select);
510 echo $OUTPUT->render($select);
513 // only one option - no plugin selector needed
519 * Print grading plugin selection tab-based navigation.
521 * @param string $active_type type of plugin on current page - import, export, report or edit
522 * @param string $active_plugin active plugin type - grader, user, cvs, ...
523 * @param array $plugin_info Array of plugins
524 * @param boolean $return return as string
526 * @return nothing or string if $return true
528 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
529 global $CFG, $COURSE;
531 if (!isset($currenttab)) { //TODO: this is weird
537 $bottom_row = array();
538 $inactive = array($active_plugin);
539 $activated = array();
544 foreach ($plugin_info as $plugin_type => $plugins) {
545 if ($plugin_type == 'strings') {
549 // If $plugins is actually the definition of a child-less parent link:
550 if (!empty($plugins->id
)) {
551 $string = $plugins->string;
552 if (!empty($plugin_info[$active_type]->parent
)) {
553 $string = $plugin_info[$active_type]->parent
->string;
556 $top_row[] = new tabobject($plugin_type, $plugins->link
, $string);
560 $first_plugin = reset($plugins);
561 $url = $first_plugin->link
;
563 if ($plugin_type == 'report') {
564 $url = $CFG->wwwroot
.'/grade/report/index.php?id='.$COURSE->id
;
567 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
569 if ($active_type == $plugin_type) {
570 foreach ($plugins as $plugin) {
571 $bottom_row[] = new tabobject($plugin->id
, $plugin->link
, $plugin->string);
572 if ($plugin->id
== $active_plugin) {
573 $inactive = array($plugin->id
);
580 $tabs[] = $bottom_row;
583 return print_tabs($tabs, $active_type, $inactive, $activated, true);
585 print_tabs($tabs, $active_type, $inactive, $activated);
590 * grade_get_plugin_info
592 * @param int $courseid The course id
593 * @param string $active_type type of plugin on current page - import, export, report or edit
594 * @param string $active_plugin active plugin type - grader, user, cvs, ...
598 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
601 $context = context_course
::instance($courseid);
603 $plugin_info = array();
606 $url_prefix = $CFG->wwwroot
. '/grade/';
609 $plugin_info['strings'] = grade_helper
::get_plugin_strings();
611 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
612 $plugin_info['report'] = $reports;
615 //showing grade categories and items make no sense if we're not within a course
616 if ($courseid!=$SITE->id
) {
617 if ($edittree = grade_helper
::get_info_edit_structure($courseid)) {
618 $plugin_info['edittree'] = $edittree;
622 if ($scale = grade_helper
::get_info_scales($courseid)) {
623 $plugin_info['scale'] = array('view'=>$scale);
626 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
627 $plugin_info['outcome'] = $outcomes;
630 if ($letters = grade_helper
::get_info_letters($courseid)) {
631 $plugin_info['letter'] = $letters;
634 if ($imports = grade_helper
::get_plugins_import($courseid)) {
635 $plugin_info['import'] = $imports;
638 if ($exports = grade_helper
::get_plugins_export($courseid)) {
639 $plugin_info['export'] = $exports;
642 foreach ($plugin_info as $plugin_type => $plugins) {
643 if (!empty($plugins->id
) && $active_plugin == $plugins->id
) {
644 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
647 foreach ($plugins as $plugin) {
648 if (is_a($plugin, 'grade_plugin_info')) {
649 if ($active_plugin == $plugin->id
) {
650 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
656 //hide course settings if we're not in a course
657 if ($courseid!=$SITE->id
) {
658 if ($setting = grade_helper
::get_info_manage_settings($courseid)) {
659 $plugin_info['settings'] = array('course'=>$setting);
663 // Put preferences last
664 if ($preferences = grade_helper
::get_plugins_report_preferences($courseid)) {
665 $plugin_info['preferences'] = $preferences;
668 foreach ($plugin_info as $plugin_type => $plugins) {
669 if (!empty($plugins->id
) && $active_plugin == $plugins->id
) {
670 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
673 foreach ($plugins as $plugin) {
674 if (is_a($plugin, 'grade_plugin_info')) {
675 if ($active_plugin == $plugin->id
) {
676 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
686 * A simple class containing info about grade plugins.
687 * Can be subclassed for special rules
689 * @package core_grades
690 * @copyright 2009 Nicolas Connault
691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
693 class grade_plugin_info
{
695 * A unique id for this plugin
701 * A URL to access this plugin
707 * The name of this plugin
713 * Another grade_plugin_info object, parent of the current one
722 * @param int $id A unique id for this plugin
723 * @param string $link A URL to access this plugin
724 * @param string $string The name of this plugin
725 * @param object $parent Another grade_plugin_info object, parent of the current one
729 public function __construct($id, $link, $string, $parent=null) {
732 $this->string = $string;
733 $this->parent
= $parent;
738 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
739 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
740 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
741 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
742 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
744 * @param int $courseid Course id
745 * @param string $active_type The type of the current page (report, settings,
746 * import, export, scales, outcomes, letters)
747 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
748 * @param string $heading The heading of the page. Tries to guess if none is given
749 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
750 * @param string $bodytags Additional attributes that will be added to the <body> tag
751 * @param string $buttons Additional buttons to display on the page
752 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
754 * @return string HTML code or nothing if $return == false
756 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
757 $heading = false, $return=false,
758 $buttons=false, $shownavigation=true) {
759 global $CFG, $OUTPUT, $PAGE;
761 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
763 // Determine the string of the active plugin
764 $stractive_plugin = ($active_plugin) ?
$plugin_info['strings']['active_plugin_str'] : $heading;
765 $stractive_type = $plugin_info['strings'][$active_type];
767 if (empty($plugin_info[$active_type]->id
) ||
!empty($plugin_info[$active_type]->parent
)) {
768 $title = $PAGE->course
->fullname
.': ' . $stractive_type . ': ' . $stractive_plugin;
770 $title = $PAGE->course
->fullname
.': ' . $stractive_plugin;
773 if ($active_type == 'report') {
774 $PAGE->set_pagelayout('report');
776 $PAGE->set_pagelayout('admin');
778 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
779 $PAGE->set_heading($title);
780 if ($buttons instanceof single_button
) {
781 $buttons = $OUTPUT->render($buttons);
783 $PAGE->set_button($buttons);
784 grade_extend_settings($plugin_info, $courseid);
786 $returnval = $OUTPUT->header();
791 // Guess heading if not given explicitly
793 $heading = $stractive_plugin;
796 if ($shownavigation) {
797 if ($CFG->grade_navmethod
== GRADE_NAVMETHOD_COMBO ||
$CFG->grade_navmethod
== GRADE_NAVMETHOD_DROPDOWN
) {
798 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
802 $returnval .= $OUTPUT->heading($heading);
804 echo $OUTPUT->heading($heading);
807 if ($CFG->grade_navmethod
== GRADE_NAVMETHOD_COMBO ||
$CFG->grade_navmethod
== GRADE_NAVMETHOD_TABS
) {
808 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
818 * Utility class used for return tracking when using edit and other forms in grade plugins
820 * @package core_grades
821 * @copyright 2009 Nicolas Connault
822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
824 class grade_plugin_return
{
834 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
836 public function grade_plugin_return($params = null) {
837 if (empty($params)) {
838 $this->type
= optional_param('gpr_type', null, PARAM_SAFEDIR
);
839 $this->plugin
= optional_param('gpr_plugin', null, PARAM_PLUGIN
);
840 $this->courseid
= optional_param('gpr_courseid', null, PARAM_INT
);
841 $this->userid
= optional_param('gpr_userid', null, PARAM_INT
);
842 $this->page
= optional_param('gpr_page', null, PARAM_INT
);
845 foreach ($params as $key=>$value) {
846 if (property_exists($this, $key)) {
847 $this->$key = $value;
854 * Returns return parameters as options array suitable for buttons.
855 * @return array options
857 public function get_options() {
858 if (empty($this->type
)) {
864 if (!empty($this->plugin
)) {
865 $params['plugin'] = $this->plugin
;
868 if (!empty($this->courseid
)) {
869 $params['id'] = $this->courseid
;
872 if (!empty($this->userid
)) {
873 $params['userid'] = $this->userid
;
876 if (!empty($this->page
)) {
877 $params['page'] = $this->page
;
886 * @param string $default default url when params not set
887 * @param array $extras Extra URL parameters
891 public function get_return_url($default, $extras=null) {
894 if (empty($this->type
) or empty($this->plugin
)) {
898 $url = $CFG->wwwroot
.'/grade/'.$this->type
.'/'.$this->plugin
.'/index.php';
901 if (!empty($this->courseid
)) {
902 $url .= $glue.'id='.$this->courseid
;
906 if (!empty($this->userid
)) {
907 $url .= $glue.'userid='.$this->userid
;
911 if (!empty($this->page
)) {
912 $url .= $glue.'page='.$this->page
;
916 if (!empty($extras)) {
917 foreach ($extras as $key=>$value) {
918 $url .= $glue.$key.'='.$value;
927 * Returns string with hidden return tracking form elements.
930 public function get_form_fields() {
931 if (empty($this->type
)) {
935 $result = '<input type="hidden" name="gpr_type" value="'.$this->type
.'" />';
937 if (!empty($this->plugin
)) {
938 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin
.'" />';
941 if (!empty($this->courseid
)) {
942 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid
.'" />';
945 if (!empty($this->userid
)) {
946 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid
.'" />';
949 if (!empty($this->page
)) {
950 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page
.'" />';
955 * Add hidden elements into mform
957 * @param object &$mform moodle form object
961 public function add_mform_elements(&$mform) {
962 if (empty($this->type
)) {
966 $mform->addElement('hidden', 'gpr_type', $this->type
);
967 $mform->setType('gpr_type', PARAM_SAFEDIR
);
969 if (!empty($this->plugin
)) {
970 $mform->addElement('hidden', 'gpr_plugin', $this->plugin
);
971 $mform->setType('gpr_plugin', PARAM_PLUGIN
);
974 if (!empty($this->courseid
)) {
975 $mform->addElement('hidden', 'gpr_courseid', $this->courseid
);
976 $mform->setType('gpr_courseid', PARAM_INT
);
979 if (!empty($this->userid
)) {
980 $mform->addElement('hidden', 'gpr_userid', $this->userid
);
981 $mform->setType('gpr_userid', PARAM_INT
);
984 if (!empty($this->page
)) {
985 $mform->addElement('hidden', 'gpr_page', $this->page
);
986 $mform->setType('gpr_page', PARAM_INT
);
991 * Add return tracking params into url
993 * @param moodle_url $url A URL
995 * @return string $url with return tracking params
997 public function add_url_params(moodle_url
$url) {
998 if (empty($this->type
)) {
1002 $url->param('gpr_type', $this->type
);
1004 if (!empty($this->plugin
)) {
1005 $url->param('gpr_plugin', $this->plugin
);
1008 if (!empty($this->courseid
)) {
1009 $url->param('gpr_courseid' ,$this->courseid
);
1012 if (!empty($this->userid
)) {
1013 $url->param('gpr_userid', $this->userid
);
1016 if (!empty($this->page
)) {
1017 $url->param('gpr_page', $this->page
);
1025 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1027 * @param string $path The path of the calling script (using __FILE__?)
1028 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1029 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1030 * an array of keys and values (e.g courseid => $courseid, itemid...)
1034 function grade_build_nav($path, $pagename=null, $id=null) {
1035 global $CFG, $COURSE, $PAGE;
1037 $strgrades = get_string('grades', 'grades');
1039 // Parse the path and build navlinks from its elements
1040 $dirroot_length = strlen($CFG->dirroot
) +
1; // Add 1 for the first slash
1041 $path = substr($path, $dirroot_length);
1042 $path = str_replace('\\', '/', $path);
1044 $path_elements = explode('/', $path);
1046 $path_elements_count = count($path_elements);
1048 // First link is always 'grade'
1049 $PAGE->navbar
->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id
)));
1052 $numberofelements = 3;
1054 // Prepare URL params string
1055 $linkparams = array();
1056 if (!is_null($id)) {
1057 if (is_array($id)) {
1058 foreach ($id as $idkey => $idvalue) {
1059 $linkparams[$idkey] = $idvalue;
1062 $linkparams['id'] = $id;
1068 // Remove file extensions from filenames
1069 foreach ($path_elements as $key => $filename) {
1070 $path_elements[$key] = str_replace('.php', '', $filename);
1073 // Second level links
1074 switch ($path_elements[1]) {
1075 case 'edit': // No link
1076 if ($path_elements[3] != 'index.php') {
1077 $numberofelements = 4;
1080 case 'import': // No link
1082 case 'export': // No link
1085 // $id is required for this link. Do not print it if $id isn't given
1086 if (!is_null($id)) {
1087 $link = new moodle_url('/grade/report/index.php', $linkparams);
1090 if ($path_elements[2] == 'grader') {
1091 $numberofelements = 4;
1096 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1097 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1098 " as the second path element after 'grade'.");
1101 $PAGE->navbar
->add(get_string($path_elements[1], 'grades'), $link);
1103 // Third level links
1104 if (empty($pagename)) {
1105 $pagename = get_string($path_elements[2], 'grades');
1108 switch ($numberofelements) {
1110 $PAGE->navbar
->add($pagename, $link);
1113 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1114 $PAGE->navbar
->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1116 $PAGE->navbar
->add($pagename);
1124 * General structure representing grade items in course
1126 * @package core_grades
1127 * @copyright 2009 Nicolas Connault
1128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1130 class grade_structure
{
1136 * Reference to modinfo for current course (for performance, to save
1137 * retrieving it from courseid every time). Not actually set except for
1138 * the grade_tree type.
1139 * @var course_modinfo
1144 * 1D array of grade items only
1149 * Returns icon of element
1151 * @param array &$element An array representing an element in the grade_tree
1152 * @param bool $spacerifnone return spacer if no icon found
1154 * @return string icon or spacer
1156 public function get_element_icon(&$element, $spacerifnone=false) {
1157 global $CFG, $OUTPUT;
1158 require_once $CFG->libdir
.'/filelib.php';
1160 switch ($element['type']) {
1163 case 'categoryitem':
1164 $is_course = $element['object']->is_course_item();
1165 $is_category = $element['object']->is_category_item();
1166 $is_scale = $element['object']->gradetype
== GRADE_TYPE_SCALE
;
1167 $is_value = $element['object']->gradetype
== GRADE_TYPE_VALUE
;
1168 $is_outcome = !empty($element['object']->outcomeid
);
1170 if ($element['object']->is_calculated()) {
1171 $strcalc = get_string('calculatedgrade', 'grades');
1172 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1173 s($strcalc).'" alt="'.s($strcalc).'"/>';
1175 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1176 if ($category = $element['object']->get_item_category()) {
1177 switch ($category->aggregation
) {
1178 case GRADE_AGGREGATE_MEAN
:
1179 case GRADE_AGGREGATE_MEDIAN
:
1180 case GRADE_AGGREGATE_WEIGHTED_MEAN
:
1181 case GRADE_AGGREGATE_WEIGHTED_MEAN2
:
1182 case GRADE_AGGREGATE_EXTRACREDIT_MEAN
:
1183 $stragg = get_string('aggregation', 'grades');
1184 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1185 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1186 case GRADE_AGGREGATE_SUM
:
1187 $stragg = get_string('aggregation', 'grades');
1188 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1189 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1193 } else if ($element['object']->itemtype
== 'mod') {
1194 //prevent outcomes being displaying the same icon as the activity they are attached to
1196 $stroutcome = s(get_string('outcome', 'grades'));
1197 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1198 'class="icon itemicon" title="'.$stroutcome.
1199 '" alt="'.$stroutcome.'"/>';
1201 $strmodname = get_string('modulename', $element['object']->itemmodule
);
1202 return '<img src="'.$OUTPUT->pix_url('icon',
1203 $element['object']->itemmodule
) . '" ' .
1204 'class="icon itemicon" title="' .s($strmodname).
1205 '" alt="' .s($strmodname).'"/>';
1207 } else if ($element['object']->itemtype
== 'manual') {
1208 if ($element['object']->is_outcome_item()) {
1209 $stroutcome = get_string('outcome', 'grades');
1210 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1211 'class="icon itemicon" title="'.s($stroutcome).
1212 '" alt="'.s($stroutcome).'"/>';
1214 $strmanual = get_string('manualitem', 'grades');
1215 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1216 'class="icon itemicon" title="'.s($strmanual).
1217 '" alt="'.s($strmanual).'"/>';
1223 $strcat = get_string('category', 'grades');
1224 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1225 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1228 if ($spacerifnone) {
1229 return $OUTPUT->spacer().' ';
1236 * Returns name of element optionally with icon and link
1238 * @param array &$element An array representing an element in the grade_tree
1239 * @param bool $withlink Whether or not this header has a link
1240 * @param bool $icon Whether or not to display an icon with this header
1241 * @param bool $spacerifnone return spacer if no icon found
1243 * @return string header
1245 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1249 $header .= $this->get_element_icon($element, $spacerifnone);
1252 $header .= $element['object']->get_name();
1254 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1255 $element['type'] != 'courseitem') {
1260 $url = $this->get_activity_link($element);
1262 $a = new stdClass();
1263 $a->name
= get_string('modulename', $element['object']->itemmodule
);
1264 $title = get_string('linktoactivity', 'grades', $a);
1266 $header = html_writer
::link($url, $header, array('title' => $title));
1273 private function get_activity_link($element) {
1275 /** @var array static cache of the grade.php file existence flags */
1276 static $hasgradephp = array();
1278 $itemtype = $element['object']->itemtype
;
1279 $itemmodule = $element['object']->itemmodule
;
1280 $iteminstance = $element['object']->iteminstance
;
1281 $itemnumber = $element['object']->itemnumber
;
1283 // Links only for module items that have valid instance, module and are
1284 // called from grade_tree with valid modinfo
1285 if ($itemtype != 'mod' ||
!$iteminstance ||
!$itemmodule ||
!$this->modinfo
) {
1289 // Get $cm efficiently and with visibility information using modinfo
1290 $instances = $this->modinfo
->get_instances();
1291 if (empty($instances[$itemmodule][$iteminstance])) {
1294 $cm = $instances[$itemmodule][$iteminstance];
1296 // Do not add link if activity is not visible to the current user
1297 if (!$cm->uservisible
) {
1301 if (!array_key_exists($itemmodule, $hasgradephp)) {
1302 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
1303 $hasgradephp[$itemmodule] = true;
1305 $hasgradephp[$itemmodule] = false;
1309 // If module has grade.php, link to that, otherwise view.php
1310 if ($hasgradephp[$itemmodule]) {
1311 $args = array('id' => $cm->id
, 'itemnumber' => $itemnumber);
1312 if (isset($element['userid'])) {
1313 $args['userid'] = $element['userid'];
1315 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1317 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id
));
1322 * Returns URL of a page that is supposed to contain detailed grade analysis
1324 * At the moment, only activity modules are supported. The method generates link
1325 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1326 * gradeid and userid. If the grade.php does not exist, null is returned.
1328 * @return moodle_url|null URL or null if unable to construct it
1330 public function get_grade_analysis_url(grade_grade
$grade) {
1332 /** @var array static cache of the grade.php file existence flags */
1333 static $hasgradephp = array();
1335 if (empty($grade->grade_item
) or !($grade->grade_item
instanceof grade_item
)) {
1336 throw new coding_exception('Passed grade without the associated grade item');
1338 $item = $grade->grade_item
;
1340 if (!$item->is_external_item()) {
1341 // at the moment, only activity modules are supported
1344 if ($item->itemtype
!== 'mod') {
1345 throw new coding_exception('Unknown external itemtype: '.$item->itemtype
);
1347 if (empty($item->iteminstance
) or empty($item->itemmodule
) or empty($this->modinfo
)) {
1351 if (!array_key_exists($item->itemmodule
, $hasgradephp)) {
1352 if (file_exists($CFG->dirroot
. '/mod/' . $item->itemmodule
. '/grade.php')) {
1353 $hasgradephp[$item->itemmodule
] = true;
1355 $hasgradephp[$item->itemmodule
] = false;
1359 if (!$hasgradephp[$item->itemmodule
]) {
1363 $instances = $this->modinfo
->get_instances();
1364 if (empty($instances[$item->itemmodule
][$item->iteminstance
])) {
1367 $cm = $instances[$item->itemmodule
][$item->iteminstance
];
1368 if (!$cm->uservisible
) {
1372 $url = new moodle_url('/mod/'.$item->itemmodule
.'/grade.php', array(
1374 'itemid' => $item->id
,
1375 'itemnumber' => $item->itemnumber
,
1376 'gradeid' => $grade->id
,
1377 'userid' => $grade->userid
,
1384 * Returns an action icon leading to the grade analysis page
1386 * @param grade_grade $grade
1389 public function get_grade_analysis_icon(grade_grade
$grade) {
1392 $url = $this->get_grade_analysis_url($grade);
1393 if (is_null($url)) {
1397 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1398 get_string('gradeanalysis', 'core_grades')));
1402 * Returns the grade eid - the grade may not exist yet.
1404 * @param grade_grade $grade_grade A grade_grade object
1406 * @return string eid
1408 public function get_grade_eid($grade_grade) {
1409 if (empty($grade_grade->id
)) {
1410 return 'n'.$grade_grade->itemid
.'u'.$grade_grade->userid
;
1412 return 'g'.$grade_grade->id
;
1417 * Returns the grade_item eid
1418 * @param grade_item $grade_item A grade_item object
1419 * @return string eid
1421 public function get_item_eid($grade_item) {
1422 return 'i'.$grade_item->id
;
1426 * Given a grade_tree element, returns an array of parameters
1427 * used to build an icon for that element.
1429 * @param array $element An array representing an element in the grade_tree
1433 public function get_params_for_iconstr($element) {
1434 $strparams = new stdClass();
1435 $strparams->category
= '';
1436 $strparams->itemname
= '';
1437 $strparams->itemmodule
= '';
1439 if (!method_exists($element['object'], 'get_name')) {
1443 $strparams->itemname
= html_to_text($element['object']->get_name());
1445 // If element name is categorytotal, get the name of the parent category
1446 if ($strparams->itemname
== get_string('categorytotal', 'grades')) {
1447 $parent = $element['object']->get_parent_category();
1448 $strparams->category
= $parent->get_name() . ' ';
1450 $strparams->category
= '';
1453 $strparams->itemmodule
= null;
1454 if (isset($element['object']->itemmodule
)) {
1455 $strparams->itemmodule
= $element['object']->itemmodule
;
1461 * Return edit icon for give element
1463 * @param array $element An array representing an element in the grade_tree
1464 * @param object $gpr A grade_plugin_return object
1468 public function get_edit_icon($element, $gpr) {
1469 global $CFG, $OUTPUT;
1471 if (!has_capability('moodle/grade:manage', $this->context
)) {
1472 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context
)) {
1473 // oki - let them override grade
1479 static $strfeedback = null;
1480 static $streditgrade = null;
1481 if (is_null($streditgrade)) {
1482 $streditgrade = get_string('editgrade', 'grades');
1483 $strfeedback = get_string('feedback');
1486 $strparams = $this->get_params_for_iconstr($element);
1488 $object = $element['object'];
1490 switch ($element['type']) {
1492 case 'categoryitem':
1494 $stredit = get_string('editverbose', 'grades', $strparams);
1495 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
1496 $url = new moodle_url('/grade/edit/tree/item.php',
1497 array('courseid' => $this->courseid
, 'id' => $object->id
));
1499 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1500 array('courseid' => $this->courseid
, 'id' => $object->id
));
1505 $stredit = get_string('editverbose', 'grades', $strparams);
1506 $url = new moodle_url('/grade/edit/tree/category.php',
1507 array('courseid' => $this->courseid
, 'id' => $object->id
));
1511 $stredit = $streditgrade;
1512 if (empty($object->id
)) {
1513 $url = new moodle_url('/grade/edit/tree/grade.php',
1514 array('courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
));
1516 $url = new moodle_url('/grade/edit/tree/grade.php',
1517 array('courseid' => $this->courseid
, 'id' => $object->id
));
1519 if (!empty($object->feedback
)) {
1520 $feedback = addslashes_js(trim(format_string($object->feedback
, $object->feedbackformat
)));
1529 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1537 * Return hiding icon for give element
1539 * @param array $element An array representing an element in the grade_tree
1540 * @param object $gpr A grade_plugin_return object
1544 public function get_hiding_icon($element, $gpr) {
1545 global $CFG, $OUTPUT;
1547 if (!has_capability('moodle/grade:manage', $this->context
) and
1548 !has_capability('moodle/grade:hide', $this->context
)) {
1552 $strparams = $this->get_params_for_iconstr($element);
1553 $strshow = get_string('showverbose', 'grades', $strparams);
1554 $strhide = get_string('hideverbose', 'grades', $strparams);
1556 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1557 $url = $gpr->add_url_params($url);
1559 if ($element['object']->is_hidden()) {
1561 $tooltip = $strshow;
1563 // Change the icon and add a tooltip showing the date
1564 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1565 $type = 'hiddenuntil';
1566 $tooltip = get_string('hiddenuntildate', 'grades',
1567 userdate($element['object']->get_hidden()));
1570 $url->param('action', 'show');
1572 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1575 $url->param('action', 'hide');
1576 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1583 * Return locking icon for given element
1585 * @param array $element An array representing an element in the grade_tree
1586 * @param object $gpr A grade_plugin_return object
1590 public function get_locking_icon($element, $gpr) {
1591 global $CFG, $OUTPUT;
1593 $strparams = $this->get_params_for_iconstr($element);
1594 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1595 $strlock = get_string('lockverbose', 'grades', $strparams);
1597 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1598 $url = $gpr->add_url_params($url);
1600 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1601 if ($element['type'] == 'grade' && $element['object']->grade_item
->is_locked()) {
1602 $strparamobj = new stdClass();
1603 $strparamobj->itemname
= $element['object']->grade_item
->itemname
;
1604 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1606 $action = html_writer
::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1607 array('class' => 'action-icon'));
1609 } else if ($element['object']->is_locked()) {
1611 $tooltip = $strunlock;
1613 // Change the icon and add a tooltip showing the date
1614 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1616 $tooltip = get_string('locktimedate', 'grades',
1617 userdate($element['object']->get_locktime()));
1620 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:unlock', $this->context
)) {
1623 $url->param('action', 'unlock');
1624 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1628 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:lock', $this->context
)) {
1631 $url->param('action', 'lock');
1632 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1640 * Return calculation icon for given element
1642 * @param array $element An array representing an element in the grade_tree
1643 * @param object $gpr A grade_plugin_return object
1647 public function get_calculation_icon($element, $gpr) {
1648 global $CFG, $OUTPUT;
1649 if (!has_capability('moodle/grade:manage', $this->context
)) {
1653 $type = $element['type'];
1654 $object = $element['object'];
1656 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1657 $strparams = $this->get_params_for_iconstr($element);
1658 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1660 $is_scale = $object->gradetype
== GRADE_TYPE_SCALE
;
1661 $is_value = $object->gradetype
== GRADE_TYPE_VALUE
;
1663 // show calculation icon only when calculation possible
1664 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1665 if ($object->is_calculated()) {
1668 $icon = 't/calc_off';
1671 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid
, 'id' => $object->id
));
1672 $url = $gpr->add_url_params($url);
1673 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
1682 * Flat structure similar to grade tree.
1684 * @uses grade_structure
1685 * @package core_grades
1686 * @copyright 2009 Nicolas Connault
1687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1689 class grade_seq
extends grade_structure
{
1692 * 1D array of elements
1697 * Constructor, retrieves and stores array of all grade_category and grade_item
1698 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1700 * @param int $courseid The course id
1701 * @param bool $category_grade_last category grade item is the last child
1702 * @param bool $nooutcomes Whether or not outcomes should be included
1704 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1707 $this->courseid
= $courseid;
1708 $this->context
= context_course
::instance($courseid);
1710 // get course grade tree
1711 $top_element = grade_category
::fetch_course_tree($courseid, true);
1713 $this->elements
= grade_seq
::flatten($top_element, $category_grade_last, $nooutcomes);
1715 foreach ($this->elements
as $key=>$unused) {
1716 $this->items
[$this->elements
[$key]['object']->id
] =& $this->elements
[$key]['object'];
1721 * Static recursive helper - makes the grade_item for category the last children
1723 * @param array &$element The seed of the recursion
1724 * @param bool $category_grade_last category grade item is the last child
1725 * @param bool $nooutcomes Whether or not outcomes should be included
1729 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1730 if (empty($element['children'])) {
1733 $children = array();
1735 foreach ($element['children'] as $sortorder=>$unused) {
1736 if ($nooutcomes and $element['type'] != 'category' and
1737 $element['children'][$sortorder]['object']->is_outcome_item()) {
1740 $children[] = $element['children'][$sortorder];
1742 unset($element['children']);
1744 if ($category_grade_last and count($children) > 1) {
1745 $cat_item = array_shift($children);
1746 array_push($children, $cat_item);
1750 foreach ($children as $child) {
1751 if ($child['type'] == 'category') {
1752 $result = $result + grade_seq
::flatten($child, $category_grade_last, $nooutcomes);
1754 $child['eid'] = 'i'.$child['object']->id
;
1755 $result[$child['object']->id
] = $child;
1763 * Parses the array in search of a given eid and returns a element object with
1764 * information about the element it has found.
1766 * @param int $eid Gradetree Element ID
1768 * @return object element
1770 public function locate_element($eid) {
1771 // it is a grade - construct a new object
1772 if (strpos($eid, 'n') === 0) {
1773 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1777 $itemid = $matches[1];
1778 $userid = $matches[2];
1780 //extra security check - the grade item must be in this tree
1781 if (!$item_el = $this->locate_element('i'.$itemid)) {
1785 // $gradea->id may be null - means does not exist yet
1786 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1788 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
1789 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1791 } else if (strpos($eid, 'g') === 0) {
1792 $id = (int) substr($eid, 1);
1793 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
1796 //extra security check - the grade item must be in this tree
1797 if (!$item_el = $this->locate_element('i'.$grade->itemid
)) {
1800 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
1801 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1804 // it is a category or item
1805 foreach ($this->elements
as $element) {
1806 if ($element['eid'] == $eid) {
1816 * This class represents a complete tree of categories, grade_items and final grades,
1817 * organises as an array primarily, but which can also be converted to other formats.
1818 * It has simple method calls with complex implementations, allowing for easy insertion,
1819 * deletion and moving of items and categories within the tree.
1821 * @uses grade_structure
1822 * @package core_grades
1823 * @copyright 2009 Nicolas Connault
1824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1826 class grade_tree
extends grade_structure
{
1829 * The basic representation of the tree as a hierarchical, 3-tiered array.
1830 * @var object $top_element
1832 public $top_element;
1835 * 2D array of grade items and categories
1836 * @var array $levels
1847 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
1848 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1850 * @param int $courseid The Course ID
1851 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1852 * @param bool $category_grade_last category grade item is the last child
1853 * @param array $collapsed array of collapsed categories
1854 * @param bool $nooutcomes Whether or not outcomes should be included
1856 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1857 $collapsed=null, $nooutcomes=false) {
1858 global $USER, $CFG, $COURSE, $DB;
1860 $this->courseid
= $courseid;
1861 $this->levels
= array();
1862 $this->context
= context_course
::instance($courseid);
1864 if (!empty($COURSE->id
) && $COURSE->id
== $this->courseid
) {
1867 $course = $DB->get_record('course', array('id' => $this->courseid
));
1869 $this->modinfo
= get_fast_modinfo($course);
1871 // get course grade tree
1872 $this->top_element
= grade_category
::fetch_course_tree($courseid, true);
1874 // collapse the categories if requested
1875 if (!empty($collapsed)) {
1876 grade_tree
::category_collapse($this->top_element
, $collapsed);
1879 // no otucomes if requested
1880 if (!empty($nooutcomes)) {
1881 grade_tree
::no_outcomes($this->top_element
);
1884 // move category item to last position in category
1885 if ($category_grade_last) {
1886 grade_tree
::category_grade_last($this->top_element
);
1890 // inject fake categories == fillers
1891 grade_tree
::inject_fillers($this->top_element
, 0);
1892 // add colspans to categories and fillers
1893 grade_tree
::inject_colspans($this->top_element
);
1896 grade_tree
::fill_levels($this->levels
, $this->top_element
, 0);
1901 * Static recursive helper - removes items from collapsed categories
1903 * @param array &$element The seed of the recursion
1904 * @param array $collapsed array of collapsed categories
1908 public function category_collapse(&$element, $collapsed) {
1909 if ($element['type'] != 'category') {
1912 if (empty($element['children']) or count($element['children']) < 2) {
1916 if (in_array($element['object']->id
, $collapsed['aggregatesonly'])) {
1917 $category_item = reset($element['children']); //keep only category item
1918 $element['children'] = array(key($element['children'])=>$category_item);
1921 if (in_array($element['object']->id
, $collapsed['gradesonly'])) { // Remove category item
1922 reset($element['children']);
1923 $first_key = key($element['children']);
1924 unset($element['children'][$first_key]);
1926 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
1927 grade_tree
::category_collapse($element['children'][$sortorder], $collapsed);
1933 * Static recursive helper - removes all outcomes
1935 * @param array &$element The seed of the recursion
1939 public function no_outcomes(&$element) {
1940 if ($element['type'] != 'category') {
1943 foreach ($element['children'] as $sortorder=>$child) {
1944 if ($element['children'][$sortorder]['type'] == 'item'
1945 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1946 unset($element['children'][$sortorder]);
1948 } else if ($element['children'][$sortorder]['type'] == 'category') {
1949 grade_tree
::no_outcomes($element['children'][$sortorder]);
1955 * Static recursive helper - makes the grade_item for category the last children
1957 * @param array &$element The seed of the recursion
1961 public function category_grade_last(&$element) {
1962 if (empty($element['children'])) {
1965 if (count($element['children']) < 2) {
1968 $first_item = reset($element['children']);
1969 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
1970 // the category item might have been already removed
1971 $order = key($element['children']);
1972 unset($element['children'][$order]);
1973 $element['children'][$order] =& $first_item;
1975 foreach ($element['children'] as $sortorder => $child) {
1976 grade_tree
::category_grade_last($element['children'][$sortorder]);
1981 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1983 * @param array &$levels The levels of the grade tree through which to recurse
1984 * @param array &$element The seed of the recursion
1985 * @param int $depth How deep are we?
1988 public function fill_levels(&$levels, &$element, $depth) {
1989 if (!array_key_exists($depth, $levels)) {
1990 $levels[$depth] = array();
1993 // prepare unique identifier
1994 if ($element['type'] == 'category') {
1995 $element['eid'] = 'c'.$element['object']->id
;
1996 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1997 $element['eid'] = 'i'.$element['object']->id
;
1998 $this->items
[$element['object']->id
] =& $element['object'];
2001 $levels[$depth][] =& $element;
2003 if (empty($element['children'])) {
2007 foreach ($element['children'] as $sortorder=>$child) {
2008 grade_tree
::fill_levels($levels, $element['children'][$sortorder], $depth);
2009 $element['children'][$sortorder]['prev'] = $prev;
2010 $element['children'][$sortorder]['next'] = 0;
2012 $element['children'][$prev]['next'] = $sortorder;
2019 * Static recursive helper - makes full tree (all leafes are at the same level)
2021 * @param array &$element The seed of the recursion
2022 * @param int $depth How deep are we?
2026 public function inject_fillers(&$element, $depth) {
2029 if (empty($element['children'])) {
2032 $chdepths = array();
2033 $chids = array_keys($element['children']);
2034 $last_child = end($chids);
2035 $first_child = reset($chids);
2037 foreach ($chids as $chid) {
2038 $chdepths[$chid] = grade_tree
::inject_fillers($element['children'][$chid], $depth);
2042 $maxdepth = reset($chdepths);
2043 foreach ($chdepths as $chid=>$chd) {
2044 if ($chd == $maxdepth) {
2047 for ($i=0; $i < $maxdepth-$chd; $i++
) {
2048 if ($chid == $first_child) {
2049 $type = 'fillerfirst';
2050 } else if ($chid == $last_child) {
2051 $type = 'fillerlast';
2055 $oldchild =& $element['children'][$chid];
2056 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2057 'eid'=>'', 'depth'=>$element['object']->depth
,
2058 'children'=>array($oldchild));
2066 * Static recursive helper - add colspan information into categories
2068 * @param array &$element The seed of the recursion
2072 public function inject_colspans(&$element) {
2073 if (empty($element['children'])) {
2077 foreach ($element['children'] as $key=>$child) {
2078 $count +
= grade_tree
::inject_colspans($element['children'][$key]);
2080 $element['colspan'] = $count;
2085 * Parses the array in search of a given eid and returns a element object with
2086 * information about the element it has found.
2087 * @param int $eid Gradetree Element ID
2088 * @return object element
2090 public function locate_element($eid) {
2091 // it is a grade - construct a new object
2092 if (strpos($eid, 'n') === 0) {
2093 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2097 $itemid = $matches[1];
2098 $userid = $matches[2];
2100 //extra security check - the grade item must be in this tree
2101 if (!$item_el = $this->locate_element('i'.$itemid)) {
2105 // $gradea->id may be null - means does not exist yet
2106 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2108 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2109 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2111 } else if (strpos($eid, 'g') === 0) {
2112 $id = (int) substr($eid, 1);
2113 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
2116 //extra security check - the grade item must be in this tree
2117 if (!$item_el = $this->locate_element('i'.$grade->itemid
)) {
2120 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2121 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2124 // it is a category or item
2125 foreach ($this->levels
as $row) {
2126 foreach ($row as $element) {
2127 if ($element['type'] == 'filler') {
2130 if ($element['eid'] == $eid) {
2140 * Returns a well-formed XML representation of the grade-tree using recursion.
2142 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2143 * @param string $tabs The control character to use for tabs
2145 * @return string $xml
2147 public function exporttoxml($root=null, $tabs="\t") {
2150 if (is_null($root)) {
2151 $root = $this->top_element
;
2152 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2153 $xml .= "<gradetree>\n";
2157 $type = 'undefined';
2158 if (strpos($root['object']->table
, 'grade_categories') !== false) {
2160 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
2162 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
2166 $xml .= "$tabs<element type=\"$type\">\n";
2167 foreach ($root['object'] as $var => $value) {
2168 if (!is_object($value) && !is_array($value) && !empty($value)) {
2169 $xml .= "$tabs\t<$var>$value</$var>\n";
2173 if (!empty($root['children'])) {
2174 $xml .= "$tabs\t<children>\n";
2175 foreach ($root['children'] as $sortorder => $child) {
2176 $xml .= $this->exportToXML($child, $tabs."\t\t");
2178 $xml .= "$tabs\t</children>\n";
2181 $xml .= "$tabs</element>\n";
2184 $xml .= "</gradetree>";
2191 * Returns a JSON representation of the grade-tree using recursion.
2193 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2194 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2198 public function exporttojson($root=null, $tabs="\t") {
2201 if (is_null($root)) {
2202 $root = $this->top_element
;
2209 if (strpos($root['object']->table
, 'grade_categories') !== false) {
2210 $name = $root['object']->fullname
;
2212 $name = $root['object']->get_name();
2214 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
2215 $name = $root['object']->itemname
;
2216 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
2217 $name = $root['object']->itemname
;
2220 $json .= "$tabs {\n";
2221 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2222 $json .= "$tabs\t \"name\": \"$name\",\n";
2224 foreach ($root['object'] as $var => $value) {
2225 if (!is_object($value) && !is_array($value) && !empty($value)) {
2226 $json .= "$tabs\t \"$var\": \"$value\",\n";
2230 $json = substr($json, 0, strrpos($json, ','));
2232 if (!empty($root['children'])) {
2233 $json .= ",\n$tabs\t\"children\": [\n";
2234 foreach ($root['children'] as $sortorder => $child) {
2235 $json .= $this->exportToJSON($child, $tabs."\t\t");
2237 $json = substr($json, 0, strrpos($json, ','));
2238 $json .= "\n$tabs\t]\n";
2244 $json .= "\n$tabs},\n";
2251 * Returns the array of levels
2255 public function get_levels() {
2256 return $this->levels
;
2260 * Returns the array of grade items
2264 public function get_items() {
2265 return $this->items
;
2269 * Returns a specific Grade Item
2271 * @param int $itemid The ID of the grade_item object
2273 * @return grade_item
2275 public function get_item($itemid) {
2276 if (array_key_exists($itemid, $this->items
)) {
2277 return $this->items
[$itemid];
2285 * Local shortcut function for creating an edit/delete button for a grade_* object.
2286 * @param string $type 'edit' or 'delete'
2287 * @param int $courseid The Course ID
2288 * @param grade_* $object The grade_* object
2289 * @return string html
2291 function grade_button($type, $courseid, $object) {
2292 global $CFG, $OUTPUT;
2293 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2294 $objectidstring = $matches[1] . 'id';
2296 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2299 $strdelete = get_string('delete');
2300 $stredit = get_string('edit');
2302 if ($type == 'delete') {
2303 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id
, 'action' => 'delete', 'sesskey' => sesskey()));
2304 } else if ($type == 'edit') {
2305 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id
));
2308 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $
{'str'.$type}, '', array('class' => 'iconsmall')));
2313 * This method adds settings to the settings block for the grade system and its
2316 * @global moodle_page $PAGE
2318 function grade_extend_settings($plugininfo, $courseid) {
2321 $gradenode = $PAGE->settingsnav
->prepend(get_string('gradeadministration', 'grades'), null, navigation_node
::TYPE_CONTAINER
);
2323 $strings = array_shift($plugininfo);
2325 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
2326 foreach ($reports as $report) {
2327 $gradenode->add($report->string, $report->link
, navigation_node
::TYPE_SETTING
, null, $report->id
, new pix_icon('i/report', ''));
2331 if ($imports = grade_helper
::get_plugins_import($courseid)) {
2332 $importnode = $gradenode->add($strings['import'], null, navigation_node
::TYPE_CONTAINER
);
2333 foreach ($imports as $import) {
2334 $importnode->add($import->string, $import->link
, navigation_node
::TYPE_SETTING
, null, $import->id
, new pix_icon('i/import', ''));
2338 if ($exports = grade_helper
::get_plugins_export($courseid)) {
2339 $exportnode = $gradenode->add($strings['export'], null, navigation_node
::TYPE_CONTAINER
);
2340 foreach ($exports as $export) {
2341 $exportnode->add($export->string, $export->link
, navigation_node
::TYPE_SETTING
, null, $export->id
, new pix_icon('i/export', ''));
2345 if ($setting = grade_helper
::get_info_manage_settings($courseid)) {
2346 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link
, navigation_node
::TYPE_SETTING
, null, $setting->id
, new pix_icon('i/settings', ''));
2349 if ($preferences = grade_helper
::get_plugins_report_preferences($courseid)) {
2350 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node
::TYPE_CONTAINER
);
2351 foreach ($preferences as $preference) {
2352 $preferencesnode->add($preference->string, $preference->link
, navigation_node
::TYPE_SETTING
, null, $preference->id
, new pix_icon('i/settings', ''));
2356 if ($letters = grade_helper
::get_info_letters($courseid)) {
2357 $letters = array_shift($letters);
2358 $gradenode->add($strings['letter'], $letters->link
, navigation_node
::TYPE_SETTING
, null, $letters->id
, new pix_icon('i/settings', ''));
2361 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
2362 $outcomes = array_shift($outcomes);
2363 $gradenode->add($strings['outcome'], $outcomes->link
, navigation_node
::TYPE_SETTING
, null, $outcomes->id
, new pix_icon('i/outcomes', ''));
2366 if ($scales = grade_helper
::get_info_scales($courseid)) {
2367 $gradenode->add($strings['scale'], $scales->link
, navigation_node
::TYPE_SETTING
, null, $scales->id
, new pix_icon('i/scales', ''));
2370 if ($categories = grade_helper
::get_info_edit_structure($courseid)) {
2371 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node
::TYPE_CONTAINER
);
2372 foreach ($categories as $category) {
2373 $categoriesnode->add($category->string, $category->link
, navigation_node
::TYPE_SETTING
, null, $category->id
, new pix_icon('i/report', ''));
2377 if ($gradenode->contains_active_node()) {
2378 // If the gradenode is active include the settings base node (gradeadministration) in
2379 // the navbar, typcially this is ignored.
2380 $PAGE->navbar
->includesettingsbase
= true;
2382 // If we can get the course admin node make sure it is closed by default
2383 // as in this case the gradenode will be opened
2384 if ($coursenode = $PAGE->settingsnav
->get('courseadmin', navigation_node
::TYPE_COURSE
)){
2385 $coursenode->make_inactive();
2386 $coursenode->forceopen
= false;
2392 * Grade helper class
2394 * This class provides several helpful functions that work irrespective of any
2397 * @copyright 2010 Sam Hemelryk
2398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2400 abstract class grade_helper
{
2402 * Cached manage settings info {@see get_info_settings}
2403 * @var grade_plugin_info|false
2405 protected static $managesetting = null;
2407 * Cached grade report plugins {@see get_plugins_reports}
2410 protected static $gradereports = null;
2412 * Cached grade report plugins preferences {@see get_info_scales}
2415 protected static $gradereportpreferences = null;
2417 * Cached scale info {@see get_info_scales}
2418 * @var grade_plugin_info|false
2420 protected static $scaleinfo = null;
2422 * Cached outcome info {@see get_info_outcomes}
2423 * @var grade_plugin_info|false
2425 protected static $outcomeinfo = null;
2427 * Cached info on edit structure {@see get_info_edit_structure}
2430 protected static $edittree = null;
2432 * Cached leftter info {@see get_info_letters}
2433 * @var grade_plugin_info|false
2435 protected static $letterinfo = null;
2437 * Cached grade import plugins {@see get_plugins_import}
2440 protected static $importplugins = null;
2442 * Cached grade export plugins {@see get_plugins_export}
2445 protected static $exportplugins = null;
2447 * Cached grade plugin strings
2450 protected static $pluginstrings = null;
2453 * Gets strings commonly used by the describe plugins
2455 * report => get_string('view'),
2456 * edittree => get_string('edittree', 'grades'),
2457 * scale => get_string('scales'),
2458 * outcome => get_string('outcomes', 'grades'),
2459 * letter => get_string('letters', 'grades'),
2460 * export => get_string('export', 'grades'),
2461 * import => get_string('import'),
2462 * preferences => get_string('mypreferences', 'grades'),
2463 * settings => get_string('settings')
2467 public static function get_plugin_strings() {
2468 if (self
::$pluginstrings === null) {
2469 self
::$pluginstrings = array(
2470 'report' => get_string('view'),
2471 'edittree' => get_string('edittree', 'grades'),
2472 'scale' => get_string('scales'),
2473 'outcome' => get_string('outcomes', 'grades'),
2474 'letter' => get_string('letters', 'grades'),
2475 'export' => get_string('export', 'grades'),
2476 'import' => get_string('import'),
2477 'preferences' => get_string('mypreferences', 'grades'),
2478 'settings' => get_string('settings')
2481 return self
::$pluginstrings;
2484 * Get grade_plugin_info object for managing settings if the user can
2486 * @param int $courseid
2487 * @return grade_plugin_info
2489 public static function get_info_manage_settings($courseid) {
2490 if (self
::$managesetting !== null) {
2491 return self
::$managesetting;
2493 $context = context_course
::instance($courseid);
2494 if (has_capability('moodle/grade:manage', $context)) {
2495 self
::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2497 self
::$managesetting = false;
2499 return self
::$managesetting;
2502 * Returns an array of plugin reports as grade_plugin_info objects
2504 * @param int $courseid
2507 public static function get_plugins_reports($courseid) {
2510 if (self
::$gradereports !== null) {
2511 return self
::$gradereports;
2513 $context = context_course
::instance($courseid);
2514 $gradereports = array();
2515 $gradepreferences = array();
2516 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
2517 //some reports make no sense if we're not within a course
2518 if ($courseid==$SITE->id
&& ($plugin=='grader' ||
$plugin=='user')) {
2522 // Remove ones we can't see
2523 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2527 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2528 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2529 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2531 // Add link to preferences tab if such a page exists
2532 if (file_exists($plugindir.'/preferences.php')) {
2533 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2534 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2537 if (count($gradereports) == 0) {
2538 $gradereports = false;
2539 $gradepreferences = false;
2540 } else if (count($gradepreferences) == 0) {
2541 $gradepreferences = false;
2542 asort($gradereports);
2544 asort($gradereports);
2545 asort($gradepreferences);
2547 self
::$gradereports = $gradereports;
2548 self
::$gradereportpreferences = $gradepreferences;
2549 return self
::$gradereports;
2552 * Returns an array of grade plugin report preferences for plugin reports that
2553 * support preferences
2554 * @param int $courseid
2557 public static function get_plugins_report_preferences($courseid) {
2558 if (self
::$gradereportpreferences !== null) {
2559 return self
::$gradereportpreferences;
2561 self
::get_plugins_reports($courseid);
2562 return self
::$gradereportpreferences;
2565 * Get information on scales
2566 * @param int $courseid
2567 * @return grade_plugin_info
2569 public static function get_info_scales($courseid) {
2570 if (self
::$scaleinfo !== null) {
2571 return self
::$scaleinfo;
2573 if (has_capability('moodle/course:managescales', context_course
::instance($courseid))) {
2574 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2575 self
::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2577 self
::$scaleinfo = false;
2579 return self
::$scaleinfo;
2582 * Get information on outcomes
2583 * @param int $courseid
2584 * @return grade_plugin_info
2586 public static function get_info_outcomes($courseid) {
2589 if (self
::$outcomeinfo !== null) {
2590 return self
::$outcomeinfo;
2592 $context = context_course
::instance($courseid);
2593 $canmanage = has_capability('moodle/grade:manage', $context);
2594 $canupdate = has_capability('moodle/course:update', $context);
2595 if (!empty($CFG->enableoutcomes
) && ($canmanage ||
$canupdate)) {
2596 $outcomes = array();
2598 if ($courseid!=$SITE->id
) {
2599 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2600 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2602 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2603 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2604 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2605 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2607 if ($courseid!=$SITE->id
) {
2608 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2609 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2612 self
::$outcomeinfo = $outcomes;
2614 self
::$outcomeinfo = false;
2616 return self
::$outcomeinfo;
2619 * Get information on editing structures
2620 * @param int $courseid
2623 public static function get_info_edit_structure($courseid) {
2624 if (self
::$edittree !== null) {
2625 return self
::$edittree;
2627 if (has_capability('moodle/grade:manage', context_course
::instance($courseid))) {
2628 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2629 self
::$edittree = array(
2630 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2631 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2634 self
::$edittree = false;
2636 return self
::$edittree;
2639 * Get information on letters
2640 * @param int $courseid
2643 public static function get_info_letters($courseid) {
2645 if (self
::$letterinfo !== null) {
2646 return self
::$letterinfo;
2648 $context = context_course
::instance($courseid);
2649 $canmanage = has_capability('moodle/grade:manage', $context);
2650 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2651 if ($canmanage ||
$canmanageletters) {
2652 // Redirect to system context when report is accessed from admin settings MDL-31633
2653 if ($context->instanceid
== $SITE->id
) {
2654 $param = array('edit' => 1);
2656 $param = array('edit' => 1,'id' => $context->id
);
2658 self
::$letterinfo = array(
2659 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id
)), get_string('view')),
2660 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2663 self
::$letterinfo = false;
2665 return self
::$letterinfo;
2668 * Get information import plugins
2669 * @param int $courseid
2672 public static function get_plugins_import($courseid) {
2675 if (self
::$importplugins !== null) {
2676 return self
::$importplugins;
2678 $importplugins = array();
2679 $context = context_course
::instance($courseid);
2681 if (has_capability('moodle/grade:import', $context)) {
2682 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2683 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2686 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2687 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2688 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2692 if ($CFG->gradepublishing
) {
2693 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2694 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2698 if (count($importplugins) > 0) {
2699 asort($importplugins);
2700 self
::$importplugins = $importplugins;
2702 self
::$importplugins = false;
2704 return self
::$importplugins;
2707 * Get information export plugins
2708 * @param int $courseid
2711 public static function get_plugins_export($courseid) {
2714 if (self
::$exportplugins !== null) {
2715 return self
::$exportplugins;
2717 $context = context_course
::instance($courseid);
2718 $exportplugins = array();
2719 if (has_capability('moodle/grade:export', $context)) {
2720 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2721 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2724 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2725 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2726 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2729 if ($CFG->gradepublishing
) {
2730 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2731 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2734 if (count($exportplugins) > 0) {
2735 asort($exportplugins);
2736 self
::$exportplugins = $exportplugins;
2738 self
::$exportplugins = false;
2740 return self
::$exportplugins;
2744 * Returns the value of a field from a user record
2746 * @param stdClass $user object
2747 * @param stdClass $field object
2748 * @return string value of the field
2750 public static function get_user_field_value($user, $field) {
2751 if (!empty($field->customid
)) {
2752 $fieldname = 'customfield_' . $field->shortname
;
2753 if (!empty($user->{$fieldname}) ||
is_numeric($user->{$fieldname})) {
2754 $fieldvalue = $user->{$fieldname};
2756 $fieldvalue = $field->default;
2759 $fieldvalue = $user->{$field->shortname
};
2765 * Returns an array of user profile fields to be included in export
2767 * @param int $courseid
2768 * @param bool $includecustomfields
2769 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2771 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2774 // Gets the fields that have to be hidden
2775 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields
));
2776 $context = context_course
::instance($courseid);
2777 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2778 if ($canseehiddenfields) {
2779 $hiddenfields = array();
2783 require_once($CFG->dirroot
.'/user/lib.php'); // Loads user_get_default_fields()
2784 require_once($CFG->dirroot
.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2785 $userdefaultfields = user_get_default_fields();
2787 // Sets the list of profile fields
2788 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields
));
2789 if (!empty($userprofilefields)) {
2790 foreach ($userprofilefields as $field) {
2791 $field = trim($field);
2792 if (in_array($field, $hiddenfields) ||
!in_array($field, $userdefaultfields)) {
2795 $obj = new stdClass();
2797 $obj->shortname
= $field;
2798 $obj->fullname
= get_string($field);
2803 // Sets the list of custom profile fields
2804 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields
));
2805 if ($includecustomfields && !empty($customprofilefields)) {
2806 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2807 $customfields = $DB->get_records_sql("SELECT f.*
2808 FROM {user_info_field} f
2809 JOIN {user_info_category} c ON f.categoryid=c.id
2810 WHERE f.shortname $wherefields
2811 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2812 if (!is_array($customfields)) {
2816 foreach ($customfields as $field) {
2817 // Make sure we can display this custom field
2818 if (!in_array($field->shortname
, $customprofilefields)) {
2820 } else if (in_array($field->shortname
, $hiddenfields)) {
2822 } else if ($field->visible
!= PROFILE_VISIBLE_ALL
&& !$canseehiddenfields) {
2826 $obj = new stdClass();
2827 $obj->customid
= $field->id
;
2828 $obj->shortname
= $field->shortname
;
2829 $obj->fullname
= format_string($field->name
);
2830 $obj->datatype
= $field->datatype
;
2831 $obj->default = $field->defaultdata
;