Merge branch 'MDL-75176' of https://github.com/call-learning/moodle
[moodle.git] / grade / lib.php
blob4d1199965dfe8aa50efaa4f297e4a3c034a55b12
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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');
28 use \core_grades\output\action_bar;
29 use \core_grades\output\general_action_bar;
31 /**
32 * This class iterates over all users that are graded in a course.
33 * Returns detailed info about users and their grades.
35 * @author Petr Skoda <skodak@moodle.org>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class graded_users_iterator {
40 /**
41 * The couse whose users we are interested in
43 protected $course;
45 /**
46 * An array of grade items or null if only user data was requested
48 protected $grade_items;
50 /**
51 * The group ID we are interested in. 0 means all groups.
53 protected $groupid;
55 /**
56 * A recordset of graded users
58 protected $users_rs;
60 /**
61 * A recordset of user grades (grade_grade instances)
63 protected $grades_rs;
65 /**
66 * Array used when moving to next user while iterating through the grades recordset
68 protected $gradestack;
70 /**
71 * The first field of the users table by which the array of users will be sorted
73 protected $sortfield1;
75 /**
76 * Should sortfield1 be ASC or DESC
78 protected $sortorder1;
80 /**
81 * The second field of the users table by which the array of users will be sorted
83 protected $sortfield2;
85 /**
86 * Should sortfield2 be ASC or DESC
88 protected $sortorder2;
90 /**
91 * Should users whose enrolment has been suspended be ignored?
93 protected $onlyactive = false;
95 /**
96 * Enable user custom fields
98 protected $allowusercustomfields = false;
101 * List of suspended users in course. This includes users whose enrolment status is suspended
102 * or enrolment has expired or not started.
104 protected $suspendedusers = array();
107 * Constructor
109 * @param object $course A course object
110 * @param array $grade_items array of grade items, if not specified only user info returned
111 * @param int $groupid iterate only group users if present
112 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
113 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
114 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
115 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
117 public function __construct($course, $grade_items=null, $groupid=0,
118 $sortfield1='lastname', $sortorder1='ASC',
119 $sortfield2='firstname', $sortorder2='ASC') {
120 $this->course = $course;
121 $this->grade_items = $grade_items;
122 $this->groupid = $groupid;
123 $this->sortfield1 = $sortfield1;
124 $this->sortorder1 = $sortorder1;
125 $this->sortfield2 = $sortfield2;
126 $this->sortorder2 = $sortorder2;
128 $this->gradestack = array();
132 * Initialise the iterator
134 * @return boolean success
136 public function init() {
137 global $CFG, $DB;
139 $this->close();
141 export_verify_grades($this->course->id);
142 $course_item = grade_item::fetch_course_item($this->course->id);
143 if ($course_item->needsupdate) {
144 // Can not calculate all final grades - sorry.
145 return false;
148 $coursecontext = context_course::instance($this->course->id);
150 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
151 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
152 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
154 $params = array_merge($params, $enrolledparams, $relatedctxparams);
156 if ($this->groupid) {
157 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
158 $groupwheresql = "AND gm.groupid = :groupid";
159 // $params contents: gradebookroles
160 $params['groupid'] = $this->groupid;
161 } else {
162 $groupsql = "";
163 $groupwheresql = "";
166 if (empty($this->sortfield1)) {
167 // We must do some sorting even if not specified.
168 $ofields = ", u.id AS usrt";
169 $order = "usrt ASC";
171 } else {
172 $ofields = ", u.$this->sortfield1 AS usrt1";
173 $order = "usrt1 $this->sortorder1";
174 if (!empty($this->sortfield2)) {
175 $ofields .= ", u.$this->sortfield2 AS usrt2";
176 $order .= ", usrt2 $this->sortorder2";
178 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
179 // User order MUST be the same in both queries,
180 // must include the only unique user->id if not already present.
181 $ofields .= ", u.id AS usrt";
182 $order .= ", usrt ASC";
186 $userfields = 'u.*';
187 $customfieldssql = '';
188 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
189 $customfieldscount = 0;
190 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
191 foreach ($customfieldsarray as $field) {
192 if (!empty($field->customid)) {
193 $customfieldssql .= "
194 LEFT JOIN (SELECT * FROM {user_info_data}
195 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
196 ON u.id = cf$customfieldscount.userid";
197 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->customid}";
198 $params['cf'.$customfieldscount] = $field->customid;
199 $customfieldscount++;
204 $users_sql = "SELECT $userfields $ofields
205 FROM {user} u
206 JOIN ($enrolledsql) je ON je.id = u.id
207 $groupsql $customfieldssql
208 JOIN (
209 SELECT DISTINCT ra.userid
210 FROM {role_assignments} ra
211 WHERE ra.roleid $gradebookroles_sql
212 AND ra.contextid $relatedctxsql
213 ) rainner ON rainner.userid = u.id
214 WHERE u.deleted = 0
215 $groupwheresql
216 ORDER BY $order";
217 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
219 if (!$this->onlyactive) {
220 $context = context_course::instance($this->course->id);
221 $this->suspendedusers = get_suspended_userids($context);
222 } else {
223 $this->suspendedusers = array();
226 if (!empty($this->grade_items)) {
227 $itemids = array_keys($this->grade_items);
228 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
229 $params = array_merge($params, $grades_params);
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
235 $groupsql
236 JOIN (
237 SELECT DISTINCT ra.userid
238 FROM {role_assignments} ra
239 WHERE ra.roleid $gradebookroles_sql
240 AND ra.contextid $relatedctxsql
241 ) rainner ON rainner.userid = u.id
242 WHERE u.deleted = 0
243 AND g.itemid $itemidsql
244 $groupwheresql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
247 } else {
248 $this->grades_rs = false;
251 return true;
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
269 } else {
270 $user = $this->users_rs->current();
271 $this->users_rs->next();
274 // find grades of this user
275 $grade_records = array();
276 while (true) {
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid)) {
282 break;
285 if ($current->userid != $user->id) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
288 break;
291 $grade_records[$current->itemid] = $current;
294 $grades = array();
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);
308 } else {
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);
314 $grades[$grade_item->id]->grade_item = $grade_item;
318 // Set user suspended status.
319 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
320 $result = new stdClass();
321 $result->user = $user;
322 $result->grades = $grades;
323 $result->feedbacks = $feedbacks;
324 return $result;
328 * Close the iterator, do not forget to call this function
330 public function close() {
331 if ($this->users_rs) {
332 $this->users_rs->close();
333 $this->users_rs = null;
335 if ($this->grades_rs) {
336 $this->grades_rs->close();
337 $this->grades_rs = null;
339 $this->gradestack = array();
343 * Should all enrolled users be exported or just those with an active enrolment?
345 * @param bool $onlyactive True to limit the export to users with an active enrolment
347 public function require_active_enrolment($onlyactive = true) {
348 if (!empty($this->users_rs)) {
349 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
351 $this->onlyactive = $onlyactive;
355 * Allow custom fields to be included
357 * @param bool $allow Whether to allow custom fields or not
358 * @return void
360 public function allow_user_custom_fields($allow = true) {
361 if ($allow) {
362 $this->allowusercustomfields = true;
363 } else {
364 $this->allowusercustomfields = false;
369 * Add a grade_grade instance to the grade stack
371 * @param grade_grade $grade Grade object
373 * @return void
375 private function _push($grade) {
376 array_push($this->gradestack, $grade);
381 * Remove a grade_grade instance from the grade stack
383 * @return grade_grade current grade object
385 private function _pop() {
386 global $DB;
387 if (empty($this->gradestack)) {
388 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
389 return null; // no grades present
392 $current = $this->grades_rs->current();
394 $this->grades_rs->next();
396 return $current;
397 } else {
398 return array_pop($this->gradestack);
404 * Print a selection popup form of the graded users in a course.
406 * @deprecated since 2.0
408 * @param int $course id of the course
409 * @param string $actionpage The page receiving the data from the popoup form
410 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
411 * @param int $groupid id of requested group, 0 means all
412 * @param int $includeall bool include all option
413 * @param bool $return If true, will return the HTML, otherwise, will print directly
414 * @return null
416 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
417 global $CFG, $USER, $OUTPUT;
418 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
421 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
422 global $USER, $CFG;
424 if (is_null($userid)) {
425 $userid = $USER->id;
427 $coursecontext = context_course::instance($course->id);
428 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
429 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
430 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
431 $menu = array(); // Will be a list of userid => user name
432 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
433 $gui = new graded_users_iterator($course, null, $groupid);
434 $gui->require_active_enrolment($showonlyactiveenrol);
435 $gui->init();
436 $label = get_string('selectauser', 'grades');
437 if ($includeall) {
438 $menu[0] = get_string('allusers', 'grades');
439 $label = get_string('selectalloroneuser', 'grades');
441 while ($userdata = $gui->next_user()) {
442 $user = $userdata->user;
443 $userfullname = fullname($user);
444 if ($user->suspendedenrolment) {
445 $menususpendedusers[$user->id] = $userfullname;
446 } else {
447 $menu[$user->id] = $userfullname;
450 $gui->close();
452 if ($includeall) {
453 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
456 if (!empty($menususpendedusers)) {
457 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
459 $gpr = new grade_plugin_return(array('type' => 'report', 'course' => $course, 'groupid' => $groupid));
460 $select = new single_select(
461 new moodle_url('/grade/report/'.$report.'/index.php', $gpr->get_options()),
462 'userid', $menu, $userid
464 $select->label = $label;
465 $select->formid = 'choosegradeuser';
466 return $select;
470 * Hide warning about changed grades during upgrade to 2.8.
472 * @param int $courseid The current course id.
474 function hide_natural_aggregation_upgrade_notice($courseid) {
475 unset_config('show_sumofgrades_upgrade_' . $courseid);
479 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
481 * @param int $courseid The current course id.
483 function grade_hide_min_max_grade_upgrade_notice($courseid) {
484 unset_config('show_min_max_grades_changed_' . $courseid);
488 * Use the grade min and max from the grade_grade.
490 * This is reserved for core use after an upgrade.
492 * @param int $courseid The current course id.
494 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
495 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
497 grade_force_full_regrading($courseid);
498 // Do this now, because it probably happened to late in the page load to be happen automatically.
499 grade_regrade_final_grades($courseid);
503 * Use the grade min and max from the grade_item.
505 * This is reserved for core use after an upgrade.
507 * @param int $courseid The current course id.
509 function grade_upgrade_use_min_max_from_grade_item($courseid) {
510 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
512 grade_force_full_regrading($courseid);
513 // Do this now, because it probably happened to late in the page load to be happen automatically.
514 grade_regrade_final_grades($courseid);
518 * Hide warning about changed grades during upgrade to 2.8.
520 * @param int $courseid The current course id.
522 function hide_aggregatesubcats_upgrade_notice($courseid) {
523 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
527 * Hide warning about changed grades due to bug fixes
529 * @param int $courseid The current course id.
531 function hide_gradebook_calculations_freeze_notice($courseid) {
532 unset_config('gradebook_calculations_freeze_' . $courseid);
536 * Print warning about changed grades during upgrade to 2.8.
538 * @param int $courseid The current course id.
539 * @param context $context The course context.
540 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
541 * @param boolean $return return as string
543 * @return nothing or string if $return true
545 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
546 global $CFG, $OUTPUT;
547 $html = '';
549 // Do not do anything if they cannot manage the grades of this course.
550 if (!has_capability('moodle/grade:manage', $context)) {
551 return $html;
554 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
555 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
556 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
557 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
559 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
560 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
562 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
563 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
565 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
567 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
568 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
570 // Hide the warning if the user told it to go away.
571 if ($hidenaturalwarning) {
572 hide_natural_aggregation_upgrade_notice($courseid);
574 // Hide the warning if the user told it to go away.
575 if ($hidesubcatswarning) {
576 hide_aggregatesubcats_upgrade_notice($courseid);
579 // Hide the min/max warning if the user told it to go away.
580 if ($hideminmaxwarning) {
581 grade_hide_min_max_grade_upgrade_notice($courseid);
582 $showminmaxwarning = false;
585 if ($useminmaxfromgradegrade) {
586 // Revert to the new behaviour, we now use the grade_grade for min/max.
587 grade_upgrade_use_min_max_from_grade_grade($courseid);
588 grade_hide_min_max_grade_upgrade_notice($courseid);
589 $showminmaxwarning = false;
591 } else if ($useminmaxfromgradeitem) {
592 // Apply the new logic, we now use the grade_item for min/max.
593 grade_upgrade_use_min_max_from_grade_item($courseid);
594 grade_hide_min_max_grade_upgrade_notice($courseid);
595 $showminmaxwarning = false;
599 if (!$hidenaturalwarning && $shownaturalwarning) {
600 $message = get_string('sumofgradesupgradedgrades', 'grades');
601 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
602 $urlparams = array( 'id' => $courseid,
603 'seensumofgradesupgradedgrades' => true,
604 'sesskey' => sesskey());
605 $goawayurl = new moodle_url($thispage, $urlparams);
606 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
607 $html .= $OUTPUT->notification($message, 'notifysuccess');
608 $html .= $goawaybutton;
611 if (!$hidesubcatswarning && $showsubcatswarning) {
612 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
613 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
614 $urlparams = array( 'id' => $courseid,
615 'seenaggregatesubcatsupgradedgrades' => true,
616 'sesskey' => sesskey());
617 $goawayurl = new moodle_url($thispage, $urlparams);
618 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
619 $html .= $OUTPUT->notification($message, 'notifysuccess');
620 $html .= $goawaybutton;
623 if ($showminmaxwarning) {
624 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
625 $urlparams = array( 'id' => $courseid,
626 'seenminmaxupgradedgrades' => true,
627 'sesskey' => sesskey());
629 $goawayurl = new moodle_url($thispage, $urlparams);
630 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
631 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
632 array('target' => '_blank'));
634 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
635 // Show the message that there were min/max issues that have been resolved.
636 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
638 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
639 $urlparams = array('id' => $courseid,
640 'useminmaxfromgradegrade' => true,
641 'sesskey' => sesskey());
642 $reverturl = new moodle_url($thispage, $urlparams);
643 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
645 $html .= $OUTPUT->notification($message);
646 $html .= $revertbutton . $hideminmaxbutton;
648 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
649 // Show the warning that there are min/max issues that have not be resolved.
650 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
652 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
653 $urlparams = array('id' => $courseid,
654 'useminmaxfromgradeitem' => true,
655 'sesskey' => sesskey());
656 $fixurl = new moodle_url($thispage, $urlparams);
657 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
659 $html .= $OUTPUT->notification($message);
660 $html .= $fixbutton . $hideminmaxbutton;
664 if ($gradebookcalculationsfreeze) {
665 if ($acceptgradebookchanges) {
666 // Accept potential changes in grades caused by extra credit bug MDL-49257.
667 hide_gradebook_calculations_freeze_notice($courseid);
668 $courseitem = grade_item::fetch_course_item($courseid);
669 $courseitem->force_regrading();
670 grade_regrade_final_grades($courseid);
672 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
673 } else {
674 // Show the warning that there may be extra credit weights problems.
675 $a = new stdClass();
676 $a->gradebookversion = $gradebookcalculationsfreeze;
677 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
678 $a->currentversion = $matches[1];
679 } else {
680 $a->currentversion = $CFG->release;
682 $a->url = get_docs_url('Gradebook_calculation_changes');
683 $message = get_string('gradebookcalculationswarning', 'grades', $a);
685 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
686 $urlparams = array('id' => $courseid,
687 'acceptgradebookchanges' => true,
688 'sesskey' => sesskey());
689 $fixurl = new moodle_url($thispage, $urlparams);
690 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
692 $html .= $OUTPUT->notification($message);
693 $html .= $fixbutton;
697 if (!empty($html)) {
698 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
701 if ($return) {
702 return $html;
703 } else {
704 echo $html;
709 * grade_get_plugin_info
711 * @param int $courseid The course id
712 * @param string $active_type type of plugin on current page - import, export, report or edit
713 * @param string $active_plugin active plugin type - grader, user, cvs, ...
715 * @return array
717 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
718 global $CFG, $SITE;
720 $context = context_course::instance($courseid);
722 $plugin_info = array();
723 $count = 0;
724 $active = '';
725 $url_prefix = $CFG->wwwroot . '/grade/';
727 // Language strings
728 $plugin_info['strings'] = grade_helper::get_plugin_strings();
730 if ($reports = grade_helper::get_plugins_reports($courseid)) {
731 $plugin_info['report'] = $reports;
734 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
735 $plugin_info['settings'] = $settings;
738 if ($scale = grade_helper::get_info_scales($courseid)) {
739 $plugin_info['scale'] = array('view'=>$scale);
742 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
743 $plugin_info['outcome'] = $outcomes;
746 if ($letters = grade_helper::get_info_letters($courseid)) {
747 $plugin_info['letter'] = $letters;
750 if ($imports = grade_helper::get_plugins_import($courseid)) {
751 $plugin_info['import'] = $imports;
754 if ($exports = grade_helper::get_plugins_export($courseid)) {
755 $plugin_info['export'] = $exports;
758 // Let other plugins add plugins here so that we get extra tabs
759 // in the gradebook.
760 $callbacks = get_plugins_with_function('extend_gradebook_plugininfo', 'lib.php');
761 foreach ($callbacks as $plugins) {
762 foreach ($plugins as $pluginfunction) {
763 $plugin_info = $pluginfunction($plugin_info, $courseid);
767 foreach ($plugin_info as $plugin_type => $plugins) {
768 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
769 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
770 break;
772 foreach ($plugins as $plugin) {
773 if (is_a($plugin, 'grade_plugin_info')) {
774 if ($active_plugin == $plugin->id) {
775 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
781 return $plugin_info;
785 * A simple class containing info about grade plugins.
786 * Can be subclassed for special rules
788 * @package core_grades
789 * @copyright 2009 Nicolas Connault
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792 class grade_plugin_info {
794 * A unique id for this plugin
796 * @var mixed
798 public $id;
800 * A URL to access this plugin
802 * @var mixed
804 public $link;
806 * The name of this plugin
808 * @var mixed
810 public $string;
812 * Another grade_plugin_info object, parent of the current one
814 * @var mixed
816 public $parent;
819 * Constructor
821 * @param int $id A unique id for this plugin
822 * @param string $link A URL to access this plugin
823 * @param string $string The name of this plugin
824 * @param object $parent Another grade_plugin_info object, parent of the current one
826 * @return void
828 public function __construct($id, $link, $string, $parent=null) {
829 $this->id = $id;
830 $this->link = $link;
831 $this->string = $string;
832 $this->parent = $parent;
837 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
838 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
839 * print_heading() etc.
841 * @param int $courseid Course id
842 * @param string $active_type The type of the current page (report, settings,
843 * import, export, scales, outcomes, letters)
844 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
845 * @param string|bool $heading The heading of the page. Tries to guess if none is given
846 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
847 * @param string|bool $buttons Additional buttons to display on the page
848 * @param boolean $shownavigation should the gradebook navigation be shown?
849 * @param string|null $headerhelpidentifier The help string identifier if required.
850 * @param string|null $headerhelpcomponent The component for the help string.
851 * @param stdClass|null $user The user object for use with the user context header.
852 * @param actionbar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
853 * to true. If $actionbar is not explicitly defined, the general action bar
854 * (\core_grades\output\general_action_bar) will be used by default.
855 * @param boolean $showtitle If set to false just show course full name as a title.
856 * @return string HTML code or nothing if $return == false
858 function print_grade_page_head(int $courseid, string $active_type, ?string $active_plugin = null, $heading = false,
859 bool $return = false, $buttons = false, bool $shownavigation = true, ?string $headerhelpidentifier = null,
860 ?string $headerhelpcomponent = null, ?stdClass $user = null, ?action_bar $actionbar = null, $showtitle = true) {
861 global $CFG, $OUTPUT, $PAGE;
863 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
864 require_once($CFG->dirroot . '/course/lib.php');
865 if (course_modules_pending_deletion($courseid, true)) {
866 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
867 \core\output\notification::NOTIFY_WARNING);
870 if ($active_type === 'preferences') {
871 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
872 $active_type = 'settings';
875 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
877 // Determine the string of the active plugin
878 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
879 $stractive_type = $plugin_info['strings'][$active_type];
881 if (!$showtitle) {
882 $title = $PAGE->course->fullname;
883 } else if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
884 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
885 } else {
886 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
889 if ($active_type == 'report') {
890 $PAGE->set_pagelayout('report');
891 } else {
892 $PAGE->set_pagelayout('admin');
894 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
895 $PAGE->set_heading($title);
896 $PAGE->set_secondary_active_tab('grades');
898 if ($buttons instanceof single_button) {
899 $buttons = $OUTPUT->render($buttons);
901 $PAGE->set_button($buttons);
902 if ($courseid != SITEID) {
903 grade_extend_settings($plugin_info, $courseid);
906 // Set the current report as active in the breadcrumbs.
907 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
908 $reportnav->make_active();
911 $returnval = $OUTPUT->header();
913 if (!$return) {
914 echo $returnval;
917 // Guess heading if not given explicitly
918 if (!$heading) {
919 $heading = $stractive_plugin;
922 if (!$showtitle) {
923 $heading = '';
926 if ($shownavigation) {
927 $renderer = $PAGE->get_renderer('core_grades');
928 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
929 if (!$actionbar) {
930 $actionbar = new general_action_bar($PAGE->context, $PAGE->url, $active_type, $active_plugin);
933 if ($return) {
934 $returnval .= $renderer->render_action_bar($actionbar);
935 } else {
936 echo $renderer->render_action_bar($actionbar);
940 $output = '';
941 // Add a help dialogue box if provided.
942 if (isset($headerhelpidentifier)) {
943 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
944 } else {
945 if (isset($user)) {
946 $output = $OUTPUT->context_header(
947 array(
948 'heading' => html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id,
949 'course' => $courseid)), fullname($user)),
950 'user' => $user,
951 'usercontext' => context_user::instance($user->id)
952 ), 2
954 } else {
955 $output = $OUTPUT->heading($heading);
959 if ($return) {
960 $returnval .= $output;
961 } else {
962 echo $output;
965 $returnval .= print_natural_aggregation_upgrade_notice($courseid, context_course::instance($courseid), $PAGE->url,
966 $return);
968 if ($return) {
969 return $returnval;
974 * Utility class used for return tracking when using edit and other forms in grade plugins
976 * @package core_grades
977 * @copyright 2009 Nicolas Connault
978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
980 class grade_plugin_return {
982 * Type of grade plugin (e.g. 'edit', 'report')
984 * @var string
986 public $type;
988 * Name of grade plugin (e.g. 'grader', 'overview')
990 * @var string
992 public $plugin;
994 * Course id being viewed
996 * @var int
998 public $courseid;
1000 * Id of user whose information is being viewed/edited
1002 * @var int
1004 public $userid;
1006 * Id of group for which information is being viewed/edited
1008 * @var int
1010 public $groupid;
1012 * Current page # within output
1014 * @var int
1016 public $page;
1019 * Constructor
1021 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1023 public function __construct($params = []) {
1024 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1025 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1026 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1027 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1028 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1029 $this->page = optional_param('gpr_page', null, PARAM_INT);
1031 foreach ($params as $key => $value) {
1032 if (property_exists($this, $key)) {
1033 $this->$key = $value;
1036 // Allow course object rather than id to be used to specify course
1037 // - avoid unnecessary use of get_course.
1038 if (array_key_exists('course', $params)) {
1039 $course = $params['course'];
1040 $this->courseid = $course->id;
1041 } else {
1042 $course = null;
1044 // If group has been explicitly set in constructor parameters,
1045 // we should respect that.
1046 if (!array_key_exists('groupid', $params)) {
1047 // Otherwise, 'group' in request parameters is a request for a change.
1048 // In that case, or if we have no group at all, we should get groupid from
1049 // groups_get_course_group, which will do some housekeeping as well as
1050 // give us the correct value.
1051 $changegroup = optional_param('group', -1, PARAM_INT);
1052 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1053 if ($course === null) {
1054 $course = get_course($this->courseid);
1056 $this->groupid = groups_get_course_group($course, true);
1062 * Old syntax of class constructor. Deprecated in PHP7.
1064 * @deprecated since Moodle 3.1
1066 public function grade_plugin_return($params = null) {
1067 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1068 self::__construct($params);
1072 * Returns return parameters as options array suitable for buttons.
1073 * @return array options
1075 public function get_options() {
1076 if (empty($this->type)) {
1077 return array();
1080 $params = array();
1082 if (!empty($this->plugin)) {
1083 $params['plugin'] = $this->plugin;
1086 if (!empty($this->courseid)) {
1087 $params['id'] = $this->courseid;
1090 if (!empty($this->userid)) {
1091 $params['userid'] = $this->userid;
1094 if (!empty($this->groupid)) {
1095 $params['group'] = $this->groupid;
1098 if (!empty($this->page)) {
1099 $params['page'] = $this->page;
1102 return $params;
1106 * Returns return url
1108 * @param string $default default url when params not set
1109 * @param array $extras Extra URL parameters
1111 * @return string url
1113 public function get_return_url($default, $extras=null) {
1114 global $CFG;
1116 if (empty($this->type) or empty($this->plugin)) {
1117 return $default;
1120 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1121 $glue = '?';
1123 if (!empty($this->courseid)) {
1124 $url .= $glue.'id='.$this->courseid;
1125 $glue = '&amp;';
1128 if (!empty($this->userid)) {
1129 $url .= $glue.'userid='.$this->userid;
1130 $glue = '&amp;';
1133 if (!empty($this->groupid)) {
1134 $url .= $glue.'group='.$this->groupid;
1135 $glue = '&amp;';
1138 if (!empty($this->page)) {
1139 $url .= $glue.'page='.$this->page;
1140 $glue = '&amp;';
1143 if (!empty($extras)) {
1144 foreach ($extras as $key=>$value) {
1145 $url .= $glue.$key.'='.$value;
1146 $glue = '&amp;';
1150 return $url;
1154 * Returns string with hidden return tracking form elements.
1155 * @return string
1157 public function get_form_fields() {
1158 if (empty($this->type)) {
1159 return '';
1162 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1164 if (!empty($this->plugin)) {
1165 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1168 if (!empty($this->courseid)) {
1169 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1172 if (!empty($this->userid)) {
1173 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1176 if (!empty($this->groupid)) {
1177 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1180 if (!empty($this->page)) {
1181 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1183 return $result;
1187 * Add hidden elements into mform
1189 * @param object &$mform moodle form object
1191 * @return void
1193 public function add_mform_elements(&$mform) {
1194 if (empty($this->type)) {
1195 return;
1198 $mform->addElement('hidden', 'gpr_type', $this->type);
1199 $mform->setType('gpr_type', PARAM_SAFEDIR);
1201 if (!empty($this->plugin)) {
1202 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1203 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1206 if (!empty($this->courseid)) {
1207 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1208 $mform->setType('gpr_courseid', PARAM_INT);
1211 if (!empty($this->userid)) {
1212 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1213 $mform->setType('gpr_userid', PARAM_INT);
1216 if (!empty($this->groupid)) {
1217 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1218 $mform->setType('gpr_groupid', PARAM_INT);
1221 if (!empty($this->page)) {
1222 $mform->addElement('hidden', 'gpr_page', $this->page);
1223 $mform->setType('gpr_page', PARAM_INT);
1228 * Add return tracking params into url
1230 * @param moodle_url $url A URL
1232 * @return string $url with return tracking params
1234 public function add_url_params(moodle_url $url) {
1235 if (empty($this->type)) {
1236 return $url;
1239 $url->param('gpr_type', $this->type);
1241 if (!empty($this->plugin)) {
1242 $url->param('gpr_plugin', $this->plugin);
1245 if (!empty($this->courseid)) {
1246 $url->param('gpr_courseid' ,$this->courseid);
1249 if (!empty($this->userid)) {
1250 $url->param('gpr_userid', $this->userid);
1253 if (!empty($this->groupid)) {
1254 $url->param('gpr_groupid', $this->groupid);
1257 if (!empty($this->page)) {
1258 $url->param('gpr_page', $this->page);
1261 return $url;
1266 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1268 * @param string $path The path of the calling script (using __FILE__?)
1269 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1270 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1271 * an array of keys and values (e.g courseid => $courseid, itemid...)
1273 * @return string
1275 function grade_build_nav($path, $pagename=null, $id=null) {
1276 global $CFG, $COURSE, $PAGE;
1278 $strgrades = get_string('grades', 'grades');
1280 // Parse the path and build navlinks from its elements
1281 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1282 $path = substr($path, $dirroot_length);
1283 $path = str_replace('\\', '/', $path);
1285 $path_elements = explode('/', $path);
1287 $path_elements_count = count($path_elements);
1289 // First link is always 'grade'
1290 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1292 $link = null;
1293 $numberofelements = 3;
1295 // Prepare URL params string
1296 $linkparams = array();
1297 if (!is_null($id)) {
1298 if (is_array($id)) {
1299 foreach ($id as $idkey => $idvalue) {
1300 $linkparams[$idkey] = $idvalue;
1302 } else {
1303 $linkparams['id'] = $id;
1307 $navlink4 = null;
1309 // Remove file extensions from filenames
1310 foreach ($path_elements as $key => $filename) {
1311 $path_elements[$key] = str_replace('.php', '', $filename);
1314 // Second level links
1315 switch ($path_elements[1]) {
1316 case 'edit': // No link
1317 if ($path_elements[3] != 'index.php') {
1318 $numberofelements = 4;
1320 break;
1321 case 'import': // No link
1322 break;
1323 case 'export': // No link
1324 break;
1325 case 'report':
1326 // $id is required for this link. Do not print it if $id isn't given
1327 if (!is_null($id)) {
1328 $link = new moodle_url('/grade/report/index.php', $linkparams);
1331 if ($path_elements[2] == 'grader') {
1332 $numberofelements = 4;
1334 break;
1336 default:
1337 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1338 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1339 " as the second path element after 'grade'.");
1340 return false;
1342 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1344 // Third level links
1345 if (empty($pagename)) {
1346 $pagename = get_string($path_elements[2], 'grades');
1349 switch ($numberofelements) {
1350 case 3:
1351 $PAGE->navbar->add($pagename, $link);
1352 break;
1353 case 4:
1354 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1355 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1357 $PAGE->navbar->add($pagename);
1358 break;
1361 return '';
1365 * General structure representing grade items in course
1367 * @package core_grades
1368 * @copyright 2009 Nicolas Connault
1369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1371 class grade_structure {
1372 public $context;
1374 public $courseid;
1377 * Reference to modinfo for current course (for performance, to save
1378 * retrieving it from courseid every time). Not actually set except for
1379 * the grade_tree type.
1380 * @var course_modinfo
1382 public $modinfo;
1385 * 1D array of grade items only
1387 public $items;
1390 * Returns icon of element
1392 * @param array &$element An array representing an element in the grade_tree
1393 * @param bool $spacerifnone return spacer if no icon found
1395 * @return string icon or spacer
1397 public function get_element_icon(&$element, $spacerifnone=false) {
1398 global $CFG, $OUTPUT;
1399 require_once $CFG->libdir.'/filelib.php';
1401 $outputstr = '';
1403 // Object holding pix_icon information before instantiation.
1404 $icon = new stdClass();
1405 $icon->attributes = array(
1406 'class' => 'icon itemicon'
1408 $icon->component = 'moodle';
1410 $none = true;
1411 switch ($element['type']) {
1412 case 'item':
1413 case 'courseitem':
1414 case 'categoryitem':
1415 $none = false;
1417 $is_course = $element['object']->is_course_item();
1418 $is_category = $element['object']->is_category_item();
1419 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1420 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1421 $is_outcome = !empty($element['object']->outcomeid);
1423 if ($element['object']->is_calculated()) {
1424 $icon->pix = 'i/calc';
1425 $icon->title = s(get_string('calculatedgrade', 'grades'));
1427 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1428 if ($category = $element['object']->get_item_category()) {
1429 $aggrstrings = grade_helper::get_aggregation_strings();
1430 $stragg = $aggrstrings[$category->aggregation];
1432 $icon->pix = 'i/calc';
1433 $icon->title = s($stragg);
1435 switch ($category->aggregation) {
1436 case GRADE_AGGREGATE_MEAN:
1437 case GRADE_AGGREGATE_MEDIAN:
1438 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1439 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1440 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1441 $icon->pix = 'i/agg_mean';
1442 break;
1443 case GRADE_AGGREGATE_SUM:
1444 $icon->pix = 'i/agg_sum';
1445 break;
1449 } else if ($element['object']->itemtype == 'mod') {
1450 // Prevent outcomes displaying the same icon as the activity they are attached to.
1451 if ($is_outcome) {
1452 $icon->pix = 'i/outcomes';
1453 $icon->title = s(get_string('outcome', 'grades'));
1454 } else {
1455 $modinfo = get_fast_modinfo($element['object']->courseid);
1456 $module = $element['object']->itemmodule;
1457 $instanceid = $element['object']->iteminstance;
1458 if (isset($modinfo->instances[$module][$instanceid])) {
1459 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
1460 } else {
1461 $icon->pix = 'monologo';
1462 $icon->component = $element['object']->itemmodule;
1464 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1466 } else if ($element['object']->itemtype == 'manual') {
1467 if ($element['object']->is_outcome_item()) {
1468 $icon->pix = 'i/outcomes';
1469 $icon->title = s(get_string('outcome', 'grades'));
1470 } else {
1471 $icon->pix = 'i/manual_item';
1472 $icon->title = s(get_string('manualitem', 'grades'));
1475 break;
1477 case 'category':
1478 $none = false;
1479 $icon->pix = 'i/folder';
1480 $icon->title = s(get_string('category', 'grades'));
1481 break;
1484 if ($none) {
1485 if ($spacerifnone) {
1486 $outputstr = $OUTPUT->spacer() . ' ';
1488 } else if (isset($icon->url)) {
1489 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
1490 } else {
1491 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1494 return $outputstr;
1498 * Returns name of element optionally with icon and link
1500 * @param array &$element An array representing an element in the grade_tree
1501 * @param bool $withlink Whether or not this header has a link
1502 * @param bool $icon Whether or not to display an icon with this header
1503 * @param bool $spacerifnone return spacer if no icon found
1504 * @param bool $withdescription Show description if defined by this item.
1505 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1506 * instead of "Category total" or "Course total"
1508 * @return string header
1510 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1511 $withdescription = false, $fulltotal = false) {
1512 $header = '';
1514 if ($icon) {
1515 $header .= $this->get_element_icon($element, $spacerifnone);
1518 $title = $element['object']->get_name($fulltotal);
1519 $titleunescaped = $element['object']->get_name($fulltotal, false);
1520 $header .= $title;
1522 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1523 $element['type'] != 'courseitem') {
1524 return $header;
1527 if ($withlink && $url = $this->get_activity_link($element)) {
1528 $a = new stdClass();
1529 $a->name = get_string('modulename', $element['object']->itemmodule);
1530 $a->title = $titleunescaped;
1531 $title = get_string('linktoactivity', 'grades', $a);
1533 $header = html_writer::link($url, $header, array('title' => $title, 'class' => 'gradeitemheader'));
1534 } else {
1535 $header = html_writer::span($header, 'gradeitemheader', array('title' => $titleunescaped, 'tabindex' => '0'));
1538 if ($withdescription) {
1539 $desc = $element['object']->get_description();
1540 if (!empty($desc)) {
1541 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1545 return $header;
1548 private function get_activity_link($element) {
1549 global $CFG;
1550 /** @var array static cache of the grade.php file existence flags */
1551 static $hasgradephp = array();
1553 $itemtype = $element['object']->itemtype;
1554 $itemmodule = $element['object']->itemmodule;
1555 $iteminstance = $element['object']->iteminstance;
1556 $itemnumber = $element['object']->itemnumber;
1558 // Links only for module items that have valid instance, module and are
1559 // called from grade_tree with valid modinfo
1560 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1561 return null;
1564 // Get $cm efficiently and with visibility information using modinfo
1565 $instances = $this->modinfo->get_instances();
1566 if (empty($instances[$itemmodule][$iteminstance])) {
1567 return null;
1569 $cm = $instances[$itemmodule][$iteminstance];
1571 // Do not add link if activity is not visible to the current user
1572 if (!$cm->uservisible) {
1573 return null;
1576 if (!array_key_exists($itemmodule, $hasgradephp)) {
1577 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1578 $hasgradephp[$itemmodule] = true;
1579 } else {
1580 $hasgradephp[$itemmodule] = false;
1584 // If module has grade.php, link to that, otherwise view.php
1585 if ($hasgradephp[$itemmodule]) {
1586 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1587 if (isset($element['userid'])) {
1588 $args['userid'] = $element['userid'];
1590 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1591 } else {
1592 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1597 * Returns URL of a page that is supposed to contain detailed grade analysis
1599 * At the moment, only activity modules are supported. The method generates link
1600 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1601 * gradeid and userid. If the grade.php does not exist, null is returned.
1603 * @return moodle_url|null URL or null if unable to construct it
1605 public function get_grade_analysis_url(grade_grade $grade) {
1606 global $CFG;
1607 /** @var array static cache of the grade.php file existence flags */
1608 static $hasgradephp = array();
1610 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1611 throw new coding_exception('Passed grade without the associated grade item');
1613 $item = $grade->grade_item;
1615 if (!$item->is_external_item()) {
1616 // at the moment, only activity modules are supported
1617 return null;
1619 if ($item->itemtype !== 'mod') {
1620 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1622 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1623 return null;
1626 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1627 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1628 $hasgradephp[$item->itemmodule] = true;
1629 } else {
1630 $hasgradephp[$item->itemmodule] = false;
1634 if (!$hasgradephp[$item->itemmodule]) {
1635 return null;
1638 $instances = $this->modinfo->get_instances();
1639 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1640 return null;
1642 $cm = $instances[$item->itemmodule][$item->iteminstance];
1643 if (!$cm->uservisible) {
1644 return null;
1647 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1648 'id' => $cm->id,
1649 'itemid' => $item->id,
1650 'itemnumber' => $item->itemnumber,
1651 'gradeid' => $grade->id,
1652 'userid' => $grade->userid,
1655 return $url;
1659 * Returns an action icon leading to the grade analysis page
1661 * @param grade_grade $grade
1662 * @return string
1664 public function get_grade_analysis_icon(grade_grade $grade) {
1665 global $OUTPUT;
1667 $url = $this->get_grade_analysis_url($grade);
1668 if (is_null($url)) {
1669 return '';
1672 $title = get_string('gradeanalysis', 'core_grades');
1673 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1674 ['title' => $title, 'aria-label' => $title]);
1678 * Returns the grade eid - the grade may not exist yet.
1680 * @param grade_grade $grade_grade A grade_grade object
1682 * @return string eid
1684 public function get_grade_eid($grade_grade) {
1685 if (empty($grade_grade->id)) {
1686 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1687 } else {
1688 return 'g'.$grade_grade->id;
1693 * Returns the grade_item eid
1694 * @param grade_item $grade_item A grade_item object
1695 * @return string eid
1697 public function get_item_eid($grade_item) {
1698 return 'ig'.$grade_item->id;
1702 * Given a grade_tree element, returns an array of parameters
1703 * used to build an icon for that element.
1705 * @param array $element An array representing an element in the grade_tree
1707 * @return array
1709 public function get_params_for_iconstr($element) {
1710 $strparams = new stdClass();
1711 $strparams->category = '';
1712 $strparams->itemname = '';
1713 $strparams->itemmodule = '';
1715 if (!method_exists($element['object'], 'get_name')) {
1716 return $strparams;
1719 $strparams->itemname = html_to_text($element['object']->get_name());
1721 // If element name is categorytotal, get the name of the parent category
1722 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1723 $parent = $element['object']->get_parent_category();
1724 $strparams->category = $parent->get_name() . ' ';
1725 } else {
1726 $strparams->category = '';
1729 $strparams->itemmodule = null;
1730 if (isset($element['object']->itemmodule)) {
1731 $strparams->itemmodule = $element['object']->itemmodule;
1733 return $strparams;
1737 * Return a reset icon for the given element.
1739 * @param array $element An array representing an element in the grade_tree
1740 * @param object $gpr A grade_plugin_return object
1741 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1742 * @return string|action_menu_link
1744 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1745 global $CFG, $OUTPUT;
1747 // Limit to category items set to use the natural weights aggregation method, and users
1748 // with the capability to manage grades.
1749 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1750 !has_capability('moodle/grade:manage', $this->context)) {
1751 return $returnactionmenulink ? null : '';
1754 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1755 $url = new moodle_url('/grade/edit/tree/action.php', array(
1756 'id' => $this->courseid,
1757 'action' => 'resetweights',
1758 'eid' => $element['eid'],
1759 'sesskey' => sesskey(),
1762 if ($returnactionmenulink) {
1763 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1764 get_string('resetweightsshort', 'grades'));
1765 } else {
1766 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1771 * Return edit icon for give element
1773 * @param array $element An array representing an element in the grade_tree
1774 * @param object $gpr A grade_plugin_return object
1775 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1776 * @return string|action_menu_link
1778 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1779 global $CFG, $OUTPUT;
1781 if (!has_capability('moodle/grade:manage', $this->context)) {
1782 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1783 // oki - let them override grade
1784 } else {
1785 return $returnactionmenulink ? null : '';
1789 static $strfeedback = null;
1790 static $streditgrade = null;
1791 if (is_null($streditgrade)) {
1792 $streditgrade = get_string('editgrade', 'grades');
1793 $strfeedback = get_string('feedback');
1796 $strparams = $this->get_params_for_iconstr($element);
1798 $object = $element['object'];
1800 switch ($element['type']) {
1801 case 'item':
1802 case 'categoryitem':
1803 case 'courseitem':
1804 $stredit = get_string('editverbose', 'grades', $strparams);
1805 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1806 $url = new moodle_url('/grade/edit/tree/item.php',
1807 array('courseid' => $this->courseid, 'id' => $object->id));
1808 } else {
1809 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1810 array('courseid' => $this->courseid, 'id' => $object->id));
1812 break;
1814 case 'category':
1815 $stredit = get_string('editverbose', 'grades', $strparams);
1816 $url = new moodle_url('/grade/edit/tree/category.php',
1817 array('courseid' => $this->courseid, 'id' => $object->id));
1818 break;
1820 case 'grade':
1821 $stredit = $streditgrade;
1822 if (empty($object->id)) {
1823 $url = new moodle_url('/grade/edit/tree/grade.php',
1824 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1825 } else {
1826 $url = new moodle_url('/grade/edit/tree/grade.php',
1827 array('courseid' => $this->courseid, 'id' => $object->id));
1829 if (!empty($object->feedback)) {
1830 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1832 break;
1834 default:
1835 $url = null;
1838 if ($url) {
1839 if ($returnactionmenulink) {
1840 return new action_menu_link_secondary($gpr->add_url_params($url),
1841 new pix_icon('t/edit', $stredit),
1842 get_string('editsettings'));
1843 } else {
1844 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1847 } else {
1848 return $returnactionmenulink ? null : '';
1853 * Return hiding icon for give element
1855 * @param array $element An array representing an element in the grade_tree
1856 * @param object $gpr A grade_plugin_return object
1857 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1858 * @return string|action_menu_link
1860 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1861 global $CFG, $OUTPUT;
1863 if (!$element['object']->can_control_visibility()) {
1864 return $returnactionmenulink ? null : '';
1867 if (!has_capability('moodle/grade:manage', $this->context) and
1868 !has_capability('moodle/grade:hide', $this->context)) {
1869 return $returnactionmenulink ? null : '';
1872 $strparams = $this->get_params_for_iconstr($element);
1873 $strshow = get_string('showverbose', 'grades', $strparams);
1874 $strhide = get_string('hideverbose', 'grades', $strparams);
1876 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1877 $url = $gpr->add_url_params($url);
1879 if ($element['object']->is_hidden()) {
1880 $type = 'show';
1881 $tooltip = $strshow;
1883 // Change the icon and add a tooltip showing the date
1884 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1885 $type = 'hiddenuntil';
1886 $tooltip = get_string('hiddenuntildate', 'grades',
1887 userdate($element['object']->get_hidden()));
1890 $url->param('action', 'show');
1892 if ($returnactionmenulink) {
1893 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1894 } else {
1895 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1898 } else {
1899 $url->param('action', 'hide');
1900 if ($returnactionmenulink) {
1901 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1902 } else {
1903 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1907 return $hideicon;
1911 * Return locking icon for given element
1913 * @param array $element An array representing an element in the grade_tree
1914 * @param object $gpr A grade_plugin_return object
1916 * @return string
1918 public function get_locking_icon($element, $gpr) {
1919 global $CFG, $OUTPUT;
1921 $strparams = $this->get_params_for_iconstr($element);
1922 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1923 $strlock = get_string('lockverbose', 'grades', $strparams);
1925 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1926 $url = $gpr->add_url_params($url);
1928 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1929 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1930 $strparamobj = new stdClass();
1931 $strparamobj->itemname = $element['object']->grade_item->itemname;
1932 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1934 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1935 array('class' => 'action-icon'));
1937 } else if ($element['object']->is_locked()) {
1938 $type = 'unlock';
1939 $tooltip = $strunlock;
1941 // Change the icon and add a tooltip showing the date
1942 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1943 $type = 'locktime';
1944 $tooltip = get_string('locktimedate', 'grades',
1945 userdate($element['object']->get_locktime()));
1948 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1949 $action = '';
1950 } else {
1951 $url->param('action', 'unlock');
1952 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1955 } else {
1956 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1957 $action = '';
1958 } else {
1959 $url->param('action', 'lock');
1960 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1964 return $action;
1968 * Return calculation icon for given element
1970 * @param array $element An array representing an element in the grade_tree
1971 * @param object $gpr A grade_plugin_return object
1972 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1973 * @return string|action_menu_link
1975 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1976 global $CFG, $OUTPUT;
1977 if (!has_capability('moodle/grade:manage', $this->context)) {
1978 return $returnactionmenulink ? null : '';
1981 $type = $element['type'];
1982 $object = $element['object'];
1984 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1985 $strparams = $this->get_params_for_iconstr($element);
1986 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1988 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1989 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1991 // show calculation icon only when calculation possible
1992 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1993 if ($object->is_calculated()) {
1994 $icon = 't/calc';
1995 } else {
1996 $icon = 't/calc_off';
1999 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2000 $url = $gpr->add_url_params($url);
2001 if ($returnactionmenulink) {
2002 return new action_menu_link_secondary($url,
2003 new pix_icon($icon, $streditcalculation),
2004 get_string('editcalculation', 'grades'));
2005 } else {
2006 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2011 return $returnactionmenulink ? null : '';
2016 * Flat structure similar to grade tree.
2018 * @uses grade_structure
2019 * @package core_grades
2020 * @copyright 2009 Nicolas Connault
2021 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2023 class grade_seq extends grade_structure {
2026 * 1D array of elements
2028 public $elements;
2031 * Constructor, retrieves and stores array of all grade_category and grade_item
2032 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2034 * @param int $courseid The course id
2035 * @param bool $category_grade_last category grade item is the last child
2036 * @param bool $nooutcomes Whether or not outcomes should be included
2038 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2039 global $USER, $CFG;
2041 $this->courseid = $courseid;
2042 $this->context = context_course::instance($courseid);
2044 // get course grade tree
2045 $top_element = grade_category::fetch_course_tree($courseid, true);
2047 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2049 foreach ($this->elements as $key=>$unused) {
2050 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2055 * Old syntax of class constructor. Deprecated in PHP7.
2057 * @deprecated since Moodle 3.1
2059 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2060 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2061 self::__construct($courseid, $category_grade_last, $nooutcomes);
2065 * Static recursive helper - makes the grade_item for category the last children
2067 * @param array &$element The seed of the recursion
2068 * @param bool $category_grade_last category grade item is the last child
2069 * @param bool $nooutcomes Whether or not outcomes should be included
2071 * @return array
2073 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2074 if (empty($element['children'])) {
2075 return array();
2077 $children = array();
2079 foreach ($element['children'] as $sortorder=>$unused) {
2080 if ($nooutcomes and $element['type'] != 'category' and
2081 $element['children'][$sortorder]['object']->is_outcome_item()) {
2082 continue;
2084 $children[] = $element['children'][$sortorder];
2086 unset($element['children']);
2088 if ($category_grade_last and count($children) > 1 and
2090 $children[0]['type'] === 'courseitem' or
2091 $children[0]['type'] === 'categoryitem'
2094 $cat_item = array_shift($children);
2095 array_push($children, $cat_item);
2098 $result = array();
2099 foreach ($children as $child) {
2100 if ($child['type'] == 'category') {
2101 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2102 } else {
2103 $child['eid'] = 'i'.$child['object']->id;
2104 $result[$child['object']->id] = $child;
2108 return $result;
2112 * Parses the array in search of a given eid and returns a element object with
2113 * information about the element it has found.
2115 * @param int $eid Gradetree Element ID
2117 * @return object element
2119 public function locate_element($eid) {
2120 // it is a grade - construct a new object
2121 if (strpos($eid, 'n') === 0) {
2122 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2123 return null;
2126 $itemid = $matches[1];
2127 $userid = $matches[2];
2129 //extra security check - the grade item must be in this tree
2130 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2131 return null;
2134 // $gradea->id may be null - means does not exist yet
2135 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2137 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2138 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2140 } else if (strpos($eid, 'g') === 0) {
2141 $id = (int) substr($eid, 1);
2142 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2143 return null;
2145 //extra security check - the grade item must be in this tree
2146 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2147 return null;
2149 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2150 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2153 // it is a category or item
2154 foreach ($this->elements as $element) {
2155 if ($element['eid'] == $eid) {
2156 return $element;
2160 return null;
2165 * This class represents a complete tree of categories, grade_items and final grades,
2166 * organises as an array primarily, but which can also be converted to other formats.
2167 * It has simple method calls with complex implementations, allowing for easy insertion,
2168 * deletion and moving of items and categories within the tree.
2170 * @uses grade_structure
2171 * @package core_grades
2172 * @copyright 2009 Nicolas Connault
2173 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2175 class grade_tree extends grade_structure {
2178 * The basic representation of the tree as a hierarchical, 3-tiered array.
2179 * @var object $top_element
2181 public $top_element;
2184 * 2D array of grade items and categories
2185 * @var array $levels
2187 public $levels;
2190 * Grade items
2191 * @var array $items
2193 public $items;
2196 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2197 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2199 * @param int $courseid The Course ID
2200 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2201 * @param bool $category_grade_last category grade item is the last child
2202 * @param array $collapsed array of collapsed categories
2203 * @param bool $nooutcomes Whether or not outcomes should be included
2205 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2206 $collapsed=null, $nooutcomes=false) {
2207 global $USER, $CFG, $COURSE, $DB;
2209 $this->courseid = $courseid;
2210 $this->levels = array();
2211 $this->context = context_course::instance($courseid);
2213 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2214 $course = $COURSE;
2215 } else {
2216 $course = $DB->get_record('course', array('id' => $this->courseid));
2218 $this->modinfo = get_fast_modinfo($course);
2220 // get course grade tree
2221 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2223 // collapse the categories if requested
2224 if (!empty($collapsed)) {
2225 grade_tree::category_collapse($this->top_element, $collapsed);
2228 // no otucomes if requested
2229 if (!empty($nooutcomes)) {
2230 grade_tree::no_outcomes($this->top_element);
2233 // move category item to last position in category
2234 if ($category_grade_last) {
2235 grade_tree::category_grade_last($this->top_element);
2238 if ($fillers) {
2239 // inject fake categories == fillers
2240 grade_tree::inject_fillers($this->top_element, 0);
2241 // add colspans to categories and fillers
2242 grade_tree::inject_colspans($this->top_element);
2245 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2250 * Old syntax of class constructor. Deprecated in PHP7.
2252 * @deprecated since Moodle 3.1
2254 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2255 $collapsed=null, $nooutcomes=false) {
2256 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2257 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2261 * Static recursive helper - removes items from collapsed categories
2263 * @param array &$element The seed of the recursion
2264 * @param array $collapsed array of collapsed categories
2266 * @return void
2268 public function category_collapse(&$element, $collapsed) {
2269 if ($element['type'] != 'category') {
2270 return;
2272 if (empty($element['children']) or count($element['children']) < 2) {
2273 return;
2276 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2277 $category_item = reset($element['children']); //keep only category item
2278 $element['children'] = array(key($element['children'])=>$category_item);
2280 } else {
2281 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2282 reset($element['children']);
2283 $first_key = key($element['children']);
2284 unset($element['children'][$first_key]);
2286 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2287 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2293 * Static recursive helper - removes all outcomes
2295 * @param array &$element The seed of the recursion
2297 * @return void
2299 public function no_outcomes(&$element) {
2300 if ($element['type'] != 'category') {
2301 return;
2303 foreach ($element['children'] as $sortorder=>$child) {
2304 if ($element['children'][$sortorder]['type'] == 'item'
2305 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2306 unset($element['children'][$sortorder]);
2308 } else if ($element['children'][$sortorder]['type'] == 'category') {
2309 grade_tree::no_outcomes($element['children'][$sortorder]);
2315 * Static recursive helper - makes the grade_item for category the last children
2317 * @param array &$element The seed of the recursion
2319 * @return void
2321 public function category_grade_last(&$element) {
2322 if (empty($element['children'])) {
2323 return;
2325 if (count($element['children']) < 2) {
2326 return;
2328 $first_item = reset($element['children']);
2329 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2330 // the category item might have been already removed
2331 $order = key($element['children']);
2332 unset($element['children'][$order]);
2333 $element['children'][$order] =& $first_item;
2335 foreach ($element['children'] as $sortorder => $child) {
2336 grade_tree::category_grade_last($element['children'][$sortorder]);
2341 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2343 * @param array &$levels The levels of the grade tree through which to recurse
2344 * @param array &$element The seed of the recursion
2345 * @param int $depth How deep are we?
2346 * @return void
2348 public function fill_levels(&$levels, &$element, $depth) {
2349 if (!array_key_exists($depth, $levels)) {
2350 $levels[$depth] = array();
2353 // prepare unique identifier
2354 if ($element['type'] == 'category') {
2355 $element['eid'] = 'cg'.$element['object']->id;
2356 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2357 $element['eid'] = 'ig'.$element['object']->id;
2358 $this->items[$element['object']->id] =& $element['object'];
2361 $levels[$depth][] =& $element;
2362 $depth++;
2363 if (empty($element['children'])) {
2364 return;
2366 $prev = 0;
2367 foreach ($element['children'] as $sortorder=>$child) {
2368 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2369 $element['children'][$sortorder]['prev'] = $prev;
2370 $element['children'][$sortorder]['next'] = 0;
2371 if ($prev) {
2372 $element['children'][$prev]['next'] = $sortorder;
2374 $prev = $sortorder;
2379 * Determines whether the grade tree item can be displayed.
2380 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2381 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2382 * can be output.
2384 * @param array $element The grade category element.
2385 * @return bool True if the grade tree item can be displayed. False, otherwise.
2387 public static function can_output_item($element) {
2388 $canoutput = true;
2390 if ($element['type'] === 'category') {
2391 $object = $element['object'];
2392 $category = grade_category::fetch(array('id' => $object->id));
2393 // Category has total, we can output this.
2394 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2395 return true;
2398 // Category has no total and has no children, no need to output this.
2399 if (empty($element['children'])) {
2400 return false;
2403 $canoutput = false;
2404 // Loop over children and make sure at least one child can be output.
2405 foreach ($element['children'] as $child) {
2406 $canoutput = self::can_output_item($child);
2407 if ($canoutput) {
2408 break;
2413 return $canoutput;
2417 * Static recursive helper - makes full tree (all leafes are at the same level)
2419 * @param array &$element The seed of the recursion
2420 * @param int $depth How deep are we?
2422 * @return int
2424 public function inject_fillers(&$element, $depth) {
2425 $depth++;
2427 if (empty($element['children'])) {
2428 return $depth;
2430 $chdepths = array();
2431 $chids = array_keys($element['children']);
2432 $last_child = end($chids);
2433 $first_child = reset($chids);
2435 foreach ($chids as $chid) {
2436 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2438 arsort($chdepths);
2440 $maxdepth = reset($chdepths);
2441 foreach ($chdepths as $chid=>$chd) {
2442 if ($chd == $maxdepth) {
2443 continue;
2445 if (!self::can_output_item($element['children'][$chid])) {
2446 continue;
2448 for ($i=0; $i < $maxdepth-$chd; $i++) {
2449 if ($chid == $first_child) {
2450 $type = 'fillerfirst';
2451 } else if ($chid == $last_child) {
2452 $type = 'fillerlast';
2453 } else {
2454 $type = 'filler';
2456 $oldchild =& $element['children'][$chid];
2457 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2458 'eid'=>'', 'depth'=>$element['object']->depth,
2459 'children'=>array($oldchild));
2463 return $maxdepth;
2467 * Static recursive helper - add colspan information into categories
2469 * @param array &$element The seed of the recursion
2471 * @return int
2473 public function inject_colspans(&$element) {
2474 if (empty($element['children'])) {
2475 return 1;
2477 $count = 0;
2478 foreach ($element['children'] as $key=>$child) {
2479 if (!self::can_output_item($child)) {
2480 continue;
2482 $count += grade_tree::inject_colspans($element['children'][$key]);
2484 $element['colspan'] = $count;
2485 return $count;
2489 * Parses the array in search of a given eid and returns a element object with
2490 * information about the element it has found.
2491 * @param int $eid Gradetree Element ID
2492 * @return object element
2494 public function locate_element($eid) {
2495 // it is a grade - construct a new object
2496 if (strpos($eid, 'n') === 0) {
2497 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2498 return null;
2501 $itemid = $matches[1];
2502 $userid = $matches[2];
2504 //extra security check - the grade item must be in this tree
2505 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2506 return null;
2509 // $gradea->id may be null - means does not exist yet
2510 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2512 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2513 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2515 } else if (strpos($eid, 'g') === 0) {
2516 $id = (int) substr($eid, 1);
2517 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2518 return null;
2520 //extra security check - the grade item must be in this tree
2521 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2522 return null;
2524 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2525 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2528 // it is a category or item
2529 foreach ($this->levels as $row) {
2530 foreach ($row as $element) {
2531 if ($element['type'] == 'filler') {
2532 continue;
2534 if ($element['eid'] == $eid) {
2535 return $element;
2540 return null;
2544 * Returns a well-formed XML representation of the grade-tree using recursion.
2546 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2547 * @param string $tabs The control character to use for tabs
2549 * @return string $xml
2551 public function exporttoxml($root=null, $tabs="\t") {
2552 $xml = null;
2553 $first = false;
2554 if (is_null($root)) {
2555 $root = $this->top_element;
2556 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2557 $xml .= "<gradetree>\n";
2558 $first = true;
2561 $type = 'undefined';
2562 if (strpos($root['object']->table, 'grade_categories') !== false) {
2563 $type = 'category';
2564 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2565 $type = 'item';
2566 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2567 $type = 'outcome';
2570 $xml .= "$tabs<element type=\"$type\">\n";
2571 foreach ($root['object'] as $var => $value) {
2572 if (!is_object($value) && !is_array($value) && !empty($value)) {
2573 $xml .= "$tabs\t<$var>$value</$var>\n";
2577 if (!empty($root['children'])) {
2578 $xml .= "$tabs\t<children>\n";
2579 foreach ($root['children'] as $sortorder => $child) {
2580 $xml .= $this->exportToXML($child, $tabs."\t\t");
2582 $xml .= "$tabs\t</children>\n";
2585 $xml .= "$tabs</element>\n";
2587 if ($first) {
2588 $xml .= "</gradetree>";
2591 return $xml;
2595 * Returns a JSON representation of the grade-tree using recursion.
2597 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2598 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2600 * @return string
2602 public function exporttojson($root=null, $tabs="\t") {
2603 $json = null;
2604 $first = false;
2605 if (is_null($root)) {
2606 $root = $this->top_element;
2607 $first = true;
2610 $name = '';
2613 if (strpos($root['object']->table, 'grade_categories') !== false) {
2614 $name = $root['object']->fullname;
2615 if ($name == '?') {
2616 $name = $root['object']->get_name();
2618 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2619 $name = $root['object']->itemname;
2620 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2621 $name = $root['object']->itemname;
2624 $json .= "$tabs {\n";
2625 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2626 $json .= "$tabs\t \"name\": \"$name\",\n";
2628 foreach ($root['object'] as $var => $value) {
2629 if (!is_object($value) && !is_array($value) && !empty($value)) {
2630 $json .= "$tabs\t \"$var\": \"$value\",\n";
2634 $json = substr($json, 0, strrpos($json, ','));
2636 if (!empty($root['children'])) {
2637 $json .= ",\n$tabs\t\"children\": [\n";
2638 foreach ($root['children'] as $sortorder => $child) {
2639 $json .= $this->exportToJSON($child, $tabs."\t\t");
2641 $json = substr($json, 0, strrpos($json, ','));
2642 $json .= "\n$tabs\t]\n";
2645 if ($first) {
2646 $json .= "\n}";
2647 } else {
2648 $json .= "\n$tabs},\n";
2651 return $json;
2655 * Returns the array of levels
2657 * @return array
2659 public function get_levels() {
2660 return $this->levels;
2664 * Returns the array of grade items
2666 * @return array
2668 public function get_items() {
2669 return $this->items;
2673 * Returns a specific Grade Item
2675 * @param int $itemid The ID of the grade_item object
2677 * @return grade_item
2679 public function get_item($itemid) {
2680 if (array_key_exists($itemid, $this->items)) {
2681 return $this->items[$itemid];
2682 } else {
2683 return false;
2689 * Local shortcut function for creating an edit/delete button for a grade_* object.
2690 * @param string $type 'edit' or 'delete'
2691 * @param int $courseid The Course ID
2692 * @param grade_* $object The grade_* object
2693 * @return string html
2695 function grade_button($type, $courseid, $object) {
2696 global $CFG, $OUTPUT;
2697 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2698 $objectidstring = $matches[1] . 'id';
2699 } else {
2700 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2703 $strdelete = get_string('delete');
2704 $stredit = get_string('edit');
2706 if ($type == 'delete') {
2707 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2708 } else if ($type == 'edit') {
2709 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2712 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2717 * This method adds settings to the settings block for the grade system and its
2718 * plugins
2720 * @global moodle_page $PAGE
2722 function grade_extend_settings($plugininfo, $courseid) {
2723 global $PAGE;
2725 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER,
2726 null, 'gradeadmin');
2728 $strings = array_shift($plugininfo);
2730 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2731 foreach ($reports as $report) {
2732 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2736 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2737 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2738 foreach ($settings as $setting) {
2739 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2743 if ($imports = grade_helper::get_plugins_import($courseid)) {
2744 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2745 foreach ($imports as $import) {
2746 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2750 if ($exports = grade_helper::get_plugins_export($courseid)) {
2751 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2752 foreach ($exports as $export) {
2753 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2757 if ($letters = grade_helper::get_info_letters($courseid)) {
2758 $letters = array_shift($letters);
2759 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2762 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2763 $outcomes = array_shift($outcomes);
2764 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2767 if ($scales = grade_helper::get_info_scales($courseid)) {
2768 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2771 if ($gradenode->contains_active_node()) {
2772 // If the gradenode is active include the settings base node (gradeadministration) in
2773 // the navbar, typcially this is ignored.
2774 $PAGE->navbar->includesettingsbase = true;
2776 // If we can get the course admin node make sure it is closed by default
2777 // as in this case the gradenode will be opened
2778 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2779 $coursenode->make_inactive();
2780 $coursenode->forceopen = false;
2786 * Grade helper class
2788 * This class provides several helpful functions that work irrespective of any
2789 * current state.
2791 * @copyright 2010 Sam Hemelryk
2792 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2794 abstract class grade_helper {
2796 * Cached manage settings info {@see get_info_settings}
2797 * @var grade_plugin_info|false
2799 protected static $managesetting = null;
2801 * Cached grade report plugins {@see get_plugins_reports}
2802 * @var array|false
2804 protected static $gradereports = null;
2806 * Cached grade report plugins preferences {@see get_info_scales}
2807 * @var array|false
2809 protected static $gradereportpreferences = null;
2811 * Cached scale info {@see get_info_scales}
2812 * @var grade_plugin_info|false
2814 protected static $scaleinfo = null;
2816 * Cached outcome info {@see get_info_outcomes}
2817 * @var grade_plugin_info|false
2819 protected static $outcomeinfo = null;
2821 * Cached leftter info {@see get_info_letters}
2822 * @var grade_plugin_info|false
2824 protected static $letterinfo = null;
2826 * Cached grade import plugins {@see get_plugins_import}
2827 * @var array|false
2829 protected static $importplugins = null;
2831 * Cached grade export plugins {@see get_plugins_export}
2832 * @var array|false
2834 protected static $exportplugins = null;
2836 * Cached grade plugin strings
2837 * @var array
2839 protected static $pluginstrings = null;
2841 * Cached grade aggregation strings
2842 * @var array
2844 protected static $aggregationstrings = null;
2847 * Gets strings commonly used by the describe plugins
2849 * report => get_string('view'),
2850 * scale => get_string('scales'),
2851 * outcome => get_string('outcomes', 'grades'),
2852 * letter => get_string('letters', 'grades'),
2853 * export => get_string('export', 'grades'),
2854 * import => get_string('import'),
2855 * settings => get_string('settings')
2857 * @return array
2859 public static function get_plugin_strings() {
2860 if (self::$pluginstrings === null) {
2861 self::$pluginstrings = array(
2862 'report' => get_string('view'),
2863 'scale' => get_string('scales'),
2864 'outcome' => get_string('outcomes', 'grades'),
2865 'letter' => get_string('letters', 'grades'),
2866 'export' => get_string('export', 'grades'),
2867 'import' => get_string('import'),
2868 'settings' => get_string('edittree', 'grades')
2871 return self::$pluginstrings;
2875 * Gets strings describing the available aggregation methods.
2877 * @return array
2879 public static function get_aggregation_strings() {
2880 if (self::$aggregationstrings === null) {
2881 self::$aggregationstrings = array(
2882 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2883 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2884 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2885 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2886 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2887 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2888 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2889 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2890 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2893 return self::$aggregationstrings;
2897 * Get grade_plugin_info object for managing settings if the user can
2899 * @param int $courseid
2900 * @return grade_plugin_info[]
2902 public static function get_info_manage_settings($courseid) {
2903 if (self::$managesetting !== null) {
2904 return self::$managesetting;
2906 $context = context_course::instance($courseid);
2907 self::$managesetting = array();
2908 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2909 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
2910 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2911 get_string('gradebooksetup', 'grades'));
2912 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2913 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2914 get_string('coursegradesettings', 'grades'));
2916 if (self::$gradereportpreferences === null) {
2917 self::get_plugins_reports($courseid);
2919 if (self::$gradereportpreferences) {
2920 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2922 return self::$managesetting;
2925 * Returns an array of plugin reports as grade_plugin_info objects
2927 * @param int $courseid
2928 * @return array
2930 public static function get_plugins_reports($courseid) {
2931 global $SITE, $CFG;
2933 if (self::$gradereports !== null) {
2934 return self::$gradereports;
2936 $context = context_course::instance($courseid);
2937 $gradereports = array();
2938 $gradepreferences = array();
2939 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2940 //some reports make no sense if we're not within a course
2941 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2942 continue;
2945 // Remove outcomes report if outcomes not enabled.
2946 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes)) {
2947 continue;
2950 // Remove ones we can't see
2951 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2952 continue;
2955 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
2956 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
2957 'moodle/grade:edit'), $context)) {
2958 continue;
2961 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2962 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2963 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2965 // Add link to preferences tab if such a page exists
2966 if (file_exists($plugindir.'/preferences.php')) {
2967 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2968 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2969 get_string('preferences', 'grades') . ': ' . $pluginstr);
2972 if (count($gradereports) == 0) {
2973 $gradereports = false;
2974 $gradepreferences = false;
2975 } else if (count($gradepreferences) == 0) {
2976 $gradepreferences = false;
2977 asort($gradereports);
2978 } else {
2979 asort($gradereports);
2980 asort($gradepreferences);
2982 self::$gradereports = $gradereports;
2983 self::$gradereportpreferences = $gradepreferences;
2984 return self::$gradereports;
2988 * Get information on scales
2989 * @param int $courseid
2990 * @return grade_plugin_info
2992 public static function get_info_scales($courseid) {
2993 if (self::$scaleinfo !== null) {
2994 return self::$scaleinfo;
2996 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2997 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2998 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2999 } else {
3000 self::$scaleinfo = false;
3002 return self::$scaleinfo;
3005 * Get information on outcomes
3006 * @param int $courseid
3007 * @return grade_plugin_info
3009 public static function get_info_outcomes($courseid) {
3010 global $CFG, $SITE;
3012 if (self::$outcomeinfo !== null) {
3013 return self::$outcomeinfo;
3015 $context = context_course::instance($courseid);
3016 $canmanage = has_capability('moodle/grade:manage', $context);
3017 $canupdate = has_capability('moodle/course:update', $context);
3018 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3019 $outcomes = array();
3020 if ($canupdate) {
3021 if ($courseid!=$SITE->id) {
3022 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3023 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3025 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3026 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3027 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3028 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3029 } else {
3030 if ($courseid!=$SITE->id) {
3031 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3032 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3035 self::$outcomeinfo = $outcomes;
3036 } else {
3037 self::$outcomeinfo = false;
3039 return self::$outcomeinfo;
3042 * Get information on letters
3043 * @param int $courseid
3044 * @return array
3046 public static function get_info_letters($courseid) {
3047 global $SITE;
3048 if (self::$letterinfo !== null) {
3049 return self::$letterinfo;
3051 $context = context_course::instance($courseid);
3052 $canmanage = has_capability('moodle/grade:manage', $context);
3053 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3054 if ($canmanage || $canmanageletters) {
3055 // Redirect to system context when report is accessed from admin settings MDL-31633
3056 if ($context->instanceid == $SITE->id) {
3057 $param = array('edit' => 1);
3058 } else {
3059 $param = array('edit' => 1,'id' => $context->id);
3061 self::$letterinfo = array(
3062 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3063 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3065 } else {
3066 self::$letterinfo = false;
3068 return self::$letterinfo;
3071 * Get information import plugins
3072 * @param int $courseid
3073 * @return array
3075 public static function get_plugins_import($courseid) {
3076 global $CFG;
3078 if (self::$importplugins !== null) {
3079 return self::$importplugins;
3081 $importplugins = array();
3082 $context = context_course::instance($courseid);
3084 if (has_capability('moodle/grade:import', $context)) {
3085 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3086 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3087 continue;
3089 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3090 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3091 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3094 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3095 // XML is the only grade import plugin that has publishing feature.
3096 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3097 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3098 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3102 if (count($importplugins) > 0) {
3103 asort($importplugins);
3104 self::$importplugins = $importplugins;
3105 } else {
3106 self::$importplugins = false;
3108 return self::$importplugins;
3111 * Get information export plugins
3112 * @param int $courseid
3113 * @return array
3115 public static function get_plugins_export($courseid) {
3116 global $CFG;
3118 if (self::$exportplugins !== null) {
3119 return self::$exportplugins;
3121 $context = context_course::instance($courseid);
3122 $exportplugins = array();
3123 $canpublishgrades = 0;
3124 if (has_capability('moodle/grade:export', $context)) {
3125 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3126 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3127 continue;
3129 // All the grade export plugins has grade publishing capabilities.
3130 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3131 $canpublishgrades++;
3134 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3135 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3136 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3139 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3140 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3141 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3142 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3145 if (count($exportplugins) > 0) {
3146 asort($exportplugins);
3147 self::$exportplugins = $exportplugins;
3148 } else {
3149 self::$exportplugins = false;
3151 return self::$exportplugins;
3155 * Returns the value of a field from a user record
3157 * @param stdClass $user object
3158 * @param stdClass $field object
3159 * @return string value of the field
3161 public static function get_user_field_value($user, $field) {
3162 if (!empty($field->customid)) {
3163 $fieldname = 'customfield_' . $field->customid;
3164 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3165 $fieldvalue = $user->{$fieldname};
3166 } else {
3167 $fieldvalue = $field->default;
3169 } else {
3170 $fieldvalue = $user->{$field->shortname};
3172 return $fieldvalue;
3176 * Returns an array of user profile fields to be included in export
3178 * @param int $courseid
3179 * @param bool $includecustomfields
3180 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3182 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3183 global $CFG, $DB;
3185 // Gets the fields that have to be hidden
3186 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3187 $context = context_course::instance($courseid);
3188 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3189 if ($canseehiddenfields) {
3190 $hiddenfields = array();
3193 $fields = array();
3194 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3195 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3196 $userdefaultfields = user_get_default_fields();
3198 // Sets the list of profile fields
3199 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3200 if (!empty($userprofilefields)) {
3201 foreach ($userprofilefields as $field) {
3202 $field = trim($field);
3203 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3204 continue;
3206 $obj = new stdClass();
3207 $obj->customid = 0;
3208 $obj->shortname = $field;
3209 $obj->fullname = get_string($field);
3210 $fields[] = $obj;
3214 // Sets the list of custom profile fields
3215 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3216 if ($includecustomfields && !empty($customprofilefields)) {
3217 $customfields = profile_get_user_fields_with_data(0);
3219 foreach ($customfields as $fieldobj) {
3220 $field = (object)$fieldobj->get_field_config_for_external();
3221 // Make sure we can display this custom field
3222 if (!in_array($field->shortname, $customprofilefields)) {
3223 continue;
3224 } else if (in_array($field->shortname, $hiddenfields)) {
3225 continue;
3226 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3227 continue;
3230 $obj = new stdClass();
3231 $obj->customid = $field->id;
3232 $obj->shortname = $field->shortname;
3233 $obj->fullname = format_string($field->name);
3234 $obj->datatype = $field->datatype;
3235 $obj->default = $field->defaultdata;
3236 $fields[] = $obj;
3240 return $fields;
3244 * This helper method gets a snapshot of all the weights for a course.
3245 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3246 * @param int $courseid
3247 * @return array of itemid -> aggregationcoef2
3249 public static function fetch_all_natural_weights_for_course($courseid) {
3250 global $DB;
3251 $result = array();
3253 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3254 foreach ($records as $record) {
3255 $result[$record->id] = $record->aggregationcoef2;
3257 return $result;
3261 * Resets all static caches.
3263 * @return void
3265 public static function reset_caches() {
3266 self::$managesetting = null;
3267 self::$gradereports = null;
3268 self::$gradereportpreferences = null;
3269 self::$scaleinfo = null;
3270 self::$outcomeinfo = null;
3271 self::$letterinfo = null;
3272 self::$importplugins = null;
3273 self::$exportplugins = null;
3274 self::$pluginstrings = null;
3275 self::$aggregationstrings = null;