Merge branch 'MDL-80633-main' of https://github.com/laurentdavid/moodle
[moodle.git] / grade / lib.php
blobe241c7ae9879c75c475f071aa30a913da58112ca
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::class)) {
774 if ($plugin_type === $active_type && $active_plugin == $plugin->id) {
775 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
781 return $plugin_info;
785 * Load a valid list of gradable users in a course.
787 * @param int $courseid The course ID.
788 * @param int|null $groupid The group ID (optional).
789 * @param bool $onlyactiveenrol Include only active enrolments.
790 * @return array $users A list of enrolled gradable users.
792 function get_gradable_users(int $courseid, ?int $groupid = null, bool $onlyactiveenrol = false): array {
793 $course = get_course($courseid);
794 // Create a graded_users_iterator because it will properly check the groups etc.
795 $gui = new graded_users_iterator($course, null, $groupid);
796 $gui->require_active_enrolment($onlyactiveenrol);
797 $gui->init();
799 // Flatten the users.
800 $users = [];
801 while ($user = $gui->next_user()) {
802 $users[$user->user->id] = $user->user;
804 $gui->close();
806 return $users;
810 * A simple class containing info about grade plugins.
811 * Can be subclassed for special rules
813 * @package core_grades
814 * @copyright 2009 Nicolas Connault
815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
817 class grade_plugin_info {
819 * A unique id for this plugin
821 * @var mixed
823 public $id;
825 * A URL to access this plugin
827 * @var mixed
829 public $link;
831 * The name of this plugin
833 * @var mixed
835 public $string;
837 * Another grade_plugin_info object, parent of the current one
839 * @var mixed
841 public $parent;
844 * Constructor
846 * @param int $id A unique id for this plugin
847 * @param string $link A URL to access this plugin
848 * @param string $string The name of this plugin
849 * @param object $parent Another grade_plugin_info object, parent of the current one
851 * @return void
853 public function __construct($id, $link, $string, $parent=null) {
854 $this->id = $id;
855 $this->link = $link;
856 $this->string = $string;
857 $this->parent = $parent;
862 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
863 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
864 * print_heading() etc.
866 * @param int $courseid Course id
867 * @param string $active_type The type of the current page (report, settings,
868 * import, export, scales, outcomes, letters)
869 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
870 * @param string|bool $heading The heading of the page.
871 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
872 * @param string|bool $buttons Additional buttons to display on the page
873 * @param boolean $shownavigation should the gradebook navigation be shown?
874 * @param string|null $headerhelpidentifier The help string identifier if required.
875 * @param string|null $headerhelpcomponent The component for the help string.
876 * @param stdClass|null $user The user object for use with the user context header.
877 * @param action_bar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
878 * to true. If $actionbar is not explicitly defined, the general action bar
879 * (\core_grades\output\general_action_bar) will be used by default.
880 * @param null $unused This parameter has been deprecated since 4.3 and should not be used anymore.
881 * @return string HTML code or nothing if $return == false
883 function print_grade_page_head(int $courseid, string $active_type, ?string $active_plugin = null, string|bool $heading = false,
884 bool $return = false, $buttons = false, bool $shownavigation = true, ?string $headerhelpidentifier = null,
885 ?string $headerhelpcomponent = null, ?stdClass $user = null, ?action_bar $actionbar = null, $unused = null) {
886 global $CFG, $OUTPUT, $PAGE, $USER;
888 if ($heading !== false) {
889 // Make sure to trim heading, including the non-breaking space character.
890 $heading = str_replace("&nbsp;", " ", $heading);
891 $heading = trim($heading);
894 if ($unused !== null) {
895 debugging('Deprecated argument passed to ' . __FUNCTION__, DEBUG_DEVELOPER);
898 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
899 require_once($CFG->dirroot . '/course/lib.php');
900 if (course_modules_pending_deletion($courseid, true)) {
901 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
902 \core\output\notification::NOTIFY_WARNING);
905 if ($active_type === 'preferences') {
906 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
907 $active_type = 'settings';
910 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
912 // Determine the string of the active plugin.
913 $stractive_type = $plugin_info['strings'][$active_type];
914 $stractiveplugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
916 if ($active_type == 'report') {
917 $PAGE->set_pagelayout('report');
918 } else {
919 $PAGE->set_pagelayout('admin');
921 $coursecontext = context_course::instance($courseid);
922 // Title will be constituted by information starting from the unique identifying information for the page.
923 if ($heading) {
924 // If heading is supplied, use this for the page title.
925 $uniquetitle = $heading;
926 } else if (in_array($active_type, ['report', 'settings'])) {
927 // For grade reports or settings pages of grade plugins, use the plugin name for the unique title.
928 $uniquetitle = $stractiveplugin;
929 // But if editing mode is turned on, check if the report plugin has an editing mode title string and use it if present.
930 if ($PAGE->user_is_editing() && $active_type === 'report') {
931 $strcomponent = "gradereport_{$active_plugin}";
932 if (get_string_manager()->string_exists('editingmode_title', $strcomponent)) {
933 $uniquetitle = get_string('editingmode_title', $strcomponent);
936 } else {
937 $uniquetitle = $stractive_type . ': ' . $stractiveplugin;
939 $titlecomponents = [
940 $uniquetitle,
941 $coursecontext->get_context_name(false),
943 $PAGE->set_title(implode(moodle_page::TITLE_SEPARATOR, $titlecomponents));
944 $PAGE->set_heading($PAGE->course->fullname);
945 $PAGE->set_secondary_active_tab('grades');
947 if ($buttons instanceof single_button) {
948 $buttons = $OUTPUT->render($buttons);
950 $PAGE->set_button($buttons);
951 if ($courseid != SITEID) {
952 grade_extend_settings($plugin_info, $courseid);
955 // Set the current report as active in the breadcrumbs.
956 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
957 $reportnav->make_active();
960 $returnval = $OUTPUT->header();
962 if (!$return) {
963 echo $returnval;
966 if ($shownavigation) {
967 $renderer = $PAGE->get_renderer('core_grades');
968 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
969 if (!$actionbar) {
970 $actionbar = new general_action_bar($PAGE->context, $PAGE->url, $active_type, $active_plugin);
973 if ($return) {
974 $returnval .= $renderer->render_action_bar($actionbar);
975 } else {
976 echo $renderer->render_action_bar($actionbar);
980 $output = '';
981 // Add a help dialogue box if provided.
982 if (isset($headerhelpidentifier) && !empty($heading)) {
983 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
984 } else if (isset($user)) {
985 $renderer = $PAGE->get_renderer('core_grades');
986 // If the user is viewing their own grade report, no need to show the "Message"
987 // and "Add to contact" buttons in the user heading.
988 $showuserbuttons = $user->id != $USER->id && !empty($CFG->messaging) &&
989 has_capability('moodle/site:sendmessage', $PAGE->context);
990 $output = $renderer->user_heading($user, $courseid, $showuserbuttons);
991 } else if (!empty($heading)) {
992 $output = $OUTPUT->heading($heading);
995 if ($return) {
996 $returnval .= $output;
997 } else {
998 echo $output;
1001 $returnval .= print_natural_aggregation_upgrade_notice($courseid, $coursecontext, $PAGE->url, $return);
1003 if ($return) {
1004 return $returnval;
1009 * Utility class used for return tracking when using edit and other forms in grade plugins
1011 * @package core_grades
1012 * @copyright 2009 Nicolas Connault
1013 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1015 class grade_plugin_return {
1017 * Type of grade plugin (e.g. 'edit', 'report')
1019 * @var string
1021 public $type;
1023 * Name of grade plugin (e.g. 'grader', 'overview')
1025 * @var string
1027 public $plugin;
1029 * Course id being viewed
1031 * @var int
1033 public $courseid;
1035 * Id of user whose information is being viewed/edited
1037 * @var int
1039 public $userid;
1041 * Id of group for which information is being viewed/edited
1043 * @var int
1045 public $groupid;
1047 * Current page # within output
1049 * @var int
1051 public $page;
1053 * Search string
1055 * @var string
1057 public $search;
1060 * Constructor
1062 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1064 public function __construct($params = []) {
1065 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1066 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1067 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1068 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1069 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1070 $this->page = optional_param('gpr_page', null, PARAM_INT);
1071 $this->search = optional_param('gpr_search', '', PARAM_NOTAGS);
1073 foreach ($params as $key => $value) {
1074 if (property_exists($this, $key)) {
1075 $this->$key = $value;
1078 // Allow course object rather than id to be used to specify course
1079 // - avoid unnecessary use of get_course.
1080 if (array_key_exists('course', $params)) {
1081 $course = $params['course'];
1082 $this->courseid = $course->id;
1083 } else {
1084 $course = null;
1086 // If group has been explicitly set in constructor parameters,
1087 // we should respect that.
1088 if (!array_key_exists('groupid', $params)) {
1089 // Otherwise, 'group' in request parameters is a request for a change.
1090 // In that case, or if we have no group at all, we should get groupid from
1091 // groups_get_course_group, which will do some housekeeping as well as
1092 // give us the correct value.
1093 $changegroup = optional_param('group', -1, PARAM_INT);
1094 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1095 if ($course === null) {
1096 $course = get_course($this->courseid);
1098 $this->groupid = groups_get_course_group($course, true);
1104 * Old syntax of class constructor. Deprecated in PHP7.
1106 * @deprecated since Moodle 3.1
1108 public function grade_plugin_return($params = null) {
1109 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1110 self::__construct($params);
1114 * Returns return parameters as options array suitable for buttons.
1115 * @return array options
1117 public function get_options() {
1118 if (empty($this->type)) {
1119 return array();
1122 $params = array();
1124 if (!empty($this->plugin)) {
1125 $params['plugin'] = $this->plugin;
1128 if (!empty($this->courseid)) {
1129 $params['id'] = $this->courseid;
1132 if (!empty($this->userid)) {
1133 $params['userid'] = $this->userid;
1136 if (!empty($this->groupid)) {
1137 $params['group'] = $this->groupid;
1140 if (!empty($this->page)) {
1141 $params['page'] = $this->page;
1144 return $params;
1148 * Returns return url
1150 * @param string $default default url when params not set
1151 * @param array $extras Extra URL parameters
1153 * @return string url
1155 public function get_return_url($default, $extras=null) {
1156 global $CFG;
1158 if (empty($this->type) or empty($this->plugin)) {
1159 return $default;
1162 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1163 $glue = '?';
1165 if (!empty($this->courseid)) {
1166 $url .= $glue.'id='.$this->courseid;
1167 $glue = '&amp;';
1170 if (!empty($this->userid)) {
1171 $url .= $glue.'userid='.$this->userid;
1172 $glue = '&amp;';
1175 if (!empty($this->groupid)) {
1176 $url .= $glue.'group='.$this->groupid;
1177 $glue = '&amp;';
1180 if (!empty($this->page)) {
1181 $url .= $glue.'page='.$this->page;
1182 $glue = '&amp;';
1185 if (!empty($extras)) {
1186 foreach ($extras as $key=>$value) {
1187 $url .= $glue.$key.'='.$value;
1188 $glue = '&amp;';
1192 return $url;
1196 * Returns string with hidden return tracking form elements.
1197 * @return string
1199 public function get_form_fields() {
1200 if (empty($this->type)) {
1201 return '';
1204 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1206 if (!empty($this->plugin)) {
1207 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1210 if (!empty($this->courseid)) {
1211 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1214 if (!empty($this->userid)) {
1215 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1218 if (!empty($this->groupid)) {
1219 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1222 if (!empty($this->page)) {
1223 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1226 if (!empty($this->search)) {
1227 $result .= html_writer::empty_tag('input',
1228 ['type' => 'hidden', 'name' => 'gpr_search', 'value' => $this->search]);
1231 return $result;
1235 * Add hidden elements into mform
1237 * @param object &$mform moodle form object
1239 * @return void
1241 public function add_mform_elements(&$mform) {
1242 if (empty($this->type)) {
1243 return;
1246 $mform->addElement('hidden', 'gpr_type', $this->type);
1247 $mform->setType('gpr_type', PARAM_SAFEDIR);
1249 if (!empty($this->plugin)) {
1250 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1251 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1254 if (!empty($this->courseid)) {
1255 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1256 $mform->setType('gpr_courseid', PARAM_INT);
1259 if (!empty($this->userid)) {
1260 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1261 $mform->setType('gpr_userid', PARAM_INT);
1264 if (!empty($this->groupid)) {
1265 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1266 $mform->setType('gpr_groupid', PARAM_INT);
1269 if (!empty($this->page)) {
1270 $mform->addElement('hidden', 'gpr_page', $this->page);
1271 $mform->setType('gpr_page', PARAM_INT);
1276 * Add return tracking params into url
1278 * @param moodle_url $url A URL
1279 * @return moodle_url with return tracking params
1281 public function add_url_params(moodle_url $url): moodle_url {
1282 if (empty($this->type)) {
1283 return $url;
1286 $url->param('gpr_type', $this->type);
1288 if (!empty($this->plugin)) {
1289 $url->param('gpr_plugin', $this->plugin);
1292 if (!empty($this->courseid)) {
1293 $url->param('gpr_courseid' ,$this->courseid);
1296 if (!empty($this->userid)) {
1297 $url->param('gpr_userid', $this->userid);
1300 if (!empty($this->groupid)) {
1301 $url->param('gpr_groupid', $this->groupid);
1304 if (!empty($this->page)) {
1305 $url->param('gpr_page', $this->page);
1308 return $url;
1313 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1315 * @param string $path The path of the calling script (using __FILE__?)
1316 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1317 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1318 * an array of keys and values (e.g courseid => $courseid, itemid...)
1320 * @return string
1322 function grade_build_nav($path, $pagename=null, $id=null) {
1323 global $CFG, $COURSE, $PAGE;
1325 $strgrades = get_string('grades', 'grades');
1327 // Parse the path and build navlinks from its elements
1328 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1329 $path = substr($path, $dirroot_length);
1330 $path = str_replace('\\', '/', $path);
1332 $path_elements = explode('/', $path);
1334 $path_elements_count = count($path_elements);
1336 // First link is always 'grade'
1337 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1339 $link = null;
1340 $numberofelements = 3;
1342 // Prepare URL params string
1343 $linkparams = array();
1344 if (!is_null($id)) {
1345 if (is_array($id)) {
1346 foreach ($id as $idkey => $idvalue) {
1347 $linkparams[$idkey] = $idvalue;
1349 } else {
1350 $linkparams['id'] = $id;
1354 $navlink4 = null;
1356 // Remove file extensions from filenames
1357 foreach ($path_elements as $key => $filename) {
1358 $path_elements[$key] = str_replace('.php', '', $filename);
1361 // Second level links
1362 switch ($path_elements[1]) {
1363 case 'edit': // No link
1364 if ($path_elements[3] != 'index.php') {
1365 $numberofelements = 4;
1367 break;
1368 case 'import': // No link
1369 break;
1370 case 'export': // No link
1371 break;
1372 case 'report':
1373 // $id is required for this link. Do not print it if $id isn't given
1374 if (!is_null($id)) {
1375 $link = new moodle_url('/grade/report/index.php', $linkparams);
1378 if ($path_elements[2] == 'grader') {
1379 $numberofelements = 4;
1381 break;
1383 default:
1384 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1385 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1386 " as the second path element after 'grade'.");
1387 return false;
1389 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1391 // Third level links
1392 if (empty($pagename)) {
1393 $pagename = get_string($path_elements[2], 'grades');
1396 switch ($numberofelements) {
1397 case 3:
1398 $PAGE->navbar->add($pagename, $link);
1399 break;
1400 case 4:
1401 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1402 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1404 $PAGE->navbar->add($pagename);
1405 break;
1408 return '';
1412 * General structure representing grade items in course
1414 * @package core_grades
1415 * @copyright 2009 Nicolas Connault
1416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1418 class grade_structure {
1419 public $context;
1421 public $courseid;
1424 * Reference to modinfo for current course (for performance, to save
1425 * retrieving it from courseid every time). Not actually set except for
1426 * the grade_tree type.
1427 * @var course_modinfo
1429 public $modinfo;
1432 * 1D array of grade items only
1434 public $items;
1437 * Returns icon of element
1439 * @param array &$element An array representing an element in the grade_tree
1440 * @param bool $spacerifnone return spacer if no icon found
1442 * @return string icon or spacer
1443 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_icon()}
1444 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1446 public function get_element_icon(&$element, $spacerifnone=false) {
1447 debugging('The function get_element_icon() is deprecated, please use grade_helper::get_element_icon() instead.',
1448 DEBUG_DEVELOPER);
1449 return grade_helper::get_element_icon($element, $spacerifnone);
1453 * Returns the string that describes the type of the element.
1455 * @param array $element An array representing an element in the grade_tree
1456 * @return string The string that describes the type of the grade element
1457 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_type_string()}
1458 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1460 public function get_element_type_string(array $element): string {
1461 debugging('The function get_element_type_string() is deprecated,' .
1462 ' please use grade_helper::get_element_type_string() instead.',
1463 DEBUG_DEVELOPER);
1464 return grade_helper::get_element_type_string($element);
1468 * Returns name of element optionally with icon and link
1470 * @param array &$element An array representing an element in the grade_tree
1471 * @param bool $withlink Whether or not this header has a link
1472 * @param bool $icon Whether or not to display an icon with this header
1473 * @param bool $spacerifnone return spacer if no icon found
1474 * @param bool $withdescription Show description if defined by this item.
1475 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1476 * instead of "Category total" or "Course total"
1477 * @param moodle_url|null $sortlink Link to sort column.
1479 * @return string header
1480 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_header()}
1481 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1483 public function get_element_header(array &$element, bool $withlink = false, bool $icon = true,
1484 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
1485 ?moodle_url $sortlink = null) {
1486 debugging('The function get_element_header() is deprecated, please use grade_helper::get_element_header() instead.',
1487 DEBUG_DEVELOPER);
1488 return grade_helper::get_element_header($element, $withlink, $icon, $spacerifnone, $withdescription,
1489 $fulltotal, $sortlink);
1493 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_activity_link()}
1494 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1496 private function get_activity_link($element) {
1497 debugging('The function get_activity_link() is deprecated, please use grade_helper::get_activity_link() instead.',
1498 DEBUG_DEVELOPER);
1499 return grade_helper::get_activity_link($element);
1503 * Returns URL of a page that is supposed to contain detailed grade analysis
1505 * At the moment, only activity modules are supported. The method generates link
1506 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1507 * gradeid and userid. If the grade.php does not exist, null is returned.
1509 * @return moodle_url|null URL or null if unable to construct it
1511 public function get_grade_analysis_url(grade_grade $grade) {
1512 global $CFG;
1513 /** @var array static cache of the grade.php file existence flags */
1514 static $hasgradephp = array();
1516 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1517 throw new coding_exception('Passed grade without the associated grade item');
1519 $item = $grade->grade_item;
1521 if (!$item->is_external_item()) {
1522 // at the moment, only activity modules are supported
1523 return null;
1525 if ($item->itemtype !== 'mod') {
1526 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1528 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1529 return null;
1532 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1533 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1534 $hasgradephp[$item->itemmodule] = true;
1535 } else {
1536 $hasgradephp[$item->itemmodule] = false;
1540 if (!$hasgradephp[$item->itemmodule]) {
1541 return null;
1544 $instances = $this->modinfo->get_instances();
1545 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1546 return null;
1548 $cm = $instances[$item->itemmodule][$item->iteminstance];
1549 if (!$cm->uservisible) {
1550 return null;
1553 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1554 'id' => $cm->id,
1555 'itemid' => $item->id,
1556 'itemnumber' => $item->itemnumber,
1557 'gradeid' => $grade->id,
1558 'userid' => $grade->userid,
1561 return $url;
1565 * Returns an action icon leading to the grade analysis page
1567 * @param grade_grade $grade
1568 * @return string
1569 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1570 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1572 public function get_grade_analysis_icon(grade_grade $grade) {
1573 global $OUTPUT;
1574 debugging('The function get_grade_analysis_icon() is deprecated, please do not use it anymore.',
1575 DEBUG_DEVELOPER);
1577 $url = $this->get_grade_analysis_url($grade);
1578 if (is_null($url)) {
1579 return '';
1582 $title = get_string('gradeanalysis', 'core_grades');
1583 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1584 ['title' => $title, 'aria-label' => $title]);
1588 * Returns a link leading to the grade analysis page
1590 * @param grade_grade $grade
1591 * @return string|null
1593 public function get_grade_analysis_link(grade_grade $grade): ?string {
1594 $url = $this->get_grade_analysis_url($grade);
1595 if (is_null($url)) {
1596 return null;
1599 $gradeanalysisstring = get_string('gradeanalysis', 'grades');
1600 return html_writer::link($url, $gradeanalysisstring,
1601 ['class' => 'dropdown-item', 'aria-label' => $gradeanalysisstring, 'role' => 'menuitem']);
1605 * Returns an action menu for the grade.
1607 * @param grade_grade $grade A grade_grade object
1608 * @return string
1610 public function get_grade_action_menu(grade_grade $grade): string {
1611 global $OUTPUT;
1613 $menuitems = [];
1615 $url = $this->get_grade_analysis_url($grade);
1616 if ($url) {
1617 $title = get_string('gradeanalysis', 'core_grades');
1618 $menuitems[] = new action_menu_link_secondary($url, null, $title);
1621 if ($menuitems) {
1622 $menu = new action_menu($menuitems);
1623 $icon = $OUTPUT->pix_icon('i/moremenu', get_string('actions'));
1624 $extraclasses = 'btn btn-link btn-icon icon-size-3 d-flex align-items-center justify-content-center no-caret';
1625 $menu->set_menu_trigger($icon, $extraclasses);
1626 $menu->set_menu_left();
1628 return $OUTPUT->render($menu);
1629 } else {
1630 return '';
1635 * Returns the grade eid - the grade may not exist yet.
1637 * @param grade_grade $grade_grade A grade_grade object
1639 * @return string eid
1641 public function get_grade_eid($grade_grade) {
1642 if (empty($grade_grade->id)) {
1643 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1644 } else {
1645 return 'g'.$grade_grade->id;
1650 * Returns the grade_item eid
1651 * @param grade_item $grade_item A grade_item object
1652 * @return string eid
1654 public function get_item_eid($grade_item) {
1655 return 'ig'.$grade_item->id;
1659 * Given a grade_tree element, returns an array of parameters
1660 * used to build an icon for that element.
1662 * @param array $element An array representing an element in the grade_tree
1664 * @return array
1666 public function get_params_for_iconstr($element) {
1667 $strparams = new stdClass();
1668 $strparams->category = '';
1669 $strparams->itemname = '';
1670 $strparams->itemmodule = '';
1672 if (!method_exists($element['object'], 'get_name')) {
1673 return $strparams;
1676 $strparams->itemname = html_to_text($element['object']->get_name());
1678 // If element name is categorytotal, get the name of the parent category
1679 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1680 $parent = $element['object']->get_parent_category();
1681 $strparams->category = $parent->get_name() . ' ';
1682 } else {
1683 $strparams->category = '';
1686 $strparams->itemmodule = null;
1687 if (isset($element['object']->itemmodule)) {
1688 $strparams->itemmodule = $element['object']->itemmodule;
1690 return $strparams;
1694 * Return a reset icon for the given element.
1696 * @param array $element An array representing an element in the grade_tree
1697 * @param object $gpr A grade_plugin_return object
1698 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1699 * @return string|action_menu_link
1700 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1701 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1703 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1704 global $CFG, $OUTPUT;
1705 debugging('The function get_reset_icon() is deprecated, please do not use it anymore.',
1706 DEBUG_DEVELOPER);
1708 // Limit to category items set to use the natural weights aggregation method, and users
1709 // with the capability to manage grades.
1710 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1711 !has_capability('moodle/grade:manage', $this->context)) {
1712 return $returnactionmenulink ? null : '';
1715 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1716 $url = new moodle_url('/grade/edit/tree/action.php', array(
1717 'id' => $this->courseid,
1718 'action' => 'resetweights',
1719 'eid' => $element['eid'],
1720 'sesskey' => sesskey(),
1723 if ($returnactionmenulink) {
1724 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1725 get_string('resetweightsshort', 'grades'));
1726 } else {
1727 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1732 * Returns a link to reset weights for the given element.
1734 * @param array $element An array representing an element in the grade_tree
1735 * @param object $gpr A grade_plugin_return object
1736 * @return string|null
1738 public function get_reset_weights_link(array $element, object $gpr): ?string {
1740 // Limit to category items set to use the natural weights aggregation method, and users
1741 // with the capability to manage grades.
1742 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1743 !has_capability('moodle/grade:manage', $this->context)) {
1744 return null;
1747 $title = get_string('resetweightsshort', 'grades');
1748 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1749 $url = new moodle_url('/grade/edit/tree/action.php', [
1750 'id' => $this->courseid,
1751 'action' => 'resetweights',
1752 'eid' => $element['eid'],
1753 'sesskey' => sesskey(),
1755 $gpr->add_url_params($url);
1756 return html_writer::link($url, $title,
1757 ['class' => 'dropdown-item', 'aria-label' => $str, 'role' => 'menuitem']);
1761 * Returns a link to delete a given element.
1763 * @param array $element An array representing an element in the grade_tree
1764 * @param object $gpr A grade_plugin_return object
1765 * @return string|null
1767 public function get_delete_link(array $element, object $gpr): ?string {
1768 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1769 if (grade_edit_tree::element_deletable($element)) {
1770 $deleteconfirmationurl = new moodle_url('index.php', [
1771 'id' => $this->courseid,
1772 'action' => 'delete',
1773 'confirm' => 1,
1774 'eid' => $element['eid'],
1775 'sesskey' => sesskey(),
1777 $gpr->add_url_params($deleteconfirmationurl);
1778 $title = get_string('delete');
1779 return html_writer::link(
1781 $title,
1783 'class' => 'dropdown-item',
1784 'aria-label' => $title,
1785 'role' => 'menuitem',
1786 'data-modal' => 'confirmation',
1787 'data-modal-title-str' => json_encode(['confirm', 'core']),
1788 'data-modal-content-str' => json_encode([
1789 'deletecheck',
1791 $element['object']->get_name()
1793 'data-modal-yes-button-str' => json_encode(['delete', 'core']),
1794 'data-modal-destination' => $deleteconfirmationurl->out(false),
1799 return null;
1803 * Returns a link to duplicate a given element.
1805 * @param array $element An array representing an element in the grade_tree
1806 * @param object $gpr A grade_plugin_return object
1807 * @return string|null
1809 public function get_duplicate_link(array $element, object $gpr): ?string {
1810 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1811 if (grade_edit_tree::element_duplicatable($element)) {
1812 $duplicateparams = [];
1813 $duplicateparams['id'] = $this->courseid;
1814 $duplicateparams['action'] = 'duplicate';
1815 $duplicateparams['eid'] = $element['eid'];
1816 $duplicateparams['sesskey'] = sesskey();
1817 $url = new moodle_url('index.php', $duplicateparams);
1818 $title = get_string('duplicate');
1819 $gpr->add_url_params($url);
1820 return html_writer::link($url, $title,
1821 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1824 return null;
1828 * Return edit icon for give element
1830 * @param array $element An array representing an element in the grade_tree
1831 * @param object $gpr A grade_plugin_return object
1832 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1833 * @return string|action_menu_link
1834 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1835 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1837 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1838 global $CFG, $OUTPUT;
1840 debugging('The function get_edit_icon() is deprecated, please do not use it anymore.',
1841 DEBUG_DEVELOPER);
1843 if (!has_capability('moodle/grade:manage', $this->context)) {
1844 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1845 // oki - let them override grade
1846 } else {
1847 return $returnactionmenulink ? null : '';
1851 static $strfeedback = null;
1852 static $streditgrade = null;
1853 if (is_null($streditgrade)) {
1854 $streditgrade = get_string('editgrade', 'grades');
1855 $strfeedback = get_string('feedback');
1858 $strparams = $this->get_params_for_iconstr($element);
1860 $object = $element['object'];
1862 switch ($element['type']) {
1863 case 'item':
1864 case 'categoryitem':
1865 case 'courseitem':
1866 $stredit = get_string('editverbose', 'grades', $strparams);
1867 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1868 $url = new moodle_url('/grade/edit/tree/item.php',
1869 array('courseid' => $this->courseid, 'id' => $object->id));
1870 } else {
1871 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1872 array('courseid' => $this->courseid, 'id' => $object->id));
1874 break;
1876 case 'category':
1877 $stredit = get_string('editverbose', 'grades', $strparams);
1878 $url = new moodle_url('/grade/edit/tree/category.php',
1879 array('courseid' => $this->courseid, 'id' => $object->id));
1880 break;
1882 case 'grade':
1883 $stredit = $streditgrade;
1884 if (empty($object->id)) {
1885 $url = new moodle_url('/grade/edit/tree/grade.php',
1886 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1887 } else {
1888 $url = new moodle_url('/grade/edit/tree/grade.php',
1889 array('courseid' => $this->courseid, 'id' => $object->id));
1891 if (!empty($object->feedback)) {
1892 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1894 break;
1896 default:
1897 $url = null;
1900 if ($url) {
1901 if ($returnactionmenulink) {
1902 return new action_menu_link_secondary($gpr->add_url_params($url),
1903 new pix_icon('t/edit', $stredit),
1904 get_string('editsettings'));
1905 } else {
1906 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1909 } else {
1910 return $returnactionmenulink ? null : '';
1915 * Returns a link leading to the edit grade/grade item/category page
1917 * @param array $element An array representing an element in the grade_tree
1918 * @param object $gpr A grade_plugin_return object
1919 * @return string|null
1921 public function get_edit_link(array $element, object $gpr): ?string {
1922 global $CFG;
1924 $url = null;
1925 $title = '';
1926 if ((!has_capability('moodle/grade:manage', $this->context) &&
1927 (!($element['type'] == 'grade') || !has_capability('moodle/grade:edit', $this->context)))) {
1928 return null;
1931 $object = $element['object'];
1933 if ($element['type'] == 'grade') {
1934 if (empty($object->id)) {
1935 $url = new moodle_url('/grade/edit/tree/grade.php',
1936 ['courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid]);
1937 } else {
1938 $url = new moodle_url('/grade/edit/tree/grade.php',
1939 ['courseid' => $this->courseid, 'id' => $object->id]);
1941 $url = $gpr->add_url_params($url);
1942 $title = get_string('editgrade', 'grades');
1943 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
1944 ($element['type'] == 'courseitem')) {
1945 $url = new moodle_url('#');
1946 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1947 return html_writer::link($url, get_string('itemsedit', 'grades'), [
1948 'class' => 'dropdown-item',
1949 'aria-label' => get_string('itemsedit', 'grades'),
1950 'role' => 'menuitem',
1951 'data-gprplugin' => $gpr->plugin,
1952 'data-courseid' => $this->courseid,
1953 'data-itemid' => $object->id, 'data-trigger' => 'add-item-form'
1955 } else if (count(grade_outcome::fetch_all_available($this->courseid)) > 0) {
1956 return html_writer::link($url, get_string('itemsedit', 'grades'), [
1957 'class' => 'dropdown-item',
1958 get_string('itemsedit', 'grades'),
1959 'role' => 'menuitem',
1960 'data-gprplugin' => $gpr->plugin,
1961 'data-courseid' => $this->courseid,
1962 'data-itemid' => $object->id, 'data-trigger' => 'add-outcome-form'
1965 } else if ($element['type'] == 'category') {
1966 $url = new moodle_url('#');
1967 $title = get_string('categoryedit', 'grades');
1968 return html_writer::link($url, $title, [
1969 'class' => 'dropdown-item',
1970 'aria-label' => $title,
1971 'role' => 'menuitem',
1972 'data-gprplugin' => $gpr->plugin,
1973 'data-courseid' => $this->courseid,
1974 'data-category' => $object->id,
1975 'data-trigger' => 'add-category-form'
1978 return html_writer::link($url, $title,
1979 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1983 * Returns link to the advanced grading page
1985 * @param array $element An array representing an element in the grade_tree
1986 * @param object $gpr A grade_plugin_return object
1987 * @return string|null
1989 public function get_advanced_grading_link(array $element, object $gpr): ?string {
1990 global $CFG;
1992 /** @var array static cache of the grade.php file existence flags */
1993 static $hasgradephp = [];
1995 $itemtype = $element['object']->itemtype;
1996 $itemmodule = $element['object']->itemmodule;
1997 $iteminstance = $element['object']->iteminstance;
1998 $itemnumber = $element['object']->itemnumber;
2000 // Links only for module items that have valid instance, module and are
2001 // called from grade_tree with valid modinfo.
2002 if ($itemtype == 'mod' && $iteminstance && $itemmodule && $this->modinfo) {
2004 // Get $cm efficiently and with visibility information using modinfo.
2005 $instances = $this->modinfo->get_instances();
2006 if (!empty($instances[$itemmodule][$iteminstance])) {
2007 $cm = $instances[$itemmodule][$iteminstance];
2009 // Do not add link if activity is not visible to the current user.
2010 if ($cm->uservisible) {
2011 if (!array_key_exists($itemmodule, $hasgradephp)) {
2012 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
2013 $hasgradephp[$itemmodule] = true;
2014 } else {
2015 $hasgradephp[$itemmodule] = false;
2019 // If module has grade.php, add link to that.
2020 if ($hasgradephp[$itemmodule]) {
2021 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
2022 if (isset($element['userid'])) {
2023 $args['userid'] = $element['userid'];
2026 $url = new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
2027 $title = get_string('advancedgrading', 'gradereport_grader',
2028 get_string('pluginname', "mod_{$itemmodule}"));
2029 $gpr->add_url_params($url);
2030 return html_writer::link($url, $title,
2031 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2037 return null;
2041 * Return hiding icon for give element
2043 * @param array $element An array representing an element in the grade_tree
2044 * @param object $gpr A grade_plugin_return object
2045 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2046 * @return string|action_menu_link
2047 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2048 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2050 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
2051 global $CFG, $OUTPUT;
2052 debugging('The function get_hiding_icon() is deprecated, please do not use it anymore.',
2053 DEBUG_DEVELOPER);
2055 if (!$element['object']->can_control_visibility()) {
2056 return $returnactionmenulink ? null : '';
2059 if (!has_capability('moodle/grade:manage', $this->context) and
2060 !has_capability('moodle/grade:hide', $this->context)) {
2061 return $returnactionmenulink ? null : '';
2064 $strparams = $this->get_params_for_iconstr($element);
2065 $strshow = get_string('showverbose', 'grades', $strparams);
2066 $strhide = get_string('hideverbose', 'grades', $strparams);
2068 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2069 $url = $gpr->add_url_params($url);
2071 if ($element['object']->is_hidden()) {
2072 $type = 'show';
2073 $tooltip = $strshow;
2075 // Change the icon and add a tooltip showing the date
2076 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2077 $type = 'hiddenuntil';
2078 $tooltip = get_string('hiddenuntildate', 'grades',
2079 userdate($element['object']->get_hidden()));
2082 $url->param('action', 'show');
2084 if ($returnactionmenulink) {
2085 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2086 } else {
2087 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2090 } else {
2091 $url->param('action', 'hide');
2092 if ($returnactionmenulink) {
2093 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2094 } else {
2095 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2099 return $hideicon;
2103 * Returns a link with url to hide/unhide grade/grade item/grade category
2105 * @param array $element An array representing an element in the grade_tree
2106 * @param object $gpr A grade_plugin_return object
2107 * @return string|null
2109 public function get_hiding_link(array $element, object $gpr): ?string {
2110 if (!$element['object']->can_control_visibility() || !has_capability('moodle/grade:manage', $this->context) ||
2111 !has_capability('moodle/grade:hide', $this->context)) {
2112 return null;
2115 $url = new moodle_url('/grade/edit/tree/action.php',
2116 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2117 $url = $gpr->add_url_params($url);
2119 if ($element['object']->is_hidden()) {
2120 $url->param('action', 'show');
2121 $title = get_string('show');
2122 } else {
2123 $url->param('action', 'hide');
2124 $title = get_string('hide');
2127 $url = html_writer::link($url, $title,
2128 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2130 if ($element['type'] == 'grade') {
2131 $item = $element['object']->grade_item;
2132 if ($item->hidden) {
2133 $strparamobj = new stdClass();
2134 $strparamobj->itemname = $item->get_name(true, true);
2135 $strnonunhideable = get_string('nonunhideableverbose', 'grades', $strparamobj);
2136 $url = html_writer::span($title, 'text-muted dropdown-item',
2137 ['title' => $strnonunhideable, 'aria-label' => $title, 'role' => 'menuitem']);
2141 return $url;
2145 * Return locking icon for given element
2147 * @param array $element An array representing an element in the grade_tree
2148 * @param object $gpr A grade_plugin_return object
2150 * @return string
2151 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2152 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2154 public function get_locking_icon($element, $gpr) {
2155 global $CFG, $OUTPUT;
2156 debugging('The function get_locking_icon() is deprecated, please do not use it anymore.',
2157 DEBUG_DEVELOPER);
2159 $strparams = $this->get_params_for_iconstr($element);
2160 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2161 $strlock = get_string('lockverbose', 'grades', $strparams);
2163 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2164 $url = $gpr->add_url_params($url);
2166 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2167 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
2168 $strparamobj = new stdClass();
2169 $strparamobj->itemname = $element['object']->grade_item->itemname;
2170 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2172 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2173 array('class' => 'action-icon'));
2175 } else if ($element['object']->is_locked()) {
2176 $type = 'unlock';
2177 $tooltip = $strunlock;
2179 // Change the icon and add a tooltip showing the date
2180 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2181 $type = 'locktime';
2182 $tooltip = get_string('locktimedate', 'grades',
2183 userdate($element['object']->get_locktime()));
2186 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
2187 $action = '';
2188 } else {
2189 $url->param('action', 'unlock');
2190 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2193 } else {
2194 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
2195 $action = '';
2196 } else {
2197 $url->param('action', 'lock');
2198 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2202 return $action;
2206 * Returns link to lock/unlock grade/grade item/grade category
2208 * @param array $element An array representing an element in the grade_tree
2209 * @param object $gpr A grade_plugin_return object
2211 * @return string|null
2213 public function get_locking_link(array $element, object $gpr): ?string {
2215 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2216 $title = '';
2217 $url = new moodle_url('/grade/edit/tree/action.php',
2218 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2219 $url = $gpr->add_url_params($url);
2221 if ($element['type'] == 'category') {
2222 // Grade categories themselves cannot be locked. We lock/unlock their grade items.
2223 $children = $element['object']->get_children(true);
2224 $alllocked = true;
2225 foreach ($children as $child) {
2226 if (!$child['object']->is_locked()) {
2227 $alllocked = false;
2228 break;
2231 if ($alllocked && has_capability('moodle/grade:unlock', $this->context)) {
2232 $title = get_string('unlock', 'grades');
2233 $url->param('action', 'unlock');
2234 } else if (!$alllocked && has_capability('moodle/grade:lock', $this->context)) {
2235 $title = get_string('lock', 'grades');
2236 $url->param('action', 'lock');
2237 } else {
2238 return null;
2240 } else if (($element['type'] == 'grade') && ($element['object']->grade_item->is_locked())) {
2241 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon.
2242 $strparamobj = new stdClass();
2243 $strparamobj->itemname = $element['object']->grade_item->get_name(true, true);
2244 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2245 $title = get_string('unlock', 'grades');
2246 return html_writer::span($title, 'text-muted dropdown-item', ['title' => $strnonunlockable,
2247 'aria-label' => $title, 'role' => 'menuitem']);
2248 } else if ($element['object']->is_locked()) {
2249 if (has_capability('moodle/grade:unlock', $this->context)) {
2250 $title = get_string('unlock', 'grades');
2251 $url->param('action', 'unlock');
2252 } else {
2253 return null;
2255 } else {
2256 if (has_capability('moodle/grade:lock', $this->context)) {
2257 $title = get_string('lock', 'grades');
2258 $url->param('action', 'lock');
2259 } else {
2260 return null;
2264 return html_writer::link($url, $title,
2265 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2266 } else {
2267 return null;
2272 * Return calculation icon for given element
2274 * @param array $element An array representing an element in the grade_tree
2275 * @param object $gpr A grade_plugin_return object
2276 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2277 * @return string|action_menu_link
2278 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2279 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2281 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2282 global $CFG, $OUTPUT;
2283 debugging('The function get_calculation_icon() is deprecated, please do not use it anymore.',
2284 DEBUG_DEVELOPER);
2286 if (!has_capability('moodle/grade:manage', $this->context)) {
2287 return $returnactionmenulink ? null : '';
2290 $type = $element['type'];
2291 $object = $element['object'];
2293 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2294 $strparams = $this->get_params_for_iconstr($element);
2295 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2297 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2298 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2300 // show calculation icon only when calculation possible
2301 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2302 if ($object->is_calculated()) {
2303 $icon = 't/calc';
2304 } else {
2305 $icon = 't/calc_off';
2308 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2309 $url = $gpr->add_url_params($url);
2310 if ($returnactionmenulink) {
2311 return new action_menu_link_secondary($url,
2312 new pix_icon($icon, $streditcalculation),
2313 get_string('editcalculation', 'grades'));
2314 } else {
2315 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2320 return $returnactionmenulink ? null : '';
2324 * Returns link to edit calculation for a grade item.
2326 * @param array $element An array representing an element in the grade_tree
2327 * @param object $gpr A grade_plugin_return object
2329 * @return string|null
2331 public function get_edit_calculation_link(array $element, object $gpr): ?string {
2333 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2334 $object = $element['object'];
2335 $isscale = $object->gradetype == GRADE_TYPE_SCALE;
2336 $isvalue = $object->gradetype == GRADE_TYPE_VALUE;
2338 // Show calculation icon only when calculation possible.
2339 if (!$object->is_external_item() && ($isscale || $isvalue)) {
2340 $editcalculationstring = get_string('editcalculation', 'grades');
2341 $url = new moodle_url('/grade/edit/tree/calculation.php',
2342 ['courseid' => $this->courseid, 'id' => $object->id]);
2343 $url = $gpr->add_url_params($url);
2344 return html_writer::link($url, $editcalculationstring,
2345 ['class' => 'dropdown-item', 'aria-label' => $editcalculationstring, 'role' => 'menuitem']);
2348 return null;
2352 * Sets status icons for the grade.
2354 * @param array $element array with grade item info
2355 * @return string|null status icons container HTML
2357 public function set_grade_status_icons(array $element): ?string {
2358 global $OUTPUT;
2360 $context = [
2361 'hidden' => $element['object']->is_hidden(),
2364 if ($element['object'] instanceof grade_grade) {
2365 $grade = $element['object'];
2366 $context['overridden'] = $grade->is_overridden();
2367 $context['excluded'] = $grade->is_excluded();
2368 $context['feedback'] = !empty($grade->feedback) && $grade->load_grade_item()->gradetype != GRADE_TYPE_TEXT;
2371 $context['classes'] = 'grade_icons data-collapse_gradeicons';
2373 if ($element['object'] instanceof grade_category) {
2374 $context['classes'] = 'category_grade_icons';
2376 $children = $element['object']->get_children(true);
2377 $alllocked = true;
2378 foreach ($children as $child) {
2379 if (!$child['object']->is_locked()) {
2380 $alllocked = false;
2381 break;
2384 if ($alllocked) {
2385 $context['locked'] = true;
2387 } else {
2388 $context['locked'] = $element['object']->is_locked();
2391 // Don't even attempt rendering if there is no status to show.
2392 if (in_array(true, $context)) {
2393 return $OUTPUT->render_from_template('core_grades/status_icons', $context);
2394 } else {
2395 return null;
2400 * Returns an action menu for the grade.
2402 * @param array $element Array with cell info.
2403 * @param string $mode Mode - gradeitem or user
2404 * @param grade_plugin_return $gpr
2405 * @param moodle_url|null $baseurl
2406 * @return string
2408 public function get_cell_action_menu(array $element, string $mode, grade_plugin_return $gpr,
2409 ?moodle_url $baseurl = null): string {
2410 global $OUTPUT, $USER;
2412 $context = new stdClass();
2414 if ($mode == 'gradeitem' || $mode == 'setup') {
2415 $editable = true;
2417 if ($element['type'] == 'grade') {
2418 $context->datatype = 'grade';
2420 $item = $element['object']->grade_item;
2421 if ($item->is_course_item() || $item->is_category_item()) {
2422 $editable = (bool)get_config('moodle', 'grade_overridecat');;
2425 if (!empty($USER->editing)) {
2426 if ($editable) {
2427 $context->editurl = $this->get_edit_link($element, $gpr);
2429 $context->hideurl = $this->get_hiding_link($element, $gpr);
2430 $context->lockurl = $this->get_locking_link($element, $gpr);
2433 $context->gradeanalysisurl = $this->get_grade_analysis_link($element['object']);
2434 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
2435 ($element['type'] == 'courseitem') || ($element['type'] == 'userfield')) {
2437 $context->datatype = 'item';
2439 if ($element['type'] == 'item') {
2440 if ($mode == 'setup') {
2441 $context->deleteurl = $this->get_delete_link($element, $gpr);
2442 $context->duplicateurl = $this->get_duplicate_link($element, $gpr);
2443 } else {
2444 $context =
2445 grade_report::get_additional_context($this->context, $this->courseid,
2446 $element, $gpr, $mode, $context, true);
2447 $context->advancedgradingurl = $this->get_advanced_grading_link($element, $gpr);
2449 $context->divider1 = true;
2452 if (($element['type'] == 'item') ||
2453 (($element['type'] == 'userfield') && ($element['name'] !== 'fullname'))) {
2454 $context->divider2 = true;
2457 if (!empty($USER->editing) || $mode == 'setup') {
2458 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2459 $context->divider2 = true;
2460 } else if (($mode !== 'setup') && ($element['type'] !== 'userfield')) {
2461 $context->divider1 = true;
2462 $context->divider2 = true;
2465 if ($element['type'] == 'item') {
2466 $context->editurl = $this->get_edit_link($element, $gpr);
2469 $context->editcalculationurl =
2470 $this->get_edit_calculation_link($element, $gpr);
2472 if (isset($element['object'])) {
2473 $object = $element['object'];
2474 if ($object->itemmodule !== 'quiz') {
2475 $context->hideurl = $this->get_hiding_link($element, $gpr);
2478 $context->lockurl = $this->get_locking_link($element, $gpr);
2481 // Sorting item.
2482 if ($baseurl) {
2483 $sortlink = clone($baseurl);
2484 if (isset($element['object']->id)) {
2485 $sortlink->param('sortitemid', $element['object']->id);
2486 } else if ($element['type'] == 'userfield') {
2487 $context->datatype = $element['name'];
2488 $sortlink->param('sortitemid', $element['name']);
2491 if (($element['type'] == 'userfield') && ($element['name'] == 'fullname')) {
2492 $sortlink->param('sortitemid', 'firstname');
2493 $context->ascendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr);
2494 $context->descendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2496 $sortlink->param('sortitemid', 'lastname');
2497 $context->ascendinglastnameurl = $this->get_sorting_link($sortlink, $gpr);
2498 $context->descendinglastnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2499 } else {
2500 $context->ascendingurl = $this->get_sorting_link($sortlink, $gpr);
2501 $context->descendingurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2504 if ($mode !== 'setup') {
2505 $context = grade_report::get_additional_context($this->context, $this->courseid,
2506 $element, $gpr, $mode, $context);
2508 } else if ($element['type'] == 'category') {
2509 $context->datatype = 'category';
2510 if ($mode !== 'setup') {
2511 $mode = 'category';
2512 $context = grade_report::get_additional_context($this->context, $this->courseid,
2513 $element, $gpr, $mode, $context);
2514 } else {
2515 $context->deleteurl = $this->get_delete_link($element, $gpr);
2516 $context->resetweightsurl = $this->get_reset_weights_link($element, $gpr);
2519 if (!empty($USER->editing) || $mode == 'setup') {
2520 if ($mode !== 'setup') {
2521 $context->divider1 = true;
2523 $context->editurl = $this->get_edit_link($element, $gpr);
2524 $context->hideurl = $this->get_hiding_link($element, $gpr);
2525 $context->lockurl = $this->get_locking_link($element, $gpr);
2529 if (isset($element['object'])) {
2530 $context->dataid = $element['object']->id;
2531 } else if ($element['type'] == 'userfield') {
2532 $context->dataid = $element['name'];
2535 if ($element['type'] != 'text' && !empty($element['object']->feedback)) {
2536 $viewfeedbackstring = get_string('viewfeedback', 'grades');
2537 $context->viewfeedbackurl = html_writer::link('#', $viewfeedbackstring, ['class' => 'dropdown-item',
2538 'aria-label' => $viewfeedbackstring, 'role' => 'menuitem', 'data-action' => 'feedback',
2539 'data-courseid' => $this->courseid]);
2541 } else if ($mode == 'user') {
2542 $context->datatype = 'user';
2543 $context = grade_report::get_additional_context($this->context, $this->courseid, $element, $gpr, $mode, $context, true);
2544 $context->dataid = $element['userid'];
2547 // Omit the second divider if there is nothing between it and the first divider.
2548 if (!isset($context->ascendingfirstnameurl) && !isset($context->ascendingurl)) {
2549 $context->divider2 = false;
2552 if ($mode == 'setup') {
2553 $context->databoundary = 'window';
2556 if (!empty($USER->editing) || isset($context->gradeanalysisurl) || isset($context->gradesonlyurl)
2557 || isset($context->aggregatesonlyurl) || isset($context->fullmodeurl) || isset($context->reporturl0)
2558 || isset($context->ascendingfirstnameurl) || isset($context->ascendingurl)
2559 || isset($context->viewfeedbackurl) || ($mode == 'setup')) {
2560 return $OUTPUT->render_from_template('core_grades/cellmenu', $context);
2562 return '';
2566 * Returns link to sort grade item column
2568 * @param moodle_url $sortlink A base link for sorting
2569 * @param object $gpr A grade_plugin_return object
2570 * @param string $direction Direction od sorting
2571 * @return string
2573 public function get_sorting_link(moodle_url $sortlink, object $gpr, string $direction = 'asc'): string {
2575 if ($direction == 'asc') {
2576 $title = get_string('asc');
2577 } else {
2578 $title = get_string('desc');
2581 $sortlink->param('sort', $direction);
2582 $gpr->add_url_params($sortlink);
2583 return html_writer::link($sortlink, $title,
2584 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2590 * Flat structure similar to grade tree.
2592 * @uses grade_structure
2593 * @package core_grades
2594 * @copyright 2009 Nicolas Connault
2595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2597 class grade_seq extends grade_structure {
2600 * 1D array of elements
2602 public $elements;
2605 * Constructor, retrieves and stores array of all grade_category and grade_item
2606 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2608 * @param int $courseid The course id
2609 * @param bool $category_grade_last category grade item is the last child
2610 * @param bool $nooutcomes Whether or not outcomes should be included
2612 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2613 global $USER, $CFG;
2615 $this->courseid = $courseid;
2616 $this->context = context_course::instance($courseid);
2618 // get course grade tree
2619 $top_element = grade_category::fetch_course_tree($courseid, true);
2621 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2623 foreach ($this->elements as $key=>$unused) {
2624 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2629 * Old syntax of class constructor. Deprecated in PHP7.
2631 * @deprecated since Moodle 3.1
2633 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2634 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2635 self::__construct($courseid, $category_grade_last, $nooutcomes);
2639 * Static recursive helper - makes the grade_item for category the last children
2641 * @param array &$element The seed of the recursion
2642 * @param bool $category_grade_last category grade item is the last child
2643 * @param bool $nooutcomes Whether or not outcomes should be included
2645 * @return array
2647 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2648 if (empty($element['children'])) {
2649 return array();
2651 $children = array();
2653 foreach ($element['children'] as $sortorder=>$unused) {
2654 if ($nooutcomes and $element['type'] != 'category' and
2655 $element['children'][$sortorder]['object']->is_outcome_item()) {
2656 continue;
2658 $children[] = $element['children'][$sortorder];
2660 unset($element['children']);
2662 if ($category_grade_last and count($children) > 1 and
2664 $children[0]['type'] === 'courseitem' or
2665 $children[0]['type'] === 'categoryitem'
2668 $cat_item = array_shift($children);
2669 array_push($children, $cat_item);
2672 $result = array();
2673 foreach ($children as $child) {
2674 if ($child['type'] == 'category') {
2675 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2676 } else {
2677 $child['eid'] = 'i'.$child['object']->id;
2678 $result[$child['object']->id] = $child;
2682 return $result;
2686 * Parses the array in search of a given eid and returns a element object with
2687 * information about the element it has found.
2689 * @param int $eid Gradetree Element ID
2691 * @return object element
2693 public function locate_element($eid) {
2694 // it is a grade - construct a new object
2695 if (strpos($eid, 'n') === 0) {
2696 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2697 return null;
2700 $itemid = $matches[1];
2701 $userid = $matches[2];
2703 //extra security check - the grade item must be in this tree
2704 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2705 return null;
2708 // $gradea->id may be null - means does not exist yet
2709 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2711 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2712 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2714 } else if (strpos($eid, 'g') === 0) {
2715 $id = (int) substr($eid, 1);
2716 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2717 return null;
2719 //extra security check - the grade item must be in this tree
2720 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2721 return null;
2723 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2724 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2727 // it is a category or item
2728 foreach ($this->elements as $element) {
2729 if ($element['eid'] == $eid) {
2730 return $element;
2734 return null;
2739 * This class represents a complete tree of categories, grade_items and final grades,
2740 * organises as an array primarily, but which can also be converted to other formats.
2741 * It has simple method calls with complex implementations, allowing for easy insertion,
2742 * deletion and moving of items and categories within the tree.
2744 * @uses grade_structure
2745 * @package core_grades
2746 * @copyright 2009 Nicolas Connault
2747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2749 class grade_tree extends grade_structure {
2752 * The basic representation of the tree as a hierarchical, 3-tiered array.
2753 * @var object $top_element
2755 public $top_element;
2758 * 2D array of grade items and categories
2759 * @var array $levels
2761 public $levels;
2764 * Grade items
2765 * @var array $items
2767 public $items;
2770 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2771 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2773 * @param int $courseid The Course ID
2774 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2775 * @param bool $category_grade_last category grade item is the last child
2776 * @param array $collapsed array of collapsed categories
2777 * @param bool $nooutcomes Whether or not outcomes should be included
2779 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2780 $collapsed=null, $nooutcomes=false) {
2781 global $USER, $CFG, $COURSE, $DB;
2783 $this->courseid = $courseid;
2784 $this->levels = array();
2785 $this->context = context_course::instance($courseid);
2787 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2788 $course = $COURSE;
2789 } else {
2790 $course = $DB->get_record('course', array('id' => $this->courseid));
2792 $this->modinfo = get_fast_modinfo($course);
2794 // get course grade tree
2795 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2797 // collapse the categories if requested
2798 if (!empty($collapsed)) {
2799 grade_tree::category_collapse($this->top_element, $collapsed);
2802 // no otucomes if requested
2803 if (!empty($nooutcomes)) {
2804 grade_tree::no_outcomes($this->top_element);
2807 // move category item to last position in category
2808 if ($category_grade_last) {
2809 grade_tree::category_grade_last($this->top_element);
2812 if ($fillers) {
2813 // inject fake categories == fillers
2814 grade_tree::inject_fillers($this->top_element, 0);
2815 // add colspans to categories and fillers
2816 grade_tree::inject_colspans($this->top_element);
2819 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2824 * Old syntax of class constructor. Deprecated in PHP7.
2826 * @deprecated since Moodle 3.1
2828 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2829 $collapsed=null, $nooutcomes=false) {
2830 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2831 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2835 * Static recursive helper - removes items from collapsed categories
2837 * @param array &$element The seed of the recursion
2838 * @param array $collapsed array of collapsed categories
2840 * @return void
2842 public function category_collapse(&$element, $collapsed) {
2843 if ($element['type'] != 'category') {
2844 return;
2846 if (empty($element['children']) or count($element['children']) < 2) {
2847 return;
2850 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2851 $category_item = reset($element['children']); //keep only category item
2852 $element['children'] = array(key($element['children'])=>$category_item);
2854 } else {
2855 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2856 reset($element['children']);
2857 $first_key = key($element['children']);
2858 unset($element['children'][$first_key]);
2860 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2861 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2867 * Static recursive helper - removes all outcomes
2869 * @param array &$element The seed of the recursion
2871 * @return void
2873 public function no_outcomes(&$element) {
2874 if ($element['type'] != 'category') {
2875 return;
2877 foreach ($element['children'] as $sortorder=>$child) {
2878 if ($element['children'][$sortorder]['type'] == 'item'
2879 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2880 unset($element['children'][$sortorder]);
2882 } else if ($element['children'][$sortorder]['type'] == 'category') {
2883 grade_tree::no_outcomes($element['children'][$sortorder]);
2889 * Static recursive helper - makes the grade_item for category the last children
2891 * @param array &$element The seed of the recursion
2893 * @return void
2895 public function category_grade_last(&$element) {
2896 if (empty($element['children'])) {
2897 return;
2899 if (count($element['children']) < 2) {
2900 return;
2902 $first_item = reset($element['children']);
2903 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2904 // the category item might have been already removed
2905 $order = key($element['children']);
2906 unset($element['children'][$order]);
2907 $element['children'][$order] =& $first_item;
2909 foreach ($element['children'] as $sortorder => $child) {
2910 grade_tree::category_grade_last($element['children'][$sortorder]);
2915 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2917 * @param array &$levels The levels of the grade tree through which to recurse
2918 * @param array &$element The seed of the recursion
2919 * @param int $depth How deep are we?
2920 * @return void
2922 public function fill_levels(&$levels, &$element, $depth) {
2923 if (!array_key_exists($depth, $levels)) {
2924 $levels[$depth] = array();
2927 // prepare unique identifier
2928 if ($element['type'] == 'category') {
2929 $element['eid'] = 'cg'.$element['object']->id;
2930 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2931 $element['eid'] = 'ig'.$element['object']->id;
2932 $this->items[$element['object']->id] =& $element['object'];
2935 $levels[$depth][] =& $element;
2936 $depth++;
2937 if (empty($element['children'])) {
2938 return;
2940 $prev = 0;
2941 foreach ($element['children'] as $sortorder=>$child) {
2942 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2943 $element['children'][$sortorder]['prev'] = $prev;
2944 $element['children'][$sortorder]['next'] = 0;
2945 if ($prev) {
2946 $element['children'][$prev]['next'] = $sortorder;
2948 $prev = $sortorder;
2953 * Determines whether the grade tree item can be displayed.
2954 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2955 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2956 * can be output.
2958 * @param array $element The grade category element.
2959 * @return bool True if the grade tree item can be displayed. False, otherwise.
2961 public static function can_output_item($element) {
2962 $canoutput = true;
2964 if ($element['type'] === 'category') {
2965 $object = $element['object'];
2966 $category = grade_category::fetch(array('id' => $object->id));
2967 // Category has total, we can output this.
2968 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2969 return true;
2972 // Category has no total and has no children, no need to output this.
2973 if (empty($element['children'])) {
2974 return false;
2977 $canoutput = false;
2978 // Loop over children and make sure at least one child can be output.
2979 foreach ($element['children'] as $child) {
2980 $canoutput = self::can_output_item($child);
2981 if ($canoutput) {
2982 break;
2987 return $canoutput;
2991 * Static recursive helper - makes full tree (all leafes are at the same level)
2993 * @param array &$element The seed of the recursion
2994 * @param int $depth How deep are we?
2996 * @return int
2998 public function inject_fillers(&$element, $depth) {
2999 $depth++;
3001 if (empty($element['children'])) {
3002 return $depth;
3004 $chdepths = array();
3005 $chids = array_keys($element['children']);
3006 $last_child = end($chids);
3007 $first_child = reset($chids);
3009 foreach ($chids as $chid) {
3010 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
3012 arsort($chdepths);
3014 $maxdepth = reset($chdepths);
3015 foreach ($chdepths as $chid=>$chd) {
3016 if ($chd == $maxdepth) {
3017 continue;
3019 if (!self::can_output_item($element['children'][$chid])) {
3020 continue;
3022 for ($i=0; $i < $maxdepth-$chd; $i++) {
3023 if ($chid == $first_child) {
3024 $type = 'fillerfirst';
3025 } else if ($chid == $last_child) {
3026 $type = 'fillerlast';
3027 } else {
3028 $type = 'filler';
3030 $oldchild =& $element['children'][$chid];
3031 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
3032 'eid'=>'', 'depth'=>$element['object']->depth,
3033 'children'=>array($oldchild));
3037 return $maxdepth;
3041 * Static recursive helper - add colspan information into categories
3043 * @param array &$element The seed of the recursion
3045 * @return int
3047 public function inject_colspans(&$element) {
3048 if (empty($element['children'])) {
3049 return 1;
3051 $count = 0;
3052 foreach ($element['children'] as $key=>$child) {
3053 if (!self::can_output_item($child)) {
3054 continue;
3056 $count += grade_tree::inject_colspans($element['children'][$key]);
3058 $element['colspan'] = $count;
3059 return $count;
3063 * Parses the array in search of a given eid and returns a element object with
3064 * information about the element it has found.
3065 * @param int $eid Gradetree Element ID
3066 * @return object element
3068 public function locate_element($eid) {
3069 // it is a grade - construct a new object
3070 if (strpos($eid, 'n') === 0) {
3071 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
3072 return null;
3075 $itemid = $matches[1];
3076 $userid = $matches[2];
3078 //extra security check - the grade item must be in this tree
3079 if (!$item_el = $this->locate_element('ig'.$itemid)) {
3080 return null;
3083 // $gradea->id may be null - means does not exist yet
3084 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
3086 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3087 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
3089 } else if (strpos($eid, 'g') === 0) {
3090 $id = (int) substr($eid, 1);
3091 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
3092 return null;
3094 //extra security check - the grade item must be in this tree
3095 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
3096 return null;
3098 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3099 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
3102 // it is a category or item
3103 foreach ($this->levels as $row) {
3104 foreach ($row as $element) {
3105 if ($element['type'] == 'filler') {
3106 continue;
3108 if ($element['eid'] == $eid) {
3109 return $element;
3114 return null;
3118 * Returns a well-formed XML representation of the grade-tree using recursion.
3120 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3121 * @param string $tabs The control character to use for tabs
3123 * @return string $xml
3125 public function exporttoxml($root=null, $tabs="\t") {
3126 $xml = null;
3127 $first = false;
3128 if (is_null($root)) {
3129 $root = $this->top_element;
3130 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
3131 $xml .= "<gradetree>\n";
3132 $first = true;
3135 $type = 'undefined';
3136 if (strpos($root['object']->table, 'grade_categories') !== false) {
3137 $type = 'category';
3138 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3139 $type = 'item';
3140 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3141 $type = 'outcome';
3144 $xml .= "$tabs<element type=\"$type\">\n";
3145 foreach ($root['object'] as $var => $value) {
3146 if (!is_object($value) && !is_array($value) && !empty($value)) {
3147 $xml .= "$tabs\t<$var>$value</$var>\n";
3151 if (!empty($root['children'])) {
3152 $xml .= "$tabs\t<children>\n";
3153 foreach ($root['children'] as $sortorder => $child) {
3154 $xml .= $this->exportToXML($child, $tabs."\t\t");
3156 $xml .= "$tabs\t</children>\n";
3159 $xml .= "$tabs</element>\n";
3161 if ($first) {
3162 $xml .= "</gradetree>";
3165 return $xml;
3169 * Returns a JSON representation of the grade-tree using recursion.
3171 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3172 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
3174 * @return string
3176 public function exporttojson($root=null, $tabs="\t") {
3177 $json = null;
3178 $first = false;
3179 if (is_null($root)) {
3180 $root = $this->top_element;
3181 $first = true;
3184 $name = '';
3187 if (strpos($root['object']->table, 'grade_categories') !== false) {
3188 $name = $root['object']->fullname;
3189 if ($name == '?') {
3190 $name = $root['object']->get_name();
3192 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3193 $name = $root['object']->itemname;
3194 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3195 $name = $root['object']->itemname;
3198 $json .= "$tabs {\n";
3199 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
3200 $json .= "$tabs\t \"name\": \"$name\",\n";
3202 foreach ($root['object'] as $var => $value) {
3203 if (!is_object($value) && !is_array($value) && !empty($value)) {
3204 $json .= "$tabs\t \"$var\": \"$value\",\n";
3208 $json = substr($json, 0, strrpos($json, ','));
3210 if (!empty($root['children'])) {
3211 $json .= ",\n$tabs\t\"children\": [\n";
3212 foreach ($root['children'] as $sortorder => $child) {
3213 $json .= $this->exportToJSON($child, $tabs."\t\t");
3215 $json = substr($json, 0, strrpos($json, ','));
3216 $json .= "\n$tabs\t]\n";
3219 if ($first) {
3220 $json .= "\n}";
3221 } else {
3222 $json .= "\n$tabs},\n";
3225 return $json;
3229 * Returns the array of levels
3231 * @return array
3233 public function get_levels() {
3234 return $this->levels;
3238 * Returns the array of grade items
3240 * @return array
3242 public function get_items() {
3243 return $this->items;
3247 * Returns a specific Grade Item
3249 * @param int $itemid The ID of the grade_item object
3251 * @return grade_item
3253 public function get_item($itemid) {
3254 if (array_key_exists($itemid, $this->items)) {
3255 return $this->items[$itemid];
3256 } else {
3257 return false;
3263 * Local shortcut function for creating an edit/delete button for a grade_* object.
3264 * @param string $type 'edit' or 'delete'
3265 * @param int $courseid The Course ID
3266 * @param grade_* $object The grade_* object
3267 * @return string html
3269 function grade_button($type, $courseid, $object) {
3270 global $CFG, $OUTPUT;
3271 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
3272 $objectidstring = $matches[1] . 'id';
3273 } else {
3274 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
3277 $strdelete = get_string('delete');
3278 $stredit = get_string('edit');
3280 if ($type == 'delete') {
3281 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
3282 } else if ($type == 'edit') {
3283 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
3286 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
3291 * This method adds settings to the settings block for the grade system and its
3292 * plugins
3294 * @global moodle_page $PAGE
3296 function grade_extend_settings($plugininfo, $courseid) {
3297 global $PAGE;
3299 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER,
3300 null, 'gradeadmin');
3302 $strings = array_shift($plugininfo);
3304 if ($reports = grade_helper::get_plugins_reports($courseid)) {
3305 foreach ($reports as $report) {
3306 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
3310 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
3311 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
3312 foreach ($settings as $setting) {
3313 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
3317 if ($imports = grade_helper::get_plugins_import($courseid)) {
3318 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
3319 foreach ($imports as $import) {
3320 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
3324 if ($exports = grade_helper::get_plugins_export($courseid)) {
3325 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
3326 foreach ($exports as $export) {
3327 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
3331 if ($letters = grade_helper::get_info_letters($courseid)) {
3332 $letters = array_shift($letters);
3333 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
3336 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
3337 $outcomes = array_shift($outcomes);
3338 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
3341 if ($scales = grade_helper::get_info_scales($courseid)) {
3342 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
3345 if ($gradenode->contains_active_node()) {
3346 // If the gradenode is active include the settings base node (gradeadministration) in
3347 // the navbar, typcially this is ignored.
3348 $PAGE->navbar->includesettingsbase = true;
3350 // If we can get the course admin node make sure it is closed by default
3351 // as in this case the gradenode will be opened
3352 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
3353 $coursenode->make_inactive();
3354 $coursenode->forceopen = false;
3360 * Grade helper class
3362 * This class provides several helpful functions that work irrespective of any
3363 * current state.
3365 * @copyright 2010 Sam Hemelryk
3366 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3368 abstract class grade_helper {
3370 * Cached manage settings info {@see get_info_settings}
3371 * @var grade_plugin_info|false
3373 protected static $managesetting = null;
3375 * Cached grade report plugins {@see get_plugins_reports}
3376 * @var array|false
3378 protected static $gradereports = null;
3380 * Cached grade report plugins preferences {@see get_info_scales}
3381 * @var array|false
3383 protected static $gradereportpreferences = null;
3385 * Cached scale info {@see get_info_scales}
3386 * @var grade_plugin_info|false
3388 protected static $scaleinfo = null;
3390 * Cached outcome info {@see get_info_outcomes}
3391 * @var grade_plugin_info|false
3393 protected static $outcomeinfo = null;
3395 * Cached leftter info {@see get_info_letters}
3396 * @var grade_plugin_info|false
3398 protected static $letterinfo = null;
3400 * Cached grade import plugins {@see get_plugins_import}
3401 * @var array|false
3403 protected static $importplugins = null;
3405 * Cached grade export plugins {@see get_plugins_export}
3406 * @var array|false
3408 protected static $exportplugins = null;
3410 * Cached grade plugin strings
3411 * @var array
3413 protected static $pluginstrings = null;
3415 * Cached grade aggregation strings
3416 * @var array
3418 protected static $aggregationstrings = null;
3421 * Cached grade tree plugin strings
3422 * @var array
3424 protected static $langstrings = [];
3427 * First checks the cached language strings, then returns match if found, or uses get_string()
3428 * to get it from the DB, caches it then returns it.
3430 * @deprecated since 4.3
3431 * @todo MDL-78780 This will be deleted in Moodle 4.7.
3432 * @param string $strcode
3433 * @param string|null $section Optional language section
3434 * @return string
3436 public static function get_lang_string(string $strcode, ?string $section = null): string {
3437 debugging('grade_helper::get_lang_string() is deprecated, please use' .
3438 ' get_string() instead.', DEBUG_DEVELOPER);
3440 if (empty(self::$langstrings[$strcode])) {
3441 self::$langstrings[$strcode] = get_string($strcode, $section);
3443 return self::$langstrings[$strcode];
3447 * Gets strings commonly used by the describe plugins
3449 * report => get_string('view'),
3450 * scale => get_string('scales'),
3451 * outcome => get_string('outcomes', 'grades'),
3452 * letter => get_string('letters', 'grades'),
3453 * export => get_string('export', 'grades'),
3454 * import => get_string('import'),
3455 * settings => get_string('settings')
3457 * @return array
3459 public static function get_plugin_strings() {
3460 if (self::$pluginstrings === null) {
3461 self::$pluginstrings = array(
3462 'report' => get_string('view'),
3463 'scale' => get_string('scales'),
3464 'outcome' => get_string('outcomes', 'grades'),
3465 'letter' => get_string('letters', 'grades'),
3466 'export' => get_string('export', 'grades'),
3467 'import' => get_string('import'),
3468 'settings' => get_string('edittree', 'grades')
3471 return self::$pluginstrings;
3475 * Gets strings describing the available aggregation methods.
3477 * @return array
3479 public static function get_aggregation_strings() {
3480 if (self::$aggregationstrings === null) {
3481 self::$aggregationstrings = array(
3482 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
3483 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
3484 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
3485 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
3486 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
3487 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
3488 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
3489 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
3490 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
3493 return self::$aggregationstrings;
3497 * Get grade_plugin_info object for managing settings if the user can
3499 * @param int $courseid
3500 * @return grade_plugin_info[]
3502 public static function get_info_manage_settings($courseid) {
3503 if (self::$managesetting !== null) {
3504 return self::$managesetting;
3506 $context = context_course::instance($courseid);
3507 self::$managesetting = array();
3508 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
3509 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3510 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3511 get_string('gradebooksetup', 'grades'));
3512 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3513 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3514 get_string('coursegradesettings', 'grades'));
3516 if (self::$gradereportpreferences === null) {
3517 self::get_plugins_reports($courseid);
3519 if (self::$gradereportpreferences) {
3520 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
3522 return self::$managesetting;
3525 * Returns an array of plugin reports as grade_plugin_info objects
3527 * @param int $courseid
3528 * @return array
3530 public static function get_plugins_reports($courseid) {
3531 global $SITE, $CFG;
3533 if (self::$gradereports !== null) {
3534 return self::$gradereports;
3536 $context = context_course::instance($courseid);
3537 $gradereports = array();
3538 $gradepreferences = array();
3539 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
3540 //some reports make no sense if we're not within a course
3541 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
3542 continue;
3545 // Remove outcomes report if outcomes not enabled.
3546 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes)) {
3547 continue;
3550 // Remove ones we can't see
3551 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3552 continue;
3555 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3556 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3557 'moodle/grade:edit'), $context)) {
3558 continue;
3561 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3562 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3563 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3565 // Add link to preferences tab if such a page exists
3566 if (file_exists($plugindir.'/preferences.php')) {
3567 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id' => $courseid));
3568 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3569 get_string('preferences', 'grades') . ': ' . $pluginstr);
3572 if (count($gradereports) == 0) {
3573 $gradereports = false;
3574 $gradepreferences = false;
3575 } else if (count($gradepreferences) == 0) {
3576 $gradepreferences = false;
3577 asort($gradereports);
3578 } else {
3579 asort($gradereports);
3580 asort($gradepreferences);
3582 self::$gradereports = $gradereports;
3583 self::$gradereportpreferences = $gradepreferences;
3584 return self::$gradereports;
3588 * Get information on scales
3589 * @param int $courseid
3590 * @return grade_plugin_info
3592 public static function get_info_scales($courseid) {
3593 if (self::$scaleinfo !== null) {
3594 return self::$scaleinfo;
3596 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
3597 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3598 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3599 } else {
3600 self::$scaleinfo = false;
3602 return self::$scaleinfo;
3605 * Get information on outcomes
3606 * @param int $courseid
3607 * @return grade_plugin_info[]|false
3609 public static function get_info_outcomes($courseid) {
3610 global $CFG, $SITE;
3612 if (self::$outcomeinfo !== null) {
3613 return self::$outcomeinfo;
3615 $context = context_course::instance($courseid);
3616 $canmanage = has_capability('moodle/grade:manage', $context);
3617 $canupdate = has_capability('moodle/course:update', $context);
3618 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3619 $outcomes = array();
3620 if ($canupdate) {
3621 if ($courseid!=$SITE->id) {
3622 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3623 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3625 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3626 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3627 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3628 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3629 } else {
3630 if ($courseid!=$SITE->id) {
3631 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3632 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3635 self::$outcomeinfo = $outcomes;
3636 } else {
3637 self::$outcomeinfo = false;
3639 return self::$outcomeinfo;
3642 * Get information on letters
3643 * @param int $courseid
3644 * @return array
3646 public static function get_info_letters($courseid) {
3647 global $SITE;
3648 if (self::$letterinfo !== null) {
3649 return self::$letterinfo;
3651 $context = context_course::instance($courseid);
3652 $canmanage = has_capability('moodle/grade:manage', $context);
3653 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3654 if ($canmanage || $canmanageletters) {
3655 // Redirect to system context when report is accessed from admin settings MDL-31633
3656 if ($context->instanceid == $SITE->id) {
3657 $param = array('edit' => 1);
3658 } else {
3659 $param = array('edit' => 1,'id' => $context->id);
3661 self::$letterinfo = array(
3662 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3663 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3665 } else {
3666 self::$letterinfo = false;
3668 return self::$letterinfo;
3671 * Get information import plugins
3672 * @param int $courseid
3673 * @return array
3675 public static function get_plugins_import($courseid) {
3676 global $CFG;
3678 if (self::$importplugins !== null) {
3679 return self::$importplugins;
3681 $importplugins = array();
3682 $context = context_course::instance($courseid);
3684 if (has_capability('moodle/grade:import', $context)) {
3685 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3686 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3687 continue;
3689 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3690 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3691 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3694 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3695 // XML is the only grade import plugin that has publishing feature.
3696 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3697 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3698 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3702 if (count($importplugins) > 0) {
3703 asort($importplugins);
3704 self::$importplugins = $importplugins;
3705 } else {
3706 self::$importplugins = false;
3708 return self::$importplugins;
3711 * Get information export plugins
3712 * @param int $courseid
3713 * @return array
3715 public static function get_plugins_export($courseid) {
3716 global $CFG;
3718 if (self::$exportplugins !== null) {
3719 return self::$exportplugins;
3721 $context = context_course::instance($courseid);
3722 $exportplugins = array();
3723 $canpublishgrades = 0;
3724 if (has_capability('moodle/grade:export', $context)) {
3725 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3726 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3727 continue;
3729 // All the grade export plugins has grade publishing capabilities.
3730 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3731 $canpublishgrades++;
3734 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3735 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3736 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3739 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3740 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3741 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3742 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3745 if (count($exportplugins) > 0) {
3746 asort($exportplugins);
3747 self::$exportplugins = $exportplugins;
3748 } else {
3749 self::$exportplugins = false;
3751 return self::$exportplugins;
3755 * Returns the value of a field from a user record
3757 * @param stdClass $user object
3758 * @param stdClass $field object
3759 * @return string value of the field
3761 public static function get_user_field_value($user, $field) {
3762 if (!empty($field->customid)) {
3763 $fieldname = 'customfield_' . $field->customid;
3764 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3765 $fieldvalue = $user->{$fieldname};
3766 } else {
3767 $fieldvalue = $field->default;
3769 } else {
3770 $fieldvalue = $user->{$field->shortname};
3772 return $fieldvalue;
3776 * Returns an array of user profile fields to be included in export
3778 * @param int $courseid
3779 * @param bool $includecustomfields
3780 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3782 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3783 global $CFG, $DB;
3785 // Gets the fields that have to be hidden
3786 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3787 $context = context_course::instance($courseid);
3788 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3789 if ($canseehiddenfields) {
3790 $hiddenfields = array();
3793 $fields = array();
3794 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3795 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3796 $userdefaultfields = user_get_default_fields();
3798 // Sets the list of profile fields
3799 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3800 if (!empty($userprofilefields)) {
3801 foreach ($userprofilefields as $field) {
3802 $field = trim($field);
3803 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3804 continue;
3806 $obj = new stdClass();
3807 $obj->customid = 0;
3808 $obj->shortname = $field;
3809 $obj->fullname = get_string($field);
3810 $fields[] = $obj;
3814 // Sets the list of custom profile fields
3815 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3816 if ($includecustomfields && !empty($customprofilefields)) {
3817 $customfields = profile_get_user_fields_with_data(0);
3819 foreach ($customfields as $fieldobj) {
3820 $field = (object)$fieldobj->get_field_config_for_external();
3821 // Make sure we can display this custom field
3822 if (!in_array($field->shortname, $customprofilefields)) {
3823 continue;
3824 } else if (in_array($field->shortname, $hiddenfields)) {
3825 continue;
3826 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3827 continue;
3830 $obj = new stdClass();
3831 $obj->customid = $field->id;
3832 $obj->shortname = $field->shortname;
3833 $obj->fullname = format_string($field->name);
3834 $obj->datatype = $field->datatype;
3835 $obj->default = $field->defaultdata;
3836 $fields[] = $obj;
3840 return $fields;
3844 * This helper method gets a snapshot of all the weights for a course.
3845 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3846 * @param int $courseid
3847 * @return array of itemid -> aggregationcoef2
3849 public static function fetch_all_natural_weights_for_course($courseid) {
3850 global $DB;
3851 $result = array();
3853 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3854 foreach ($records as $record) {
3855 $result[$record->id] = $record->aggregationcoef2;
3857 return $result;
3861 * Resets all static caches.
3863 * @return void
3865 public static function reset_caches() {
3866 self::$managesetting = null;
3867 self::$gradereports = null;
3868 self::$gradereportpreferences = null;
3869 self::$scaleinfo = null;
3870 self::$outcomeinfo = null;
3871 self::$letterinfo = null;
3872 self::$importplugins = null;
3873 self::$exportplugins = null;
3874 self::$pluginstrings = null;
3875 self::$aggregationstrings = null;
3879 * Returns icon of element
3881 * @param array $element An array representing an element in the grade_tree
3882 * @param bool $spacerifnone return spacer if no icon found
3884 * @return string icon or spacer
3886 public static function get_element_icon(array $element, bool $spacerifnone = false): string {
3887 global $CFG, $OUTPUT;
3888 require_once($CFG->libdir . '/filelib.php');
3890 $outputstr = '';
3892 // Object holding pix_icon information before instantiation.
3893 $icon = new stdClass();
3894 $icon->attributes = ['class' => 'icon itemicon'];
3895 $icon->component = 'moodle';
3897 $none = true;
3898 switch ($element['type']) {
3899 case 'item':
3900 case 'courseitem':
3901 case 'categoryitem':
3902 $none = false;
3904 $iscourse = $element['object']->is_course_item();
3905 $iscategory = $element['object']->is_category_item();
3906 $isscale = $element['object']->gradetype == GRADE_TYPE_SCALE;
3907 $isvalue = $element['object']->gradetype == GRADE_TYPE_VALUE;
3908 $isoutcome = !empty($element['object']->outcomeid);
3910 if ($element['object']->is_calculated()) {
3911 $icon->pix = 'i/calc';
3912 $icon->title = s(get_string('calculatedgrade', 'grades'));
3914 } else if (($iscourse || $iscategory) && ($isscale || $isvalue)) {
3915 if ($category = $element['object']->get_item_category()) {
3916 $aggrstrings = self::get_aggregation_strings();
3917 $stragg = $aggrstrings[$category->aggregation];
3919 $icon->pix = 'i/calc';
3920 $icon->title = s($stragg);
3922 switch ($category->aggregation) {
3923 case GRADE_AGGREGATE_MEAN:
3924 case GRADE_AGGREGATE_MEDIAN:
3925 case GRADE_AGGREGATE_WEIGHTED_MEAN:
3926 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
3927 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
3928 $icon->pix = 'i/agg_mean';
3929 break;
3930 case GRADE_AGGREGATE_SUM:
3931 $icon->pix = 'i/agg_sum';
3932 break;
3936 } else if ($element['object']->itemtype == 'mod') {
3937 // Prevent outcomes displaying the same icon as the activity they are attached to.
3938 if ($isoutcome) {
3939 $icon->pix = 'i/outcomes';
3940 $icon->title = s(get_string('outcome', 'grades'));
3941 } else {
3942 $modinfo = get_fast_modinfo($element['object']->courseid);
3943 $module = $element['object']->itemmodule;
3944 $instanceid = $element['object']->iteminstance;
3945 if (isset($modinfo->instances[$module][$instanceid])) {
3946 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
3947 } else {
3948 $icon->pix = 'monologo';
3949 $icon->component = $element['object']->itemmodule;
3951 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
3953 } else if ($element['object']->itemtype == 'manual') {
3954 if ($element['object']->is_outcome_item()) {
3955 $icon->pix = 'i/outcomes';
3956 $icon->title = s(get_string('outcome', 'grades'));
3957 } else {
3958 $icon->pix = 'i/manual_item';
3959 $icon->title = s(get_string('manualitem', 'grades'));
3962 break;
3964 case 'category':
3965 $none = false;
3966 $icon->pix = 'i/folder';
3967 $icon->title = s(get_string('category', 'grades'));
3968 break;
3971 if ($none) {
3972 if ($spacerifnone) {
3973 $outputstr = $OUTPUT->spacer() . ' ';
3975 } else if (isset($icon->url)) {
3976 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
3977 } else {
3978 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
3981 return $outputstr;
3985 * Returns the string that describes the type of the element.
3987 * @param array $element An array representing an element in the grade_tree
3988 * @return string The string that describes the type of the grade element
3990 public static function get_element_type_string(array $element): string {
3991 // If the element is a grade category.
3992 if ($element['type'] == 'category') {
3993 return get_string('category', 'grades');
3995 // If the element is a grade item.
3996 if (in_array($element['type'], ['item', 'courseitem', 'categoryitem'])) {
3997 // If calculated grade item.
3998 if ($element['object']->is_calculated()) {
3999 return get_string('calculatedgrade', 'grades');
4001 // If aggregated type grade item.
4002 if ($element['object']->is_aggregate_item()) {
4003 return get_string('aggregation', 'core_grades');
4005 // If external grade item (module, plugin, etc.).
4006 if ($element['object']->is_external_item()) {
4007 // If outcome grade item.
4008 if ($element['object']->is_outcome_item()) {
4009 return get_string('outcome', 'grades');
4011 return get_string('modulename', $element['object']->itemmodule);
4013 // If manual grade item.
4014 if ($element['object']->itemtype == 'manual') {
4015 // If outcome grade item.
4016 if ($element['object']->is_outcome_item()) {
4017 return get_string('outcome', 'grades');
4019 return get_string('manualitem', 'grades');
4023 return '';
4027 * Returns name of element optionally with icon and link
4029 * @param array $element An array representing an element in the grade_tree
4030 * @param bool $withlink Whether or not this header has a link
4031 * @param bool $icon Whether or not to display an icon with this header
4032 * @param bool $spacerifnone return spacer if no icon found
4033 * @param bool $withdescription Show description if defined by this item.
4034 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
4035 * instead of "Category total" or "Course total"
4036 * @param moodle_url|null $sortlink Link to sort column.
4038 * @return string header
4040 public static function get_element_header(array $element, bool $withlink = false, bool $icon = true,
4041 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
4042 ?moodle_url $sortlink = null): string {
4043 $header = '';
4045 if ($icon) {
4046 $header .= self::get_element_icon($element, $spacerifnone);
4049 $title = $element['object']->get_name($fulltotal);
4050 $titleunescaped = $element['object']->get_name($fulltotal, false);
4051 $header .= $title;
4053 if ($element['type'] != 'item' && $element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
4054 return $header;
4057 if ($sortlink) {
4058 $url = $sortlink;
4059 $header = html_writer::link($url, $header, [
4060 'title' => $titleunescaped,
4061 'class' => 'gradeitemheader ',
4063 } else {
4064 if ($withlink && $url = self::get_activity_link($element)) {
4065 $a = new stdClass();
4066 $a->name = get_string('modulename', $element['object']->itemmodule);
4067 $a->title = $titleunescaped;
4068 $title = get_string('linktoactivity', 'grades', $a);
4069 $header = html_writer::link($url, $header, [
4070 'title' => $title,
4071 'class' => 'gradeitemheader ',
4073 } else {
4074 $header = html_writer::span($header, 'gradeitemheader ', [
4075 'title' => $titleunescaped,
4076 'tabindex' => '0',
4081 if ($withdescription) {
4082 $desc = $element['object']->get_description();
4083 if (!empty($desc)) {
4084 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
4088 return $header;
4092 * Returns a link to activity
4094 * @param array $element An array representing an element in the grade_tree
4095 * @return moodle_url|null link to activity or null if not found
4097 public static function get_activity_link(array $element): ?moodle_url {
4098 $itemtype = $element['object']->itemtype;
4099 $itemmodule = $element['object']->itemmodule;
4100 $iteminstance = $element['object']->iteminstance;
4102 // Links only for module items that have valid instance, module and are
4103 // called from grade_tree with valid modinfo.
4104 $modinfo = get_fast_modinfo($element['object']->courseid);
4105 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$modinfo) {
4106 return null;
4109 // Get $cm efficiently and with visibility information using modinfo.
4110 $instances = $modinfo->get_instances();
4111 if (empty($instances[$itemmodule][$iteminstance])) {
4112 return null;
4114 $cm = $instances[$itemmodule][$iteminstance];
4116 // Do not add link if activity is not visible to the current user.
4117 if (!$cm->uservisible) {
4118 return null;
4121 return new moodle_url('/mod/' . $itemmodule . '/view.php', ['id' => $cm->id]);