MDL-80394 core_grades: Revert changes to graded_users_iterator
[moodle.git] / grade / lib.php
blob43bdacc6e595e406d04160992e0179fa99ec4377
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;
989 $output = $renderer->user_heading($user, $courseid, $showuserbuttons);
990 } else if (!empty($heading)) {
991 $output = $OUTPUT->heading($heading);
994 if ($return) {
995 $returnval .= $output;
996 } else {
997 echo $output;
1000 $returnval .= print_natural_aggregation_upgrade_notice($courseid, $coursecontext, $PAGE->url, $return);
1002 if ($return) {
1003 return $returnval;
1008 * Utility class used for return tracking when using edit and other forms in grade plugins
1010 * @package core_grades
1011 * @copyright 2009 Nicolas Connault
1012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1014 class grade_plugin_return {
1016 * Type of grade plugin (e.g. 'edit', 'report')
1018 * @var string
1020 public $type;
1022 * Name of grade plugin (e.g. 'grader', 'overview')
1024 * @var string
1026 public $plugin;
1028 * Course id being viewed
1030 * @var int
1032 public $courseid;
1034 * Id of user whose information is being viewed/edited
1036 * @var int
1038 public $userid;
1040 * Id of group for which information is being viewed/edited
1042 * @var int
1044 public $groupid;
1046 * Current page # within output
1048 * @var int
1050 public $page;
1052 * Search string
1054 * @var string
1056 public $search;
1059 * Constructor
1061 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1063 public function __construct($params = []) {
1064 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1065 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1066 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1067 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1068 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1069 $this->page = optional_param('gpr_page', null, PARAM_INT);
1070 $this->search = optional_param('gpr_search', '', PARAM_NOTAGS);
1072 foreach ($params as $key => $value) {
1073 if (property_exists($this, $key)) {
1074 $this->$key = $value;
1077 // Allow course object rather than id to be used to specify course
1078 // - avoid unnecessary use of get_course.
1079 if (array_key_exists('course', $params)) {
1080 $course = $params['course'];
1081 $this->courseid = $course->id;
1082 } else {
1083 $course = null;
1085 // If group has been explicitly set in constructor parameters,
1086 // we should respect that.
1087 if (!array_key_exists('groupid', $params)) {
1088 // Otherwise, 'group' in request parameters is a request for a change.
1089 // In that case, or if we have no group at all, we should get groupid from
1090 // groups_get_course_group, which will do some housekeeping as well as
1091 // give us the correct value.
1092 $changegroup = optional_param('group', -1, PARAM_INT);
1093 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1094 if ($course === null) {
1095 $course = get_course($this->courseid);
1097 $this->groupid = groups_get_course_group($course, true);
1103 * Old syntax of class constructor. Deprecated in PHP7.
1105 * @deprecated since Moodle 3.1
1107 public function grade_plugin_return($params = null) {
1108 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1109 self::__construct($params);
1113 * Returns return parameters as options array suitable for buttons.
1114 * @return array options
1116 public function get_options() {
1117 if (empty($this->type)) {
1118 return array();
1121 $params = array();
1123 if (!empty($this->plugin)) {
1124 $params['plugin'] = $this->plugin;
1127 if (!empty($this->courseid)) {
1128 $params['id'] = $this->courseid;
1131 if (!empty($this->userid)) {
1132 $params['userid'] = $this->userid;
1135 if (!empty($this->groupid)) {
1136 $params['group'] = $this->groupid;
1139 if (!empty($this->page)) {
1140 $params['page'] = $this->page;
1143 return $params;
1147 * Returns return url
1149 * @param string $default default url when params not set
1150 * @param array $extras Extra URL parameters
1152 * @return string url
1154 public function get_return_url($default, $extras=null) {
1155 global $CFG;
1157 if (empty($this->type) or empty($this->plugin)) {
1158 return $default;
1161 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1162 $glue = '?';
1164 if (!empty($this->courseid)) {
1165 $url .= $glue.'id='.$this->courseid;
1166 $glue = '&amp;';
1169 if (!empty($this->userid)) {
1170 $url .= $glue.'userid='.$this->userid;
1171 $glue = '&amp;';
1174 if (!empty($this->groupid)) {
1175 $url .= $glue.'group='.$this->groupid;
1176 $glue = '&amp;';
1179 if (!empty($this->page)) {
1180 $url .= $glue.'page='.$this->page;
1181 $glue = '&amp;';
1184 if (!empty($extras)) {
1185 foreach ($extras as $key=>$value) {
1186 $url .= $glue.$key.'='.$value;
1187 $glue = '&amp;';
1191 return $url;
1195 * Returns string with hidden return tracking form elements.
1196 * @return string
1198 public function get_form_fields() {
1199 if (empty($this->type)) {
1200 return '';
1203 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1205 if (!empty($this->plugin)) {
1206 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1209 if (!empty($this->courseid)) {
1210 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1213 if (!empty($this->userid)) {
1214 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1217 if (!empty($this->groupid)) {
1218 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1221 if (!empty($this->page)) {
1222 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1225 if (!empty($this->search)) {
1226 $result .= html_writer::empty_tag('input',
1227 ['type' => 'hidden', 'name' => 'gpr_search', 'value' => $this->search]);
1230 return $result;
1234 * Add hidden elements into mform
1236 * @param object &$mform moodle form object
1238 * @return void
1240 public function add_mform_elements(&$mform) {
1241 if (empty($this->type)) {
1242 return;
1245 $mform->addElement('hidden', 'gpr_type', $this->type);
1246 $mform->setType('gpr_type', PARAM_SAFEDIR);
1248 if (!empty($this->plugin)) {
1249 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1250 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1253 if (!empty($this->courseid)) {
1254 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1255 $mform->setType('gpr_courseid', PARAM_INT);
1258 if (!empty($this->userid)) {
1259 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1260 $mform->setType('gpr_userid', PARAM_INT);
1263 if (!empty($this->groupid)) {
1264 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1265 $mform->setType('gpr_groupid', PARAM_INT);
1268 if (!empty($this->page)) {
1269 $mform->addElement('hidden', 'gpr_page', $this->page);
1270 $mform->setType('gpr_page', PARAM_INT);
1275 * Add return tracking params into url
1277 * @param moodle_url $url A URL
1278 * @return moodle_url with return tracking params
1280 public function add_url_params(moodle_url $url): moodle_url {
1281 if (empty($this->type)) {
1282 return $url;
1285 $url->param('gpr_type', $this->type);
1287 if (!empty($this->plugin)) {
1288 $url->param('gpr_plugin', $this->plugin);
1291 if (!empty($this->courseid)) {
1292 $url->param('gpr_courseid' ,$this->courseid);
1295 if (!empty($this->userid)) {
1296 $url->param('gpr_userid', $this->userid);
1299 if (!empty($this->groupid)) {
1300 $url->param('gpr_groupid', $this->groupid);
1303 if (!empty($this->page)) {
1304 $url->param('gpr_page', $this->page);
1307 return $url;
1312 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1314 * @param string $path The path of the calling script (using __FILE__?)
1315 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1316 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1317 * an array of keys and values (e.g courseid => $courseid, itemid...)
1319 * @return string
1321 function grade_build_nav($path, $pagename=null, $id=null) {
1322 global $CFG, $COURSE, $PAGE;
1324 $strgrades = get_string('grades', 'grades');
1326 // Parse the path and build navlinks from its elements
1327 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1328 $path = substr($path, $dirroot_length);
1329 $path = str_replace('\\', '/', $path);
1331 $path_elements = explode('/', $path);
1333 $path_elements_count = count($path_elements);
1335 // First link is always 'grade'
1336 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1338 $link = null;
1339 $numberofelements = 3;
1341 // Prepare URL params string
1342 $linkparams = array();
1343 if (!is_null($id)) {
1344 if (is_array($id)) {
1345 foreach ($id as $idkey => $idvalue) {
1346 $linkparams[$idkey] = $idvalue;
1348 } else {
1349 $linkparams['id'] = $id;
1353 $navlink4 = null;
1355 // Remove file extensions from filenames
1356 foreach ($path_elements as $key => $filename) {
1357 $path_elements[$key] = str_replace('.php', '', $filename);
1360 // Second level links
1361 switch ($path_elements[1]) {
1362 case 'edit': // No link
1363 if ($path_elements[3] != 'index.php') {
1364 $numberofelements = 4;
1366 break;
1367 case 'import': // No link
1368 break;
1369 case 'export': // No link
1370 break;
1371 case 'report':
1372 // $id is required for this link. Do not print it if $id isn't given
1373 if (!is_null($id)) {
1374 $link = new moodle_url('/grade/report/index.php', $linkparams);
1377 if ($path_elements[2] == 'grader') {
1378 $numberofelements = 4;
1380 break;
1382 default:
1383 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1384 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1385 " as the second path element after 'grade'.");
1386 return false;
1388 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1390 // Third level links
1391 if (empty($pagename)) {
1392 $pagename = get_string($path_elements[2], 'grades');
1395 switch ($numberofelements) {
1396 case 3:
1397 $PAGE->navbar->add($pagename, $link);
1398 break;
1399 case 4:
1400 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1401 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1403 $PAGE->navbar->add($pagename);
1404 break;
1407 return '';
1411 * General structure representing grade items in course
1413 * @package core_grades
1414 * @copyright 2009 Nicolas Connault
1415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1417 class grade_structure {
1418 public $context;
1420 public $courseid;
1423 * Reference to modinfo for current course (for performance, to save
1424 * retrieving it from courseid every time). Not actually set except for
1425 * the grade_tree type.
1426 * @var course_modinfo
1428 public $modinfo;
1431 * 1D array of grade items only
1433 public $items;
1436 * Returns icon of element
1438 * @param array &$element An array representing an element in the grade_tree
1439 * @param bool $spacerifnone return spacer if no icon found
1441 * @return string icon or spacer
1442 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_icon()}
1443 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1445 public function get_element_icon(&$element, $spacerifnone=false) {
1446 debugging('The function get_element_icon() is deprecated, please use grade_helper::get_element_icon() instead.',
1447 DEBUG_DEVELOPER);
1448 return grade_helper::get_element_icon($element, $spacerifnone);
1452 * Returns the string that describes the type of the element.
1454 * @param array $element An array representing an element in the grade_tree
1455 * @return string The string that describes the type of the grade element
1456 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_type_string()}
1457 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1459 public function get_element_type_string(array $element): string {
1460 debugging('The function get_element_type_string() is deprecated,' .
1461 ' please use grade_helper::get_element_type_string() instead.',
1462 DEBUG_DEVELOPER);
1463 return grade_helper::get_element_type_string($element);
1467 * Returns name of element optionally with icon and link
1469 * @param array &$element An array representing an element in the grade_tree
1470 * @param bool $withlink Whether or not this header has a link
1471 * @param bool $icon Whether or not to display an icon with this header
1472 * @param bool $spacerifnone return spacer if no icon found
1473 * @param bool $withdescription Show description if defined by this item.
1474 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1475 * instead of "Category total" or "Course total"
1476 * @param moodle_url|null $sortlink Link to sort column.
1478 * @return string header
1479 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_header()}
1480 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1482 public function get_element_header(array &$element, bool $withlink = false, bool $icon = true,
1483 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
1484 ?moodle_url $sortlink = null) {
1485 debugging('The function get_element_header() is deprecated, please use grade_helper::get_element_header() instead.',
1486 DEBUG_DEVELOPER);
1487 return grade_helper::get_element_header($element, $withlink, $icon, $spacerifnone, $withdescription,
1488 $fulltotal, $sortlink);
1492 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_activity_link()}
1493 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1495 private function get_activity_link($element) {
1496 debugging('The function get_activity_link() is deprecated, please use grade_helper::get_activity_link() instead.',
1497 DEBUG_DEVELOPER);
1498 return grade_helper::get_activity_link($element);
1502 * Returns URL of a page that is supposed to contain detailed grade analysis
1504 * At the moment, only activity modules are supported. The method generates link
1505 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1506 * gradeid and userid. If the grade.php does not exist, null is returned.
1508 * @return moodle_url|null URL or null if unable to construct it
1510 public function get_grade_analysis_url(grade_grade $grade) {
1511 global $CFG;
1512 /** @var array static cache of the grade.php file existence flags */
1513 static $hasgradephp = array();
1515 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1516 throw new coding_exception('Passed grade without the associated grade item');
1518 $item = $grade->grade_item;
1520 if (!$item->is_external_item()) {
1521 // at the moment, only activity modules are supported
1522 return null;
1524 if ($item->itemtype !== 'mod') {
1525 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1527 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1528 return null;
1531 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1532 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1533 $hasgradephp[$item->itemmodule] = true;
1534 } else {
1535 $hasgradephp[$item->itemmodule] = false;
1539 if (!$hasgradephp[$item->itemmodule]) {
1540 return null;
1543 $instances = $this->modinfo->get_instances();
1544 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1545 return null;
1547 $cm = $instances[$item->itemmodule][$item->iteminstance];
1548 if (!$cm->uservisible) {
1549 return null;
1552 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1553 'id' => $cm->id,
1554 'itemid' => $item->id,
1555 'itemnumber' => $item->itemnumber,
1556 'gradeid' => $grade->id,
1557 'userid' => $grade->userid,
1560 return $url;
1564 * Returns an action icon leading to the grade analysis page
1566 * @param grade_grade $grade
1567 * @return string
1568 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1569 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1571 public function get_grade_analysis_icon(grade_grade $grade) {
1572 global $OUTPUT;
1573 debugging('The function get_grade_analysis_icon() is deprecated, please do not use it anymore.',
1574 DEBUG_DEVELOPER);
1576 $url = $this->get_grade_analysis_url($grade);
1577 if (is_null($url)) {
1578 return '';
1581 $title = get_string('gradeanalysis', 'core_grades');
1582 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1583 ['title' => $title, 'aria-label' => $title]);
1587 * Returns a link leading to the grade analysis page
1589 * @param grade_grade $grade
1590 * @return string|null
1592 public function get_grade_analysis_link(grade_grade $grade): ?string {
1593 $url = $this->get_grade_analysis_url($grade);
1594 if (is_null($url)) {
1595 return null;
1598 $gradeanalysisstring = get_string('gradeanalysis', 'grades');
1599 return html_writer::link($url, $gradeanalysisstring,
1600 ['class' => 'dropdown-item', 'aria-label' => $gradeanalysisstring, 'role' => 'menuitem']);
1604 * Returns an action menu for the grade.
1606 * @param grade_grade $grade A grade_grade object
1607 * @return string
1609 public function get_grade_action_menu(grade_grade $grade) : string {
1610 global $OUTPUT;
1612 $menuitems = [];
1614 $url = $this->get_grade_analysis_url($grade);
1615 if ($url) {
1616 $title = get_string('gradeanalysis', 'core_grades');
1617 $menuitems[] = new action_menu_link_secondary($url, null, $title);
1620 if ($menuitems) {
1621 $menu = new action_menu($menuitems);
1622 $icon = $OUTPUT->pix_icon('i/moremenu', get_string('actions'));
1623 $extraclasses = 'btn btn-link btn-icon icon-size-3 d-flex align-items-center justify-content-center';
1624 $menu->set_menu_trigger($icon, $extraclasses);
1625 $menu->set_menu_left();
1627 return $OUTPUT->render($menu);
1628 } else {
1629 return '';
1634 * Returns the grade eid - the grade may not exist yet.
1636 * @param grade_grade $grade_grade A grade_grade object
1638 * @return string eid
1640 public function get_grade_eid($grade_grade) {
1641 if (empty($grade_grade->id)) {
1642 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1643 } else {
1644 return 'g'.$grade_grade->id;
1649 * Returns the grade_item eid
1650 * @param grade_item $grade_item A grade_item object
1651 * @return string eid
1653 public function get_item_eid($grade_item) {
1654 return 'ig'.$grade_item->id;
1658 * Given a grade_tree element, returns an array of parameters
1659 * used to build an icon for that element.
1661 * @param array $element An array representing an element in the grade_tree
1663 * @return array
1665 public function get_params_for_iconstr($element) {
1666 $strparams = new stdClass();
1667 $strparams->category = '';
1668 $strparams->itemname = '';
1669 $strparams->itemmodule = '';
1671 if (!method_exists($element['object'], 'get_name')) {
1672 return $strparams;
1675 $strparams->itemname = html_to_text($element['object']->get_name());
1677 // If element name is categorytotal, get the name of the parent category
1678 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1679 $parent = $element['object']->get_parent_category();
1680 $strparams->category = $parent->get_name() . ' ';
1681 } else {
1682 $strparams->category = '';
1685 $strparams->itemmodule = null;
1686 if (isset($element['object']->itemmodule)) {
1687 $strparams->itemmodule = $element['object']->itemmodule;
1689 return $strparams;
1693 * Return a reset icon for the given element.
1695 * @param array $element An array representing an element in the grade_tree
1696 * @param object $gpr A grade_plugin_return object
1697 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1698 * @return string|action_menu_link
1699 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1700 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1702 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1703 global $CFG, $OUTPUT;
1704 debugging('The function get_reset_icon() is deprecated, please do not use it anymore.',
1705 DEBUG_DEVELOPER);
1707 // Limit to category items set to use the natural weights aggregation method, and users
1708 // with the capability to manage grades.
1709 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1710 !has_capability('moodle/grade:manage', $this->context)) {
1711 return $returnactionmenulink ? null : '';
1714 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1715 $url = new moodle_url('/grade/edit/tree/action.php', array(
1716 'id' => $this->courseid,
1717 'action' => 'resetweights',
1718 'eid' => $element['eid'],
1719 'sesskey' => sesskey(),
1722 if ($returnactionmenulink) {
1723 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1724 get_string('resetweightsshort', 'grades'));
1725 } else {
1726 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1731 * Returns a link to reset weights for the given element.
1733 * @param array $element An array representing an element in the grade_tree
1734 * @param object $gpr A grade_plugin_return object
1735 * @return string|null
1737 public function get_reset_weights_link(array $element, object $gpr): ?string {
1739 // Limit to category items set to use the natural weights aggregation method, and users
1740 // with the capability to manage grades.
1741 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1742 !has_capability('moodle/grade:manage', $this->context)) {
1743 return null;
1746 $title = get_string('resetweightsshort', 'grades');
1747 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1748 $url = new moodle_url('/grade/edit/tree/action.php', [
1749 'id' => $this->courseid,
1750 'action' => 'resetweights',
1751 'eid' => $element['eid'],
1752 'sesskey' => sesskey(),
1754 $gpr->add_url_params($url);
1755 return html_writer::link($url, $title,
1756 ['class' => 'dropdown-item', 'aria-label' => $str, 'role' => 'menuitem']);
1760 * Returns a link to delete a given element.
1762 * @param array $element An array representing an element in the grade_tree
1763 * @param object $gpr A grade_plugin_return object
1764 * @return string|null
1766 public function get_delete_link(array $element, object $gpr): ?string {
1767 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1768 if (grade_edit_tree::element_deletable($element)) {
1769 $deleteconfirmationurl = new moodle_url('index.php', [
1770 'id' => $this->courseid,
1771 'action' => 'delete',
1772 'confirm' => 1,
1773 'eid' => $element['eid'],
1774 'sesskey' => sesskey(),
1776 $gpr->add_url_params($deleteconfirmationurl);
1777 $title = get_string('delete');
1778 return html_writer::link(
1780 $title,
1782 'class' => 'dropdown-item',
1783 'aria-label' => $title,
1784 'role' => 'menuitem',
1785 'data-modal' => 'confirmation',
1786 'data-modal-title-str' => json_encode(['confirm', 'core']),
1787 'data-modal-content-str' => json_encode([
1788 'deletecheck',
1790 $element['object']->get_name()
1792 'data-modal-yes-button-str' => json_encode(['delete', 'core']),
1793 'data-modal-destination' => $deleteconfirmationurl->out(false),
1798 return null;
1802 * Returns a link to duplicate a given element.
1804 * @param array $element An array representing an element in the grade_tree
1805 * @param object $gpr A grade_plugin_return object
1806 * @return string|null
1808 public function get_duplicate_link(array $element, object $gpr): ?string {
1809 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1810 if (grade_edit_tree::element_duplicatable($element)) {
1811 $duplicateparams = [];
1812 $duplicateparams['id'] = $this->courseid;
1813 $duplicateparams['action'] = 'duplicate';
1814 $duplicateparams['eid'] = $element['eid'];
1815 $duplicateparams['sesskey'] = sesskey();
1816 $url = new moodle_url('index.php', $duplicateparams);
1817 $title = get_string('duplicate');
1818 $gpr->add_url_params($url);
1819 return html_writer::link($url, $title,
1820 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1823 return null;
1827 * Return edit icon for give element
1829 * @param array $element An array representing an element in the grade_tree
1830 * @param object $gpr A grade_plugin_return object
1831 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1832 * @return string|action_menu_link
1833 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1834 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1836 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1837 global $CFG, $OUTPUT;
1839 debugging('The function get_edit_icon() is deprecated, please do not use it anymore.',
1840 DEBUG_DEVELOPER);
1842 if (!has_capability('moodle/grade:manage', $this->context)) {
1843 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1844 // oki - let them override grade
1845 } else {
1846 return $returnactionmenulink ? null : '';
1850 static $strfeedback = null;
1851 static $streditgrade = null;
1852 if (is_null($streditgrade)) {
1853 $streditgrade = get_string('editgrade', 'grades');
1854 $strfeedback = get_string('feedback');
1857 $strparams = $this->get_params_for_iconstr($element);
1859 $object = $element['object'];
1861 switch ($element['type']) {
1862 case 'item':
1863 case 'categoryitem':
1864 case 'courseitem':
1865 $stredit = get_string('editverbose', 'grades', $strparams);
1866 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1867 $url = new moodle_url('/grade/edit/tree/item.php',
1868 array('courseid' => $this->courseid, 'id' => $object->id));
1869 } else {
1870 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1871 array('courseid' => $this->courseid, 'id' => $object->id));
1873 break;
1875 case 'category':
1876 $stredit = get_string('editverbose', 'grades', $strparams);
1877 $url = new moodle_url('/grade/edit/tree/category.php',
1878 array('courseid' => $this->courseid, 'id' => $object->id));
1879 break;
1881 case 'grade':
1882 $stredit = $streditgrade;
1883 if (empty($object->id)) {
1884 $url = new moodle_url('/grade/edit/tree/grade.php',
1885 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1886 } else {
1887 $url = new moodle_url('/grade/edit/tree/grade.php',
1888 array('courseid' => $this->courseid, 'id' => $object->id));
1890 if (!empty($object->feedback)) {
1891 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1893 break;
1895 default:
1896 $url = null;
1899 if ($url) {
1900 if ($returnactionmenulink) {
1901 return new action_menu_link_secondary($gpr->add_url_params($url),
1902 new pix_icon('t/edit', $stredit),
1903 get_string('editsettings'));
1904 } else {
1905 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1908 } else {
1909 return $returnactionmenulink ? null : '';
1914 * Returns a link leading to the edit grade/grade item/category page
1916 * @param array $element An array representing an element in the grade_tree
1917 * @param object $gpr A grade_plugin_return object
1918 * @return string|null
1920 public function get_edit_link(array $element, object $gpr): ?string {
1921 global $CFG;
1923 $url = null;
1924 $title = '';
1925 if ((!has_capability('moodle/grade:manage', $this->context) &&
1926 (!($element['type'] == 'grade') || !has_capability('moodle/grade:edit', $this->context)))) {
1927 return null;
1930 $object = $element['object'];
1932 if ($element['type'] == 'grade') {
1933 if (empty($object->id)) {
1934 $url = new moodle_url('/grade/edit/tree/grade.php',
1935 ['courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid]);
1936 } else {
1937 $url = new moodle_url('/grade/edit/tree/grade.php',
1938 ['courseid' => $this->courseid, 'id' => $object->id]);
1940 $url = $gpr->add_url_params($url);
1941 $title = get_string('editgrade', 'grades');
1942 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
1943 ($element['type'] == 'courseitem')) {
1944 $url = new moodle_url('#');
1945 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1946 return html_writer::link($url, get_string('itemsedit', 'grades'), [
1947 'class' => 'dropdown-item',
1948 'aria-label' => get_string('itemsedit', 'grades'),
1949 'role' => 'menuitem',
1950 'data-gprplugin' => $gpr->plugin,
1951 'data-courseid' => $this->courseid,
1952 'data-itemid' => $object->id, 'data-trigger' => 'add-item-form'
1954 } else if (count(grade_outcome::fetch_all_available($this->courseid)) > 0) {
1955 return html_writer::link($url, get_string('itemsedit', 'grades'), [
1956 'class' => 'dropdown-item',
1957 get_string('itemsedit', 'grades'),
1958 'role' => 'menuitem',
1959 'data-gprplugin' => $gpr->plugin,
1960 'data-courseid' => $this->courseid,
1961 'data-itemid' => $object->id, 'data-trigger' => 'add-outcome-form'
1964 } else if ($element['type'] == 'category') {
1965 $url = new moodle_url('#');
1966 $title = get_string('categoryedit', 'grades');
1967 return html_writer::link($url, $title, [
1968 'class' => 'dropdown-item',
1969 'aria-label' => $title,
1970 'role' => 'menuitem',
1971 'data-gprplugin' => $gpr->plugin,
1972 'data-courseid' => $this->courseid,
1973 'data-category' => $object->id,
1974 'data-trigger' => 'add-category-form'
1977 return html_writer::link($url, $title,
1978 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1982 * Returns link to the advanced grading page
1984 * @param array $element An array representing an element in the grade_tree
1985 * @param object $gpr A grade_plugin_return object
1986 * @return string|null
1988 public function get_advanced_grading_link(array $element, object $gpr): ?string {
1989 global $CFG;
1991 /** @var array static cache of the grade.php file existence flags */
1992 static $hasgradephp = [];
1994 $itemtype = $element['object']->itemtype;
1995 $itemmodule = $element['object']->itemmodule;
1996 $iteminstance = $element['object']->iteminstance;
1997 $itemnumber = $element['object']->itemnumber;
1999 // Links only for module items that have valid instance, module and are
2000 // called from grade_tree with valid modinfo.
2001 if ($itemtype == 'mod' && $iteminstance && $itemmodule && $this->modinfo) {
2003 // Get $cm efficiently and with visibility information using modinfo.
2004 $instances = $this->modinfo->get_instances();
2005 if (!empty($instances[$itemmodule][$iteminstance])) {
2006 $cm = $instances[$itemmodule][$iteminstance];
2008 // Do not add link if activity is not visible to the current user.
2009 if ($cm->uservisible) {
2010 if (!array_key_exists($itemmodule, $hasgradephp)) {
2011 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
2012 $hasgradephp[$itemmodule] = true;
2013 } else {
2014 $hasgradephp[$itemmodule] = false;
2018 // If module has grade.php, add link to that.
2019 if ($hasgradephp[$itemmodule]) {
2020 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
2021 if (isset($element['userid'])) {
2022 $args['userid'] = $element['userid'];
2025 $url = new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
2026 $title = get_string('advancedgrading', 'gradereport_grader', $itemmodule);
2027 $gpr->add_url_params($url);
2028 return html_writer::link($url, $title,
2029 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2035 return null;
2039 * Return hiding icon for give element
2041 * @param array $element An array representing an element in the grade_tree
2042 * @param object $gpr A grade_plugin_return object
2043 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2044 * @return string|action_menu_link
2045 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2046 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2048 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
2049 global $CFG, $OUTPUT;
2050 debugging('The function get_hiding_icon() is deprecated, please do not use it anymore.',
2051 DEBUG_DEVELOPER);
2053 if (!$element['object']->can_control_visibility()) {
2054 return $returnactionmenulink ? null : '';
2057 if (!has_capability('moodle/grade:manage', $this->context) and
2058 !has_capability('moodle/grade:hide', $this->context)) {
2059 return $returnactionmenulink ? null : '';
2062 $strparams = $this->get_params_for_iconstr($element);
2063 $strshow = get_string('showverbose', 'grades', $strparams);
2064 $strhide = get_string('hideverbose', 'grades', $strparams);
2066 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2067 $url = $gpr->add_url_params($url);
2069 if ($element['object']->is_hidden()) {
2070 $type = 'show';
2071 $tooltip = $strshow;
2073 // Change the icon and add a tooltip showing the date
2074 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2075 $type = 'hiddenuntil';
2076 $tooltip = get_string('hiddenuntildate', 'grades',
2077 userdate($element['object']->get_hidden()));
2080 $url->param('action', 'show');
2082 if ($returnactionmenulink) {
2083 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2084 } else {
2085 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2088 } else {
2089 $url->param('action', 'hide');
2090 if ($returnactionmenulink) {
2091 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2092 } else {
2093 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2097 return $hideicon;
2101 * Returns a link with url to hide/unhide grade/grade item/grade category
2103 * @param array $element An array representing an element in the grade_tree
2104 * @param object $gpr A grade_plugin_return object
2105 * @return string|null
2107 public function get_hiding_link(array $element, object $gpr): ?string {
2108 if (!$element['object']->can_control_visibility() || !has_capability('moodle/grade:manage', $this->context) ||
2109 !has_capability('moodle/grade:hide', $this->context)) {
2110 return null;
2113 $url = new moodle_url('/grade/edit/tree/action.php',
2114 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2115 $url = $gpr->add_url_params($url);
2117 if ($element['object']->is_hidden()) {
2118 $url->param('action', 'show');
2119 $title = get_string('show');
2120 } else {
2121 $url->param('action', 'hide');
2122 $title = get_string('hide');
2125 $url = html_writer::link($url, $title,
2126 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2128 if ($element['type'] == 'grade') {
2129 $item = $element['object']->grade_item;
2130 if ($item->hidden) {
2131 $strparamobj = new stdClass();
2132 $strparamobj->itemname = $item->get_name(true, true);
2133 $strnonunhideable = get_string('nonunhideableverbose', 'grades', $strparamobj);
2134 $url = html_writer::span($title, 'text-muted dropdown-item',
2135 ['title' => $strnonunhideable, 'aria-label' => $title, 'role' => 'menuitem']);
2139 return $url;
2143 * Return locking icon for given element
2145 * @param array $element An array representing an element in the grade_tree
2146 * @param object $gpr A grade_plugin_return object
2148 * @return string
2149 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2150 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2152 public function get_locking_icon($element, $gpr) {
2153 global $CFG, $OUTPUT;
2154 debugging('The function get_locking_icon() is deprecated, please do not use it anymore.',
2155 DEBUG_DEVELOPER);
2157 $strparams = $this->get_params_for_iconstr($element);
2158 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2159 $strlock = get_string('lockverbose', 'grades', $strparams);
2161 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2162 $url = $gpr->add_url_params($url);
2164 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2165 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
2166 $strparamobj = new stdClass();
2167 $strparamobj->itemname = $element['object']->grade_item->itemname;
2168 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2170 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2171 array('class' => 'action-icon'));
2173 } else if ($element['object']->is_locked()) {
2174 $type = 'unlock';
2175 $tooltip = $strunlock;
2177 // Change the icon and add a tooltip showing the date
2178 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2179 $type = 'locktime';
2180 $tooltip = get_string('locktimedate', 'grades',
2181 userdate($element['object']->get_locktime()));
2184 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
2185 $action = '';
2186 } else {
2187 $url->param('action', 'unlock');
2188 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2191 } else {
2192 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
2193 $action = '';
2194 } else {
2195 $url->param('action', 'lock');
2196 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2200 return $action;
2204 * Returns link to lock/unlock grade/grade item/grade category
2206 * @param array $element An array representing an element in the grade_tree
2207 * @param object $gpr A grade_plugin_return object
2209 * @return string|null
2211 public function get_locking_link(array $element, object $gpr): ?string {
2213 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2214 $title = '';
2215 $url = new moodle_url('/grade/edit/tree/action.php',
2216 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2217 $url = $gpr->add_url_params($url);
2219 if ($element['type'] == 'category') {
2220 // Grade categories themselves cannot be locked. We lock/unlock their grade items.
2221 $children = $element['object']->get_children(true);
2222 $alllocked = true;
2223 foreach ($children as $child) {
2224 if (!$child['object']->is_locked()) {
2225 $alllocked = false;
2226 break;
2229 if ($alllocked && has_capability('moodle/grade:unlock', $this->context)) {
2230 $title = get_string('unlock', 'grades');
2231 $url->param('action', 'unlock');
2232 } else if (!$alllocked && has_capability('moodle/grade:lock', $this->context)) {
2233 $title = get_string('lock', 'grades');
2234 $url->param('action', 'lock');
2235 } else {
2236 return null;
2238 } else if (($element['type'] == 'grade') && ($element['object']->grade_item->is_locked())) {
2239 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon.
2240 $strparamobj = new stdClass();
2241 $strparamobj->itemname = $element['object']->grade_item->get_name(true, true);
2242 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2243 $title = get_string('unlock', 'grades');
2244 return html_writer::span($title, 'text-muted dropdown-item', ['title' => $strnonunlockable,
2245 'aria-label' => $title, 'role' => 'menuitem']);
2246 } else if ($element['object']->is_locked()) {
2247 if (has_capability('moodle/grade:unlock', $this->context)) {
2248 $title = get_string('unlock', 'grades');
2249 $url->param('action', 'unlock');
2250 } else {
2251 return null;
2253 } else {
2254 if (has_capability('moodle/grade:lock', $this->context)) {
2255 $title = get_string('lock', 'grades');
2256 $url->param('action', 'lock');
2257 } else {
2258 return null;
2262 return html_writer::link($url, $title,
2263 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2264 } else {
2265 return null;
2270 * Return calculation icon for given element
2272 * @param array $element An array representing an element in the grade_tree
2273 * @param object $gpr A grade_plugin_return object
2274 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2275 * @return string|action_menu_link
2276 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2277 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2279 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2280 global $CFG, $OUTPUT;
2281 debugging('The function get_calculation_icon() is deprecated, please do not use it anymore.',
2282 DEBUG_DEVELOPER);
2284 if (!has_capability('moodle/grade:manage', $this->context)) {
2285 return $returnactionmenulink ? null : '';
2288 $type = $element['type'];
2289 $object = $element['object'];
2291 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2292 $strparams = $this->get_params_for_iconstr($element);
2293 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2295 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2296 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2298 // show calculation icon only when calculation possible
2299 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2300 if ($object->is_calculated()) {
2301 $icon = 't/calc';
2302 } else {
2303 $icon = 't/calc_off';
2306 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2307 $url = $gpr->add_url_params($url);
2308 if ($returnactionmenulink) {
2309 return new action_menu_link_secondary($url,
2310 new pix_icon($icon, $streditcalculation),
2311 get_string('editcalculation', 'grades'));
2312 } else {
2313 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2318 return $returnactionmenulink ? null : '';
2322 * Returns link to edit calculation for a grade item.
2324 * @param array $element An array representing an element in the grade_tree
2325 * @param object $gpr A grade_plugin_return object
2327 * @return string|null
2329 public function get_edit_calculation_link(array $element, object $gpr): ?string {
2331 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2332 $object = $element['object'];
2333 $isscale = $object->gradetype == GRADE_TYPE_SCALE;
2334 $isvalue = $object->gradetype == GRADE_TYPE_VALUE;
2336 // Show calculation icon only when calculation possible.
2337 if (!$object->is_external_item() && ($isscale || $isvalue)) {
2338 $editcalculationstring = get_string('editcalculation', 'grades');
2339 $url = new moodle_url('/grade/edit/tree/calculation.php',
2340 ['courseid' => $this->courseid, 'id' => $object->id]);
2341 $url = $gpr->add_url_params($url);
2342 return html_writer::link($url, $editcalculationstring,
2343 ['class' => 'dropdown-item', 'aria-label' => $editcalculationstring, 'role' => 'menuitem']);
2346 return null;
2350 * Sets status icons for the grade.
2352 * @param array $element array with grade item info
2353 * @return string|null status icons container HTML
2355 public function set_grade_status_icons(array $element): ?string {
2356 global $OUTPUT;
2358 $context = [
2359 'hidden' => $element['object']->is_hidden(),
2362 if ($element['object'] instanceof grade_grade) {
2363 $grade = $element['object'];
2364 $context['overridden'] = $grade->is_overridden();
2365 $context['excluded'] = $grade->is_excluded();
2366 $context['feedback'] = !empty($grade->feedback) && $grade->load_grade_item()->gradetype != GRADE_TYPE_TEXT;
2369 $context['classes'] = 'grade_icons data-collapse_gradeicons';
2371 if ($element['object'] instanceof grade_category) {
2372 $context['classes'] = 'category_grade_icons';
2374 $children = $element['object']->get_children(true);
2375 $alllocked = true;
2376 foreach ($children as $child) {
2377 if (!$child['object']->is_locked()) {
2378 $alllocked = false;
2379 break;
2382 if ($alllocked) {
2383 $context['locked'] = true;
2385 } else {
2386 $context['locked'] = $element['object']->is_locked();
2389 // Don't even attempt rendering if there is no status to show.
2390 if (in_array(true, $context)) {
2391 return $OUTPUT->render_from_template('core_grades/status_icons', $context);
2392 } else {
2393 return null;
2398 * Returns an action menu for the grade.
2400 * @param array $element Array with cell info.
2401 * @param string $mode Mode - gradeitem or user
2402 * @param grade_plugin_return $gpr
2403 * @param moodle_url|null $baseurl
2404 * @return string
2406 public function get_cell_action_menu(array $element, string $mode, grade_plugin_return $gpr,
2407 ?moodle_url $baseurl = null): string {
2408 global $OUTPUT, $USER;
2410 $context = new stdClass();
2412 if ($mode == 'gradeitem' || $mode == 'setup') {
2413 $editable = true;
2415 if ($element['type'] == 'grade') {
2416 $context->datatype = 'grade';
2418 $item = $element['object']->grade_item;
2419 if ($item->is_course_item() || $item->is_category_item()) {
2420 $editable = (bool)get_config('moodle', 'grade_overridecat');;
2423 if (!empty($USER->editing)) {
2424 if ($editable) {
2425 $context->editurl = $this->get_edit_link($element, $gpr);
2427 $context->hideurl = $this->get_hiding_link($element, $gpr);
2428 $context->lockurl = $this->get_locking_link($element, $gpr);
2431 $context->gradeanalysisurl = $this->get_grade_analysis_link($element['object']);
2432 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
2433 ($element['type'] == 'courseitem') || ($element['type'] == 'userfield')) {
2435 $context->datatype = 'item';
2437 if ($element['type'] == 'item') {
2438 if ($mode == 'setup') {
2439 $context->deleteurl = $this->get_delete_link($element, $gpr);
2440 $context->duplicateurl = $this->get_duplicate_link($element, $gpr);
2441 } else {
2442 $context =
2443 grade_report::get_additional_context($this->context, $this->courseid,
2444 $element, $gpr, $mode, $context, true);
2445 $context->advancedgradingurl = $this->get_advanced_grading_link($element, $gpr);
2447 $context->divider1 = true;
2450 if (($element['type'] == 'item') ||
2451 (($element['type'] == 'userfield') && ($element['name'] !== 'fullname'))) {
2452 $context->divider2 = true;
2455 if (!empty($USER->editing) || $mode == 'setup') {
2456 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2457 $context->divider2 = true;
2458 } else if (($mode !== 'setup') && ($element['type'] !== 'userfield')) {
2459 $context->divider1 = true;
2460 $context->divider2 = true;
2463 if ($element['type'] == 'item') {
2464 $context->editurl = $this->get_edit_link($element, $gpr);
2467 $context->editcalculationurl =
2468 $this->get_edit_calculation_link($element, $gpr);
2470 if (isset($element['object'])) {
2471 $object = $element['object'];
2472 if ($object->itemmodule !== 'quiz') {
2473 $context->hideurl = $this->get_hiding_link($element, $gpr);
2476 $context->lockurl = $this->get_locking_link($element, $gpr);
2479 // Sorting item.
2480 if ($baseurl) {
2481 $sortlink = clone($baseurl);
2482 if (isset($element['object']->id)) {
2483 $sortlink->param('sortitemid', $element['object']->id);
2484 } else if ($element['type'] == 'userfield') {
2485 $context->datatype = $element['name'];
2486 $sortlink->param('sortitemid', $element['name']);
2489 if (($element['type'] == 'userfield') && ($element['name'] == 'fullname')) {
2490 $sortlink->param('sortitemid', 'firstname');
2491 $context->ascendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr);
2492 $context->descendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2494 $sortlink->param('sortitemid', 'lastname');
2495 $context->ascendinglastnameurl = $this->get_sorting_link($sortlink, $gpr);
2496 $context->descendinglastnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2497 } else {
2498 $context->ascendingurl = $this->get_sorting_link($sortlink, $gpr);
2499 $context->descendingurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2502 if ($mode !== 'setup') {
2503 $context = grade_report::get_additional_context($this->context, $this->courseid,
2504 $element, $gpr, $mode, $context);
2506 } else if ($element['type'] == 'category') {
2507 $context->datatype = 'category';
2508 if ($mode !== 'setup') {
2509 $mode = 'category';
2510 $context = grade_report::get_additional_context($this->context, $this->courseid,
2511 $element, $gpr, $mode, $context);
2512 } else {
2513 $context->deleteurl = $this->get_delete_link($element, $gpr);
2514 $context->resetweightsurl = $this->get_reset_weights_link($element, $gpr);
2517 if (!empty($USER->editing) || $mode == 'setup') {
2518 if ($mode !== 'setup') {
2519 $context->divider1 = true;
2521 $context->editurl = $this->get_edit_link($element, $gpr);
2522 $context->hideurl = $this->get_hiding_link($element, $gpr);
2523 $context->lockurl = $this->get_locking_link($element, $gpr);
2527 if (isset($element['object'])) {
2528 $context->dataid = $element['object']->id;
2529 } else if ($element['type'] == 'userfield') {
2530 $context->dataid = $element['name'];
2533 if ($element['type'] != 'text' && !empty($element['object']->feedback)) {
2534 $viewfeedbackstring = get_string('viewfeedback', 'grades');
2535 $context->viewfeedbackurl = html_writer::link('#', $viewfeedbackstring, ['class' => 'dropdown-item',
2536 'aria-label' => $viewfeedbackstring, 'role' => 'menuitem', 'data-action' => 'feedback',
2537 'data-courseid' => $this->courseid]);
2539 } else if ($mode == 'user') {
2540 $context->datatype = 'user';
2541 $context = grade_report::get_additional_context($this->context, $this->courseid, $element, $gpr, $mode, $context, true);
2542 $context->dataid = $element['userid'];
2545 // Omit the second divider if there is nothing between it and the first divider.
2546 if (!isset($context->ascendingfirstnameurl) && !isset($context->ascendingurl)) {
2547 $context->divider2 = false;
2550 if ($mode == 'setup') {
2551 $context->databoundary = 'window';
2554 if (!empty($USER->editing) || isset($context->gradeanalysisurl) || isset($context->gradesonlyurl)
2555 || isset($context->aggregatesonlyurl) || isset($context->fullmodeurl) || isset($context->reporturl0)
2556 || isset($context->ascendingfirstnameurl) || isset($context->ascendingurl)
2557 || isset($context->viewfeedbackurl) || ($mode == 'setup')) {
2558 return $OUTPUT->render_from_template('core_grades/cellmenu', $context);
2560 return '';
2564 * Returns link to sort grade item column
2566 * @param moodle_url $sortlink A base link for sorting
2567 * @param object $gpr A grade_plugin_return object
2568 * @param string $direction Direction od sorting
2569 * @return string
2571 public function get_sorting_link(moodle_url $sortlink, object $gpr, string $direction = 'asc'): string {
2573 if ($direction == 'asc') {
2574 $title = get_string('asc');
2575 } else {
2576 $title = get_string('desc');
2579 $sortlink->param('sort', $direction);
2580 $gpr->add_url_params($sortlink);
2581 return html_writer::link($sortlink, $title,
2582 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2588 * Flat structure similar to grade tree.
2590 * @uses grade_structure
2591 * @package core_grades
2592 * @copyright 2009 Nicolas Connault
2593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2595 class grade_seq extends grade_structure {
2598 * 1D array of elements
2600 public $elements;
2603 * Constructor, retrieves and stores array of all grade_category and grade_item
2604 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2606 * @param int $courseid The course id
2607 * @param bool $category_grade_last category grade item is the last child
2608 * @param bool $nooutcomes Whether or not outcomes should be included
2610 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2611 global $USER, $CFG;
2613 $this->courseid = $courseid;
2614 $this->context = context_course::instance($courseid);
2616 // get course grade tree
2617 $top_element = grade_category::fetch_course_tree($courseid, true);
2619 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2621 foreach ($this->elements as $key=>$unused) {
2622 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2627 * Old syntax of class constructor. Deprecated in PHP7.
2629 * @deprecated since Moodle 3.1
2631 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2632 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2633 self::__construct($courseid, $category_grade_last, $nooutcomes);
2637 * Static recursive helper - makes the grade_item for category the last children
2639 * @param array &$element The seed of the recursion
2640 * @param bool $category_grade_last category grade item is the last child
2641 * @param bool $nooutcomes Whether or not outcomes should be included
2643 * @return array
2645 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2646 if (empty($element['children'])) {
2647 return array();
2649 $children = array();
2651 foreach ($element['children'] as $sortorder=>$unused) {
2652 if ($nooutcomes and $element['type'] != 'category' and
2653 $element['children'][$sortorder]['object']->is_outcome_item()) {
2654 continue;
2656 $children[] = $element['children'][$sortorder];
2658 unset($element['children']);
2660 if ($category_grade_last and count($children) > 1 and
2662 $children[0]['type'] === 'courseitem' or
2663 $children[0]['type'] === 'categoryitem'
2666 $cat_item = array_shift($children);
2667 array_push($children, $cat_item);
2670 $result = array();
2671 foreach ($children as $child) {
2672 if ($child['type'] == 'category') {
2673 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2674 } else {
2675 $child['eid'] = 'i'.$child['object']->id;
2676 $result[$child['object']->id] = $child;
2680 return $result;
2684 * Parses the array in search of a given eid and returns a element object with
2685 * information about the element it has found.
2687 * @param int $eid Gradetree Element ID
2689 * @return object element
2691 public function locate_element($eid) {
2692 // it is a grade - construct a new object
2693 if (strpos($eid, 'n') === 0) {
2694 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2695 return null;
2698 $itemid = $matches[1];
2699 $userid = $matches[2];
2701 //extra security check - the grade item must be in this tree
2702 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2703 return null;
2706 // $gradea->id may be null - means does not exist yet
2707 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2709 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2710 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2712 } else if (strpos($eid, 'g') === 0) {
2713 $id = (int) substr($eid, 1);
2714 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2715 return null;
2717 //extra security check - the grade item must be in this tree
2718 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2719 return null;
2721 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2722 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2725 // it is a category or item
2726 foreach ($this->elements as $element) {
2727 if ($element['eid'] == $eid) {
2728 return $element;
2732 return null;
2737 * This class represents a complete tree of categories, grade_items and final grades,
2738 * organises as an array primarily, but which can also be converted to other formats.
2739 * It has simple method calls with complex implementations, allowing for easy insertion,
2740 * deletion and moving of items and categories within the tree.
2742 * @uses grade_structure
2743 * @package core_grades
2744 * @copyright 2009 Nicolas Connault
2745 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2747 class grade_tree extends grade_structure {
2750 * The basic representation of the tree as a hierarchical, 3-tiered array.
2751 * @var object $top_element
2753 public $top_element;
2756 * 2D array of grade items and categories
2757 * @var array $levels
2759 public $levels;
2762 * Grade items
2763 * @var array $items
2765 public $items;
2768 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2769 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2771 * @param int $courseid The Course ID
2772 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2773 * @param bool $category_grade_last category grade item is the last child
2774 * @param array $collapsed array of collapsed categories
2775 * @param bool $nooutcomes Whether or not outcomes should be included
2777 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2778 $collapsed=null, $nooutcomes=false) {
2779 global $USER, $CFG, $COURSE, $DB;
2781 $this->courseid = $courseid;
2782 $this->levels = array();
2783 $this->context = context_course::instance($courseid);
2785 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2786 $course = $COURSE;
2787 } else {
2788 $course = $DB->get_record('course', array('id' => $this->courseid));
2790 $this->modinfo = get_fast_modinfo($course);
2792 // get course grade tree
2793 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2795 // collapse the categories if requested
2796 if (!empty($collapsed)) {
2797 grade_tree::category_collapse($this->top_element, $collapsed);
2800 // no otucomes if requested
2801 if (!empty($nooutcomes)) {
2802 grade_tree::no_outcomes($this->top_element);
2805 // move category item to last position in category
2806 if ($category_grade_last) {
2807 grade_tree::category_grade_last($this->top_element);
2810 if ($fillers) {
2811 // inject fake categories == fillers
2812 grade_tree::inject_fillers($this->top_element, 0);
2813 // add colspans to categories and fillers
2814 grade_tree::inject_colspans($this->top_element);
2817 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2822 * Old syntax of class constructor. Deprecated in PHP7.
2824 * @deprecated since Moodle 3.1
2826 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2827 $collapsed=null, $nooutcomes=false) {
2828 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2829 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2833 * Static recursive helper - removes items from collapsed categories
2835 * @param array &$element The seed of the recursion
2836 * @param array $collapsed array of collapsed categories
2838 * @return void
2840 public function category_collapse(&$element, $collapsed) {
2841 if ($element['type'] != 'category') {
2842 return;
2844 if (empty($element['children']) or count($element['children']) < 2) {
2845 return;
2848 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2849 $category_item = reset($element['children']); //keep only category item
2850 $element['children'] = array(key($element['children'])=>$category_item);
2852 } else {
2853 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2854 reset($element['children']);
2855 $first_key = key($element['children']);
2856 unset($element['children'][$first_key]);
2858 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2859 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2865 * Static recursive helper - removes all outcomes
2867 * @param array &$element The seed of the recursion
2869 * @return void
2871 public function no_outcomes(&$element) {
2872 if ($element['type'] != 'category') {
2873 return;
2875 foreach ($element['children'] as $sortorder=>$child) {
2876 if ($element['children'][$sortorder]['type'] == 'item'
2877 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2878 unset($element['children'][$sortorder]);
2880 } else if ($element['children'][$sortorder]['type'] == 'category') {
2881 grade_tree::no_outcomes($element['children'][$sortorder]);
2887 * Static recursive helper - makes the grade_item for category the last children
2889 * @param array &$element The seed of the recursion
2891 * @return void
2893 public function category_grade_last(&$element) {
2894 if (empty($element['children'])) {
2895 return;
2897 if (count($element['children']) < 2) {
2898 return;
2900 $first_item = reset($element['children']);
2901 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2902 // the category item might have been already removed
2903 $order = key($element['children']);
2904 unset($element['children'][$order]);
2905 $element['children'][$order] =& $first_item;
2907 foreach ($element['children'] as $sortorder => $child) {
2908 grade_tree::category_grade_last($element['children'][$sortorder]);
2913 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2915 * @param array &$levels The levels of the grade tree through which to recurse
2916 * @param array &$element The seed of the recursion
2917 * @param int $depth How deep are we?
2918 * @return void
2920 public function fill_levels(&$levels, &$element, $depth) {
2921 if (!array_key_exists($depth, $levels)) {
2922 $levels[$depth] = array();
2925 // prepare unique identifier
2926 if ($element['type'] == 'category') {
2927 $element['eid'] = 'cg'.$element['object']->id;
2928 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2929 $element['eid'] = 'ig'.$element['object']->id;
2930 $this->items[$element['object']->id] =& $element['object'];
2933 $levels[$depth][] =& $element;
2934 $depth++;
2935 if (empty($element['children'])) {
2936 return;
2938 $prev = 0;
2939 foreach ($element['children'] as $sortorder=>$child) {
2940 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2941 $element['children'][$sortorder]['prev'] = $prev;
2942 $element['children'][$sortorder]['next'] = 0;
2943 if ($prev) {
2944 $element['children'][$prev]['next'] = $sortorder;
2946 $prev = $sortorder;
2951 * Determines whether the grade tree item can be displayed.
2952 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2953 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2954 * can be output.
2956 * @param array $element The grade category element.
2957 * @return bool True if the grade tree item can be displayed. False, otherwise.
2959 public static function can_output_item($element) {
2960 $canoutput = true;
2962 if ($element['type'] === 'category') {
2963 $object = $element['object'];
2964 $category = grade_category::fetch(array('id' => $object->id));
2965 // Category has total, we can output this.
2966 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2967 return true;
2970 // Category has no total and has no children, no need to output this.
2971 if (empty($element['children'])) {
2972 return false;
2975 $canoutput = false;
2976 // Loop over children and make sure at least one child can be output.
2977 foreach ($element['children'] as $child) {
2978 $canoutput = self::can_output_item($child);
2979 if ($canoutput) {
2980 break;
2985 return $canoutput;
2989 * Static recursive helper - makes full tree (all leafes are at the same level)
2991 * @param array &$element The seed of the recursion
2992 * @param int $depth How deep are we?
2994 * @return int
2996 public function inject_fillers(&$element, $depth) {
2997 $depth++;
2999 if (empty($element['children'])) {
3000 return $depth;
3002 $chdepths = array();
3003 $chids = array_keys($element['children']);
3004 $last_child = end($chids);
3005 $first_child = reset($chids);
3007 foreach ($chids as $chid) {
3008 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
3010 arsort($chdepths);
3012 $maxdepth = reset($chdepths);
3013 foreach ($chdepths as $chid=>$chd) {
3014 if ($chd == $maxdepth) {
3015 continue;
3017 if (!self::can_output_item($element['children'][$chid])) {
3018 continue;
3020 for ($i=0; $i < $maxdepth-$chd; $i++) {
3021 if ($chid == $first_child) {
3022 $type = 'fillerfirst';
3023 } else if ($chid == $last_child) {
3024 $type = 'fillerlast';
3025 } else {
3026 $type = 'filler';
3028 $oldchild =& $element['children'][$chid];
3029 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
3030 'eid'=>'', 'depth'=>$element['object']->depth,
3031 'children'=>array($oldchild));
3035 return $maxdepth;
3039 * Static recursive helper - add colspan information into categories
3041 * @param array &$element The seed of the recursion
3043 * @return int
3045 public function inject_colspans(&$element) {
3046 if (empty($element['children'])) {
3047 return 1;
3049 $count = 0;
3050 foreach ($element['children'] as $key=>$child) {
3051 if (!self::can_output_item($child)) {
3052 continue;
3054 $count += grade_tree::inject_colspans($element['children'][$key]);
3056 $element['colspan'] = $count;
3057 return $count;
3061 * Parses the array in search of a given eid and returns a element object with
3062 * information about the element it has found.
3063 * @param int $eid Gradetree Element ID
3064 * @return object element
3066 public function locate_element($eid) {
3067 // it is a grade - construct a new object
3068 if (strpos($eid, 'n') === 0) {
3069 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
3070 return null;
3073 $itemid = $matches[1];
3074 $userid = $matches[2];
3076 //extra security check - the grade item must be in this tree
3077 if (!$item_el = $this->locate_element('ig'.$itemid)) {
3078 return null;
3081 // $gradea->id may be null - means does not exist yet
3082 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
3084 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3085 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
3087 } else if (strpos($eid, 'g') === 0) {
3088 $id = (int) substr($eid, 1);
3089 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
3090 return null;
3092 //extra security check - the grade item must be in this tree
3093 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
3094 return null;
3096 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3097 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
3100 // it is a category or item
3101 foreach ($this->levels as $row) {
3102 foreach ($row as $element) {
3103 if ($element['type'] == 'filler') {
3104 continue;
3106 if ($element['eid'] == $eid) {
3107 return $element;
3112 return null;
3116 * Returns a well-formed XML representation of the grade-tree using recursion.
3118 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3119 * @param string $tabs The control character to use for tabs
3121 * @return string $xml
3123 public function exporttoxml($root=null, $tabs="\t") {
3124 $xml = null;
3125 $first = false;
3126 if (is_null($root)) {
3127 $root = $this->top_element;
3128 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
3129 $xml .= "<gradetree>\n";
3130 $first = true;
3133 $type = 'undefined';
3134 if (strpos($root['object']->table, 'grade_categories') !== false) {
3135 $type = 'category';
3136 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3137 $type = 'item';
3138 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3139 $type = 'outcome';
3142 $xml .= "$tabs<element type=\"$type\">\n";
3143 foreach ($root['object'] as $var => $value) {
3144 if (!is_object($value) && !is_array($value) && !empty($value)) {
3145 $xml .= "$tabs\t<$var>$value</$var>\n";
3149 if (!empty($root['children'])) {
3150 $xml .= "$tabs\t<children>\n";
3151 foreach ($root['children'] as $sortorder => $child) {
3152 $xml .= $this->exportToXML($child, $tabs."\t\t");
3154 $xml .= "$tabs\t</children>\n";
3157 $xml .= "$tabs</element>\n";
3159 if ($first) {
3160 $xml .= "</gradetree>";
3163 return $xml;
3167 * Returns a JSON representation of the grade-tree using recursion.
3169 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3170 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
3172 * @return string
3174 public function exporttojson($root=null, $tabs="\t") {
3175 $json = null;
3176 $first = false;
3177 if (is_null($root)) {
3178 $root = $this->top_element;
3179 $first = true;
3182 $name = '';
3185 if (strpos($root['object']->table, 'grade_categories') !== false) {
3186 $name = $root['object']->fullname;
3187 if ($name == '?') {
3188 $name = $root['object']->get_name();
3190 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3191 $name = $root['object']->itemname;
3192 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3193 $name = $root['object']->itemname;
3196 $json .= "$tabs {\n";
3197 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
3198 $json .= "$tabs\t \"name\": \"$name\",\n";
3200 foreach ($root['object'] as $var => $value) {
3201 if (!is_object($value) && !is_array($value) && !empty($value)) {
3202 $json .= "$tabs\t \"$var\": \"$value\",\n";
3206 $json = substr($json, 0, strrpos($json, ','));
3208 if (!empty($root['children'])) {
3209 $json .= ",\n$tabs\t\"children\": [\n";
3210 foreach ($root['children'] as $sortorder => $child) {
3211 $json .= $this->exportToJSON($child, $tabs."\t\t");
3213 $json = substr($json, 0, strrpos($json, ','));
3214 $json .= "\n$tabs\t]\n";
3217 if ($first) {
3218 $json .= "\n}";
3219 } else {
3220 $json .= "\n$tabs},\n";
3223 return $json;
3227 * Returns the array of levels
3229 * @return array
3231 public function get_levels() {
3232 return $this->levels;
3236 * Returns the array of grade items
3238 * @return array
3240 public function get_items() {
3241 return $this->items;
3245 * Returns a specific Grade Item
3247 * @param int $itemid The ID of the grade_item object
3249 * @return grade_item
3251 public function get_item($itemid) {
3252 if (array_key_exists($itemid, $this->items)) {
3253 return $this->items[$itemid];
3254 } else {
3255 return false;
3261 * Local shortcut function for creating an edit/delete button for a grade_* object.
3262 * @param string $type 'edit' or 'delete'
3263 * @param int $courseid The Course ID
3264 * @param grade_* $object The grade_* object
3265 * @return string html
3267 function grade_button($type, $courseid, $object) {
3268 global $CFG, $OUTPUT;
3269 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
3270 $objectidstring = $matches[1] . 'id';
3271 } else {
3272 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
3275 $strdelete = get_string('delete');
3276 $stredit = get_string('edit');
3278 if ($type == 'delete') {
3279 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
3280 } else if ($type == 'edit') {
3281 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
3284 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
3289 * This method adds settings to the settings block for the grade system and its
3290 * plugins
3292 * @global moodle_page $PAGE
3294 function grade_extend_settings($plugininfo, $courseid) {
3295 global $PAGE;
3297 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER,
3298 null, 'gradeadmin');
3300 $strings = array_shift($plugininfo);
3302 if ($reports = grade_helper::get_plugins_reports($courseid)) {
3303 foreach ($reports as $report) {
3304 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
3308 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
3309 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
3310 foreach ($settings as $setting) {
3311 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
3315 if ($imports = grade_helper::get_plugins_import($courseid)) {
3316 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
3317 foreach ($imports as $import) {
3318 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
3322 if ($exports = grade_helper::get_plugins_export($courseid)) {
3323 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
3324 foreach ($exports as $export) {
3325 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
3329 if ($letters = grade_helper::get_info_letters($courseid)) {
3330 $letters = array_shift($letters);
3331 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
3334 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
3335 $outcomes = array_shift($outcomes);
3336 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
3339 if ($scales = grade_helper::get_info_scales($courseid)) {
3340 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
3343 if ($gradenode->contains_active_node()) {
3344 // If the gradenode is active include the settings base node (gradeadministration) in
3345 // the navbar, typcially this is ignored.
3346 $PAGE->navbar->includesettingsbase = true;
3348 // If we can get the course admin node make sure it is closed by default
3349 // as in this case the gradenode will be opened
3350 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
3351 $coursenode->make_inactive();
3352 $coursenode->forceopen = false;
3358 * Grade helper class
3360 * This class provides several helpful functions that work irrespective of any
3361 * current state.
3363 * @copyright 2010 Sam Hemelryk
3364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3366 abstract class grade_helper {
3368 * Cached manage settings info {@see get_info_settings}
3369 * @var grade_plugin_info|false
3371 protected static $managesetting = null;
3373 * Cached grade report plugins {@see get_plugins_reports}
3374 * @var array|false
3376 protected static $gradereports = null;
3378 * Cached grade report plugins preferences {@see get_info_scales}
3379 * @var array|false
3381 protected static $gradereportpreferences = null;
3383 * Cached scale info {@see get_info_scales}
3384 * @var grade_plugin_info|false
3386 protected static $scaleinfo = null;
3388 * Cached outcome info {@see get_info_outcomes}
3389 * @var grade_plugin_info|false
3391 protected static $outcomeinfo = null;
3393 * Cached leftter info {@see get_info_letters}
3394 * @var grade_plugin_info|false
3396 protected static $letterinfo = null;
3398 * Cached grade import plugins {@see get_plugins_import}
3399 * @var array|false
3401 protected static $importplugins = null;
3403 * Cached grade export plugins {@see get_plugins_export}
3404 * @var array|false
3406 protected static $exportplugins = null;
3408 * Cached grade plugin strings
3409 * @var array
3411 protected static $pluginstrings = null;
3413 * Cached grade aggregation strings
3414 * @var array
3416 protected static $aggregationstrings = null;
3419 * Cached grade tree plugin strings
3420 * @var array
3422 protected static $langstrings = [];
3425 * First checks the cached language strings, then returns match if found, or uses get_string()
3426 * to get it from the DB, caches it then returns it.
3428 * @deprecated since 4.3
3429 * @todo MDL-78780 This will be deleted in Moodle 4.7.
3430 * @param string $strcode
3431 * @param string|null $section Optional language section
3432 * @return string
3434 public static function get_lang_string(string $strcode, ?string $section = null): string {
3435 debugging('grade_helper::get_lang_string() is deprecated, please use' .
3436 ' get_string() instead.', DEBUG_DEVELOPER);
3438 if (empty(self::$langstrings[$strcode])) {
3439 self::$langstrings[$strcode] = get_string($strcode, $section);
3441 return self::$langstrings[$strcode];
3445 * Gets strings commonly used by the describe plugins
3447 * report => get_string('view'),
3448 * scale => get_string('scales'),
3449 * outcome => get_string('outcomes', 'grades'),
3450 * letter => get_string('letters', 'grades'),
3451 * export => get_string('export', 'grades'),
3452 * import => get_string('import'),
3453 * settings => get_string('settings')
3455 * @return array
3457 public static function get_plugin_strings() {
3458 if (self::$pluginstrings === null) {
3459 self::$pluginstrings = array(
3460 'report' => get_string('view'),
3461 'scale' => get_string('scales'),
3462 'outcome' => get_string('outcomes', 'grades'),
3463 'letter' => get_string('letters', 'grades'),
3464 'export' => get_string('export', 'grades'),
3465 'import' => get_string('import'),
3466 'settings' => get_string('edittree', 'grades')
3469 return self::$pluginstrings;
3473 * Gets strings describing the available aggregation methods.
3475 * @return array
3477 public static function get_aggregation_strings() {
3478 if (self::$aggregationstrings === null) {
3479 self::$aggregationstrings = array(
3480 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
3481 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
3482 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
3483 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
3484 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
3485 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
3486 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
3487 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
3488 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
3491 return self::$aggregationstrings;
3495 * Get grade_plugin_info object for managing settings if the user can
3497 * @param int $courseid
3498 * @return grade_plugin_info[]
3500 public static function get_info_manage_settings($courseid) {
3501 if (self::$managesetting !== null) {
3502 return self::$managesetting;
3504 $context = context_course::instance($courseid);
3505 self::$managesetting = array();
3506 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
3507 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3508 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3509 get_string('gradebooksetup', 'grades'));
3510 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3511 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3512 get_string('coursegradesettings', 'grades'));
3514 if (self::$gradereportpreferences === null) {
3515 self::get_plugins_reports($courseid);
3517 if (self::$gradereportpreferences) {
3518 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
3520 return self::$managesetting;
3523 * Returns an array of plugin reports as grade_plugin_info objects
3525 * @param int $courseid
3526 * @return array
3528 public static function get_plugins_reports($courseid) {
3529 global $SITE, $CFG;
3531 if (self::$gradereports !== null) {
3532 return self::$gradereports;
3534 $context = context_course::instance($courseid);
3535 $gradereports = array();
3536 $gradepreferences = array();
3537 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
3538 //some reports make no sense if we're not within a course
3539 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
3540 continue;
3543 // Remove outcomes report if outcomes not enabled.
3544 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes)) {
3545 continue;
3548 // Remove ones we can't see
3549 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3550 continue;
3553 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3554 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3555 'moodle/grade:edit'), $context)) {
3556 continue;
3559 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3560 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3561 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3563 // Add link to preferences tab if such a page exists
3564 if (file_exists($plugindir.'/preferences.php')) {
3565 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id' => $courseid));
3566 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3567 get_string('preferences', 'grades') . ': ' . $pluginstr);
3570 if (count($gradereports) == 0) {
3571 $gradereports = false;
3572 $gradepreferences = false;
3573 } else if (count($gradepreferences) == 0) {
3574 $gradepreferences = false;
3575 asort($gradereports);
3576 } else {
3577 asort($gradereports);
3578 asort($gradepreferences);
3580 self::$gradereports = $gradereports;
3581 self::$gradereportpreferences = $gradepreferences;
3582 return self::$gradereports;
3586 * Get information on scales
3587 * @param int $courseid
3588 * @return grade_plugin_info
3590 public static function get_info_scales($courseid) {
3591 if (self::$scaleinfo !== null) {
3592 return self::$scaleinfo;
3594 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
3595 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3596 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3597 } else {
3598 self::$scaleinfo = false;
3600 return self::$scaleinfo;
3603 * Get information on outcomes
3604 * @param int $courseid
3605 * @return grade_plugin_info[]|false
3607 public static function get_info_outcomes($courseid) {
3608 global $CFG, $SITE;
3610 if (self::$outcomeinfo !== null) {
3611 return self::$outcomeinfo;
3613 $context = context_course::instance($courseid);
3614 $canmanage = has_capability('moodle/grade:manage', $context);
3615 $canupdate = has_capability('moodle/course:update', $context);
3616 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3617 $outcomes = array();
3618 if ($canupdate) {
3619 if ($courseid!=$SITE->id) {
3620 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3621 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3623 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3624 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3625 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3626 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3627 } else {
3628 if ($courseid!=$SITE->id) {
3629 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3630 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3633 self::$outcomeinfo = $outcomes;
3634 } else {
3635 self::$outcomeinfo = false;
3637 return self::$outcomeinfo;
3640 * Get information on letters
3641 * @param int $courseid
3642 * @return array
3644 public static function get_info_letters($courseid) {
3645 global $SITE;
3646 if (self::$letterinfo !== null) {
3647 return self::$letterinfo;
3649 $context = context_course::instance($courseid);
3650 $canmanage = has_capability('moodle/grade:manage', $context);
3651 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3652 if ($canmanage || $canmanageletters) {
3653 // Redirect to system context when report is accessed from admin settings MDL-31633
3654 if ($context->instanceid == $SITE->id) {
3655 $param = array('edit' => 1);
3656 } else {
3657 $param = array('edit' => 1,'id' => $context->id);
3659 self::$letterinfo = array(
3660 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3661 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3663 } else {
3664 self::$letterinfo = false;
3666 return self::$letterinfo;
3669 * Get information import plugins
3670 * @param int $courseid
3671 * @return array
3673 public static function get_plugins_import($courseid) {
3674 global $CFG;
3676 if (self::$importplugins !== null) {
3677 return self::$importplugins;
3679 $importplugins = array();
3680 $context = context_course::instance($courseid);
3682 if (has_capability('moodle/grade:import', $context)) {
3683 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3684 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3685 continue;
3687 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3688 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3689 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3692 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3693 // XML is the only grade import plugin that has publishing feature.
3694 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3695 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3696 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3700 if (count($importplugins) > 0) {
3701 asort($importplugins);
3702 self::$importplugins = $importplugins;
3703 } else {
3704 self::$importplugins = false;
3706 return self::$importplugins;
3709 * Get information export plugins
3710 * @param int $courseid
3711 * @return array
3713 public static function get_plugins_export($courseid) {
3714 global $CFG;
3716 if (self::$exportplugins !== null) {
3717 return self::$exportplugins;
3719 $context = context_course::instance($courseid);
3720 $exportplugins = array();
3721 $canpublishgrades = 0;
3722 if (has_capability('moodle/grade:export', $context)) {
3723 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3724 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3725 continue;
3727 // All the grade export plugins has grade publishing capabilities.
3728 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3729 $canpublishgrades++;
3732 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3733 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3734 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3737 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3738 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3739 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3740 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3743 if (count($exportplugins) > 0) {
3744 asort($exportplugins);
3745 self::$exportplugins = $exportplugins;
3746 } else {
3747 self::$exportplugins = false;
3749 return self::$exportplugins;
3753 * Returns the value of a field from a user record
3755 * @param stdClass $user object
3756 * @param stdClass $field object
3757 * @return string value of the field
3759 public static function get_user_field_value($user, $field) {
3760 if (!empty($field->customid)) {
3761 $fieldname = 'customfield_' . $field->customid;
3762 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3763 $fieldvalue = $user->{$fieldname};
3764 } else {
3765 $fieldvalue = $field->default;
3767 } else {
3768 $fieldvalue = $user->{$field->shortname};
3770 return $fieldvalue;
3774 * Returns an array of user profile fields to be included in export
3776 * @param int $courseid
3777 * @param bool $includecustomfields
3778 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3780 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3781 global $CFG, $DB;
3783 // Gets the fields that have to be hidden
3784 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3785 $context = context_course::instance($courseid);
3786 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3787 if ($canseehiddenfields) {
3788 $hiddenfields = array();
3791 $fields = array();
3792 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3793 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3794 $userdefaultfields = user_get_default_fields();
3796 // Sets the list of profile fields
3797 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3798 if (!empty($userprofilefields)) {
3799 foreach ($userprofilefields as $field) {
3800 $field = trim($field);
3801 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3802 continue;
3804 $obj = new stdClass();
3805 $obj->customid = 0;
3806 $obj->shortname = $field;
3807 $obj->fullname = get_string($field);
3808 $fields[] = $obj;
3812 // Sets the list of custom profile fields
3813 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3814 if ($includecustomfields && !empty($customprofilefields)) {
3815 $customfields = profile_get_user_fields_with_data(0);
3817 foreach ($customfields as $fieldobj) {
3818 $field = (object)$fieldobj->get_field_config_for_external();
3819 // Make sure we can display this custom field
3820 if (!in_array($field->shortname, $customprofilefields)) {
3821 continue;
3822 } else if (in_array($field->shortname, $hiddenfields)) {
3823 continue;
3824 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3825 continue;
3828 $obj = new stdClass();
3829 $obj->customid = $field->id;
3830 $obj->shortname = $field->shortname;
3831 $obj->fullname = format_string($field->name);
3832 $obj->datatype = $field->datatype;
3833 $obj->default = $field->defaultdata;
3834 $fields[] = $obj;
3838 return $fields;
3842 * This helper method gets a snapshot of all the weights for a course.
3843 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3844 * @param int $courseid
3845 * @return array of itemid -> aggregationcoef2
3847 public static function fetch_all_natural_weights_for_course($courseid) {
3848 global $DB;
3849 $result = array();
3851 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3852 foreach ($records as $record) {
3853 $result[$record->id] = $record->aggregationcoef2;
3855 return $result;
3859 * Resets all static caches.
3861 * @return void
3863 public static function reset_caches() {
3864 self::$managesetting = null;
3865 self::$gradereports = null;
3866 self::$gradereportpreferences = null;
3867 self::$scaleinfo = null;
3868 self::$outcomeinfo = null;
3869 self::$letterinfo = null;
3870 self::$importplugins = null;
3871 self::$exportplugins = null;
3872 self::$pluginstrings = null;
3873 self::$aggregationstrings = null;
3877 * Returns icon of element
3879 * @param array $element An array representing an element in the grade_tree
3880 * @param bool $spacerifnone return spacer if no icon found
3882 * @return string icon or spacer
3884 public static function get_element_icon(array $element, bool $spacerifnone = false): string {
3885 global $CFG, $OUTPUT;
3886 require_once($CFG->libdir . '/filelib.php');
3888 $outputstr = '';
3890 // Object holding pix_icon information before instantiation.
3891 $icon = new stdClass();
3892 $icon->attributes = ['class' => 'icon itemicon'];
3893 $icon->component = 'moodle';
3895 $none = true;
3896 switch ($element['type']) {
3897 case 'item':
3898 case 'courseitem':
3899 case 'categoryitem':
3900 $none = false;
3902 $iscourse = $element['object']->is_course_item();
3903 $iscategory = $element['object']->is_category_item();
3904 $isscale = $element['object']->gradetype == GRADE_TYPE_SCALE;
3905 $isvalue = $element['object']->gradetype == GRADE_TYPE_VALUE;
3906 $isoutcome = !empty($element['object']->outcomeid);
3908 if ($element['object']->is_calculated()) {
3909 $icon->pix = 'i/calc';
3910 $icon->title = s(get_string('calculatedgrade', 'grades'));
3912 } else if (($iscourse || $iscategory) && ($isscale || $isvalue)) {
3913 if ($category = $element['object']->get_item_category()) {
3914 $aggrstrings = self::get_aggregation_strings();
3915 $stragg = $aggrstrings[$category->aggregation];
3917 $icon->pix = 'i/calc';
3918 $icon->title = s($stragg);
3920 switch ($category->aggregation) {
3921 case GRADE_AGGREGATE_MEAN:
3922 case GRADE_AGGREGATE_MEDIAN:
3923 case GRADE_AGGREGATE_WEIGHTED_MEAN:
3924 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
3925 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
3926 $icon->pix = 'i/agg_mean';
3927 break;
3928 case GRADE_AGGREGATE_SUM:
3929 $icon->pix = 'i/agg_sum';
3930 break;
3934 } else if ($element['object']->itemtype == 'mod') {
3935 // Prevent outcomes displaying the same icon as the activity they are attached to.
3936 if ($isoutcome) {
3937 $icon->pix = 'i/outcomes';
3938 $icon->title = s(get_string('outcome', 'grades'));
3939 } else {
3940 $modinfo = get_fast_modinfo($element['object']->courseid);
3941 $module = $element['object']->itemmodule;
3942 $instanceid = $element['object']->iteminstance;
3943 if (isset($modinfo->instances[$module][$instanceid])) {
3944 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
3945 } else {
3946 $icon->pix = 'monologo';
3947 $icon->component = $element['object']->itemmodule;
3949 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
3951 } else if ($element['object']->itemtype == 'manual') {
3952 if ($element['object']->is_outcome_item()) {
3953 $icon->pix = 'i/outcomes';
3954 $icon->title = s(get_string('outcome', 'grades'));
3955 } else {
3956 $icon->pix = 'i/manual_item';
3957 $icon->title = s(get_string('manualitem', 'grades'));
3960 break;
3962 case 'category':
3963 $none = false;
3964 $icon->pix = 'i/folder';
3965 $icon->title = s(get_string('category', 'grades'));
3966 break;
3969 if ($none) {
3970 if ($spacerifnone) {
3971 $outputstr = $OUTPUT->spacer() . ' ';
3973 } else if (isset($icon->url)) {
3974 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
3975 } else {
3976 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
3979 return $outputstr;
3983 * Returns the string that describes the type of the element.
3985 * @param array $element An array representing an element in the grade_tree
3986 * @return string The string that describes the type of the grade element
3988 public static function get_element_type_string(array $element): string {
3989 // If the element is a grade category.
3990 if ($element['type'] == 'category') {
3991 return get_string('category', 'grades');
3993 // If the element is a grade item.
3994 if (in_array($element['type'], ['item', 'courseitem', 'categoryitem'])) {
3995 // If calculated grade item.
3996 if ($element['object']->is_calculated()) {
3997 return get_string('calculatedgrade', 'grades');
3999 // If aggregated type grade item.
4000 if ($element['object']->is_aggregate_item()) {
4001 return get_string('aggregation', 'core_grades');
4003 // If external grade item (module, plugin, etc.).
4004 if ($element['object']->is_external_item()) {
4005 // If outcome grade item.
4006 if ($element['object']->is_outcome_item()) {
4007 return get_string('outcome', 'grades');
4009 return get_string('modulename', $element['object']->itemmodule);
4011 // If manual grade item.
4012 if ($element['object']->itemtype == 'manual') {
4013 // If outcome grade item.
4014 if ($element['object']->is_outcome_item()) {
4015 return get_string('outcome', 'grades');
4017 return get_string('manualitem', 'grades');
4021 return '';
4025 * Returns name of element optionally with icon and link
4027 * @param array $element An array representing an element in the grade_tree
4028 * @param bool $withlink Whether or not this header has a link
4029 * @param bool $icon Whether or not to display an icon with this header
4030 * @param bool $spacerifnone return spacer if no icon found
4031 * @param bool $withdescription Show description if defined by this item.
4032 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
4033 * instead of "Category total" or "Course total"
4034 * @param moodle_url|null $sortlink Link to sort column.
4036 * @return string header
4038 public static function get_element_header(array $element, bool $withlink = false, bool $icon = true,
4039 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
4040 ?moodle_url $sortlink = null): string {
4041 $header = '';
4043 if ($icon) {
4044 $header .= self::get_element_icon($element, $spacerifnone);
4047 $title = $element['object']->get_name($fulltotal);
4048 $titleunescaped = $element['object']->get_name($fulltotal, false);
4049 $header .= $title;
4051 if ($element['type'] != 'item' && $element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
4052 return $header;
4055 if ($sortlink) {
4056 $url = $sortlink;
4057 $header = html_writer::link($url, $header, [
4058 'title' => $titleunescaped,
4059 'class' => 'gradeitemheader ',
4061 } else {
4062 if ($withlink && $url = self::get_activity_link($element)) {
4063 $a = new stdClass();
4064 $a->name = get_string('modulename', $element['object']->itemmodule);
4065 $a->title = $titleunescaped;
4066 $title = get_string('linktoactivity', 'grades', $a);
4067 $header = html_writer::link($url, $header, [
4068 'title' => $title,
4069 'class' => 'gradeitemheader ',
4071 } else {
4072 $header = html_writer::span($header, 'gradeitemheader ', [
4073 'title' => $titleunescaped,
4074 'tabindex' => '0',
4079 if ($withdescription) {
4080 $desc = $element['object']->get_description();
4081 if (!empty($desc)) {
4082 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
4086 return $header;
4090 * Returns a link to grading page if grade.php exists in the module or link to activity
4092 * @param array $element An array representing an element in the grade_tree
4094 * @return string|null link to grading page|activity or null if not found
4096 public static function get_activity_link(array $element): ?string {
4097 global $CFG;
4098 /** @var array static cache of the grade.php file existence flags */
4099 static $hasgradephp = [];
4101 $itemtype = $element['object']->itemtype;
4102 $itemmodule = $element['object']->itemmodule;
4103 $iteminstance = $element['object']->iteminstance;
4104 $itemnumber = $element['object']->itemnumber;
4106 // Links only for module items that have valid instance, module and are
4107 // called from grade_tree with valid modinfo.
4108 $modinfo = get_fast_modinfo($element['object']->courseid);
4109 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$modinfo) {
4110 return null;
4113 // Get $cm efficiently and with visibility information using modinfo.
4114 $instances = $modinfo->get_instances();
4115 if (empty($instances[$itemmodule][$iteminstance])) {
4116 return null;
4118 $cm = $instances[$itemmodule][$iteminstance];
4120 // Do not add link if activity is not visible to the current user.
4121 if (!$cm->uservisible) {
4122 return null;
4125 if (!array_key_exists($itemmodule, $hasgradephp)) {
4126 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
4127 $hasgradephp[$itemmodule] = true;
4128 } else {
4129 $hasgradephp[$itemmodule] = false;
4133 // If module has grade.php, link to that, otherwise view.php.
4134 if ($hasgradephp[$itemmodule]) {
4135 $args = ['id' => $cm->id, 'itemnumber' => $itemnumber];
4136 if (isset($element['userid'])) {
4137 $args['userid'] = $element['userid'];
4139 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
4140 } else {
4141 return new moodle_url('/mod/' . $itemmodule . '/view.php', ['id' => $cm->id]);