Automatically generated installer lang files
[moodle.git] / grade / lib.php
blob1bfaa0b128b8955419bfa96953920723f12c2bfa
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir . '/gradelib.php');
26 require_once($CFG->dirroot . '/grade/export/lib.php');
28 use \core_grades\output\action_bar;
29 use \core_grades\output\general_action_bar;
31 /**
32 * This class iterates over all users that are graded in a course.
33 * Returns detailed info about users and their grades.
35 * @author Petr Skoda <skodak@moodle.org>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class graded_users_iterator {
40 /**
41 * The couse whose users we are interested in
43 protected $course;
45 /**
46 * An array of grade items or null if only user data was requested
48 protected $grade_items;
50 /**
51 * The group ID we are interested in. 0 means all groups.
53 protected $groupid;
55 /**
56 * A recordset of graded users
58 protected $users_rs;
60 /**
61 * A recordset of user grades (grade_grade instances)
63 protected $grades_rs;
65 /**
66 * Array used when moving to next user while iterating through the grades recordset
68 protected $gradestack;
70 /**
71 * The first field of the users table by which the array of users will be sorted
73 protected $sortfield1;
75 /**
76 * Should sortfield1 be ASC or DESC
78 protected $sortorder1;
80 /**
81 * The second field of the users table by which the array of users will be sorted
83 protected $sortfield2;
85 /**
86 * Should sortfield2 be ASC or DESC
88 protected $sortorder2;
90 /**
91 * Should users whose enrolment has been suspended be ignored?
93 protected $onlyactive = false;
95 /**
96 * Enable user custom fields
98 protected $allowusercustomfields = false;
101 * List of suspended users in course. This includes users whose enrolment status is suspended
102 * or enrolment has expired or not started.
104 protected $suspendedusers = array();
107 * Constructor
109 * @param object $course A course object
110 * @param array $grade_items array of grade items, if not specified only user info returned
111 * @param int $groupid iterate only group users if present
112 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
113 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
114 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
115 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
117 public function __construct($course, $grade_items=null, $groupid=0,
118 $sortfield1='lastname', $sortorder1='ASC',
119 $sortfield2='firstname', $sortorder2='ASC') {
120 $this->course = $course;
121 $this->grade_items = $grade_items;
122 $this->groupid = $groupid;
123 $this->sortfield1 = $sortfield1;
124 $this->sortorder1 = $sortorder1;
125 $this->sortfield2 = $sortfield2;
126 $this->sortorder2 = $sortorder2;
128 $this->gradestack = array();
132 * Initialise the iterator
134 * @return boolean success
136 public function init() {
137 global $CFG, $DB;
139 $this->close();
141 export_verify_grades($this->course->id);
142 $course_item = grade_item::fetch_course_item($this->course->id);
143 if ($course_item->needsupdate) {
144 // Can not calculate all final grades - sorry.
145 return false;
148 $coursecontext = context_course::instance($this->course->id);
150 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
151 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
152 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
154 $params = array_merge($params, $enrolledparams, $relatedctxparams);
156 if ($this->groupid) {
157 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
158 $groupwheresql = "AND gm.groupid = :groupid";
159 // $params contents: gradebookroles
160 $params['groupid'] = $this->groupid;
161 } else {
162 $groupsql = "";
163 $groupwheresql = "";
166 if (empty($this->sortfield1)) {
167 // We must do some sorting even if not specified.
168 $ofields = ", u.id AS usrt";
169 $order = "usrt ASC";
171 } else {
172 $ofields = ", u.$this->sortfield1 AS usrt1";
173 $order = "usrt1 $this->sortorder1";
174 if (!empty($this->sortfield2)) {
175 $ofields .= ", u.$this->sortfield2 AS usrt2";
176 $order .= ", usrt2 $this->sortorder2";
178 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
179 // User order MUST be the same in both queries,
180 // must include the only unique user->id if not already present.
181 $ofields .= ", u.id AS usrt";
182 $order .= ", usrt ASC";
186 $userfields = 'u.*';
187 $customfieldssql = '';
188 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
189 $customfieldscount = 0;
190 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
191 foreach ($customfieldsarray as $field) {
192 if (!empty($field->customid)) {
193 $customfieldssql .= "
194 LEFT JOIN (SELECT * FROM {user_info_data}
195 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
196 ON u.id = cf$customfieldscount.userid";
197 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->customid}";
198 $params['cf'.$customfieldscount] = $field->customid;
199 $customfieldscount++;
204 $users_sql = "SELECT $userfields $ofields
205 FROM {user} u
206 JOIN ($enrolledsql) je ON je.id = u.id
207 $groupsql $customfieldssql
208 JOIN (
209 SELECT DISTINCT ra.userid
210 FROM {role_assignments} ra
211 WHERE ra.roleid $gradebookroles_sql
212 AND ra.contextid $relatedctxsql
213 ) rainner ON rainner.userid = u.id
214 WHERE u.deleted = 0
215 $groupwheresql
216 ORDER BY $order";
217 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
219 if (!$this->onlyactive) {
220 $context = context_course::instance($this->course->id);
221 $this->suspendedusers = get_suspended_userids($context);
222 } else {
223 $this->suspendedusers = array();
226 if (!empty($this->grade_items)) {
227 $itemids = array_keys($this->grade_items);
228 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
229 $params = array_merge($params, $grades_params);
231 $grades_sql = "SELECT g.* $ofields
232 FROM {grade_grades} g
233 JOIN {user} u ON g.userid = u.id
234 JOIN ($enrolledsql) je ON je.id = u.id
235 $groupsql
236 JOIN (
237 SELECT DISTINCT ra.userid
238 FROM {role_assignments} ra
239 WHERE ra.roleid $gradebookroles_sql
240 AND ra.contextid $relatedctxsql
241 ) rainner ON rainner.userid = u.id
242 WHERE u.deleted = 0
243 AND g.itemid $itemidsql
244 $groupwheresql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
247 } else {
248 $this->grades_rs = false;
251 return true;
255 * Returns information about the next user
256 * @return mixed array of user info, all grades and feedback or null when no more users found
258 public function next_user() {
259 if (!$this->users_rs) {
260 return false; // no users present
263 if (!$this->users_rs->valid()) {
264 if ($current = $this->_pop()) {
265 // this is not good - user or grades updated between the two reads above :-(
268 return false; // no more users
269 } else {
270 $user = $this->users_rs->current();
271 $this->users_rs->next();
274 // find grades of this user
275 $grade_records = array();
276 while (true) {
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid)) {
282 break;
285 if ($current->userid != $user->id) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
288 break;
291 $grade_records[$current->itemid] = $current;
294 $grades = array();
295 $feedbacks = array();
297 if (!empty($this->grade_items)) {
298 foreach ($this->grade_items as $grade_item) {
299 if (!isset($feedbacks[$grade_item->id])) {
300 $feedbacks[$grade_item->id] = new stdClass();
302 if (array_key_exists($grade_item->id, $grade_records)) {
303 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
304 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
305 unset($grade_records[$grade_item->id]->feedback);
306 unset($grade_records[$grade_item->id]->feedbackformat);
307 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
308 } else {
309 $feedbacks[$grade_item->id]->feedback = '';
310 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
311 $grades[$grade_item->id] =
312 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
314 $grades[$grade_item->id]->grade_item = $grade_item;
318 // Set user suspended status.
319 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
320 $result = new stdClass();
321 $result->user = $user;
322 $result->grades = $grades;
323 $result->feedbacks = $feedbacks;
324 return $result;
328 * Close the iterator, do not forget to call this function
330 public function close() {
331 if ($this->users_rs) {
332 $this->users_rs->close();
333 $this->users_rs = null;
335 if ($this->grades_rs) {
336 $this->grades_rs->close();
337 $this->grades_rs = null;
339 $this->gradestack = array();
343 * Should all enrolled users be exported or just those with an active enrolment?
345 * @param bool $onlyactive True to limit the export to users with an active enrolment
347 public function require_active_enrolment($onlyactive = true) {
348 if (!empty($this->users_rs)) {
349 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
351 $this->onlyactive = $onlyactive;
355 * Allow custom fields to be included
357 * @param bool $allow Whether to allow custom fields or not
358 * @return void
360 public function allow_user_custom_fields($allow = true) {
361 if ($allow) {
362 $this->allowusercustomfields = true;
363 } else {
364 $this->allowusercustomfields = false;
369 * Add a grade_grade instance to the grade stack
371 * @param grade_grade $grade Grade object
373 * @return void
375 private function _push($grade) {
376 array_push($this->gradestack, $grade);
381 * Remove a grade_grade instance from the grade stack
383 * @return grade_grade current grade object
385 private function _pop() {
386 global $DB;
387 if (empty($this->gradestack)) {
388 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
389 return null; // no grades present
392 $current = $this->grades_rs->current();
394 $this->grades_rs->next();
396 return $current;
397 } else {
398 return array_pop($this->gradestack);
404 * Print a selection popup form of the graded users in a course.
406 * @deprecated since 2.0
408 * @param int $course id of the course
409 * @param string $actionpage The page receiving the data from the popoup form
410 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
411 * @param int $groupid id of requested group, 0 means all
412 * @param int $includeall bool include all option
413 * @param bool $return If true, will return the HTML, otherwise, will print directly
414 * @return null
416 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
417 global $CFG, $USER, $OUTPUT;
418 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
421 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
422 global $USER, $CFG;
424 if (is_null($userid)) {
425 $userid = $USER->id;
427 $coursecontext = context_course::instance($course->id);
428 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
429 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
430 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
431 $menu = array(); // Will be a list of userid => user name
432 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
433 $gui = new graded_users_iterator($course, null, $groupid);
434 $gui->require_active_enrolment($showonlyactiveenrol);
435 $gui->init();
436 $label = get_string('selectauser', 'grades');
437 if ($includeall) {
438 $menu[0] = get_string('allusers', 'grades');
439 $label = get_string('selectalloroneuser', 'grades');
441 while ($userdata = $gui->next_user()) {
442 $user = $userdata->user;
443 $userfullname = fullname($user);
444 if ($user->suspendedenrolment) {
445 $menususpendedusers[$user->id] = $userfullname;
446 } else {
447 $menu[$user->id] = $userfullname;
450 $gui->close();
452 if ($includeall) {
453 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
456 if (!empty($menususpendedusers)) {
457 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
459 $gpr = new grade_plugin_return(array('type' => 'report', 'course' => $course, 'groupid' => $groupid));
460 $select = new single_select(
461 new moodle_url('/grade/report/'.$report.'/index.php', $gpr->get_options()),
462 'userid', $menu, $userid
464 $select->label = $label;
465 $select->formid = 'choosegradeuser';
466 return $select;
470 * Hide warning about changed grades during upgrade to 2.8.
472 * @param int $courseid The current course id.
474 function hide_natural_aggregation_upgrade_notice($courseid) {
475 unset_config('show_sumofgrades_upgrade_' . $courseid);
479 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
481 * @param int $courseid The current course id.
483 function grade_hide_min_max_grade_upgrade_notice($courseid) {
484 unset_config('show_min_max_grades_changed_' . $courseid);
488 * Use the grade min and max from the grade_grade.
490 * This is reserved for core use after an upgrade.
492 * @param int $courseid The current course id.
494 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
495 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
497 grade_force_full_regrading($courseid);
498 // Do this now, because it probably happened to late in the page load to be happen automatically.
499 grade_regrade_final_grades($courseid);
503 * Use the grade min and max from the grade_item.
505 * This is reserved for core use after an upgrade.
507 * @param int $courseid The current course id.
509 function grade_upgrade_use_min_max_from_grade_item($courseid) {
510 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
512 grade_force_full_regrading($courseid);
513 // Do this now, because it probably happened to late in the page load to be happen automatically.
514 grade_regrade_final_grades($courseid);
518 * Hide warning about changed grades during upgrade to 2.8.
520 * @param int $courseid The current course id.
522 function hide_aggregatesubcats_upgrade_notice($courseid) {
523 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
527 * Hide warning about changed grades due to bug fixes
529 * @param int $courseid The current course id.
531 function hide_gradebook_calculations_freeze_notice($courseid) {
532 unset_config('gradebook_calculations_freeze_' . $courseid);
536 * Print warning about changed grades during upgrade to 2.8.
538 * @param int $courseid The current course id.
539 * @param context $context The course context.
540 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
541 * @param boolean $return return as string
543 * @return nothing or string if $return true
545 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
546 global $CFG, $OUTPUT;
547 $html = '';
549 // Do not do anything if they cannot manage the grades of this course.
550 if (!has_capability('moodle/grade:manage', $context)) {
551 return $html;
554 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
555 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
556 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
557 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
559 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
560 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
562 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
563 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
565 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
567 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
568 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
570 // Hide the warning if the user told it to go away.
571 if ($hidenaturalwarning) {
572 hide_natural_aggregation_upgrade_notice($courseid);
574 // Hide the warning if the user told it to go away.
575 if ($hidesubcatswarning) {
576 hide_aggregatesubcats_upgrade_notice($courseid);
579 // Hide the min/max warning if the user told it to go away.
580 if ($hideminmaxwarning) {
581 grade_hide_min_max_grade_upgrade_notice($courseid);
582 $showminmaxwarning = false;
585 if ($useminmaxfromgradegrade) {
586 // Revert to the new behaviour, we now use the grade_grade for min/max.
587 grade_upgrade_use_min_max_from_grade_grade($courseid);
588 grade_hide_min_max_grade_upgrade_notice($courseid);
589 $showminmaxwarning = false;
591 } else if ($useminmaxfromgradeitem) {
592 // Apply the new logic, we now use the grade_item for min/max.
593 grade_upgrade_use_min_max_from_grade_item($courseid);
594 grade_hide_min_max_grade_upgrade_notice($courseid);
595 $showminmaxwarning = false;
599 if (!$hidenaturalwarning && $shownaturalwarning) {
600 $message = get_string('sumofgradesupgradedgrades', 'grades');
601 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
602 $urlparams = array( 'id' => $courseid,
603 'seensumofgradesupgradedgrades' => true,
604 'sesskey' => sesskey());
605 $goawayurl = new moodle_url($thispage, $urlparams);
606 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
607 $html .= $OUTPUT->notification($message, 'notifysuccess');
608 $html .= $goawaybutton;
611 if (!$hidesubcatswarning && $showsubcatswarning) {
612 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
613 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
614 $urlparams = array( 'id' => $courseid,
615 'seenaggregatesubcatsupgradedgrades' => true,
616 'sesskey' => sesskey());
617 $goawayurl = new moodle_url($thispage, $urlparams);
618 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
619 $html .= $OUTPUT->notification($message, 'notifysuccess');
620 $html .= $goawaybutton;
623 if ($showminmaxwarning) {
624 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
625 $urlparams = array( 'id' => $courseid,
626 'seenminmaxupgradedgrades' => true,
627 'sesskey' => sesskey());
629 $goawayurl = new moodle_url($thispage, $urlparams);
630 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
631 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
632 array('target' => '_blank'));
634 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
635 // Show the message that there were min/max issues that have been resolved.
636 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
638 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
639 $urlparams = array('id' => $courseid,
640 'useminmaxfromgradegrade' => true,
641 'sesskey' => sesskey());
642 $reverturl = new moodle_url($thispage, $urlparams);
643 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
645 $html .= $OUTPUT->notification($message);
646 $html .= $revertbutton . $hideminmaxbutton;
648 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
649 // Show the warning that there are min/max issues that have not be resolved.
650 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
652 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
653 $urlparams = array('id' => $courseid,
654 'useminmaxfromgradeitem' => true,
655 'sesskey' => sesskey());
656 $fixurl = new moodle_url($thispage, $urlparams);
657 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
659 $html .= $OUTPUT->notification($message);
660 $html .= $fixbutton . $hideminmaxbutton;
664 if ($gradebookcalculationsfreeze) {
665 if ($acceptgradebookchanges) {
666 // Accept potential changes in grades caused by extra credit bug MDL-49257.
667 hide_gradebook_calculations_freeze_notice($courseid);
668 $courseitem = grade_item::fetch_course_item($courseid);
669 $courseitem->force_regrading();
670 grade_regrade_final_grades($courseid);
672 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
673 } else {
674 // Show the warning that there may be extra credit weights problems.
675 $a = new stdClass();
676 $a->gradebookversion = $gradebookcalculationsfreeze;
677 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
678 $a->currentversion = $matches[1];
679 } else {
680 $a->currentversion = $CFG->release;
682 $a->url = get_docs_url('Gradebook_calculation_changes');
683 $message = get_string('gradebookcalculationswarning', 'grades', $a);
685 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
686 $urlparams = array('id' => $courseid,
687 'acceptgradebookchanges' => true,
688 'sesskey' => sesskey());
689 $fixurl = new moodle_url($thispage, $urlparams);
690 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
692 $html .= $OUTPUT->notification($message);
693 $html .= $fixbutton;
697 if (!empty($html)) {
698 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
701 if ($return) {
702 return $html;
703 } else {
704 echo $html;
709 * grade_get_plugin_info
711 * @param int $courseid The course id
712 * @param string $active_type type of plugin on current page - import, export, report or edit
713 * @param string $active_plugin active plugin type - grader, user, cvs, ...
715 * @return array
717 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
718 global $CFG, $SITE;
720 $context = context_course::instance($courseid);
722 $plugin_info = array();
723 $count = 0;
724 $active = '';
725 $url_prefix = $CFG->wwwroot . '/grade/';
727 // Language strings
728 $plugin_info['strings'] = grade_helper::get_plugin_strings();
730 if ($reports = grade_helper::get_plugins_reports($courseid)) {
731 $plugin_info['report'] = $reports;
734 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
735 $plugin_info['settings'] = $settings;
738 if ($scale = grade_helper::get_info_scales($courseid)) {
739 $plugin_info['scale'] = array('view'=>$scale);
742 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
743 $plugin_info['outcome'] = $outcomes;
746 if ($letters = grade_helper::get_info_letters($courseid)) {
747 $plugin_info['letter'] = $letters;
750 if ($imports = grade_helper::get_plugins_import($courseid)) {
751 $plugin_info['import'] = $imports;
754 if ($exports = grade_helper::get_plugins_export($courseid)) {
755 $plugin_info['export'] = $exports;
758 // Let other plugins add plugins here so that we get extra tabs
759 // in the gradebook.
760 $callbacks = get_plugins_with_function('extend_gradebook_plugininfo', 'lib.php');
761 foreach ($callbacks as $plugins) {
762 foreach ($plugins as $pluginfunction) {
763 $plugin_info = $pluginfunction($plugin_info, $courseid);
767 foreach ($plugin_info as $plugin_type => $plugins) {
768 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
769 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
770 break;
772 foreach ($plugins as $plugin) {
773 if (is_a($plugin, 'grade_plugin_info')) {
774 if ($active_plugin == $plugin->id) {
775 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
781 return $plugin_info;
785 * A simple class containing info about grade plugins.
786 * Can be subclassed for special rules
788 * @package core_grades
789 * @copyright 2009 Nicolas Connault
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792 class grade_plugin_info {
794 * A unique id for this plugin
796 * @var mixed
798 public $id;
800 * A URL to access this plugin
802 * @var mixed
804 public $link;
806 * The name of this plugin
808 * @var mixed
810 public $string;
812 * Another grade_plugin_info object, parent of the current one
814 * @var mixed
816 public $parent;
819 * Constructor
821 * @param int $id A unique id for this plugin
822 * @param string $link A URL to access this plugin
823 * @param string $string The name of this plugin
824 * @param object $parent Another grade_plugin_info object, parent of the current one
826 * @return void
828 public function __construct($id, $link, $string, $parent=null) {
829 $this->id = $id;
830 $this->link = $link;
831 $this->string = $string;
832 $this->parent = $parent;
837 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
838 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
839 * print_heading() etc.
841 * @param int $courseid Course id
842 * @param string $active_type The type of the current page (report, settings,
843 * import, export, scales, outcomes, letters)
844 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
845 * @param string|bool $heading The heading of the page. Tries to guess if none is given
846 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
847 * @param string|bool $buttons Additional buttons to display on the page
848 * @param boolean $shownavigation should the gradebook navigation be shown?
849 * @param string|null $headerhelpidentifier The help string identifier if required.
850 * @param string|null $headerhelpcomponent The component for the help string.
851 * @param stdClass|null $user The user object for use with the user context header.
852 * @param actionbar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
853 * to true. If $actionbar is not explicitly defined, the general action bar
854 * (\core_grades\output\general_action_bar) will be used by default.
855 * @param boolean $showtitle If set to false just show course full name as a title.
856 * @return string HTML code or nothing if $return == false
858 function print_grade_page_head(int $courseid, string $active_type, ?string $active_plugin = null, $heading = false,
859 bool $return = false, $buttons = false, bool $shownavigation = true, ?string $headerhelpidentifier = null,
860 ?string $headerhelpcomponent = null, ?stdClass $user = null, ?action_bar $actionbar = null, $showtitle = true) {
861 global $CFG, $OUTPUT, $PAGE;
863 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
864 require_once($CFG->dirroot . '/course/lib.php');
865 if (course_modules_pending_deletion($courseid, true)) {
866 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
867 \core\output\notification::NOTIFY_WARNING);
870 if ($active_type === 'preferences') {
871 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
872 $active_type = 'settings';
875 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
877 // Determine the string of the active plugin
878 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
879 $stractive_type = $plugin_info['strings'][$active_type];
881 if (!$showtitle) {
882 $title = $PAGE->course->fullname;
883 } else if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
884 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
885 } else {
886 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
889 if ($active_type == 'report') {
890 $PAGE->set_pagelayout('report');
891 } else {
892 $PAGE->set_pagelayout('admin');
894 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
895 $PAGE->set_heading($title);
896 $PAGE->set_secondary_active_tab('grades');
898 if ($buttons instanceof single_button) {
899 $buttons = $OUTPUT->render($buttons);
901 $PAGE->set_button($buttons);
902 if ($courseid != SITEID) {
903 grade_extend_settings($plugin_info, $courseid);
906 // Set the current report as active in the breadcrumbs.
907 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
908 $reportnav->make_active();
911 $returnval = $OUTPUT->header();
913 if (!$return) {
914 echo $returnval;
917 // Guess heading if not given explicitly
918 if (!$heading) {
919 $heading = $stractive_plugin;
922 if (!$showtitle) {
923 $heading = '';
926 if ($shownavigation) {
927 $renderer = $PAGE->get_renderer('core_grades');
928 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
929 if (!$actionbar) {
930 $actionbar = new general_action_bar($PAGE->context, $PAGE->url, $active_type, $active_plugin);
933 if ($return) {
934 $returnval .= $renderer->render_action_bar($actionbar);
935 } else {
936 echo $renderer->render_action_bar($actionbar);
940 $output = '';
941 // Add a help dialogue box if provided.
942 if (isset($headerhelpidentifier)) {
943 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
944 } else {
945 if (isset($user)) {
946 $renderer = $PAGE->get_renderer('core_grades');
947 $output = $OUTPUT->heading($renderer->user_heading($user, $courseid));
948 } else {
949 $output = $OUTPUT->heading($heading);
953 if ($return) {
954 $returnval .= $output;
955 } else {
956 echo $output;
959 $returnval .= print_natural_aggregation_upgrade_notice($courseid, context_course::instance($courseid), $PAGE->url,
960 $return);
962 if ($return) {
963 return $returnval;
968 * Utility class used for return tracking when using edit and other forms in grade plugins
970 * @package core_grades
971 * @copyright 2009 Nicolas Connault
972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
974 class grade_plugin_return {
976 * Type of grade plugin (e.g. 'edit', 'report')
978 * @var string
980 public $type;
982 * Name of grade plugin (e.g. 'grader', 'overview')
984 * @var string
986 public $plugin;
988 * Course id being viewed
990 * @var int
992 public $courseid;
994 * Id of user whose information is being viewed/edited
996 * @var int
998 public $userid;
1000 * Id of group for which information is being viewed/edited
1002 * @var int
1004 public $groupid;
1006 * Current page # within output
1008 * @var int
1010 public $page;
1013 * Constructor
1015 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1017 public function __construct($params = []) {
1018 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1019 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1020 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1021 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1022 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1023 $this->page = optional_param('gpr_page', null, PARAM_INT);
1025 foreach ($params as $key => $value) {
1026 if (property_exists($this, $key)) {
1027 $this->$key = $value;
1030 // Allow course object rather than id to be used to specify course
1031 // - avoid unnecessary use of get_course.
1032 if (array_key_exists('course', $params)) {
1033 $course = $params['course'];
1034 $this->courseid = $course->id;
1035 } else {
1036 $course = null;
1038 // If group has been explicitly set in constructor parameters,
1039 // we should respect that.
1040 if (!array_key_exists('groupid', $params)) {
1041 // Otherwise, 'group' in request parameters is a request for a change.
1042 // In that case, or if we have no group at all, we should get groupid from
1043 // groups_get_course_group, which will do some housekeeping as well as
1044 // give us the correct value.
1045 $changegroup = optional_param('group', -1, PARAM_INT);
1046 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1047 if ($course === null) {
1048 $course = get_course($this->courseid);
1050 $this->groupid = groups_get_course_group($course, true);
1056 * Old syntax of class constructor. Deprecated in PHP7.
1058 * @deprecated since Moodle 3.1
1060 public function grade_plugin_return($params = null) {
1061 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1062 self::__construct($params);
1066 * Returns return parameters as options array suitable for buttons.
1067 * @return array options
1069 public function get_options() {
1070 if (empty($this->type)) {
1071 return array();
1074 $params = array();
1076 if (!empty($this->plugin)) {
1077 $params['plugin'] = $this->plugin;
1080 if (!empty($this->courseid)) {
1081 $params['id'] = $this->courseid;
1084 if (!empty($this->userid)) {
1085 $params['userid'] = $this->userid;
1088 if (!empty($this->groupid)) {
1089 $params['group'] = $this->groupid;
1092 if (!empty($this->page)) {
1093 $params['page'] = $this->page;
1096 return $params;
1100 * Returns return url
1102 * @param string $default default url when params not set
1103 * @param array $extras Extra URL parameters
1105 * @return string url
1107 public function get_return_url($default, $extras=null) {
1108 global $CFG;
1110 if (empty($this->type) or empty($this->plugin)) {
1111 return $default;
1114 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1115 $glue = '?';
1117 if (!empty($this->courseid)) {
1118 $url .= $glue.'id='.$this->courseid;
1119 $glue = '&amp;';
1122 if (!empty($this->userid)) {
1123 $url .= $glue.'userid='.$this->userid;
1124 $glue = '&amp;';
1127 if (!empty($this->groupid)) {
1128 $url .= $glue.'group='.$this->groupid;
1129 $glue = '&amp;';
1132 if (!empty($this->page)) {
1133 $url .= $glue.'page='.$this->page;
1134 $glue = '&amp;';
1137 if (!empty($extras)) {
1138 foreach ($extras as $key=>$value) {
1139 $url .= $glue.$key.'='.$value;
1140 $glue = '&amp;';
1144 return $url;
1148 * Returns string with hidden return tracking form elements.
1149 * @return string
1151 public function get_form_fields() {
1152 if (empty($this->type)) {
1153 return '';
1156 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1158 if (!empty($this->plugin)) {
1159 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1162 if (!empty($this->courseid)) {
1163 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1166 if (!empty($this->userid)) {
1167 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1170 if (!empty($this->groupid)) {
1171 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1174 if (!empty($this->page)) {
1175 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1177 return $result;
1181 * Add hidden elements into mform
1183 * @param object &$mform moodle form object
1185 * @return void
1187 public function add_mform_elements(&$mform) {
1188 if (empty($this->type)) {
1189 return;
1192 $mform->addElement('hidden', 'gpr_type', $this->type);
1193 $mform->setType('gpr_type', PARAM_SAFEDIR);
1195 if (!empty($this->plugin)) {
1196 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1197 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1200 if (!empty($this->courseid)) {
1201 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1202 $mform->setType('gpr_courseid', PARAM_INT);
1205 if (!empty($this->userid)) {
1206 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1207 $mform->setType('gpr_userid', PARAM_INT);
1210 if (!empty($this->groupid)) {
1211 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1212 $mform->setType('gpr_groupid', PARAM_INT);
1215 if (!empty($this->page)) {
1216 $mform->addElement('hidden', 'gpr_page', $this->page);
1217 $mform->setType('gpr_page', PARAM_INT);
1222 * Add return tracking params into url
1224 * @param moodle_url $url A URL
1225 * @return moodle_url with return tracking params
1227 public function add_url_params(moodle_url $url): moodle_url {
1228 if (empty($this->type)) {
1229 return $url;
1232 $url->param('gpr_type', $this->type);
1234 if (!empty($this->plugin)) {
1235 $url->param('gpr_plugin', $this->plugin);
1238 if (!empty($this->courseid)) {
1239 $url->param('gpr_courseid' ,$this->courseid);
1242 if (!empty($this->userid)) {
1243 $url->param('gpr_userid', $this->userid);
1246 if (!empty($this->groupid)) {
1247 $url->param('gpr_groupid', $this->groupid);
1250 if (!empty($this->page)) {
1251 $url->param('gpr_page', $this->page);
1254 return $url;
1259 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1261 * @param string $path The path of the calling script (using __FILE__?)
1262 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1263 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1264 * an array of keys and values (e.g courseid => $courseid, itemid...)
1266 * @return string
1268 function grade_build_nav($path, $pagename=null, $id=null) {
1269 global $CFG, $COURSE, $PAGE;
1271 $strgrades = get_string('grades', 'grades');
1273 // Parse the path and build navlinks from its elements
1274 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1275 $path = substr($path, $dirroot_length);
1276 $path = str_replace('\\', '/', $path);
1278 $path_elements = explode('/', $path);
1280 $path_elements_count = count($path_elements);
1282 // First link is always 'grade'
1283 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1285 $link = null;
1286 $numberofelements = 3;
1288 // Prepare URL params string
1289 $linkparams = array();
1290 if (!is_null($id)) {
1291 if (is_array($id)) {
1292 foreach ($id as $idkey => $idvalue) {
1293 $linkparams[$idkey] = $idvalue;
1295 } else {
1296 $linkparams['id'] = $id;
1300 $navlink4 = null;
1302 // Remove file extensions from filenames
1303 foreach ($path_elements as $key => $filename) {
1304 $path_elements[$key] = str_replace('.php', '', $filename);
1307 // Second level links
1308 switch ($path_elements[1]) {
1309 case 'edit': // No link
1310 if ($path_elements[3] != 'index.php') {
1311 $numberofelements = 4;
1313 break;
1314 case 'import': // No link
1315 break;
1316 case 'export': // No link
1317 break;
1318 case 'report':
1319 // $id is required for this link. Do not print it if $id isn't given
1320 if (!is_null($id)) {
1321 $link = new moodle_url('/grade/report/index.php', $linkparams);
1324 if ($path_elements[2] == 'grader') {
1325 $numberofelements = 4;
1327 break;
1329 default:
1330 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1331 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1332 " as the second path element after 'grade'.");
1333 return false;
1335 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1337 // Third level links
1338 if (empty($pagename)) {
1339 $pagename = get_string($path_elements[2], 'grades');
1342 switch ($numberofelements) {
1343 case 3:
1344 $PAGE->navbar->add($pagename, $link);
1345 break;
1346 case 4:
1347 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1348 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1350 $PAGE->navbar->add($pagename);
1351 break;
1354 return '';
1358 * General structure representing grade items in course
1360 * @package core_grades
1361 * @copyright 2009 Nicolas Connault
1362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1364 class grade_structure {
1365 public $context;
1367 public $courseid;
1370 * Reference to modinfo for current course (for performance, to save
1371 * retrieving it from courseid every time). Not actually set except for
1372 * the grade_tree type.
1373 * @var course_modinfo
1375 public $modinfo;
1378 * 1D array of grade items only
1380 public $items;
1383 * Returns icon of element
1385 * @param array &$element An array representing an element in the grade_tree
1386 * @param bool $spacerifnone return spacer if no icon found
1388 * @return string icon or spacer
1390 public function get_element_icon(&$element, $spacerifnone=false) {
1391 global $CFG, $OUTPUT;
1392 require_once $CFG->libdir.'/filelib.php';
1394 $outputstr = '';
1396 // Object holding pix_icon information before instantiation.
1397 $icon = new stdClass();
1398 $icon->attributes = array(
1399 'class' => 'icon itemicon'
1401 $icon->component = 'moodle';
1403 $none = true;
1404 switch ($element['type']) {
1405 case 'item':
1406 case 'courseitem':
1407 case 'categoryitem':
1408 $none = false;
1410 $is_course = $element['object']->is_course_item();
1411 $is_category = $element['object']->is_category_item();
1412 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1413 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1414 $is_outcome = !empty($element['object']->outcomeid);
1416 if ($element['object']->is_calculated()) {
1417 $icon->pix = 'i/calc';
1418 $icon->title = s(get_string('calculatedgrade', 'grades'));
1420 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1421 if ($category = $element['object']->get_item_category()) {
1422 $aggrstrings = grade_helper::get_aggregation_strings();
1423 $stragg = $aggrstrings[$category->aggregation];
1425 $icon->pix = 'i/calc';
1426 $icon->title = s($stragg);
1428 switch ($category->aggregation) {
1429 case GRADE_AGGREGATE_MEAN:
1430 case GRADE_AGGREGATE_MEDIAN:
1431 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1432 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1433 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1434 $icon->pix = 'i/agg_mean';
1435 break;
1436 case GRADE_AGGREGATE_SUM:
1437 $icon->pix = 'i/agg_sum';
1438 break;
1442 } else if ($element['object']->itemtype == 'mod') {
1443 // Prevent outcomes displaying the same icon as the activity they are attached to.
1444 if ($is_outcome) {
1445 $icon->pix = 'i/outcomes';
1446 $icon->title = s(get_string('outcome', 'grades'));
1447 } else {
1448 $modinfo = get_fast_modinfo($element['object']->courseid);
1449 $module = $element['object']->itemmodule;
1450 $instanceid = $element['object']->iteminstance;
1451 if (isset($modinfo->instances[$module][$instanceid])) {
1452 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
1453 } else {
1454 $icon->pix = 'monologo';
1455 $icon->component = $element['object']->itemmodule;
1457 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1459 } else if ($element['object']->itemtype == 'manual') {
1460 if ($element['object']->is_outcome_item()) {
1461 $icon->pix = 'i/outcomes';
1462 $icon->title = s(get_string('outcome', 'grades'));
1463 } else {
1464 $icon->pix = 'i/manual_item';
1465 $icon->title = s(get_string('manualitem', 'grades'));
1468 break;
1470 case 'category':
1471 $none = false;
1472 $icon->pix = 'i/folder';
1473 $icon->title = s(get_string('category', 'grades'));
1474 break;
1477 if ($none) {
1478 if ($spacerifnone) {
1479 $outputstr = $OUTPUT->spacer() . ' ';
1481 } else if (isset($icon->url)) {
1482 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
1483 } else {
1484 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1487 return $outputstr;
1491 * Returns the string that describes the type of the element.
1493 * @param array $element An array representing an element in the grade_tree
1494 * @return string The string that describes the type of the grade element
1496 public function get_element_type_string(array $element): string {
1497 // If the element is a grade category.
1498 if ($element['type'] == 'category') {
1499 return get_string('category', 'grades');
1501 // If the element is a grade item.
1502 if (in_array($element['type'], ['item', 'courseitem', 'categoryitem'])) {
1503 // If calculated grade item.
1504 if ($element['object']->is_calculated()) {
1505 return get_string('calculatedgrade', 'grades');
1507 // If aggregated type grade item.
1508 if ($element['object']->is_aggregate_item()) {
1509 return get_string('aggregation', 'core_grades');
1511 // If external grade item (module, plugin, etc.).
1512 if ($element['object']->is_external_item()) {
1513 // If outcome grade item.
1514 if ($element['object']->is_outcome_item()) {
1515 return get_string('outcome', 'grades');
1517 return get_string('modulename', $element['object']->itemmodule);
1519 // If manual grade item.
1520 if ($element['object']->itemtype == 'manual') {
1521 // If outcome grade item.
1522 if ($element['object']->is_outcome_item()) {
1523 return get_string('outcome', 'grades');
1525 return get_string('manualitem', 'grades');
1529 return '';
1533 * Returns name of element optionally with icon and link
1535 * @param array &$element An array representing an element in the grade_tree
1536 * @param bool $withlink Whether or not this header has a link
1537 * @param bool $icon Whether or not to display an icon with this header
1538 * @param bool $spacerifnone return spacer if no icon found
1539 * @param bool $withdescription Show description if defined by this item.
1540 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1541 * instead of "Category total" or "Course total"
1542 * @param moodle_url|null $sortlink Link to sort column.
1544 * @return string header
1546 public function get_element_header(array &$element, bool $withlink = false, bool $icon = true,
1547 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
1548 ?moodle_url $sortlink = null) {
1549 $header = '';
1551 if ($icon) {
1552 $header .= $this->get_element_icon($element, $spacerifnone);
1555 $title = $element['object']->get_name($fulltotal);
1556 $titleunescaped = $element['object']->get_name($fulltotal, false);
1557 $header .= $title;
1559 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1560 $element['type'] != 'courseitem') {
1561 return $header;
1564 if ($sortlink) {
1565 $url = $sortlink;
1566 $header = html_writer::link($url, $header,
1567 ['title' => $titleunescaped, 'class' => 'gradeitemheader']);
1570 if (!$sortlink) {
1571 if ($withlink && $url = $this->get_activity_link($element)) {
1572 $a = new stdClass();
1573 $a->name = get_string('modulename', $element['object']->itemmodule);
1574 $a->title = $titleunescaped;
1575 $title = get_string('linktoactivity', 'grades', $a);
1576 $header = html_writer::link($url, $header, ['title' => $title, 'class' => 'gradeitemheader']);
1577 } else {
1578 $header = html_writer::span($header, 'gradeitemheader', ['title' => $titleunescaped, 'tabindex' => '0']);
1582 if ($withdescription) {
1583 $desc = $element['object']->get_description();
1584 if (!empty($desc)) {
1585 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1589 return $header;
1592 private function get_activity_link($element) {
1593 global $CFG;
1594 /** @var array static cache of the grade.php file existence flags */
1595 static $hasgradephp = array();
1597 $itemtype = $element['object']->itemtype;
1598 $itemmodule = $element['object']->itemmodule;
1599 $iteminstance = $element['object']->iteminstance;
1600 $itemnumber = $element['object']->itemnumber;
1602 // Links only for module items that have valid instance, module and are
1603 // called from grade_tree with valid modinfo
1604 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1605 return null;
1608 // Get $cm efficiently and with visibility information using modinfo
1609 $instances = $this->modinfo->get_instances();
1610 if (empty($instances[$itemmodule][$iteminstance])) {
1611 return null;
1613 $cm = $instances[$itemmodule][$iteminstance];
1615 // Do not add link if activity is not visible to the current user
1616 if (!$cm->uservisible) {
1617 return null;
1620 if (!array_key_exists($itemmodule, $hasgradephp)) {
1621 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1622 $hasgradephp[$itemmodule] = true;
1623 } else {
1624 $hasgradephp[$itemmodule] = false;
1628 // If module has grade.php, link to that, otherwise view.php
1629 if ($hasgradephp[$itemmodule]) {
1630 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1631 if (isset($element['userid'])) {
1632 $args['userid'] = $element['userid'];
1634 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1635 } else {
1636 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1641 * Returns URL of a page that is supposed to contain detailed grade analysis
1643 * At the moment, only activity modules are supported. The method generates link
1644 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1645 * gradeid and userid. If the grade.php does not exist, null is returned.
1647 * @return moodle_url|null URL or null if unable to construct it
1649 public function get_grade_analysis_url(grade_grade $grade) {
1650 global $CFG;
1651 /** @var array static cache of the grade.php file existence flags */
1652 static $hasgradephp = array();
1654 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1655 throw new coding_exception('Passed grade without the associated grade item');
1657 $item = $grade->grade_item;
1659 if (!$item->is_external_item()) {
1660 // at the moment, only activity modules are supported
1661 return null;
1663 if ($item->itemtype !== 'mod') {
1664 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1666 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1667 return null;
1670 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1671 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1672 $hasgradephp[$item->itemmodule] = true;
1673 } else {
1674 $hasgradephp[$item->itemmodule] = false;
1678 if (!$hasgradephp[$item->itemmodule]) {
1679 return null;
1682 $instances = $this->modinfo->get_instances();
1683 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1684 return null;
1686 $cm = $instances[$item->itemmodule][$item->iteminstance];
1687 if (!$cm->uservisible) {
1688 return null;
1691 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1692 'id' => $cm->id,
1693 'itemid' => $item->id,
1694 'itemnumber' => $item->itemnumber,
1695 'gradeid' => $grade->id,
1696 'userid' => $grade->userid,
1699 return $url;
1703 * Returns an action icon leading to the grade analysis page
1705 * @param grade_grade $grade
1706 * @return string
1707 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1708 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1710 public function get_grade_analysis_icon(grade_grade $grade) {
1711 global $OUTPUT;
1712 debugging('The function get_grade_analysis_icon() is deprecated, please do not use it anymore.',
1713 DEBUG_DEVELOPER);
1715 $url = $this->get_grade_analysis_url($grade);
1716 if (is_null($url)) {
1717 return '';
1720 $title = get_string('gradeanalysis', 'core_grades');
1721 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1722 ['title' => $title, 'aria-label' => $title]);
1726 * Returns a link leading to the grade analysis page
1728 * @param grade_grade $grade
1729 * @return string|null
1731 public function get_grade_analysis_link(grade_grade $grade): ?string {
1732 $url = $this->get_grade_analysis_url($grade);
1733 if (is_null($url)) {
1734 return null;
1737 $gradeanalysisstring = grade_helper::get_lang_string('gradeanalysis', 'grades');
1738 return html_writer::link($url, $gradeanalysisstring,
1739 ['class' => 'dropdown-item', 'aria-label' => $gradeanalysisstring, 'role' => 'menuitem']);
1743 * Returns an action menu for the grade.
1745 * @param grade_grade $grade A grade_grade object
1746 * @return string
1748 public function get_grade_action_menu(grade_grade $grade) : string {
1749 global $OUTPUT;
1751 $menuitems = [];
1753 $url = $this->get_grade_analysis_url($grade);
1754 if ($url) {
1755 $title = get_string('gradeanalysis', 'core_grades');
1756 $menuitems[] = new action_menu_link_secondary($url, null, $title);
1759 if ($menuitems) {
1760 $menu = new action_menu($menuitems);
1761 $icon = $OUTPUT->pix_icon('i/dropdown', get_string('actions'));
1762 $extraclasses = 'btn btn-icon icon-size-2 bg-secondary d-flex align-items-center justify-content-center';
1763 $menu->set_menu_trigger($icon, $extraclasses);
1764 $menu->set_menu_left();
1766 return $OUTPUT->render($menu);
1767 } else {
1768 return '';
1773 * Returns the grade eid - the grade may not exist yet.
1775 * @param grade_grade $grade_grade A grade_grade object
1777 * @return string eid
1779 public function get_grade_eid($grade_grade) {
1780 if (empty($grade_grade->id)) {
1781 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1782 } else {
1783 return 'g'.$grade_grade->id;
1788 * Returns the grade_item eid
1789 * @param grade_item $grade_item A grade_item object
1790 * @return string eid
1792 public function get_item_eid($grade_item) {
1793 return 'ig'.$grade_item->id;
1797 * Given a grade_tree element, returns an array of parameters
1798 * used to build an icon for that element.
1800 * @param array $element An array representing an element in the grade_tree
1802 * @return array
1804 public function get_params_for_iconstr($element) {
1805 $strparams = new stdClass();
1806 $strparams->category = '';
1807 $strparams->itemname = '';
1808 $strparams->itemmodule = '';
1810 if (!method_exists($element['object'], 'get_name')) {
1811 return $strparams;
1814 $strparams->itemname = html_to_text($element['object']->get_name());
1816 // If element name is categorytotal, get the name of the parent category
1817 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1818 $parent = $element['object']->get_parent_category();
1819 $strparams->category = $parent->get_name() . ' ';
1820 } else {
1821 $strparams->category = '';
1824 $strparams->itemmodule = null;
1825 if (isset($element['object']->itemmodule)) {
1826 $strparams->itemmodule = $element['object']->itemmodule;
1828 return $strparams;
1832 * Return a reset icon for the given element.
1834 * @param array $element An array representing an element in the grade_tree
1835 * @param object $gpr A grade_plugin_return object
1836 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1837 * @return string|action_menu_link
1838 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1839 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1841 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1842 global $CFG, $OUTPUT;
1843 debugging('The function get_reset_icon() is deprecated, please do not use it anymore.',
1844 DEBUG_DEVELOPER);
1846 // Limit to category items set to use the natural weights aggregation method, and users
1847 // with the capability to manage grades.
1848 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1849 !has_capability('moodle/grade:manage', $this->context)) {
1850 return $returnactionmenulink ? null : '';
1853 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1854 $url = new moodle_url('/grade/edit/tree/action.php', array(
1855 'id' => $this->courseid,
1856 'action' => 'resetweights',
1857 'eid' => $element['eid'],
1858 'sesskey' => sesskey(),
1861 if ($returnactionmenulink) {
1862 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1863 get_string('resetweightsshort', 'grades'));
1864 } else {
1865 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1870 * Returns a link to reset weights for the given element.
1872 * @param array $element An array representing an element in the grade_tree
1873 * @param object $gpr A grade_plugin_return object
1874 * @return string|null
1876 public function get_reset_weights_link(array $element, object $gpr): ?string {
1878 // Limit to category items set to use the natural weights aggregation method, and users
1879 // with the capability to manage grades.
1880 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1881 !has_capability('moodle/grade:manage', $this->context)) {
1882 return null;
1885 $title = grade_helper::get_lang_string('resetweightsshort', 'grades');
1886 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1887 $url = new moodle_url('/grade/edit/tree/action.php', [
1888 'id' => $this->courseid,
1889 'action' => 'resetweights',
1890 'eid' => $element['eid'],
1891 'sesskey' => sesskey(),
1893 $gpr->add_url_params($url);
1894 return html_writer::link($url, $title,
1895 ['class' => 'dropdown-item', 'aria-label' => $str, 'role' => 'menuitem']);
1899 * Returns a link to delete a given element.
1901 * @param array $element An array representing an element in the grade_tree
1902 * @param object $gpr A grade_plugin_return object
1903 * @return string|null
1905 public function get_delete_link(array $element, object $gpr): ?string {
1906 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1907 if (grade_edit_tree::element_deletable($element)) {
1908 $url = new moodle_url('index.php',
1909 ['id' => $this->courseid, 'action' => 'delete', 'eid' => $element['eid'], 'sesskey' => sesskey()]);
1910 $title = grade_helper::get_lang_string('delete');
1911 $gpr->add_url_params($url);
1912 return html_writer::link($url, $title,
1913 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1916 return null;
1920 * Returns a link to duplicate a given element.
1922 * @param array $element An array representing an element in the grade_tree
1923 * @param object $gpr A grade_plugin_return object
1924 * @return string|null
1926 public function get_duplicate_link(array $element, object $gpr): ?string {
1927 if ($element['type'] == 'item' || ($element['type'] == 'category' && $element['depth'] > 1)) {
1928 if (grade_edit_tree::element_duplicatable($element)) {
1929 $duplicateparams = [];
1930 $duplicateparams['id'] = $this->courseid;
1931 $duplicateparams['action'] = 'duplicate';
1932 $duplicateparams['eid'] = $element['eid'];
1933 $duplicateparams['sesskey'] = sesskey();
1934 $url = new moodle_url('index.php', $duplicateparams);
1935 $title = grade_helper::get_lang_string('duplicate');
1936 $gpr->add_url_params($url);
1937 return html_writer::link($url, $title,
1938 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1941 return null;
1945 * Return edit icon for give element
1947 * @param array $element An array representing an element in the grade_tree
1948 * @param object $gpr A grade_plugin_return object
1949 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1950 * @return string|action_menu_link
1951 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1952 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1954 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1955 global $CFG, $OUTPUT;
1957 debugging('The function get_edit_icon() is deprecated, please do not use it anymore.',
1958 DEBUG_DEVELOPER);
1960 if (!has_capability('moodle/grade:manage', $this->context)) {
1961 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1962 // oki - let them override grade
1963 } else {
1964 return $returnactionmenulink ? null : '';
1968 static $strfeedback = null;
1969 static $streditgrade = null;
1970 if (is_null($streditgrade)) {
1971 $streditgrade = get_string('editgrade', 'grades');
1972 $strfeedback = get_string('feedback');
1975 $strparams = $this->get_params_for_iconstr($element);
1977 $object = $element['object'];
1979 switch ($element['type']) {
1980 case 'item':
1981 case 'categoryitem':
1982 case 'courseitem':
1983 $stredit = get_string('editverbose', 'grades', $strparams);
1984 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1985 $url = new moodle_url('/grade/edit/tree/item.php',
1986 array('courseid' => $this->courseid, 'id' => $object->id));
1987 } else {
1988 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1989 array('courseid' => $this->courseid, 'id' => $object->id));
1991 break;
1993 case 'category':
1994 $stredit = get_string('editverbose', 'grades', $strparams);
1995 $url = new moodle_url('/grade/edit/tree/category.php',
1996 array('courseid' => $this->courseid, 'id' => $object->id));
1997 break;
1999 case 'grade':
2000 $stredit = $streditgrade;
2001 if (empty($object->id)) {
2002 $url = new moodle_url('/grade/edit/tree/grade.php',
2003 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
2004 } else {
2005 $url = new moodle_url('/grade/edit/tree/grade.php',
2006 array('courseid' => $this->courseid, 'id' => $object->id));
2008 if (!empty($object->feedback)) {
2009 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
2011 break;
2013 default:
2014 $url = null;
2017 if ($url) {
2018 if ($returnactionmenulink) {
2019 return new action_menu_link_secondary($gpr->add_url_params($url),
2020 new pix_icon('t/edit', $stredit),
2021 get_string('editsettings'));
2022 } else {
2023 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
2026 } else {
2027 return $returnactionmenulink ? null : '';
2032 * Returns a link leading to the edit grade/grade item/category page
2034 * @param array $element An array representing an element in the grade_tree
2035 * @param object $gpr A grade_plugin_return object
2036 * @return string|null
2038 public function get_edit_link(array $element, object $gpr): ?string {
2039 $url = null;
2040 $title = '';
2041 if ((!has_capability('moodle/grade:manage', $this->context) &&
2042 (!($element['type'] == 'grade') || !has_capability('moodle/grade:edit', $this->context)))) {
2043 return null;
2046 $object = $element['object'];
2048 if ($element['type'] == 'grade') {
2049 if (empty($object->id)) {
2050 $url = new moodle_url('/grade/edit/tree/grade.php',
2051 ['courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid]);
2052 } else {
2053 $url = new moodle_url('/grade/edit/tree/grade.php',
2054 ['courseid' => $this->courseid, 'id' => $object->id]);
2056 $url = $gpr->add_url_params($url);
2057 $title = grade_helper::get_lang_string('editgrade', 'grades');
2058 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
2059 ($element['type'] == 'courseitem')) {
2060 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
2061 $url = new moodle_url('/grade/edit/tree/item.php',
2062 ['courseid' => $this->courseid, 'id' => $object->id]);
2063 } else {
2064 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
2065 ['courseid' => $this->courseid, 'id' => $object->id]);
2067 $url = $gpr->add_url_params($url);
2068 $title = grade_helper::get_lang_string('itemsedit', 'grades');
2069 } else if ($element['type'] == 'category') {
2070 $url = new moodle_url('/grade/edit/tree/category.php',
2071 ['courseid' => $this->courseid, 'id' => $object->id]);
2072 $url = $gpr->add_url_params($url);
2073 $title = grade_helper::get_lang_string('categoryedit', 'grades');
2075 return html_writer::link($url, $title,
2076 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2080 * Returns link to the advanced grading page
2082 * @param array $element An array representing an element in the grade_tree
2083 * @param object $gpr A grade_plugin_return object
2084 * @return string|null
2086 public function get_advanced_grading_link(array $element, object $gpr): ?string {
2087 global $CFG;
2089 /** @var array static cache of the grade.php file existence flags */
2090 static $hasgradephp = [];
2092 $itemtype = $element['object']->itemtype;
2093 $itemmodule = $element['object']->itemmodule;
2094 $iteminstance = $element['object']->iteminstance;
2095 $itemnumber = $element['object']->itemnumber;
2097 // Links only for module items that have valid instance, module and are
2098 // called from grade_tree with valid modinfo.
2099 if ($itemtype == 'mod' && $iteminstance && $itemmodule && $this->modinfo) {
2101 // Get $cm efficiently and with visibility information using modinfo.
2102 $instances = $this->modinfo->get_instances();
2103 if (!empty($instances[$itemmodule][$iteminstance])) {
2104 $cm = $instances[$itemmodule][$iteminstance];
2106 // Do not add link if activity is not visible to the current user.
2107 if ($cm->uservisible) {
2108 if (!array_key_exists($itemmodule, $hasgradephp)) {
2109 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
2110 $hasgradephp[$itemmodule] = true;
2111 } else {
2112 $hasgradephp[$itemmodule] = false;
2116 // If module has grade.php, add link to that.
2117 if ($hasgradephp[$itemmodule]) {
2118 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
2119 if (isset($element['userid'])) {
2120 $args['userid'] = $element['userid'];
2123 $url = new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
2124 $title = get_string('advancedgrading', 'gradereport_grader', $itemmodule);
2125 $gpr->add_url_params($url);
2126 return html_writer::link($url, $title,
2127 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2133 return null;
2137 * Return hiding icon for give element
2139 * @param array $element An array representing an element in the grade_tree
2140 * @param object $gpr A grade_plugin_return object
2141 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2142 * @return string|action_menu_link
2143 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2144 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2146 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
2147 global $CFG, $OUTPUT;
2148 debugging('The function get_hiding_icon() is deprecated, please do not use it anymore.',
2149 DEBUG_DEVELOPER);
2151 if (!$element['object']->can_control_visibility()) {
2152 return $returnactionmenulink ? null : '';
2155 if (!has_capability('moodle/grade:manage', $this->context) and
2156 !has_capability('moodle/grade:hide', $this->context)) {
2157 return $returnactionmenulink ? null : '';
2160 $strparams = $this->get_params_for_iconstr($element);
2161 $strshow = get_string('showverbose', 'grades', $strparams);
2162 $strhide = get_string('hideverbose', 'grades', $strparams);
2164 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2165 $url = $gpr->add_url_params($url);
2167 if ($element['object']->is_hidden()) {
2168 $type = 'show';
2169 $tooltip = $strshow;
2171 // Change the icon and add a tooltip showing the date
2172 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2173 $type = 'hiddenuntil';
2174 $tooltip = get_string('hiddenuntildate', 'grades',
2175 userdate($element['object']->get_hidden()));
2178 $url->param('action', 'show');
2180 if ($returnactionmenulink) {
2181 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2182 } else {
2183 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2186 } else {
2187 $url->param('action', 'hide');
2188 if ($returnactionmenulink) {
2189 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2190 } else {
2191 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2195 return $hideicon;
2199 * Returns a link with url to hide/unhide grade/grade item/grade category
2201 * @param array $element An array representing an element in the grade_tree
2202 * @param object $gpr A grade_plugin_return object
2203 * @return string|null
2205 public function get_hiding_link(array $element, object $gpr): ?string {
2206 if (!$element['object']->can_control_visibility() || !has_capability('moodle/grade:manage', $this->context) ||
2207 !has_capability('moodle/grade:hide', $this->context)) {
2208 return null;
2211 $url = new moodle_url('/grade/edit/tree/action.php',
2212 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2213 $url = $gpr->add_url_params($url);
2215 if ($element['object']->is_hidden()) {
2216 $url->param('action', 'show');
2217 $title = grade_helper::get_lang_string('show');
2218 } else {
2219 $url->param('action', 'hide');
2220 $title = grade_helper::get_lang_string('hide');
2223 $url = html_writer::link($url, $title,
2224 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2226 if ($element['type'] == 'grade') {
2227 $item = $element['object']->grade_item;
2228 if ($item->hidden) {
2229 $strparamobj = new stdClass();
2230 $strparamobj->itemname = $item->get_name(true, true);
2231 $strnonunhideable = get_string('nonunhideableverbose', 'grades', $strparamobj);
2232 $url = html_writer::span($title, 'text-muted dropdown-item',
2233 ['title' => $strnonunhideable, 'aria-label' => $title, 'role' => 'menuitem']);
2237 return $url;
2241 * Return locking icon for given element
2243 * @param array $element An array representing an element in the grade_tree
2244 * @param object $gpr A grade_plugin_return object
2246 * @return string
2247 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2248 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2250 public function get_locking_icon($element, $gpr) {
2251 global $CFG, $OUTPUT;
2252 debugging('The function get_locking_icon() is deprecated, please do not use it anymore.',
2253 DEBUG_DEVELOPER);
2255 $strparams = $this->get_params_for_iconstr($element);
2256 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2257 $strlock = get_string('lockverbose', 'grades', $strparams);
2259 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2260 $url = $gpr->add_url_params($url);
2262 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2263 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
2264 $strparamobj = new stdClass();
2265 $strparamobj->itemname = $element['object']->grade_item->itemname;
2266 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2268 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2269 array('class' => 'action-icon'));
2271 } else if ($element['object']->is_locked()) {
2272 $type = 'unlock';
2273 $tooltip = $strunlock;
2275 // Change the icon and add a tooltip showing the date
2276 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2277 $type = 'locktime';
2278 $tooltip = get_string('locktimedate', 'grades',
2279 userdate($element['object']->get_locktime()));
2282 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
2283 $action = '';
2284 } else {
2285 $url->param('action', 'unlock');
2286 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2289 } else {
2290 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
2291 $action = '';
2292 } else {
2293 $url->param('action', 'lock');
2294 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2298 return $action;
2302 * Returns link to lock/unlock grade/grade item/grade category
2304 * @param array $element An array representing an element in the grade_tree
2305 * @param object $gpr A grade_plugin_return object
2307 * @return string|null
2309 public function get_locking_link(array $element, object $gpr): ?string {
2311 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2312 $title = '';
2313 $url = new moodle_url('/grade/edit/tree/action.php',
2314 ['id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2315 $url = $gpr->add_url_params($url);
2317 if (($element['type'] == 'grade') && ($element['object']->grade_item->is_locked())) {
2318 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon.
2319 $strparamobj = new stdClass();
2320 $strparamobj->itemname = $element['object']->grade_item->get_name(true, true);
2321 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2322 $title = grade_helper::get_lang_string('unlock', 'grades');
2323 return html_writer::span($title, 'text-muted dropdown-item', ['title' => $strnonunlockable,
2324 'aria-label' => $title, 'role' => 'menuitem']);
2325 } else if ($element['object']->is_locked()) {
2326 if (has_capability('moodle/grade:unlock', $this->context)) {
2327 $title = grade_helper::get_lang_string('unlock', 'grades');
2328 $url->param('action', 'unlock');
2329 } else {
2330 return null;
2332 } else {
2333 if (has_capability('moodle/grade:lock', $this->context)) {
2334 $title = grade_helper::get_lang_string('lock', 'grades');
2335 $url->param('action', 'lock');
2336 } else {
2337 return null;
2341 return html_writer::link($url, $title,
2342 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2343 } else {
2344 return null;
2349 * Return calculation icon for given element
2351 * @param array $element An array representing an element in the grade_tree
2352 * @param object $gpr A grade_plugin_return object
2353 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2354 * @return string|action_menu_link
2355 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2356 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2358 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2359 global $CFG, $OUTPUT;
2360 debugging('The function get_calculation_icon() is deprecated, please do not use it anymore.',
2361 DEBUG_DEVELOPER);
2363 if (!has_capability('moodle/grade:manage', $this->context)) {
2364 return $returnactionmenulink ? null : '';
2367 $type = $element['type'];
2368 $object = $element['object'];
2370 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2371 $strparams = $this->get_params_for_iconstr($element);
2372 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2374 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2375 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2377 // show calculation icon only when calculation possible
2378 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2379 if ($object->is_calculated()) {
2380 $icon = 't/calc';
2381 } else {
2382 $icon = 't/calc_off';
2385 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2386 $url = $gpr->add_url_params($url);
2387 if ($returnactionmenulink) {
2388 return new action_menu_link_secondary($url,
2389 new pix_icon($icon, $streditcalculation),
2390 get_string('editcalculation', 'grades'));
2391 } else {
2392 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2397 return $returnactionmenulink ? null : '';
2401 * Returns link to edit calculation for a grade item.
2403 * @param array $element An array representing an element in the grade_tree
2404 * @param object $gpr A grade_plugin_return object
2406 * @return string|null
2408 public function get_edit_calculation_link(array $element, object $gpr): ?string {
2410 if (has_capability('moodle/grade:manage', $this->context) && isset($element['object'])) {
2411 $object = $element['object'];
2412 $isscale = $object->gradetype == GRADE_TYPE_SCALE;
2413 $isvalue = $object->gradetype == GRADE_TYPE_VALUE;
2415 // Show calculation icon only when calculation possible.
2416 if (!$object->is_external_item() && ($isscale || $isvalue)) {
2417 $editcalculationstring = grade_helper::get_lang_string('editcalculation', 'grades');
2418 $url = new moodle_url('/grade/edit/tree/calculation.php',
2419 ['courseid' => $this->courseid, 'id' => $object->id]);
2420 $url = $gpr->add_url_params($url);
2421 return html_writer::link($url, $editcalculationstring,
2422 ['class' => 'dropdown-item', 'aria-label' => $editcalculationstring, 'role' => 'menuitem']);
2425 return null;
2429 * Sets status icons for the grade.
2431 * @param array $element array with grade item info
2432 * @return string status icons container HTML
2434 public function set_grade_status_icons(array $element): string {
2435 global $OUTPUT;
2437 $attributes = ['class' => 'text-muted'];
2439 $statusicons = '';
2440 if ($element['object']->is_hidden()) {
2441 $statusicons .= $OUTPUT->pix_icon('i/show', grade_helper::get_lang_string('hidden', 'grades'),
2442 'moodle', $attributes);
2445 if ($element['object']->is_locked()) {
2446 $statusicons .= $OUTPUT->pix_icon('i/lock', grade_helper::get_lang_string('locked', 'grades'),
2447 'moodle', $attributes);
2450 if ($element['object'] instanceof grade_grade) {
2451 $grade = $element['object'];
2452 if ($grade->is_overridden()) {
2453 $statusicons .= $OUTPUT->pix_icon('i/overriden_grade',
2454 grade_helper::get_lang_string('overridden', 'grades'), 'moodle', $attributes);
2457 if ($grade->is_excluded()) {
2458 $statusicons .= $OUTPUT->pix_icon('i/excluded', grade_helper::get_lang_string('excluded', 'grades'),
2459 'moodle', $attributes);
2463 $class = 'grade_icons';
2464 if (isset($element['type']) && ($element['type'] == 'category')) {
2465 $class = 'category_grade_icons';
2467 if ($statusicons) {
2468 $statusicons = $OUTPUT->container($statusicons, $class);
2470 return $statusicons;
2474 * Returns an action menu for the grade.
2476 * @param array $element Array with cell info.
2477 * @param string $mode Mode - gradeitem or user
2478 * @param grade_plugin_return $gpr
2479 * @param moodle_url|null $baseurl
2480 * @return string
2482 public function get_cell_action_menu(array $element, string $mode, grade_plugin_return $gpr,
2483 ?moodle_url $baseurl = null): string {
2484 global $OUTPUT, $USER;
2486 $context = new stdClass();
2488 if ($mode == 'gradeitem' || $mode == 'setup') {
2489 $editable = true;
2491 if ($element['type'] == 'grade') {
2492 $item = $element['object']->grade_item;
2493 if ($item->is_course_item() || $item->is_category_item()) {
2494 $editable = (bool)get_config('moodle', 'grade_overridecat');;
2497 if (!empty($USER->editing)) {
2498 if ($editable) {
2499 $context->editurl = $this->get_edit_link($element, $gpr);
2501 $context->hideurl = $this->get_hiding_link($element, $gpr);
2502 $context->lockurl = $this->get_locking_link($element, $gpr);
2505 $context->gradeanalysisurl = $this->get_grade_analysis_link($element['object']);
2506 } else if (($element['type'] == 'item') || ($element['type'] == 'categoryitem') ||
2507 ($element['type'] == 'courseitem') || ($element['type'] == 'userfield')) {
2509 $context->datatype = 'item';
2511 if ($element['type'] == 'item') {
2512 if ($mode == 'setup') {
2513 $context->deleteurl = $this->get_delete_link($element, $gpr);
2514 $context->duplicateurl = $this->get_duplicate_link($element, $gpr);
2515 } else {
2516 $context =
2517 grade_report::get_additional_context($this->context, $this->courseid,
2518 $element, $gpr, $mode, $context, true);
2519 $context->advancedgradingurl = $this->get_advanced_grading_link($element, $gpr);
2523 if ($element['type'] == 'item') {
2524 $context->divider1 = true;
2527 if (!empty($USER->editing) || $mode == 'setup') {
2528 if (($element['type'] !== 'userfield') && ($mode !== 'setup')) {
2529 $context->divider1 = true;
2530 $context->divider2 = true;
2533 if ($element['type'] == 'item') {
2534 $context->editurl = $this->get_edit_link($element, $gpr);
2537 $context->editcalculationurl =
2538 $this->get_edit_calculation_link($element, $gpr);
2540 if (isset($element['object'])) {
2541 $object = $element['object'];
2542 if ($object->itemmodule !== 'quiz') {
2543 $context->hideurl = $this->get_hiding_link($element, $gpr);
2546 $context->lockurl = $this->get_locking_link($element, $gpr);
2549 // Sorting item.
2550 if ($baseurl) {
2551 $sortlink = $baseurl;
2552 if (isset($element['object']->id)) {
2553 $sortlink->param('sortitemid', $element['object']->id);
2554 } else if ($element['type'] == 'userfield') {
2555 $context->datatype = $element['name'];
2556 $sortlink->param('sortitemid', $element['name']);
2559 if (($element['type'] == 'userfield') && ($element['name'] == 'fullname')) {
2560 $sortlink->param('sortitemid', 'firstname');
2561 $context->ascendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr);
2562 $context->descendingfirstnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2564 $sortlink->param('sortitemid', 'lastname');
2565 $context->ascendinglastnameurl = $this->get_sorting_link($sortlink, $gpr);
2566 $context->descendinglastnameurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2567 } else {
2568 $context->ascendingurl = $this->get_sorting_link($sortlink, $gpr);
2569 $context->descendingurl = $this->get_sorting_link($sortlink, $gpr, 'desc');
2572 } else if ($element['type'] == 'category') {
2573 $context->datatype = 'category';
2574 if ($mode !== 'setup') {
2575 $mode = 'category';
2576 $context = grade_report::get_additional_context($this->context, $this->courseid,
2577 $element, $gpr, $mode, $context);
2578 } else {
2579 $context->deleteurl = $this->get_delete_link($element, $gpr);
2580 $context->resetweightsurl = $this->get_reset_weights_link($element, $gpr);
2583 if (!empty($USER->editing) || $mode == 'setup') {
2584 if ($mode !== 'setup') {
2585 $context->divider1 = true;
2587 $context->editurl = $this->get_edit_link($element, $gpr);
2588 $context->hideurl = $this->get_hiding_link($element, $gpr);
2589 $context->lockurl = $this->get_locking_link($element, $gpr);
2593 if (isset($element['object'])) {
2594 $context->dataid = $element['object']->id;
2595 } else if ($element['type'] == 'userfield') {
2596 $context->dataid = $element['name'];
2598 } else if ($mode == 'user') {
2599 $context->datatype = 'user';
2600 $context = grade_report::get_additional_context($this->context, $this->courseid, $element, $gpr, $mode, $context, true);
2601 $context->dataid = $element['userid'];
2604 if (!empty($USER->editing) || isset($context->gradeanalysisurl) || isset($context->gradesonlyurl)
2605 || isset($context->aggregatesonlyurl) || isset($context->fullmodeurl) || isset($context->reporturl0)
2606 || isset($context->ascendingfirstnameurl) || isset($context->ascendingurl) || ($mode == 'setup')) {
2607 return $OUTPUT->render_from_template('core_grades/cellmenu', $context);
2609 return '';
2613 * Returns link to sort grade item column
2615 * @param moodle_url $sortlink A base link for sorting
2616 * @param object $gpr A grade_plugin_return object
2617 * @param string $direction Direction od sorting
2618 * @return string
2620 public function get_sorting_link(moodle_url $sortlink, object $gpr, string $direction = 'asc'): string {
2622 if ($direction == 'asc') {
2623 $title = grade_helper::get_lang_string('asc');
2624 } else {
2625 $title = grade_helper::get_lang_string('desc');
2628 $sortlink->param('sort', $direction);
2629 $gpr->add_url_params($sortlink);
2630 return html_writer::link($sortlink, $title,
2631 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2637 * Flat structure similar to grade tree.
2639 * @uses grade_structure
2640 * @package core_grades
2641 * @copyright 2009 Nicolas Connault
2642 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2644 class grade_seq extends grade_structure {
2647 * 1D array of elements
2649 public $elements;
2652 * Constructor, retrieves and stores array of all grade_category and grade_item
2653 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2655 * @param int $courseid The course id
2656 * @param bool $category_grade_last category grade item is the last child
2657 * @param bool $nooutcomes Whether or not outcomes should be included
2659 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2660 global $USER, $CFG;
2662 $this->courseid = $courseid;
2663 $this->context = context_course::instance($courseid);
2665 // get course grade tree
2666 $top_element = grade_category::fetch_course_tree($courseid, true);
2668 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2670 foreach ($this->elements as $key=>$unused) {
2671 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2676 * Old syntax of class constructor. Deprecated in PHP7.
2678 * @deprecated since Moodle 3.1
2680 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2681 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2682 self::__construct($courseid, $category_grade_last, $nooutcomes);
2686 * Static recursive helper - makes the grade_item for category the last children
2688 * @param array &$element The seed of the recursion
2689 * @param bool $category_grade_last category grade item is the last child
2690 * @param bool $nooutcomes Whether or not outcomes should be included
2692 * @return array
2694 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2695 if (empty($element['children'])) {
2696 return array();
2698 $children = array();
2700 foreach ($element['children'] as $sortorder=>$unused) {
2701 if ($nooutcomes and $element['type'] != 'category' and
2702 $element['children'][$sortorder]['object']->is_outcome_item()) {
2703 continue;
2705 $children[] = $element['children'][$sortorder];
2707 unset($element['children']);
2709 if ($category_grade_last and count($children) > 1 and
2711 $children[0]['type'] === 'courseitem' or
2712 $children[0]['type'] === 'categoryitem'
2715 $cat_item = array_shift($children);
2716 array_push($children, $cat_item);
2719 $result = array();
2720 foreach ($children as $child) {
2721 if ($child['type'] == 'category') {
2722 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2723 } else {
2724 $child['eid'] = 'i'.$child['object']->id;
2725 $result[$child['object']->id] = $child;
2729 return $result;
2733 * Parses the array in search of a given eid and returns a element object with
2734 * information about the element it has found.
2736 * @param int $eid Gradetree Element ID
2738 * @return object element
2740 public function locate_element($eid) {
2741 // it is a grade - construct a new object
2742 if (strpos($eid, 'n') === 0) {
2743 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2744 return null;
2747 $itemid = $matches[1];
2748 $userid = $matches[2];
2750 //extra security check - the grade item must be in this tree
2751 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2752 return null;
2755 // $gradea->id may be null - means does not exist yet
2756 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2758 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2759 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2761 } else if (strpos($eid, 'g') === 0) {
2762 $id = (int) substr($eid, 1);
2763 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2764 return null;
2766 //extra security check - the grade item must be in this tree
2767 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2768 return null;
2770 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2771 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2774 // it is a category or item
2775 foreach ($this->elements as $element) {
2776 if ($element['eid'] == $eid) {
2777 return $element;
2781 return null;
2786 * This class represents a complete tree of categories, grade_items and final grades,
2787 * organises as an array primarily, but which can also be converted to other formats.
2788 * It has simple method calls with complex implementations, allowing for easy insertion,
2789 * deletion and moving of items and categories within the tree.
2791 * @uses grade_structure
2792 * @package core_grades
2793 * @copyright 2009 Nicolas Connault
2794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2796 class grade_tree extends grade_structure {
2799 * The basic representation of the tree as a hierarchical, 3-tiered array.
2800 * @var object $top_element
2802 public $top_element;
2805 * 2D array of grade items and categories
2806 * @var array $levels
2808 public $levels;
2811 * Grade items
2812 * @var array $items
2814 public $items;
2817 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2818 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2820 * @param int $courseid The Course ID
2821 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2822 * @param bool $category_grade_last category grade item is the last child
2823 * @param array $collapsed array of collapsed categories
2824 * @param bool $nooutcomes Whether or not outcomes should be included
2826 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2827 $collapsed=null, $nooutcomes=false) {
2828 global $USER, $CFG, $COURSE, $DB;
2830 $this->courseid = $courseid;
2831 $this->levels = array();
2832 $this->context = context_course::instance($courseid);
2834 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2835 $course = $COURSE;
2836 } else {
2837 $course = $DB->get_record('course', array('id' => $this->courseid));
2839 $this->modinfo = get_fast_modinfo($course);
2841 // get course grade tree
2842 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2844 // collapse the categories if requested
2845 if (!empty($collapsed)) {
2846 grade_tree::category_collapse($this->top_element, $collapsed);
2849 // no otucomes if requested
2850 if (!empty($nooutcomes)) {
2851 grade_tree::no_outcomes($this->top_element);
2854 // move category item to last position in category
2855 if ($category_grade_last) {
2856 grade_tree::category_grade_last($this->top_element);
2859 if ($fillers) {
2860 // inject fake categories == fillers
2861 grade_tree::inject_fillers($this->top_element, 0);
2862 // add colspans to categories and fillers
2863 grade_tree::inject_colspans($this->top_element);
2866 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2871 * Old syntax of class constructor. Deprecated in PHP7.
2873 * @deprecated since Moodle 3.1
2875 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2876 $collapsed=null, $nooutcomes=false) {
2877 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2878 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2882 * Static recursive helper - removes items from collapsed categories
2884 * @param array &$element The seed of the recursion
2885 * @param array $collapsed array of collapsed categories
2887 * @return void
2889 public function category_collapse(&$element, $collapsed) {
2890 if ($element['type'] != 'category') {
2891 return;
2893 if (empty($element['children']) or count($element['children']) < 2) {
2894 return;
2897 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2898 $category_item = reset($element['children']); //keep only category item
2899 $element['children'] = array(key($element['children'])=>$category_item);
2901 } else {
2902 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2903 reset($element['children']);
2904 $first_key = key($element['children']);
2905 unset($element['children'][$first_key]);
2907 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2908 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2914 * Static recursive helper - removes all outcomes
2916 * @param array &$element The seed of the recursion
2918 * @return void
2920 public function no_outcomes(&$element) {
2921 if ($element['type'] != 'category') {
2922 return;
2924 foreach ($element['children'] as $sortorder=>$child) {
2925 if ($element['children'][$sortorder]['type'] == 'item'
2926 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2927 unset($element['children'][$sortorder]);
2929 } else if ($element['children'][$sortorder]['type'] == 'category') {
2930 grade_tree::no_outcomes($element['children'][$sortorder]);
2936 * Static recursive helper - makes the grade_item for category the last children
2938 * @param array &$element The seed of the recursion
2940 * @return void
2942 public function category_grade_last(&$element) {
2943 if (empty($element['children'])) {
2944 return;
2946 if (count($element['children']) < 2) {
2947 return;
2949 $first_item = reset($element['children']);
2950 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2951 // the category item might have been already removed
2952 $order = key($element['children']);
2953 unset($element['children'][$order]);
2954 $element['children'][$order] =& $first_item;
2956 foreach ($element['children'] as $sortorder => $child) {
2957 grade_tree::category_grade_last($element['children'][$sortorder]);
2962 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2964 * @param array &$levels The levels of the grade tree through which to recurse
2965 * @param array &$element The seed of the recursion
2966 * @param int $depth How deep are we?
2967 * @return void
2969 public function fill_levels(&$levels, &$element, $depth) {
2970 if (!array_key_exists($depth, $levels)) {
2971 $levels[$depth] = array();
2974 // prepare unique identifier
2975 if ($element['type'] == 'category') {
2976 $element['eid'] = 'cg'.$element['object']->id;
2977 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2978 $element['eid'] = 'ig'.$element['object']->id;
2979 $this->items[$element['object']->id] =& $element['object'];
2982 $levels[$depth][] =& $element;
2983 $depth++;
2984 if (empty($element['children'])) {
2985 return;
2987 $prev = 0;
2988 foreach ($element['children'] as $sortorder=>$child) {
2989 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2990 $element['children'][$sortorder]['prev'] = $prev;
2991 $element['children'][$sortorder]['next'] = 0;
2992 if ($prev) {
2993 $element['children'][$prev]['next'] = $sortorder;
2995 $prev = $sortorder;
3000 * Determines whether the grade tree item can be displayed.
3001 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
3002 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
3003 * can be output.
3005 * @param array $element The grade category element.
3006 * @return bool True if the grade tree item can be displayed. False, otherwise.
3008 public static function can_output_item($element) {
3009 $canoutput = true;
3011 if ($element['type'] === 'category') {
3012 $object = $element['object'];
3013 $category = grade_category::fetch(array('id' => $object->id));
3014 // Category has total, we can output this.
3015 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
3016 return true;
3019 // Category has no total and has no children, no need to output this.
3020 if (empty($element['children'])) {
3021 return false;
3024 $canoutput = false;
3025 // Loop over children and make sure at least one child can be output.
3026 foreach ($element['children'] as $child) {
3027 $canoutput = self::can_output_item($child);
3028 if ($canoutput) {
3029 break;
3034 return $canoutput;
3038 * Static recursive helper - makes full tree (all leafes are at the same level)
3040 * @param array &$element The seed of the recursion
3041 * @param int $depth How deep are we?
3043 * @return int
3045 public function inject_fillers(&$element, $depth) {
3046 $depth++;
3048 if (empty($element['children'])) {
3049 return $depth;
3051 $chdepths = array();
3052 $chids = array_keys($element['children']);
3053 $last_child = end($chids);
3054 $first_child = reset($chids);
3056 foreach ($chids as $chid) {
3057 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
3059 arsort($chdepths);
3061 $maxdepth = reset($chdepths);
3062 foreach ($chdepths as $chid=>$chd) {
3063 if ($chd == $maxdepth) {
3064 continue;
3066 if (!self::can_output_item($element['children'][$chid])) {
3067 continue;
3069 for ($i=0; $i < $maxdepth-$chd; $i++) {
3070 if ($chid == $first_child) {
3071 $type = 'fillerfirst';
3072 } else if ($chid == $last_child) {
3073 $type = 'fillerlast';
3074 } else {
3075 $type = 'filler';
3077 $oldchild =& $element['children'][$chid];
3078 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
3079 'eid'=>'', 'depth'=>$element['object']->depth,
3080 'children'=>array($oldchild));
3084 return $maxdepth;
3088 * Static recursive helper - add colspan information into categories
3090 * @param array &$element The seed of the recursion
3092 * @return int
3094 public function inject_colspans(&$element) {
3095 if (empty($element['children'])) {
3096 return 1;
3098 $count = 0;
3099 foreach ($element['children'] as $key=>$child) {
3100 if (!self::can_output_item($child)) {
3101 continue;
3103 $count += grade_tree::inject_colspans($element['children'][$key]);
3105 $element['colspan'] = $count;
3106 return $count;
3110 * Parses the array in search of a given eid and returns a element object with
3111 * information about the element it has found.
3112 * @param int $eid Gradetree Element ID
3113 * @return object element
3115 public function locate_element($eid) {
3116 // it is a grade - construct a new object
3117 if (strpos($eid, 'n') === 0) {
3118 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
3119 return null;
3122 $itemid = $matches[1];
3123 $userid = $matches[2];
3125 //extra security check - the grade item must be in this tree
3126 if (!$item_el = $this->locate_element('ig'.$itemid)) {
3127 return null;
3130 // $gradea->id may be null - means does not exist yet
3131 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
3133 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3134 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
3136 } else if (strpos($eid, 'g') === 0) {
3137 $id = (int) substr($eid, 1);
3138 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
3139 return null;
3141 //extra security check - the grade item must be in this tree
3142 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
3143 return null;
3145 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
3146 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
3149 // it is a category or item
3150 foreach ($this->levels as $row) {
3151 foreach ($row as $element) {
3152 if ($element['type'] == 'filler') {
3153 continue;
3155 if ($element['eid'] == $eid) {
3156 return $element;
3161 return null;
3165 * Returns a well-formed XML representation of the grade-tree using recursion.
3167 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3168 * @param string $tabs The control character to use for tabs
3170 * @return string $xml
3172 public function exporttoxml($root=null, $tabs="\t") {
3173 $xml = null;
3174 $first = false;
3175 if (is_null($root)) {
3176 $root = $this->top_element;
3177 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
3178 $xml .= "<gradetree>\n";
3179 $first = true;
3182 $type = 'undefined';
3183 if (strpos($root['object']->table, 'grade_categories') !== false) {
3184 $type = 'category';
3185 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3186 $type = 'item';
3187 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3188 $type = 'outcome';
3191 $xml .= "$tabs<element type=\"$type\">\n";
3192 foreach ($root['object'] as $var => $value) {
3193 if (!is_object($value) && !is_array($value) && !empty($value)) {
3194 $xml .= "$tabs\t<$var>$value</$var>\n";
3198 if (!empty($root['children'])) {
3199 $xml .= "$tabs\t<children>\n";
3200 foreach ($root['children'] as $sortorder => $child) {
3201 $xml .= $this->exportToXML($child, $tabs."\t\t");
3203 $xml .= "$tabs\t</children>\n";
3206 $xml .= "$tabs</element>\n";
3208 if ($first) {
3209 $xml .= "</gradetree>";
3212 return $xml;
3216 * Returns a JSON representation of the grade-tree using recursion.
3218 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3219 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
3221 * @return string
3223 public function exporttojson($root=null, $tabs="\t") {
3224 $json = null;
3225 $first = false;
3226 if (is_null($root)) {
3227 $root = $this->top_element;
3228 $first = true;
3231 $name = '';
3234 if (strpos($root['object']->table, 'grade_categories') !== false) {
3235 $name = $root['object']->fullname;
3236 if ($name == '?') {
3237 $name = $root['object']->get_name();
3239 } else if (strpos($root['object']->table, 'grade_items') !== false) {
3240 $name = $root['object']->itemname;
3241 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
3242 $name = $root['object']->itemname;
3245 $json .= "$tabs {\n";
3246 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
3247 $json .= "$tabs\t \"name\": \"$name\",\n";
3249 foreach ($root['object'] as $var => $value) {
3250 if (!is_object($value) && !is_array($value) && !empty($value)) {
3251 $json .= "$tabs\t \"$var\": \"$value\",\n";
3255 $json = substr($json, 0, strrpos($json, ','));
3257 if (!empty($root['children'])) {
3258 $json .= ",\n$tabs\t\"children\": [\n";
3259 foreach ($root['children'] as $sortorder => $child) {
3260 $json .= $this->exportToJSON($child, $tabs."\t\t");
3262 $json = substr($json, 0, strrpos($json, ','));
3263 $json .= "\n$tabs\t]\n";
3266 if ($first) {
3267 $json .= "\n}";
3268 } else {
3269 $json .= "\n$tabs},\n";
3272 return $json;
3276 * Returns the array of levels
3278 * @return array
3280 public function get_levels() {
3281 return $this->levels;
3285 * Returns the array of grade items
3287 * @return array
3289 public function get_items() {
3290 return $this->items;
3294 * Returns a specific Grade Item
3296 * @param int $itemid The ID of the grade_item object
3298 * @return grade_item
3300 public function get_item($itemid) {
3301 if (array_key_exists($itemid, $this->items)) {
3302 return $this->items[$itemid];
3303 } else {
3304 return false;
3310 * Local shortcut function for creating an edit/delete button for a grade_* object.
3311 * @param string $type 'edit' or 'delete'
3312 * @param int $courseid The Course ID
3313 * @param grade_* $object The grade_* object
3314 * @return string html
3316 function grade_button($type, $courseid, $object) {
3317 global $CFG, $OUTPUT;
3318 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
3319 $objectidstring = $matches[1] . 'id';
3320 } else {
3321 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
3324 $strdelete = get_string('delete');
3325 $stredit = get_string('edit');
3327 if ($type == 'delete') {
3328 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
3329 } else if ($type == 'edit') {
3330 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
3333 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
3338 * This method adds settings to the settings block for the grade system and its
3339 * plugins
3341 * @global moodle_page $PAGE
3343 function grade_extend_settings($plugininfo, $courseid) {
3344 global $PAGE;
3346 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER,
3347 null, 'gradeadmin');
3349 $strings = array_shift($plugininfo);
3351 if ($reports = grade_helper::get_plugins_reports($courseid)) {
3352 foreach ($reports as $report) {
3353 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
3357 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
3358 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
3359 foreach ($settings as $setting) {
3360 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
3364 if ($imports = grade_helper::get_plugins_import($courseid)) {
3365 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
3366 foreach ($imports as $import) {
3367 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
3371 if ($exports = grade_helper::get_plugins_export($courseid)) {
3372 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
3373 foreach ($exports as $export) {
3374 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
3378 if ($letters = grade_helper::get_info_letters($courseid)) {
3379 $letters = array_shift($letters);
3380 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
3383 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
3384 $outcomes = array_shift($outcomes);
3385 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
3388 if ($scales = grade_helper::get_info_scales($courseid)) {
3389 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
3392 if ($gradenode->contains_active_node()) {
3393 // If the gradenode is active include the settings base node (gradeadministration) in
3394 // the navbar, typcially this is ignored.
3395 $PAGE->navbar->includesettingsbase = true;
3397 // If we can get the course admin node make sure it is closed by default
3398 // as in this case the gradenode will be opened
3399 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
3400 $coursenode->make_inactive();
3401 $coursenode->forceopen = false;
3407 * Grade helper class
3409 * This class provides several helpful functions that work irrespective of any
3410 * current state.
3412 * @copyright 2010 Sam Hemelryk
3413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3415 abstract class grade_helper {
3417 * Cached manage settings info {@see get_info_settings}
3418 * @var grade_plugin_info|false
3420 protected static $managesetting = null;
3422 * Cached grade report plugins {@see get_plugins_reports}
3423 * @var array|false
3425 protected static $gradereports = null;
3427 * Cached grade report plugins preferences {@see get_info_scales}
3428 * @var array|false
3430 protected static $gradereportpreferences = null;
3432 * Cached scale info {@see get_info_scales}
3433 * @var grade_plugin_info|false
3435 protected static $scaleinfo = null;
3437 * Cached outcome info {@see get_info_outcomes}
3438 * @var grade_plugin_info|false
3440 protected static $outcomeinfo = null;
3442 * Cached leftter info {@see get_info_letters}
3443 * @var grade_plugin_info|false
3445 protected static $letterinfo = null;
3447 * Cached grade import plugins {@see get_plugins_import}
3448 * @var array|false
3450 protected static $importplugins = null;
3452 * Cached grade export plugins {@see get_plugins_export}
3453 * @var array|false
3455 protected static $exportplugins = null;
3457 * Cached grade plugin strings
3458 * @var array
3460 protected static $pluginstrings = null;
3462 * Cached grade aggregation strings
3463 * @var array
3465 protected static $aggregationstrings = null;
3468 * Cached grade tree plugin strings
3469 * @var array
3471 protected static $langstrings = [];
3474 * First checks the cached language strings, then returns match if found, or uses get_string()
3475 * to get it from the DB, caches it then returns it.
3477 * @param string $strcode
3478 * @param string|null $section Optional language section
3479 * @return string
3481 public static function get_lang_string(string $strcode, ?string $section = null): string {
3482 if (empty(self::$langstrings[$strcode])) {
3483 self::$langstrings[$strcode] = get_string($strcode, $section);
3485 return self::$langstrings[$strcode];
3489 * Gets strings commonly used by the describe plugins
3491 * report => get_string('view'),
3492 * scale => get_string('scales'),
3493 * outcome => get_string('outcomes', 'grades'),
3494 * letter => get_string('letters', 'grades'),
3495 * export => get_string('export', 'grades'),
3496 * import => get_string('import'),
3497 * settings => get_string('settings')
3499 * @return array
3501 public static function get_plugin_strings() {
3502 if (self::$pluginstrings === null) {
3503 self::$pluginstrings = array(
3504 'report' => get_string('view'),
3505 'scale' => get_string('scales'),
3506 'outcome' => get_string('outcomes', 'grades'),
3507 'letter' => get_string('letters', 'grades'),
3508 'export' => get_string('export', 'grades'),
3509 'import' => get_string('import'),
3510 'settings' => get_string('edittree', 'grades')
3513 return self::$pluginstrings;
3517 * Gets strings describing the available aggregation methods.
3519 * @return array
3521 public static function get_aggregation_strings() {
3522 if (self::$aggregationstrings === null) {
3523 self::$aggregationstrings = array(
3524 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
3525 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
3526 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
3527 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
3528 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
3529 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
3530 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
3531 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
3532 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
3535 return self::$aggregationstrings;
3539 * Get grade_plugin_info object for managing settings if the user can
3541 * @param int $courseid
3542 * @return grade_plugin_info[]
3544 public static function get_info_manage_settings($courseid) {
3545 if (self::$managesetting !== null) {
3546 return self::$managesetting;
3548 $context = context_course::instance($courseid);
3549 self::$managesetting = array();
3550 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
3551 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3552 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3553 get_string('gradebooksetup', 'grades'));
3554 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3555 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3556 get_string('coursegradesettings', 'grades'));
3558 if (self::$gradereportpreferences === null) {
3559 self::get_plugins_reports($courseid);
3561 if (self::$gradereportpreferences) {
3562 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
3564 return self::$managesetting;
3567 * Returns an array of plugin reports as grade_plugin_info objects
3569 * @param int $courseid
3570 * @return array
3572 public static function get_plugins_reports($courseid) {
3573 global $SITE, $CFG;
3575 if (self::$gradereports !== null) {
3576 return self::$gradereports;
3578 $context = context_course::instance($courseid);
3579 $gradereports = array();
3580 $gradepreferences = array();
3581 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
3582 //some reports make no sense if we're not within a course
3583 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
3584 continue;
3587 // Remove outcomes report if outcomes not enabled.
3588 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes)) {
3589 continue;
3592 // Remove ones we can't see
3593 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3594 continue;
3597 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3598 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3599 'moodle/grade:edit'), $context)) {
3600 continue;
3603 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3604 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3605 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3607 // Add link to preferences tab if such a page exists
3608 if (file_exists($plugindir.'/preferences.php')) {
3609 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id' => $courseid));
3610 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3611 get_string('preferences', 'grades') . ': ' . $pluginstr);
3614 if (count($gradereports) == 0) {
3615 $gradereports = false;
3616 $gradepreferences = false;
3617 } else if (count($gradepreferences) == 0) {
3618 $gradepreferences = false;
3619 asort($gradereports);
3620 } else {
3621 asort($gradereports);
3622 asort($gradepreferences);
3624 self::$gradereports = $gradereports;
3625 self::$gradereportpreferences = $gradepreferences;
3626 return self::$gradereports;
3630 * Get information on scales
3631 * @param int $courseid
3632 * @return grade_plugin_info
3634 public static function get_info_scales($courseid) {
3635 if (self::$scaleinfo !== null) {
3636 return self::$scaleinfo;
3638 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
3639 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3640 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3641 } else {
3642 self::$scaleinfo = false;
3644 return self::$scaleinfo;
3647 * Get information on outcomes
3648 * @param int $courseid
3649 * @return grade_plugin_info
3651 public static function get_info_outcomes($courseid) {
3652 global $CFG, $SITE;
3654 if (self::$outcomeinfo !== null) {
3655 return self::$outcomeinfo;
3657 $context = context_course::instance($courseid);
3658 $canmanage = has_capability('moodle/grade:manage', $context);
3659 $canupdate = has_capability('moodle/course:update', $context);
3660 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3661 $outcomes = array();
3662 if ($canupdate) {
3663 if ($courseid!=$SITE->id) {
3664 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3665 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3667 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3668 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3669 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3670 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3671 } else {
3672 if ($courseid!=$SITE->id) {
3673 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3674 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3677 self::$outcomeinfo = $outcomes;
3678 } else {
3679 self::$outcomeinfo = false;
3681 return self::$outcomeinfo;
3684 * Get information on letters
3685 * @param int $courseid
3686 * @return array
3688 public static function get_info_letters($courseid) {
3689 global $SITE;
3690 if (self::$letterinfo !== null) {
3691 return self::$letterinfo;
3693 $context = context_course::instance($courseid);
3694 $canmanage = has_capability('moodle/grade:manage', $context);
3695 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3696 if ($canmanage || $canmanageletters) {
3697 // Redirect to system context when report is accessed from admin settings MDL-31633
3698 if ($context->instanceid == $SITE->id) {
3699 $param = array('edit' => 1);
3700 } else {
3701 $param = array('edit' => 1,'id' => $context->id);
3703 self::$letterinfo = array(
3704 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3705 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3707 } else {
3708 self::$letterinfo = false;
3710 return self::$letterinfo;
3713 * Get information import plugins
3714 * @param int $courseid
3715 * @return array
3717 public static function get_plugins_import($courseid) {
3718 global $CFG;
3720 if (self::$importplugins !== null) {
3721 return self::$importplugins;
3723 $importplugins = array();
3724 $context = context_course::instance($courseid);
3726 if (has_capability('moodle/grade:import', $context)) {
3727 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3728 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3729 continue;
3731 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3732 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3733 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3736 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3737 // XML is the only grade import plugin that has publishing feature.
3738 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3739 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3740 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3744 if (count($importplugins) > 0) {
3745 asort($importplugins);
3746 self::$importplugins = $importplugins;
3747 } else {
3748 self::$importplugins = false;
3750 return self::$importplugins;
3753 * Get information export plugins
3754 * @param int $courseid
3755 * @return array
3757 public static function get_plugins_export($courseid) {
3758 global $CFG;
3760 if (self::$exportplugins !== null) {
3761 return self::$exportplugins;
3763 $context = context_course::instance($courseid);
3764 $exportplugins = array();
3765 $canpublishgrades = 0;
3766 if (has_capability('moodle/grade:export', $context)) {
3767 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3768 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3769 continue;
3771 // All the grade export plugins has grade publishing capabilities.
3772 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3773 $canpublishgrades++;
3776 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3777 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3778 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3781 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3782 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3783 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3784 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3787 if (count($exportplugins) > 0) {
3788 asort($exportplugins);
3789 self::$exportplugins = $exportplugins;
3790 } else {
3791 self::$exportplugins = false;
3793 return self::$exportplugins;
3797 * Returns the value of a field from a user record
3799 * @param stdClass $user object
3800 * @param stdClass $field object
3801 * @return string value of the field
3803 public static function get_user_field_value($user, $field) {
3804 if (!empty($field->customid)) {
3805 $fieldname = 'customfield_' . $field->customid;
3806 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3807 $fieldvalue = $user->{$fieldname};
3808 } else {
3809 $fieldvalue = $field->default;
3811 } else {
3812 $fieldvalue = $user->{$field->shortname};
3814 return $fieldvalue;
3818 * Returns an array of user profile fields to be included in export
3820 * @param int $courseid
3821 * @param bool $includecustomfields
3822 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3824 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3825 global $CFG, $DB;
3827 // Gets the fields that have to be hidden
3828 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3829 $context = context_course::instance($courseid);
3830 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3831 if ($canseehiddenfields) {
3832 $hiddenfields = array();
3835 $fields = array();
3836 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3837 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3838 $userdefaultfields = user_get_default_fields();
3840 // Sets the list of profile fields
3841 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3842 if (!empty($userprofilefields)) {
3843 foreach ($userprofilefields as $field) {
3844 $field = trim($field);
3845 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3846 continue;
3848 $obj = new stdClass();
3849 $obj->customid = 0;
3850 $obj->shortname = $field;
3851 $obj->fullname = get_string($field);
3852 $fields[] = $obj;
3856 // Sets the list of custom profile fields
3857 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3858 if ($includecustomfields && !empty($customprofilefields)) {
3859 $customfields = profile_get_user_fields_with_data(0);
3861 foreach ($customfields as $fieldobj) {
3862 $field = (object)$fieldobj->get_field_config_for_external();
3863 // Make sure we can display this custom field
3864 if (!in_array($field->shortname, $customprofilefields)) {
3865 continue;
3866 } else if (in_array($field->shortname, $hiddenfields)) {
3867 continue;
3868 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3869 continue;
3872 $obj = new stdClass();
3873 $obj->customid = $field->id;
3874 $obj->shortname = $field->shortname;
3875 $obj->fullname = format_string($field->name);
3876 $obj->datatype = $field->datatype;
3877 $obj->default = $field->defaultdata;
3878 $fields[] = $obj;
3882 return $fields;
3886 * This helper method gets a snapshot of all the weights for a course.
3887 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3888 * @param int $courseid
3889 * @return array of itemid -> aggregationcoef2
3891 public static function fetch_all_natural_weights_for_course($courseid) {
3892 global $DB;
3893 $result = array();
3895 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3896 foreach ($records as $record) {
3897 $result[$record->id] = $record->aggregationcoef2;
3899 return $result;
3903 * Resets all static caches.
3905 * @return void
3907 public static function reset_caches() {
3908 self::$managesetting = null;
3909 self::$gradereports = null;
3910 self::$gradereportpreferences = null;
3911 self::$scaleinfo = null;
3912 self::$outcomeinfo = null;
3913 self::$letterinfo = null;
3914 self::$importplugins = null;
3915 self::$exportplugins = null;
3916 self::$pluginstrings = null;
3917 self::$aggregationstrings = null;