Merge branch 'MDL-69993-310' of git://github.com/paulholden/moodle into MOODLE_310_STABLE
[moodle.git] / grade / lib.php
CommitLineData
cf72e2dd 1<?php
cf72e2dd 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.
13//
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/>.
16
cf72e2dd 17/**
18 * Functions used by gradebook plugins and reports.
19 *
a153c9f2 20 * @package core_grades
cf72e2dd 21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
8ad36f4c 24
63d2081e
MN
25require_once($CFG->libdir . '/gradelib.php');
26require_once($CFG->dirroot . '/grade/export/lib.php');
7a6b7acf 27
0f5660f7 28/**
29 * This class iterates over all users that are graded in a course.
b9f49659 30 * Returns detailed info about users and their grades.
cf72e2dd 31 *
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0f5660f7 34 */
35class graded_users_iterator {
728ff21b
AD
36
37 /**
38 * The couse whose users we are interested in
39 */
40 protected $course;
41
42 /**
43 * An array of grade items or null if only user data was requested
44 */
45 protected $grade_items;
46
47 /**
48 * The group ID we are interested in. 0 means all groups.
49 */
50 protected $groupid;
51
52 /**
53 * A recordset of graded users
54 */
55 protected $users_rs;
56
57 /**
58 * A recordset of user grades (grade_grade instances)
59 */
60 protected $grades_rs;
61
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
64 */
65 protected $gradestack;
66
67 /**
68 * The first field of the users table by which the array of users will be sorted
69 */
70 protected $sortfield1;
71
72 /**
73 * Should sortfield1 be ASC or DESC
74 */
75 protected $sortorder1;
76
77 /**
78 * The second field of the users table by which the array of users will be sorted
79 */
80 protected $sortfield2;
81
82 /**
83 * Should sortfield2 be ASC or DESC
84 */
85 protected $sortorder2;
0f5660f7 86
78ab98bc
AD
87 /**
88 * Should users whose enrolment has been suspended be ignored?
89 */
90 protected $onlyactive = false;
91
61c8e0d7
FM
92 /**
93 * Enable user custom fields
94 */
95 protected $allowusercustomfields = false;
96
38c1dd19
RT
97 /**
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
100 */
101 protected $suspendedusers = array();
102
0f5660f7 103 /**
104 * Constructor
cf72e2dd 105 *
106 * @param object $course A course object
107 * @param array $grade_items array of grade items, if not specified only user info returned
108 * @param int $groupid iterate only group users if present
d08bba83 109 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
110 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
111 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
112 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
0f5660f7 113 */
728ff21b 114 public function __construct($course, $grade_items=null, $groupid=0,
cf72e2dd 115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
0f5660f7 117 $this->course = $course;
118 $this->grade_items = $grade_items;
119 $this->groupid = $groupid;
d08bba83 120 $this->sortfield1 = $sortfield1;
121 $this->sortorder1 = $sortorder1;
122 $this->sortfield2 = $sortfield2;
123 $this->sortorder2 = $sortorder2;
0f5660f7 124
125 $this->gradestack = array();
126 }
127
128 /**
129 * Initialise the iterator
728ff21b 130 *
0f5660f7 131 * @return boolean success
132 */
d24832f9 133 public function init() {
134 global $CFG, $DB;
0f5660f7 135
136 $this->close();
137
63d2081e 138 export_verify_grades($this->course->id);
0f5660f7 139 $course_item = grade_item::fetch_course_item($this->course->id);
140 if ($course_item->needsupdate) {
4e829d48 141 // Can not calculate all final grades - sorry.
0f5660f7 142 return false;
143 }
144
d4060472 145 $coursecontext = context_course::instance($this->course->id);
656d17c2 146
4e829d48
MN
147 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
148 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
78ab98bc 149 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
656d17c2 150
4e829d48 151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
0f5660f7 152
153 if ($this->groupid) {
d24832f9 154 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
e58fcb35 155 $groupwheresql = "AND gm.groupid = :groupid";
d24832f9 156 // $params contents: gradebookroles
e58fcb35 157 $params['groupid'] = $this->groupid;
0f5660f7 158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
161 }
162
345674ca 163 if (empty($this->sortfield1)) {
4e829d48 164 // We must do some sorting even if not specified.
345674ca 165 $ofields = ", u.id AS usrt";
166 $order = "usrt ASC";
167
168 } else {
169 $ofields = ", u.$this->sortfield1 AS usrt1";
170 $order = "usrt1 $this->sortorder1";
171 if (!empty($this->sortfield2)) {
0febb12d 172 $ofields .= ", u.$this->sortfield2 AS usrt2";
345674ca 173 $order .= ", usrt2 $this->sortorder2";
174 }
175 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
4e829d48
MN
176 // User order MUST be the same in both queries,
177 // must include the only unique user->id if not already present.
345674ca 178 $ofields .= ", u.id AS usrt";
179 $order .= ", usrt ASC";
180 }
181 }
182
293f42b6
CF
183 $userfields = 'u.*';
184 $customfieldssql = '';
61c8e0d7
FM
185 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
186 $customfieldscount = 0;
187 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
188 foreach ($customfieldsarray as $field) {
189 if (!empty($field->customid)) {
293f42b6 190 $customfieldssql .= "
61c8e0d7
FM
191 LEFT JOIN (SELECT * FROM {user_info_data}
192 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
193 ON u.id = cf$customfieldscount.userid";
1ef14a5a 194 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->customid}";
61c8e0d7
FM
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
293f42b6
CF
197 }
198 }
199 }
200
293f42b6 201 $users_sql = "SELECT $userfields $ofields
d24832f9 202 FROM {user} u
656d17c2 203 JOIN ($enrolledsql) je ON je.id = u.id
293f42b6 204 $groupsql $customfieldssql
656d17c2
AD
205 JOIN (
206 SELECT DISTINCT ra.userid
207 FROM {role_assignments} ra
208 WHERE ra.roleid $gradebookroles_sql
4e829d48 209 AND ra.contextid $relatedctxsql
656d17c2
AD
210 ) rainner ON rainner.userid = u.id
211 WHERE u.deleted = 0
345674ca 212 $groupwheresql
213 ORDER BY $order";
d24832f9 214 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
0f5660f7 215
38c1dd19
RT
216 if (!$this->onlyactive) {
217 $context = context_course::instance($this->course->id);
218 $this->suspendedusers = get_suspended_userids($context);
219 } else {
220 $this->suspendedusers = array();
221 }
222
0f5660f7 223 if (!empty($this->grade_items)) {
224 $itemids = array_keys($this->grade_items);
cf717dc2 225 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
d24832f9 226 $params = array_merge($params, $grades_params);
0f5660f7 227
345674ca 228 $grades_sql = "SELECT g.* $ofields
d24832f9 229 FROM {grade_grades} g
656d17c2
AD
230 JOIN {user} u ON g.userid = u.id
231 JOIN ($enrolledsql) je ON je.id = u.id
0f5660f7 232 $groupsql
656d17c2
AD
233 JOIN (
234 SELECT DISTINCT ra.userid
235 FROM {role_assignments} ra
236 WHERE ra.roleid $gradebookroles_sql
4e829d48 237 AND ra.contextid $relatedctxsql
4f82032a 238 ) rainner ON rainner.userid = u.id
656d17c2
AD
239 WHERE u.deleted = 0
240 AND g.itemid $itemidsql
241 $groupwheresql
345674ca 242 ORDER BY $order, g.itemid ASC";
d24832f9 243 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
345674ca 244 } else {
245 $this->grades_rs = false;
0f5660f7 246 }
345674ca 247
0f5660f7 248 return true;
249 }
250
251 /**
252 * Returns information about the next user
253 * @return mixed array of user info, all grades and feedback or null when no more users found
254 */
728ff21b 255 public function next_user() {
03cedd62 256 if (!$this->users_rs) {
0f5660f7 257 return false; // no users present
258 }
259
5c75a0a3 260 if (!$this->users_rs->valid()) {
345674ca 261 if ($current = $this->_pop()) {
262 // this is not good - user or grades updated between the two reads above :-(
263 }
264
0f5660f7 265 return false; // no more users
5c75a0a3 266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
0f5660f7 269 }
270
345674ca 271 // find grades of this user
0f5660f7 272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
276 }
277
5c75a0a3 278 if (empty($current->userid)) {
279 break;
280 }
281
345674ca 282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
0f5660f7 284 $this->_push($current);
285 break;
286 }
287
288 $grade_records[$current->itemid] = $current;
289 }
290
291 $grades = array();
292 $feedbacks = array();
293
d08bba83 294 if (!empty($this->grade_items)) {
345674ca 295 foreach ($this->grade_items as $grade_item) {
6189c7b4
FM
296 if (!isset($feedbacks[$grade_item->id])) {
297 $feedbacks[$grade_item->id] = new stdClass();
298 }
345674ca 299 if (array_key_exists($grade_item->id, $grade_records)) {
300 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
301 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
302 unset($grade_records[$grade_item->id]->feedback);
303 unset($grade_records[$grade_item->id]->feedbackformat);
304 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
305 } else {
306 $feedbacks[$grade_item->id]->feedback = '';
307 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
cf72e2dd 308 $grades[$grade_item->id] =
309 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
345674ca 310 }
9901bdf7 311 $grades[$grade_item->id]->grade_item = $grade_item;
0f5660f7 312 }
313 }
314
38c1dd19
RT
315 // Set user suspended status.
316 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
ace9051c 317 $result = new stdClass();
0f5660f7 318 $result->user = $user;
319 $result->grades = $grades;
320 $result->feedbacks = $feedbacks;
0f5660f7 321 return $result;
322 }
323
324 /**
728ff21b 325 * Close the iterator, do not forget to call this function
0f5660f7 326 */
728ff21b 327 public function close() {
caffc55a 328 if ($this->users_rs) {
d24832f9 329 $this->users_rs->close();
caffc55a 330 $this->users_rs = null;
0f5660f7 331 }
caffc55a 332 if ($this->grades_rs) {
d24832f9 333 $this->grades_rs->close();
caffc55a 334 $this->grades_rs = null;
0f5660f7 335 }
336 $this->gradestack = array();
337 }
338
78ab98bc
AD
339 /**
340 * Should all enrolled users be exported or just those with an active enrolment?
341 *
342 * @param bool $onlyactive True to limit the export to users with an active enrolment
343 */
344 public function require_active_enrolment($onlyactive = true) {
345 if (!empty($this->users_rs)) {
346 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
347 }
348 $this->onlyactive = $onlyactive;
349 }
350
61c8e0d7
FM
351 /**
352 * Allow custom fields to be included
353 *
354 * @param bool $allow Whether to allow custom fields or not
355 * @return void
356 */
357 public function allow_user_custom_fields($allow = true) {
358 if ($allow) {
359 $this->allowusercustomfields = true;
360 } else {
361 $this->allowusercustomfields = false;
362 }
363 }
cf72e2dd 364
0f5660f7 365 /**
728ff21b 366 * Add a grade_grade instance to the grade stack
cf72e2dd 367 *
368 * @param grade_grade $grade Grade object
369 *
370 * @return void
0f5660f7 371 */
728ff21b 372 private function _push($grade) {
0f5660f7 373 array_push($this->gradestack, $grade);
374 }
375
cf72e2dd 376
0f5660f7 377 /**
728ff21b 378 * Remove a grade_grade instance from the grade stack
cf72e2dd 379 *
728ff21b 380 * @return grade_grade current grade object
0f5660f7 381 */
728ff21b 382 private function _pop() {
d24832f9 383 global $DB;
0f5660f7 384 if (empty($this->gradestack)) {
8de7c8a7 385 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
cf72e2dd 386 return null; // no grades present
0f5660f7 387 }
388
7ce5df86
AD
389 $current = $this->grades_rs->current();
390
391 $this->grades_rs->next();
0f5660f7 392
7ce5df86 393 return $current;
0f5660f7 394 } else {
395 return array_pop($this->gradestack);
396 }
397 }
398}
399
d08bba83 400/**
401 * Print a selection popup form of the graded users in a course.
402 *
4d5059d4
SH
403 * @deprecated since 2.0
404 *
cf72e2dd 405 * @param int $course id of the course
d08bba83 406 * @param string $actionpage The page receiving the data from the popoup form
cf72e2dd 407 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
408 * @param int $groupid id of requested group, 0 means all
409 * @param int $includeall bool include all option
410 * @param bool $return If true, will return the HTML, otherwise, will print directly
d08bba83 411 * @return null
412 */
7ac88172 413function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
714b4745 414 global $CFG, $USER, $OUTPUT;
4d5059d4
SH
415 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
416}
345674ca 417
4d5059d4 418function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
4e829d48 419 global $USER, $CFG;
f9510667 420
879c99bb 421 if (is_null($userid)) {
422 $userid = $USER->id;
423 }
38c1dd19
RT
424 $coursecontext = context_course::instance($course->id);
425 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
426 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
427 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
d08bba83 428 $menu = array(); // Will be a list of userid => user name
38c1dd19 429 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
772229f3 430 $gui = new graded_users_iterator($course, null, $groupid);
38c1dd19 431 $gui->require_active_enrolment($showonlyactiveenrol);
d08bba83 432 $gui->init();
10f5c046 433 $label = get_string('selectauser', 'grades');
7ac88172 434 if ($includeall) {
879c99bb 435 $menu[0] = get_string('allusers', 'grades');
10f5c046 436 $label = get_string('selectalloroneuser', 'grades');
d08bba83 437 }
d08bba83 438 while ($userdata = $gui->next_user()) {
439 $user = $userdata->user;
38c1dd19
RT
440 $userfullname = fullname($user);
441 if ($user->suspendedenrolment) {
442 $menususpendedusers[$user->id] = $userfullname;
443 } else {
444 $menu[$user->id] = $userfullname;
445 }
d08bba83 446 }
d08bba83 447 $gui->close();
448
7ac88172 449 if ($includeall) {
38c1dd19
RT
450 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
451 }
452
453 if (!empty($menususpendedusers)) {
454 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
879c99bb 455 }
9a2da737
NP
456 $gpr = new grade_plugin_return(array('type' => 'report', 'course' => $course, 'groupid' => $groupid));
457 $select = new single_select(
458 new moodle_url('/grade/report/'.$report.'/index.php', $gpr->get_options()),
459 'userid', $menu, $userid
460 );
f8dab966
PS
461 $select->label = $label;
462 $select->formid = 'choosegradeuser';
4d5059d4 463 return $select;
d08bba83 464}
465
a9937aec
DW
466/**
467 * Hide warning about changed grades during upgrade to 2.8.
468 *
469 * @param int $courseid The current course id.
470 */
471function hide_natural_aggregation_upgrade_notice($courseid) {
c8eb1fae 472 unset_config('show_sumofgrades_upgrade_' . $courseid);
a9937aec
DW
473}
474
c07775df
EM
475/**
476 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
477 *
478 * @param int $courseid The current course id.
479 */
ebea19cb 480function grade_hide_min_max_grade_upgrade_notice($courseid) {
c07775df
EM
481 unset_config('show_min_max_grades_changed_' . $courseid);
482}
483
484/**
ebea19cb
FM
485 * Use the grade min and max from the grade_grade.
486 *
487 * This is reserved for core use after an upgrade.
c07775df
EM
488 *
489 * @param int $courseid The current course id.
490 */
ebea19cb
FM
491function grade_upgrade_use_min_max_from_grade_grade($courseid) {
492 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
c07775df
EM
493
494 grade_force_full_regrading($courseid);
495 // Do this now, because it probably happened to late in the page load to be happen automatically.
496 grade_regrade_final_grades($courseid);
497}
498
499/**
ebea19cb
FM
500 * Use the grade min and max from the grade_item.
501 *
502 * This is reserved for core use after an upgrade.
c07775df
EM
503 *
504 * @param int $courseid The current course id.
505 */
ebea19cb
FM
506function grade_upgrade_use_min_max_from_grade_item($courseid) {
507 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
c07775df
EM
508
509 grade_force_full_regrading($courseid);
510 // Do this now, because it probably happened to late in the page load to be happen automatically.
511 grade_regrade_final_grades($courseid);
512}
513
47d6e6a7
DW
514/**
515 * Hide warning about changed grades during upgrade to 2.8.
516 *
517 * @param int $courseid The current course id.
518 */
519function hide_aggregatesubcats_upgrade_notice($courseid) {
520 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
521}
522
deb3d5ed
MG
523/**
524 * Hide warning about changed grades due to bug fixes
525 *
526 * @param int $courseid The current course id.
527 */
528function hide_gradebook_calculations_freeze_notice($courseid) {
529 unset_config('gradebook_calculations_freeze_' . $courseid);
530}
531
a9937aec
DW
532/**
533 * Print warning about changed grades during upgrade to 2.8.
534 *
535 * @param int $courseid The current course id.
536 * @param context $context The course context.
eafab799 537 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
a9937aec
DW
538 * @param boolean $return return as string
539 *
540 * @return nothing or string if $return true
541 */
eafab799 542function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
ebea19cb 543 global $CFG, $OUTPUT;
a9937aec 544 $html = '';
a9937aec 545
ebea19cb
FM
546 // Do not do anything if they cannot manage the grades of this course.
547 if (!has_capability('moodle/grade:manage', $context)) {
548 return $html;
549 }
550
eafab799
DW
551 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
552 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
553 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
554 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
ebea19cb 555
c07775df
EM
556 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
557 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
eafab799 558
ebea19cb
FM
559 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
560 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
561
562 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
eafab799 563
deb3d5ed
MG
564 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
565 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
566
eafab799
DW
567 // Hide the warning if the user told it to go away.
568 if ($hidenaturalwarning) {
569 hide_natural_aggregation_upgrade_notice($courseid);
570 }
571 // Hide the warning if the user told it to go away.
572 if ($hidesubcatswarning) {
573 hide_aggregatesubcats_upgrade_notice($courseid);
574 }
575
ebea19cb 576 // Hide the min/max warning if the user told it to go away.
c07775df 577 if ($hideminmaxwarning) {
ebea19cb
FM
578 grade_hide_min_max_grade_upgrade_notice($courseid);
579 $showminmaxwarning = false;
c07775df
EM
580 }
581
ebea19cb
FM
582 if ($useminmaxfromgradegrade) {
583 // Revert to the new behaviour, we now use the grade_grade for min/max.
584 grade_upgrade_use_min_max_from_grade_grade($courseid);
585 grade_hide_min_max_grade_upgrade_notice($courseid);
586 $showminmaxwarning = false;
587
588 } else if ($useminmaxfromgradeitem) {
589 // Apply the new logic, we now use the grade_item for min/max.
590 grade_upgrade_use_min_max_from_grade_item($courseid);
591 grade_hide_min_max_grade_upgrade_notice($courseid);
592 $showminmaxwarning = false;
c07775df
EM
593 }
594
595
eafab799 596 if (!$hidenaturalwarning && $shownaturalwarning) {
a9937aec 597 $message = get_string('sumofgradesupgradedgrades', 'grades');
47d6e6a7 598 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
a9937aec
DW
599 $urlparams = array( 'id' => $courseid,
600 'seensumofgradesupgradedgrades' => true,
601 'sesskey' => sesskey());
eafab799 602 $goawayurl = new moodle_url($thispage, $urlparams);
a9937aec
DW
603 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
604 $html .= $OUTPUT->notification($message, 'notifysuccess');
605 $html .= $goawaybutton;
606 }
607
eafab799 608 if (!$hidesubcatswarning && $showsubcatswarning) {
47d6e6a7
DW
609 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
610 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
611 $urlparams = array( 'id' => $courseid,
612 'seenaggregatesubcatsupgradedgrades' => true,
613 'sesskey' => sesskey());
eafab799 614 $goawayurl = new moodle_url($thispage, $urlparams);
47d6e6a7
DW
615 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
616 $html .= $OUTPUT->notification($message, 'notifysuccess');
617 $html .= $goawaybutton;
618 }
619
ebea19cb 620 if ($showminmaxwarning) {
c07775df
EM
621 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
622 $urlparams = array( 'id' => $courseid,
623 'seenminmaxupgradedgrades' => true,
624 'sesskey' => sesskey());
ebea19cb 625
c07775df 626 $goawayurl = new moodle_url($thispage, $urlparams);
ebea19cb
FM
627 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
628 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
629 array('target' => '_blank'));
630
631 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
632 // Show the message that there were min/max issues that have been resolved.
633 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
634
635 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
636 $urlparams = array('id' => $courseid,
637 'useminmaxfromgradegrade' => true,
638 'sesskey' => sesskey());
639 $reverturl = new moodle_url($thispage, $urlparams);
640 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
641
f677ece5 642 $html .= $OUTPUT->notification($message);
ebea19cb
FM
643 $html .= $revertbutton . $hideminmaxbutton;
644
645 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
646 // Show the warning that there are min/max issues that have not be resolved.
647 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
648
649 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
650 $urlparams = array('id' => $courseid,
651 'useminmaxfromgradeitem' => true,
652 'sesskey' => sesskey());
653 $fixurl = new moodle_url($thispage, $urlparams);
654 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
655
f677ece5 656 $html .= $OUTPUT->notification($message);
ebea19cb
FM
657 $html .= $fixbutton . $hideminmaxbutton;
658 }
c07775df
EM
659 }
660
deb3d5ed
MG
661 if ($gradebookcalculationsfreeze) {
662 if ($acceptgradebookchanges) {
663 // Accept potential changes in grades caused by extra credit bug MDL-49257.
664 hide_gradebook_calculations_freeze_notice($courseid);
665 $courseitem = grade_item::fetch_course_item($courseid);
666 $courseitem->force_regrading();
667 grade_regrade_final_grades($courseid);
668
669 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
670 } else {
671 // Show the warning that there may be extra credit weights problems.
672 $a = new stdClass();
673 $a->gradebookversion = $gradebookcalculationsfreeze;
674 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
675 $a->currentversion = $matches[1];
676 } else {
677 $a->currentversion = $CFG->release;
678 }
6e4b8381 679 $a->url = get_docs_url('Gradebook_calculation_changes');
deb3d5ed
MG
680 $message = get_string('gradebookcalculationswarning', 'grades', $a);
681
682 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
683 $urlparams = array('id' => $courseid,
684 'acceptgradebookchanges' => true,
685 'sesskey' => sesskey());
686 $fixurl = new moodle_url($thispage, $urlparams);
687 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
688
f677ece5 689 $html .= $OUTPUT->notification($message);
deb3d5ed
MG
690 $html .= $fixbutton;
691 }
692 }
693
ebea19cb
FM
694 if (!empty($html)) {
695 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
c07775df
EM
696 }
697
a9937aec
DW
698 if ($return) {
699 return $html;
700 } else {
701 echo $html;
702 }
703}
704
0610812a 705/**
706 * Print grading plugin selection popup form.
707 *
cf72e2dd 708 * @param array $plugin_info An array of plugins containing information for the selector
0610812a 709 * @param boolean $return return as string
cf72e2dd 710 *
0610812a 711 * @return nothing or string if $return true
712 */
f1a3e072 713function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
714b4745 714 global $CFG, $OUTPUT, $PAGE;
dc482cfa 715
716 $menu = array();
717 $count = 0;
718 $active = '';
719
720 foreach ($plugin_info as $plugin_type => $plugins) {
721 if ($plugin_type == 'strings') {
722 continue;
723 }
724
7981d537 725 $first_plugin = reset($plugins);
dc482cfa 726
f1a3e072
PS
727 $sectionname = $plugin_info['strings'][$plugin_type];
728 $section = array();
d4dcfc6b 729
f1a3e072 730 foreach ($plugins as $plugin) {
d4dcfc6b 731 $link = $plugin->link->out(false);
f1a3e072
PS
732 $section[$link] = $plugin->string;
733 $count++;
734 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
735 $active = $link;
dc482cfa 736 }
737 }
f1a3e072
PS
738
739 if ($section) {
740 $menu[] = array($sectionname=>$section);
741 }
dc482cfa 742 }
743
cf72e2dd 744 // finally print/return the popup form
dc482cfa 745 if ($count > 1) {
f1a3e072 746 $select = new url_select($menu, $active, null, 'choosepluginreport');
29bea634 747 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
7981d537 748 if ($return) {
f1a3e072 749 return $OUTPUT->render($select);
7981d537 750 } else {
f1a3e072 751 echo $OUTPUT->render($select);
7981d537 752 }
dc482cfa 753 } else {
754 // only one option - no plugin selector needed
755 return '';
756 }
757}
758
759/**
760 * Print grading plugin selection tab-based navigation.
761 *
cf72e2dd 762 * @param string $active_type type of plugin on current page - import, export, report or edit
763 * @param string $active_plugin active plugin type - grader, user, cvs, ...
764 * @param array $plugin_info Array of plugins
dc482cfa 765 * @param boolean $return return as string
cf72e2dd 766 *
dc482cfa 767 * @return nothing or string if $return true
768 */
b827784e 769function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
dc482cfa 770 global $CFG, $COURSE;
1c1f64a2 771
e1513ca9 772 if (!isset($currenttab)) { //TODO: this is weird
dc482cfa 773 $currenttab = '';
774 }
775
776 $tabs = array();
777 $top_row = array();
778 $bottom_row = array();
779 $inactive = array($active_plugin);
f48d5209 780 $activated = array($active_type);
dc482cfa 781
782 $count = 0;
783 $active = '';
784
785 foreach ($plugin_info as $plugin_type => $plugins) {
786 if ($plugin_type == 'strings') {
787 continue;
788 }
789
790 // If $plugins is actually the definition of a child-less parent link:
cf72e2dd 791 if (!empty($plugins->id)) {
792 $string = $plugins->string;
793 if (!empty($plugin_info[$active_type]->parent)) {
794 $string = $plugin_info[$active_type]->parent->string;
27eef3bb 795 }
796
cf72e2dd 797 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
dc482cfa 798 continue;
799 }
800
801 $first_plugin = reset($plugins);
cf72e2dd 802 $url = $first_plugin->link;
dc482cfa 803
804 if ($plugin_type == 'report') {
805 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
806 }
807
808 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
809
810 if ($active_type == $plugin_type) {
811 foreach ($plugins as $plugin) {
cf72e2dd 812 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
813 if ($plugin->id == $active_plugin) {
814 $inactive = array($plugin->id);
dc482cfa 815 }
816 }
817 }
818 }
819
b0842f61
MG
820 // Do not display rows that contain only one item, they are not helpful.
821 if (count($top_row) > 1) {
822 $tabs[] = $top_row;
823 }
824 if (count($bottom_row) > 1) {
825 $tabs[] = $bottom_row;
826 }
827 if (empty($tabs)) {
828 return;
829 }
830
831 $rv = html_writer::div(print_tabs($tabs, $active_plugin, $inactive, $activated, true), 'grade-navigation');
dc482cfa 832
833 if ($return) {
b0842f61 834 return $rv;
dc482cfa 835 } else {
b0842f61 836 echo $rv;
dc482cfa 837 }
838}
839
cf72e2dd 840/**
841 * grade_get_plugin_info
842 *
843 * @param int $courseid The course id
844 * @param string $active_type type of plugin on current page - import, export, report or edit
845 * @param string $active_plugin active plugin type - grader, user, cvs, ...
846 *
847 * @return array
848 */
dc482cfa 849function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
f7fcf4cd 850 global $CFG, $SITE;
cbff94ba 851
d4060472 852 $context = context_course::instance($courseid);
cbff94ba 853
dc482cfa 854 $plugin_info = array();
6e2f3121 855 $count = 0;
3af29899 856 $active = '';
dc482cfa 857 $url_prefix = $CFG->wwwroot . '/grade/';
858
859 // Language strings
4d5059d4 860 $plugin_info['strings'] = grade_helper::get_plugin_strings();
b827784e 861
4d5059d4
SH
862 if ($reports = grade_helper::get_plugins_reports($courseid)) {
863 $plugin_info['report'] = $reports;
b827784e 864 }
c46aeeab 865
eb84b779
MG
866 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
867 $plugin_info['settings'] = $settings;
868 }
869
4d5059d4
SH
870 if ($scale = grade_helper::get_info_scales($courseid)) {
871 $plugin_info['scale'] = array('view'=>$scale);
cbff94ba 872 }
dc482cfa 873
4d5059d4
SH
874 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
875 $plugin_info['outcome'] = $outcomes;
cbff94ba 876 }
cbff94ba 877
4d5059d4
SH
878 if ($letters = grade_helper::get_info_letters($courseid)) {
879 $plugin_info['letter'] = $letters;
cbff94ba 880 }
4d5059d4
SH
881
882 if ($imports = grade_helper::get_plugins_import($courseid)) {
883 $plugin_info['import'] = $imports;
281ffa4a 884 }
c46aeeab 885
4d5059d4
SH
886 if ($exports = grade_helper::get_plugins_export($courseid)) {
887 $plugin_info['export'] = $exports;
281ffa4a 888 }
281ffa4a 889
4d5059d4
SH
890 foreach ($plugin_info as $plugin_type => $plugins) {
891 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
892 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
893 break;
281ffa4a 894 }
4d5059d4
SH
895 foreach ($plugins as $plugin) {
896 if (is_a($plugin, 'grade_plugin_info')) {
897 if ($active_plugin == $plugin->id) {
898 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
899 }
3af29899 900 }
281ffa4a 901 }
cbff94ba 902 }
c46aeeab 903
dc482cfa 904 return $plugin_info;
905}
284abb09 906
cf72e2dd 907/**
908 * A simple class containing info about grade plugins.
909 * Can be subclassed for special rules
910 *
a153c9f2 911 * @package core_grades
cf72e2dd 912 * @copyright 2009 Nicolas Connault
913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
914 */
915class grade_plugin_info {
916 /**
917 * A unique id for this plugin
918 *
919 * @var mixed
920 */
921 public $id;
922 /**
923 * A URL to access this plugin
924 *
925 * @var mixed
926 */
927 public $link;
928 /**
929 * The name of this plugin
930 *
931 * @var mixed
932 */
933 public $string;
934 /**
935 * Another grade_plugin_info object, parent of the current one
936 *
937 * @var mixed
938 */
939 public $parent;
940
941 /**
942 * Constructor
943 *
944 * @param int $id A unique id for this plugin
945 * @param string $link A URL to access this plugin
946 * @param string $string The name of this plugin
947 * @param object $parent Another grade_plugin_info object, parent of the current one
948 *
949 * @return void
950 */
951 public function __construct($id, $link, $string, $parent=null) {
952 $this->id = $id;
953 $this->link = $link;
954 $this->string = $string;
955 $this->parent = $parent;
956 }
957}
958
de0300ea 959/**
960 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
961 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
962 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
963 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
964 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
965 *
cf72e2dd 966 * @param int $courseid Course id
967 * @param string $active_type The type of the current page (report, settings,
968 * import, export, scales, outcomes, letters)
969 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
970 * @param string $heading The heading of the page. Tries to guess if none is given
de0300ea 971 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
cf72e2dd 972 * @param string $bodytags Additional attributes that will be added to the <body> tag
973 * @param string $buttons Additional buttons to display on the page
5625d33d 974 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
1464bcc8
AG
975 * @param string $headerhelpidentifier The help string identifier if required.
976 * @param string $headerhelpcomponent The component for the help string.
1acbd1f9 977 * @param stdClass $user The user object for use with the user context header.
de0300ea 978 *
979 * @return string HTML code or nothing if $return == false
980 */
cf72e2dd 981function print_grade_page_head($courseid, $active_type, $active_plugin=null,
34a2777c 982 $heading = false, $return=false,
1acbd1f9
AG
983 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null,
984 $user = null) {
4d5059d4 985 global $CFG, $OUTPUT, $PAGE;
c46aeeab 986
45bd824e
JD
987 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
988 require_once($CFG->dirroot . '/course/lib.php');
36272110 989 if (course_modules_pending_deletion($courseid, true)) {
45bd824e
JD
990 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
991 \core\output\notification::NOTIFY_WARNING);
992 }
993
eb84b779
MG
994 if ($active_type === 'preferences') {
995 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
996 $active_type = 'settings';
997 }
998
dc482cfa 999 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
c46aeeab 1000
dc482cfa 1001 // Determine the string of the active plugin
1002 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
1003 $stractive_type = $plugin_info['strings'][$active_type];
e0724506 1004
cf72e2dd 1005 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
4d5059d4
SH
1006 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
1007 } else {
1008 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
c4c97a6d 1009 }
1010
367a75fa
SH
1011 if ($active_type == 'report') {
1012 $PAGE->set_pagelayout('report');
1013 } else {
1014 $PAGE->set_pagelayout('admin');
1015 }
4d5059d4 1016 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
f3df5e14 1017 $PAGE->set_heading($title);
4d5059d4
SH
1018 if ($buttons instanceof single_button) {
1019 $buttons = $OUTPUT->render($buttons);
1020 }
f3df5e14 1021 $PAGE->set_button($buttons);
6bf696bb
MG
1022 if ($courseid != SITEID) {
1023 grade_extend_settings($plugin_info, $courseid);
1024 }
4d5059d4 1025
0c31d924
AN
1026 // Set the current report as active in the breadcrumbs.
1027 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
1028 $reportnav->make_active();
1029 }
1030
f3df5e14 1031 $returnval = $OUTPUT->header();
1464bcc8 1032
f3df5e14 1033 if (!$return) {
1034 echo $returnval;
1035 }
dc482cfa 1036
1037 // Guess heading if not given explicitly
1038 if (!$heading) {
1039 $heading = $stractive_plugin;
1040 }
1041
2821c495 1042 if ($shownavigation) {
1acbd1f9 1043 $navselector = null;
6bf696bb
MG
1044 if ($courseid != SITEID &&
1045 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1acbd1f9
AG
1046 // It's absolutely essential that this grade plugin selector is shown after the user header. Just ask Fred.
1047 $navselector = print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, true);
1048 if ($return) {
1049 $returnval .= $navselector;
1050 } else if (!isset($user)) {
1051 echo $navselector;
1052 }
2821c495 1053 }
5625d33d 1054
1464bcc8
AG
1055 $output = '';
1056 // Add a help dialogue box if provided.
1057 if (isset($headerhelpidentifier)) {
1058 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1059 } else {
1acbd1f9
AG
1060 if (isset($user)) {
1061 $output = $OUTPUT->context_header(
1062 array(
013abd64
LB
1063 'heading' => html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id,
1064 'course' => $courseid)), fullname($user)),
1acbd1f9
AG
1065 'user' => $user,
1066 'usercontext' => context_user::instance($user->id)
1067 ), 2
1068 ) . $navselector;
1069 } else {
1070 $output = $OUTPUT->heading($heading);
1071 }
1464bcc8
AG
1072 }
1073
5625d33d 1074 if ($return) {
1464bcc8 1075 $returnval .= $output;
5625d33d 1076 } else {
1464bcc8 1077 echo $output;
5625d33d
AD
1078 }
1079
6bf696bb
MG
1080 if ($courseid != SITEID &&
1081 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
2821c495
AD
1082 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1083 }
8354e716 1084 }
dc482cfa 1085
eafab799
DW
1086 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1087 context_course::instance($courseid),
f01972d9 1088 $PAGE->url,
eafab799
DW
1089 $return);
1090
dc482cfa 1091 if ($return) {
1092 return $returnval;
6e2f3121 1093 }
cbff94ba 1094}
1095
0610812a 1096/**
7a6b7acf 1097 * Utility class used for return tracking when using edit and other forms in grade plugins
cf72e2dd 1098 *
a153c9f2 1099 * @package core_grades
cf72e2dd 1100 * @copyright 2009 Nicolas Connault
1101 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0610812a 1102 */
3af29899 1103class grade_plugin_return {
9a2da737
NP
1104 /**
1105 * Type of grade plugin (e.g. 'edit', 'report')
1106 *
1107 * @var string
1108 */
d24832f9 1109 public $type;
9a2da737
NP
1110 /**
1111 * Name of grade plugin (e.g. 'grader', 'overview')
1112 *
1113 * @var string
1114 */
d24832f9 1115 public $plugin;
9a2da737
NP
1116 /**
1117 * Course id being viewed
1118 *
1119 * @var int
1120 */
d24832f9 1121 public $courseid;
9a2da737
NP
1122 /**
1123 * Id of user whose information is being viewed/edited
1124 *
1125 * @var int
1126 */
d24832f9 1127 public $userid;
9a2da737
NP
1128 /**
1129 * Id of group for which information is being viewed/edited
1130 *
1131 * @var int
1132 */
1133 public $groupid;
1134 /**
1135 * Current page # within output
1136 *
1137 * @var int
1138 */
d24832f9 1139 public $page;
281ffa4a 1140
0610812a 1141 /**
1142 * Constructor
cf72e2dd 1143 *
9a2da737 1144 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
0610812a 1145 */
9a2da737
NP
1146 public function __construct($params = []) {
1147 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1148 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1149 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1150 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1151 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1152 $this->page = optional_param('gpr_page', null, PARAM_INT);
1153
1154 foreach ($params as $key => $value) {
1155 if (property_exists($this, $key)) {
1156 $this->$key = $value;
1157 }
1158 }
1159 // Allow course object rather than id to be used to specify course
1160 // - avoid unnecessary use of get_course.
1161 if (array_key_exists('course', $params)) {
1162 $course = $params['course'];
1163 $this->courseid = $course->id;
a983b6ec 1164 } else {
9a2da737
NP
1165 $course = null;
1166 }
1167 // If group has been explicitly set in constructor parameters,
1168 // we should respect that.
1169 if (!array_key_exists('groupid', $params)) {
1170 // Otherwise, 'group' in request parameters is a request for a change.
1171 // In that case, or if we have no group at all, we should get groupid from
1172 // groups_get_course_group, which will do some housekeeping as well as
1173 // give us the correct value.
1174 $changegroup = optional_param('group', -1, PARAM_INT);
1175 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1176 if ($course === null) {
1177 $course = get_course($this->courseid);
3af29899 1178 }
9a2da737 1179 $this->groupid = groups_get_course_group($course, true);
cbff94ba 1180 }
1181 }
6cd8c592 1182 }
1183
9e313e79
DM
1184 /**
1185 * Old syntax of class constructor. Deprecated in PHP7.
1186 *
1187 * @deprecated since Moodle 3.1
1188 */
1189 public function grade_plugin_return($params = null) {
1190 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1191 self::__construct($params);
1192 }
1193
0610812a 1194 /**
1195 * Returns return parameters as options array suitable for buttons.
1196 * @return array options
1197 */
d24832f9 1198 public function get_options() {
7a6b7acf 1199 if (empty($this->type)) {
3af29899 1200 return array();
865e9a82 1201 }
6cd8c592 1202
3af29899 1203 $params = array();
6cd8c592 1204
7a6b7acf 1205 if (!empty($this->plugin)) {
1206 $params['plugin'] = $this->plugin;
1207 }
6cd8c592 1208
3af29899 1209 if (!empty($this->courseid)) {
1210 $params['id'] = $this->courseid;
6cd8c592 1211 }
9c61ba4d 1212
3af29899 1213 if (!empty($this->userid)) {
1214 $params['userid'] = $this->userid;
9c61ba4d 1215 }
9c61ba4d 1216
9a2da737
NP
1217 if (!empty($this->groupid)) {
1218 $params['group'] = $this->groupid;
1219 }
1220
3af29899 1221 if (!empty($this->page)) {
1222 $params['page'] = $this->page;
cbff94ba 1223 }
865e9a82 1224
3af29899 1225 return $params;
cbff94ba 1226 }
cbff94ba 1227
0610812a 1228 /**
1229 * Returns return url
cf72e2dd 1230 *
0610812a 1231 * @param string $default default url when params not set
cf72e2dd 1232 * @param array $extras Extra URL parameters
1233 *
0610812a 1234 * @return string url
1235 */
d24832f9 1236 public function get_return_url($default, $extras=null) {
3af29899 1237 global $CFG;
cbff94ba 1238
3af29899 1239 if (empty($this->type) or empty($this->plugin)) {
1240 return $default;
cbff94ba 1241 }
1242
65dd61bd 1243 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1244 $glue = '?';
cbff94ba 1245
3af29899 1246 if (!empty($this->courseid)) {
1247 $url .= $glue.'id='.$this->courseid;
1248 $glue = '&amp;';
cbff94ba 1249 }
cbff94ba 1250
3af29899 1251 if (!empty($this->userid)) {
1252 $url .= $glue.'userid='.$this->userid;
1253 $glue = '&amp;';
cbff94ba 1254 }
7e2d7c92 1255
9a2da737
NP
1256 if (!empty($this->groupid)) {
1257 $url .= $glue.'group='.$this->groupid;
1258 $glue = '&amp;';
1259 }
1260
3af29899 1261 if (!empty($this->page)) {
1262 $url .= $glue.'page='.$this->page;
65dd61bd 1263 $glue = '&amp;';
1264 }
1265
1266 if (!empty($extras)) {
cf72e2dd 1267 foreach ($extras as $key=>$value) {
65dd61bd 1268 $url .= $glue.$key.'='.$value;
1269 $glue = '&amp;';
7a6b7acf 1270 }
cbff94ba 1271 }
cbff94ba 1272
3af29899 1273 return $url;
cbff94ba 1274 }
cbff94ba 1275
0610812a 1276 /**
1277 * Returns string with hidden return tracking form elements.
1278 * @return string
1279 */
d24832f9 1280 public function get_form_fields() {
7a6b7acf 1281 if (empty($this->type)) {
3af29899 1282 return '';
cbff94ba 1283 }
cbff94ba 1284
3af29899 1285 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 1286
1287 if (!empty($this->plugin)) {
1288 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1289 }
0ca5abd6 1290
3af29899 1291 if (!empty($this->courseid)) {
1292 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 1293 }
cbff94ba 1294
3af29899 1295 if (!empty($this->userid)) {
1296 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 1297 }
cbff94ba 1298
9a2da737
NP
1299 if (!empty($this->groupid)) {
1300 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1301 }
1302
3af29899 1303 if (!empty($this->page)) {
1304 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 1305 }
9a2da737 1306 return $result;
cbff94ba 1307 }
cbff94ba 1308
0610812a 1309 /**
1310 * Add hidden elements into mform
cf72e2dd 1311 *
1312 * @param object &$mform moodle form object
1313 *
0610812a 1314 * @return void
1315 */
d24832f9 1316 public function add_mform_elements(&$mform) {
7a6b7acf 1317 if (empty($this->type)) {
3af29899 1318 return;
cbff94ba 1319 }
cbff94ba 1320
3af29899 1321 $mform->addElement('hidden', 'gpr_type', $this->type);
1322 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 1323
7a6b7acf 1324 if (!empty($this->plugin)) {
1325 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
aff24313 1326 $mform->setType('gpr_plugin', PARAM_PLUGIN);
7a6b7acf 1327 }
97033c86 1328
3af29899 1329 if (!empty($this->courseid)) {
1330 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1331 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 1332 }
cbff94ba 1333
3af29899 1334 if (!empty($this->userid)) {
1335 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1336 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 1337 }
cbff94ba 1338
9a2da737
NP
1339 if (!empty($this->groupid)) {
1340 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1341 $mform->setType('gpr_groupid', PARAM_INT);
1342 }
1343
3af29899 1344 if (!empty($this->page)) {
1345 $mform->addElement('hidden', 'gpr_page', $this->page);
1346 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 1347 }
1348 }
281ffa4a 1349
0610812a 1350 /**
1351 * Add return tracking params into url
cf72e2dd 1352 *
1c1f64a2 1353 * @param moodle_url $url A URL
cf72e2dd 1354 *
6ef4878b 1355 * @return string $url with return tracking params
0610812a 1356 */
1c1f64a2 1357 public function add_url_params(moodle_url $url) {
7a6b7acf 1358 if (empty($this->type)) {
3af29899 1359 return $url;
cbff94ba 1360 }
5609f9e6 1361
1c1f64a2 1362 $url->param('gpr_type', $this->type);
cbff94ba 1363
7a6b7acf 1364 if (!empty($this->plugin)) {
1c1f64a2 1365 $url->param('gpr_plugin', $this->plugin);
7a6b7acf 1366 }
cbff94ba 1367
3af29899 1368 if (!empty($this->courseid)) {
1c1f64a2 1369 $url->param('gpr_courseid' ,$this->courseid);
cbff94ba 1370 }
cbff94ba 1371
3af29899 1372 if (!empty($this->userid)) {
1c1f64a2 1373 $url->param('gpr_userid', $this->userid);
cbff94ba 1374 }
0a8a95c9 1375
9a2da737
NP
1376 if (!empty($this->groupid)) {
1377 $url->param('gpr_groupid', $this->groupid);
1378 }
1379
3af29899 1380 if (!empty($this->page)) {
1c1f64a2 1381 $url->param('gpr_page', $this->page);
0a8a95c9 1382 }
5a412dbf 1383
3af29899 1384 return $url;
5a412dbf 1385 }
5a412dbf 1386}
7a6b7acf 1387
826c5f86 1388/**
1389 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
cf72e2dd 1390 *
826c5f86 1391 * @param string $path The path of the calling script (using __FILE__?)
1392 * @param string $pagename The language string to use as the last part of the navigation (non-link)
cf72e2dd 1393 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1394 * an array of keys and values (e.g courseid => $courseid, itemid...)
1395 *
826c5f86 1396 * @return string
1397 */
1398function grade_build_nav($path, $pagename=null, $id=null) {
f3df5e14 1399 global $CFG, $COURSE, $PAGE;
826c5f86 1400
1401 $strgrades = get_string('grades', 'grades');
1402
1403 // Parse the path and build navlinks from its elements
1404 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1405 $path = substr($path, $dirroot_length);
1406 $path = str_replace('\\', '/', $path);
1407
1408 $path_elements = explode('/', $path);
1409
1410 $path_elements_count = count($path_elements);
1411
826c5f86 1412 // First link is always 'grade'
a6855934 1413 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
826c5f86 1414
f3df5e14 1415 $link = null;
826c5f86 1416 $numberofelements = 3;
1417
1418 // Prepare URL params string
f3df5e14 1419 $linkparams = array();
826c5f86 1420 if (!is_null($id)) {
1421 if (is_array($id)) {
1422 foreach ($id as $idkey => $idvalue) {
f3df5e14 1423 $linkparams[$idkey] = $idvalue;
826c5f86 1424 }
1425 } else {
f3df5e14 1426 $linkparams['id'] = $id;
826c5f86 1427 }
1428 }
1429
1430 $navlink4 = null;
1431
0f78c4de 1432 // Remove file extensions from filenames
1433 foreach ($path_elements as $key => $filename) {
1434 $path_elements[$key] = str_replace('.php', '', $filename);
1435 }
1436
826c5f86 1437 // Second level links
1438 switch ($path_elements[1]) {
1439 case 'edit': // No link
1440 if ($path_elements[3] != 'index.php') {
1441 $numberofelements = 4;
1442 }
1443 break;
1444 case 'import': // No link
1445 break;
1446 case 'export': // No link
1447 break;
1448 case 'report':
1449 // $id is required for this link. Do not print it if $id isn't given
1450 if (!is_null($id)) {
a6855934 1451 $link = new moodle_url('/grade/report/index.php', $linkparams);
826c5f86 1452 }
1453
1454 if ($path_elements[2] == 'grader') {
1455 $numberofelements = 4;
1456 }
1457 break;
1458
1459 default:
1460 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
cf72e2dd 1461 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1462 " as the second path element after 'grade'.");
826c5f86 1463 return false;
1464 }
f3df5e14 1465 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
826c5f86 1466
1467 // Third level links
1468 if (empty($pagename)) {
1469 $pagename = get_string($path_elements[2], 'grades');
1470 }
1471
1472 switch ($numberofelements) {
1473 case 3:
f3df5e14 1474 $PAGE->navbar->add($pagename, $link);
826c5f86 1475 break;
1476 case 4:
826c5f86 1477 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
b5e7b2bf 1478 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
826c5f86 1479 }
f3df5e14 1480 $PAGE->navbar->add($pagename);
826c5f86 1481 break;
1482 }
826c5f86 1483
f3df5e14 1484 return '';
d4795a07 1485}
7a6b7acf 1486
e98871a2 1487/**
6cc3e350 1488 * General structure representing grade items in course
cf72e2dd 1489 *
a153c9f2 1490 * @package core_grades
cf72e2dd 1491 * @copyright 2009 Nicolas Connault
1492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e98871a2 1493 */
6cc3e350 1494class grade_structure {
d24832f9 1495 public $context;
e98871a2 1496
d24832f9 1497 public $courseid;
e98871a2 1498
73ca5f01 1499 /**
1500 * Reference to modinfo for current course (for performance, to save
1501 * retrieving it from courseid every time). Not actually set except for
1502 * the grade_tree type.
1503 * @var course_modinfo
1504 */
1505 public $modinfo;
1506
e98871a2 1507 /**
1508 * 1D array of grade items only
1509 */
d24832f9 1510 public $items;
e98871a2 1511
6391ebe7 1512 /**
6cc3e350 1513 * Returns icon of element
cf72e2dd 1514 *
1515 * @param array &$element An array representing an element in the grade_tree
1516 * @param bool $spacerifnone return spacer if no icon found
1517 *
6cc3e350 1518 * @return string icon or spacer
6391ebe7 1519 */
d24832f9 1520 public function get_element_icon(&$element, $spacerifnone=false) {
6b608f8f 1521 global $CFG, $OUTPUT;
559276b1 1522 require_once $CFG->libdir.'/filelib.php';
6cc3e350 1523
1ef48469
JC
1524 $outputstr = '';
1525
1526 // Object holding pix_icon information before instantiation.
1527 $icon = new stdClass();
1528 $icon->attributes = array(
09235e24 1529 'class' => 'icon itemicon'
1ef48469
JC
1530 );
1531 $icon->component = 'moodle';
1532
1533 $none = true;
6cc3e350 1534 switch ($element['type']) {
1535 case 'item':
1536 case 'courseitem':
1537 case 'categoryitem':
1ef48469
JC
1538 $none = false;
1539
cf72e2dd 1540 $is_course = $element['object']->is_course_item();
1541 $is_category = $element['object']->is_category_item();
1542 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1543 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
0077f571 1544 $is_outcome = !empty($element['object']->outcomeid);
cf72e2dd 1545
6cc3e350 1546 if ($element['object']->is_calculated()) {
1ef48469
JC
1547 $icon->pix = 'i/calc';
1548 $icon->title = s(get_string('calculatedgrade', 'grades'));
6cc3e350 1549
cf72e2dd 1550 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
6cc3e350 1551 if ($category = $element['object']->get_item_category()) {
bfe969e8
DW
1552 $aggrstrings = grade_helper::get_aggregation_strings();
1553 $stragg = $aggrstrings[$category->aggregation];
1ef48469
JC
1554
1555 $icon->pix = 'i/calc';
1556 $icon->title = s($stragg);
1557
6cc3e350 1558 switch ($category->aggregation) {
1559 case GRADE_AGGREGATE_MEAN:
1560 case GRADE_AGGREGATE_MEDIAN:
1561 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1426edac 1562 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
6cc3e350 1563 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1ef48469
JC
1564 $icon->pix = 'i/agg_mean';
1565 break;
0758a08e 1566 case GRADE_AGGREGATE_SUM:
1ef48469
JC
1567 $icon->pix = 'i/agg_sum';
1568 break;
6cc3e350 1569 }
1570 }
1571
1572 } else if ($element['object']->itemtype == 'mod') {
1ef48469 1573 // Prevent outcomes displaying the same icon as the activity they are attached to.
0077f571 1574 if ($is_outcome) {
1ef48469
JC
1575 $icon->pix = 'i/outcomes';
1576 $icon->title = s(get_string('outcome', 'grades'));
0077f571 1577 } else {
bc6a7431
MG
1578 $modinfo = get_fast_modinfo($element['object']->courseid);
1579 $module = $element['object']->itemmodule;
1580 $instanceid = $element['object']->iteminstance;
1581 if (isset($modinfo->instances[$module][$instanceid])) {
1582 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
1583 } else {
1584 $icon->pix = 'icon';
1585 $icon->component = $element['object']->itemmodule;
1586 }
1ef48469 1587 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
0077f571 1588 }
6cc3e350 1589 } else if ($element['object']->itemtype == 'manual') {
1590 if ($element['object']->is_outcome_item()) {
1ef48469
JC
1591 $icon->pix = 'i/outcomes';
1592 $icon->title = s(get_string('outcome', 'grades'));
6cc3e350 1593 } else {
1ef48469
JC
1594 $icon->pix = 'i/manual_item';
1595 $icon->title = s(get_string('manualitem', 'grades'));
6cc3e350 1596 }
1597 }
1598 break;
1599
1600 case 'category':
1ef48469
JC
1601 $none = false;
1602 $icon->pix = 'i/folder';
1603 $icon->title = s(get_string('category', 'grades'));
1604 break;
6cc3e350 1605 }
1606
1ef48469
JC
1607 if ($none) {
1608 if ($spacerifnone) {
1609 $outputstr = $OUTPUT->spacer() . ' ';
1610 }
bc6a7431
MG
1611 } else if (isset($icon->url)) {
1612 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
6cc3e350 1613 } else {
1ef48469 1614 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
6cc3e350 1615 }
1ef48469
JC
1616
1617 return $outputstr;
6cc3e350 1618 }
6391ebe7 1619
e98871a2 1620 /**
6cc3e350 1621 * Returns name of element optionally with icon and link
cf72e2dd 1622 *
1623 * @param array &$element An array representing an element in the grade_tree
1624 * @param bool $withlink Whether or not this header has a link
1625 * @param bool $icon Whether or not to display an icon with this header
1626 * @param bool $spacerifnone return spacer if no icon found
65c2ac93 1627 * @param bool $withdescription Show description if defined by this item.
41e62a90
AN
1628 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1629 * instead of "Category total" or "Course total"
cf72e2dd 1630 *
1631 * @return string header
e98871a2 1632 */
41e62a90
AN
1633 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1634 $withdescription = false, $fulltotal = false) {
6cc3e350 1635 $header = '';
1636
1637 if ($icon) {
1638 $header .= $this->get_element_icon($element, $spacerifnone);
1639 }
1640
89eacee7
JB
1641 $title = $element['object']->get_name($fulltotal);
1642 $header .= $title;
6cc3e350 1643
cf72e2dd 1644 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1645 $element['type'] != 'courseitem') {
6cc3e350 1646 return $header;
1647 }
1648
43cd76e8
JC
1649 if ($withlink && $url = $this->get_activity_link($element)) {
1650 $a = new stdClass();
1651 $a->name = get_string('modulename', $element['object']->itemmodule);
89eacee7 1652 $a->title = $title;
43cd76e8
JC
1653 $title = get_string('linktoactivity', 'grades', $a);
1654
89eacee7 1655 $header = html_writer::link($url, $header, array('title' => $title, 'class' => 'gradeitemheader'));
43cd76e8 1656 } else {
89eacee7 1657 $header = html_writer::span($header, 'gradeitemheader', array('title' => $title, 'tabindex' => '0'));
6cc3e350 1658 }
1659
65c2ac93
DW
1660 if ($withdescription) {
1661 $desc = $element['object']->get_description();
1662 if (!empty($desc)) {
1663 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1664 }
1665 }
1666
6cc3e350 1667 return $header;
1668 }
1669
73ca5f01 1670 private function get_activity_link($element) {
1671 global $CFG;
eff314b0
DM
1672 /** @var array static cache of the grade.php file existence flags */
1673 static $hasgradephp = array();
73ca5f01 1674
1675 $itemtype = $element['object']->itemtype;
1676 $itemmodule = $element['object']->itemmodule;
1677 $iteminstance = $element['object']->iteminstance;
25ab1d50 1678 $itemnumber = $element['object']->itemnumber;
73ca5f01 1679
1680 // Links only for module items that have valid instance, module and are
1681 // called from grade_tree with valid modinfo
1682 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1683 return null;
1684 }
1685
1686 // Get $cm efficiently and with visibility information using modinfo
1687 $instances = $this->modinfo->get_instances();
1688 if (empty($instances[$itemmodule][$iteminstance])) {
1689 return null;
1690 }
1691 $cm = $instances[$itemmodule][$iteminstance];
1692
1693 // Do not add link if activity is not visible to the current user
1694 if (!$cm->uservisible) {
1695 return null;
1696 }
1697
eff314b0
DM
1698 if (!array_key_exists($itemmodule, $hasgradephp)) {
1699 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1700 $hasgradephp[$itemmodule] = true;
1701 } else {
1702 $hasgradephp[$itemmodule] = false;
1703 }
1704 }
1705
73ca5f01 1706 // If module has grade.php, link to that, otherwise view.php
eff314b0 1707 if ($hasgradephp[$itemmodule]) {
c97933ff
MG
1708 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1709 if (isset($element['userid'])) {
1710 $args['userid'] = $element['userid'];
1711 }
1712 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
73ca5f01 1713 } else {
1714 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1715 }
1716 }
1717
bb17ac1e
DM
1718 /**
1719 * Returns URL of a page that is supposed to contain detailed grade analysis
1720 *
bb17ac1e
DM
1721 * At the moment, only activity modules are supported. The method generates link
1722 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
eff314b0 1723 * gradeid and userid. If the grade.php does not exist, null is returned.
bb17ac1e
DM
1724 *
1725 * @return moodle_url|null URL or null if unable to construct it
1726 */
1727 public function get_grade_analysis_url(grade_grade $grade) {
eff314b0
DM
1728 global $CFG;
1729 /** @var array static cache of the grade.php file existence flags */
1730 static $hasgradephp = array();
bb17ac1e
DM
1731
1732 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1733 throw new coding_exception('Passed grade without the associated grade item');
1734 }
1735 $item = $grade->grade_item;
1736
1737 if (!$item->is_external_item()) {
1738 // at the moment, only activity modules are supported
1739 return null;
1740 }
1741 if ($item->itemtype !== 'mod') {
1742 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1743 }
1744 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1745 return null;
1746 }
1747
eff314b0
DM
1748 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1749 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1750 $hasgradephp[$item->itemmodule] = true;
1751 } else {
1752 $hasgradephp[$item->itemmodule] = false;
1753 }
1754 }
1755
1756 if (!$hasgradephp[$item->itemmodule]) {
1757 return null;
1758 }
1759
bb17ac1e
DM
1760 $instances = $this->modinfo->get_instances();
1761 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1762 return null;
1763 }
1764 $cm = $instances[$item->itemmodule][$item->iteminstance];
1765 if (!$cm->uservisible) {
1766 return null;
1767 }
1768
1769 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1770 'id' => $cm->id,
1771 'itemid' => $item->id,
1772 'itemnumber' => $item->itemnumber,
1773 'gradeid' => $grade->id,
1774 'userid' => $grade->userid,
1775 ));
1776
1777 return $url;
1778 }
1779
1780 /**
1781 * Returns an action icon leading to the grade analysis page
1782 *
1783 * @param grade_grade $grade
1784 * @return string
1785 */
1786 public function get_grade_analysis_icon(grade_grade $grade) {
1787 global $OUTPUT;
1788
1789 $url = $this->get_grade_analysis_url($grade);
1790 if (is_null($url)) {
1791 return '';
1792 }
1793
4e9b0c42
SR
1794 $title = get_string('gradeanalysis', 'core_grades');
1795 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1796 ['title' => $title, 'aria-label' => $title]);
bb17ac1e
DM
1797 }
1798
6cc3e350 1799 /**
1800 * Returns the grade eid - the grade may not exist yet.
cf72e2dd 1801 *
1802 * @param grade_grade $grade_grade A grade_grade object
1803 *
6cc3e350 1804 * @return string eid
1805 */
d24832f9 1806 public function get_grade_eid($grade_grade) {
6cc3e350 1807 if (empty($grade_grade->id)) {
1808 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1809 } else {
1810 return 'g'.$grade_grade->id;
1811 }
1812 }
1813
1814 /**
1815 * Returns the grade_item eid
cf72e2dd 1816 * @param grade_item $grade_item A grade_item object
6cc3e350 1817 * @return string eid
1818 */
d24832f9 1819 public function get_item_eid($grade_item) {
ddb9c95f 1820 return 'ig'.$grade_item->id;
6cc3e350 1821 }
1822
cf72e2dd 1823 /**
1824 * Given a grade_tree element, returns an array of parameters
1825 * used to build an icon for that element.
1826 *
1827 * @param array $element An array representing an element in the grade_tree
1828 *
1829 * @return array
1830 */
1831 public function get_params_for_iconstr($element) {
9ecd4386 1832 $strparams = new stdClass();
1833 $strparams->category = '';
1834 $strparams->itemname = '';
1835 $strparams->itemmodule = '';
cf72e2dd 1836
9ecd4386 1837 if (!method_exists($element['object'], 'get_name')) {
1838 return $strparams;
1839 }
345674ca 1840
b285c5aa 1841 $strparams->itemname = html_to_text($element['object']->get_name());
9ecd4386 1842
1843 // If element name is categorytotal, get the name of the parent category
1844 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1845 $parent = $element['object']->get_parent_category();
1846 $strparams->category = $parent->get_name() . ' ';
1847 } else {
1848 $strparams->category = '';
1849 }
1850
1851 $strparams->itemmodule = null;
1852 if (isset($element['object']->itemmodule)) {
1853 $strparams->itemmodule = $element['object']->itemmodule;
345674ca 1854 }
9ecd4386 1855 return $strparams;
1856 }
1857
ae93f353
FM
1858 /**
1859 * Return a reset icon for the given element.
1860 *
1861 * @param array $element An array representing an element in the grade_tree
1862 * @param object $gpr A grade_plugin_return object
079b2e52
MG
1863 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1864 * @return string|action_menu_link
ae93f353 1865 */
079b2e52 1866 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
ae93f353
FM
1867 global $CFG, $OUTPUT;
1868
1869 // Limit to category items set to use the natural weights aggregation method, and users
1870 // with the capability to manage grades.
1871 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1872 !has_capability('moodle/grade:manage', $this->context)) {
079b2e52 1873 return $returnactionmenulink ? null : '';
ae93f353
FM
1874 }
1875
1876 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1877 $url = new moodle_url('/grade/edit/tree/action.php', array(
1878 'id' => $this->courseid,
1879 'action' => 'resetweights',
1880 'eid' => $element['eid'],
1881 'sesskey' => sesskey(),
1882 ));
1883
079b2e52
MG
1884 if ($returnactionmenulink) {
1885 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1886 get_string('resetweightsshort', 'grades'));
1887 } else {
1888 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1889 }
ae93f353
FM
1890 }
1891
6cc3e350 1892 /**
1893 * Return edit icon for give element
cf72e2dd 1894 *
1895 * @param array $element An array representing an element in the grade_tree
1896 * @param object $gpr A grade_plugin_return object
079b2e52
MG
1897 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1898 * @return string|action_menu_link
6cc3e350 1899 */
079b2e52 1900 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
6b608f8f 1901 global $CFG, $OUTPUT;
6cc3e350 1902
1903 if (!has_capability('moodle/grade:manage', $this->context)) {
1904 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1905 // oki - let them override grade
1906 } else {
079b2e52 1907 return $returnactionmenulink ? null : '';
6cc3e350 1908 }
1909 }
1910
05aba805 1911 static $strfeedback = null;
1912 static $streditgrade = null;
1913 if (is_null($streditgrade)) {
1914 $streditgrade = get_string('editgrade', 'grades');
1915 $strfeedback = get_string('feedback');
6cc3e350 1916 }
1917
9ecd4386 1918 $strparams = $this->get_params_for_iconstr($element);
6ef4878b 1919
6cc3e350 1920 $object = $element['object'];
6cc3e350 1921
1922 switch ($element['type']) {
1923 case 'item':
1924 case 'categoryitem':
1925 case 'courseitem':
9ecd4386 1926 $stredit = get_string('editverbose', 'grades', $strparams);
6cc3e350 1927 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
a6855934 1928 $url = new moodle_url('/grade/edit/tree/item.php',
1c1f64a2 1929 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1930 } else {
a6855934 1931 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1c1f64a2 1932 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1933 }
6cc3e350 1934 break;
1935
1936 case 'category':
9ecd4386 1937 $stredit = get_string('editverbose', 'grades', $strparams);
a6855934 1938 $url = new moodle_url('/grade/edit/tree/category.php',
1c1f64a2 1939 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1940 break;
1941
1942 case 'grade':
05aba805 1943 $stredit = $streditgrade;
6cc3e350 1944 if (empty($object->id)) {
a6855934 1945 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1946 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
6cc3e350 1947 } else {
a6855934 1948 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1949 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1950 }
6cc3e350 1951 if (!empty($object->feedback)) {
1952 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
6cc3e350 1953 }
1954 break;
1955
1956 default:
1957 $url = null;
1958 }
1959
1960 if ($url) {
079b2e52
MG
1961 if ($returnactionmenulink) {
1962 return new action_menu_link_secondary($gpr->add_url_params($url),
1963 new pix_icon('t/edit', $stredit),
1964 get_string('editsettings'));
1965 } else {
1966 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1967 }
6cc3e350 1968
1969 } else {
079b2e52 1970 return $returnactionmenulink ? null : '';
6cc3e350 1971 }
1972 }
1973
1974 /**
1975 * Return hiding icon for give element
cf72e2dd 1976 *
1977 * @param array $element An array representing an element in the grade_tree
1978 * @param object $gpr A grade_plugin_return object
079b2e52
MG
1979 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1980 * @return string|action_menu_link
6cc3e350 1981 */
079b2e52 1982 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
5d3b9994 1983 global $CFG, $OUTPUT;
6cc3e350 1984
39873128 1985 if (!$element['object']->can_control_visibility()) {
079b2e52 1986 return $returnactionmenulink ? null : '';
39873128
TH
1987 }
1988
cf72e2dd 1989 if (!has_capability('moodle/grade:manage', $this->context) and
1990 !has_capability('moodle/grade:hide', $this->context)) {
079b2e52 1991 return $returnactionmenulink ? null : '';
6cc3e350 1992 }
1993
345674ca 1994 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1995 $strshow = get_string('showverbose', 'grades', $strparams);
345674ca 1996 $strhide = get_string('hideverbose', 'grades', $strparams);
6cc3e350 1997
a6855934 1998 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 1999 $url = $gpr->add_url_params($url);
1c1f64a2 2000
6cc3e350 2001 if ($element['object']->is_hidden()) {
8ae8bf8a 2002 $type = 'show';
6cc3e350 2003 $tooltip = $strshow;
2004
cf72e2dd 2005 // Change the icon and add a tooltip showing the date
2006 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
8ae8bf8a 2007 $type = 'hiddenuntil';
cf72e2dd 2008 $tooltip = get_string('hiddenuntildate', 'grades',
2009 userdate($element['object']->get_hidden()));
6cc3e350 2010 }
2011
8ae8bf8a 2012 $url->param('action', 'show');
b9cc756e 2013
079b2e52
MG
2014 if ($returnactionmenulink) {
2015 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2016 } else {
2017 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2018 }
6cc3e350 2019
2020 } else {
8ae8bf8a 2021 $url->param('action', 'hide');
079b2e52
MG
2022 if ($returnactionmenulink) {
2023 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2024 } else {
2025 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2026 }
6cc3e350 2027 }
1c1f64a2 2028
8ae8bf8a 2029 return $hideicon;
6cc3e350 2030 }
2031
2032 /**
2673c733 2033 * Return locking icon for given element
cf72e2dd 2034 *
2035 * @param array $element An array representing an element in the grade_tree
2036 * @param object $gpr A grade_plugin_return object
2037 *
6cc3e350 2038 * @return string
2039 */
d24832f9 2040 public function get_locking_icon($element, $gpr) {
6b608f8f 2041 global $CFG, $OUTPUT;
6cc3e350 2042
345674ca 2043 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 2044 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2045 $strlock = get_string('lockverbose', 'grades', $strparams);
d24832f9 2046
a6855934 2047 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 2048 $url = $gpr->add_url_params($url);
1c1f64a2 2049
2673c733 2050 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2051 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
2052 $strparamobj = new stdClass();
2053 $strparamobj->itemname = $element['object']->grade_item->itemname;
2054 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1c1f64a2 2055
0cddd851
FM
2056 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2057 array('class' => 'action-icon'));
8ae8bf8a 2058
cf72e2dd 2059 } else if ($element['object']->is_locked()) {
8ae8bf8a 2060 $type = 'unlock';
6cc3e350 2061 $tooltip = $strunlock;
2062
cf72e2dd 2063 // Change the icon and add a tooltip showing the date
2064 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
8ae8bf8a 2065 $type = 'locktime';
cf72e2dd 2066 $tooltip = get_string('locktimedate', 'grades',
2067 userdate($element['object']->get_locktime()));
6cc3e350 2068 }
2069
8ae8bf8a
PS
2070 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
2071 $action = '';
2072 } else {
2073 $url->param('action', 'unlock');
c63923bd 2074 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
6cc3e350 2075 }
6cc3e350 2076
2077 } else {
8ae8bf8a
PS
2078 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
2079 $action = '';
2080 } else {
2081 $url->param('action', 'lock');
c63923bd 2082 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
6cc3e350 2083 }
6cc3e350 2084 }
8ae8bf8a 2085
6cc3e350 2086 return $action;
2087 }
2088
2089 /**
2090 * Return calculation icon for given element
cf72e2dd 2091 *
2092 * @param array $element An array representing an element in the grade_tree
2093 * @param object $gpr A grade_plugin_return object
079b2e52
MG
2094 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2095 * @return string|action_menu_link
6cc3e350 2096 */
079b2e52 2097 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
666e8458 2098 global $CFG, $OUTPUT;
6cc3e350 2099 if (!has_capability('moodle/grade:manage', $this->context)) {
079b2e52 2100 return $returnactionmenulink ? null : '';
6cc3e350 2101 }
2102
6cc3e350 2103 $type = $element['type'];
2104 $object = $element['object'];
2105
2106 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
345674ca 2107 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 2108 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
6cc3e350 2109
cf72e2dd 2110 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2111 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2112
6cc3e350 2113 // show calculation icon only when calculation possible
cf72e2dd 2114 if (!$object->is_external_item() and ($is_scale or $is_value)) {
6cc3e350 2115 if ($object->is_calculated()) {
666e8458 2116 $icon = 't/calc';
6cc3e350 2117 } else {
666e8458 2118 $icon = 't/calc_off';
6cc3e350 2119 }
cf72e2dd 2120
a6855934 2121 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
8ae8bf8a 2122 $url = $gpr->add_url_params($url);
079b2e52
MG
2123 if ($returnactionmenulink) {
2124 return new action_menu_link_secondary($url,
2125 new pix_icon($icon, $streditcalculation),
2126 get_string('editcalculation', 'grades'));
2127 } else {
2128 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2129 }
6cc3e350 2130 }
2131 }
2132
079b2e52 2133 return $returnactionmenulink ? null : '';
6cc3e350 2134 }
2135}
2136
2137/**
2138 * Flat structure similar to grade tree.
cf72e2dd 2139 *
2140 * @uses grade_structure
a153c9f2 2141 * @package core_grades
cf72e2dd 2142 * @copyright 2009 Nicolas Connault
2143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6cc3e350 2144 */
2145class grade_seq extends grade_structure {
2146
6cc3e350 2147 /**
2148 * 1D array of elements
2149 */
d24832f9 2150 public $elements;
e98871a2 2151
2152 /**
2153 * Constructor, retrieves and stores array of all grade_category and grade_item
2154 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 2155 *
2156 * @param int $courseid The course id
2157 * @param bool $category_grade_last category grade item is the last child
2158 * @param bool $nooutcomes Whether or not outcomes should be included
e98871a2 2159 */
c4d0b752 2160 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
e98871a2 2161 global $USER, $CFG;
2162
2163 $this->courseid = $courseid;
d4060472 2164 $this->context = context_course::instance($courseid);
e98871a2 2165
2166 // get course grade tree
2167 $top_element = grade_category::fetch_course_tree($courseid, true);
2168
6391ebe7 2169 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2170
2171 foreach ($this->elements as $key=>$unused) {
b89a70ce 2172 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
6391ebe7 2173 }
e98871a2 2174 }
2175
9e313e79
DM
2176 /**
2177 * Old syntax of class constructor. Deprecated in PHP7.
2178 *
2179 * @deprecated since Moodle 3.1
2180 */
2181 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2182 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2183 self::__construct($courseid, $category_grade_last, $nooutcomes);
2184 }
2185
e98871a2 2186 /**
2187 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 2188 *
2189 * @param array &$element The seed of the recursion
2190 * @param bool $category_grade_last category grade item is the last child
2191 * @param bool $nooutcomes Whether or not outcomes should be included
2192 *
2193 * @return array
e98871a2 2194 */
d24832f9 2195 public function flatten(&$element, $category_grade_last, $nooutcomes) {
e98871a2 2196 if (empty($element['children'])) {
2197 return array();
2198 }
2199 $children = array();
2200
2201 foreach ($element['children'] as $sortorder=>$unused) {
cf72e2dd 2202 if ($nooutcomes and $element['type'] != 'category' and
2203 $element['children'][$sortorder]['object']->is_outcome_item()) {
e98871a2 2204 continue;
2205 }
2206 $children[] = $element['children'][$sortorder];
2207 }
2208 unset($element['children']);
2209
28437460
NP
2210 if ($category_grade_last and count($children) > 1 and
2211 (
2212 $children[0]['type'] === 'courseitem' or
2213 $children[0]['type'] === 'categoryitem'
2214 )
2215 ) {
e98871a2 2216 $cat_item = array_shift($children);
2217 array_push($children, $cat_item);
2218 }
2219
2220 $result = array();
2221 foreach ($children as $child) {
e0724506 2222 if ($child['type'] == 'category') {
6391ebe7 2223 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
e98871a2 2224 } else {
2225 $child['eid'] = 'i'.$child['object']->id;
6391ebe7 2226 $result[$child['object']->id] = $child;
e98871a2 2227 }
2228 }
2229
2230 return $result;
2231 }
2232
2233 /**
2234 * Parses the array in search of a given eid and returns a element object with
2235 * information about the element it has found.
cf72e2dd 2236 *
2237 * @param int $eid Gradetree Element ID
2238 *
e98871a2 2239 * @return object element
2240 */
d24832f9 2241 public function locate_element($eid) {
e98871a2 2242 // it is a grade - construct a new object
2243 if (strpos($eid, 'n') === 0) {
2244 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2245 return null;
2246 }
2247
2248 $itemid = $matches[1];
2249 $userid = $matches[2];
2250
2251 //extra security check - the grade item must be in this tree
ddb9c95f 2252 if (!$item_el = $this->locate_element('ig'.$itemid)) {
e98871a2 2253 return null;
2254 }
2255
2256 // $gradea->id may be null - means does not exist yet
2257 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2258
2259 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2260 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2261
2262 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 2263 $id = (int) substr($eid, 1);
e98871a2 2264 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2265 return null;
2266 }
2267 //extra security check - the grade item must be in this tree
ddb9c95f 2268 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
e98871a2 2269 return null;
2270 }
2271 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2272 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2273 }
2274
2275 // it is a category or item
6391ebe7 2276 foreach ($this->elements as $element) {
6cc3e350 2277 if ($element['eid'] == $eid) {
2278 return $element;
2279 }
e98871a2 2280 }
6cc3e350 2281
2282 return null;
e98871a2 2283 }
e98871a2 2284}
2285
7a6b7acf 2286/**
2287 * This class represents a complete tree of categories, grade_items and final grades,
2288 * organises as an array primarily, but which can also be converted to other formats.
2289 * It has simple method calls with complex implementations, allowing for easy insertion,
2290 * deletion and moving of items and categories within the tree.
cf72e2dd 2291 *
2292 * @uses grade_structure
a153c9f2 2293 * @package core_grades
cf72e2dd 2294 * @copyright 2009 Nicolas Connault
2295 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7a6b7acf 2296 */
6cc3e350 2297class grade_tree extends grade_structure {
7a6b7acf 2298
2299 /**
2300 * The basic representation of the tree as a hierarchical, 3-tiered array.
2301 * @var object $top_element
2302 */
d24832f9 2303 public $top_element;
7a6b7acf 2304
7a6b7acf 2305 /**
2306 * 2D array of grade items and categories
cf72e2dd 2307 * @var array $levels
7a6b7acf 2308 */
d24832f9 2309 public $levels;
7a6b7acf 2310
b89a70ce 2311 /**
2312 * Grade items
cf72e2dd 2313 * @var array $items
b89a70ce 2314 */
d24832f9 2315 public $items;
b89a70ce 2316
7a6b7acf 2317 /**
2318 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 2319 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 2320 *
2321 * @param int $courseid The Course ID
2322 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2323 * @param bool $category_grade_last category grade item is the last child
4faf5f99 2324 * @param array $collapsed array of collapsed categories
cf72e2dd 2325 * @param bool $nooutcomes Whether or not outcomes should be included
7a6b7acf 2326 */
c4d0b752 2327 public function __construct($courseid, $fillers=true, $category_grade_last=false,
cf72e2dd 2328 $collapsed=null, $nooutcomes=false) {
73ca5f01 2329 global $USER, $CFG, $COURSE, $DB;
7a6b7acf 2330
2331 $this->courseid = $courseid;
7a6b7acf 2332 $this->levels = array();
d4060472 2333 $this->context = context_course::instance($courseid);
7a6b7acf 2334
73ca5f01 2335 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2336 $course = $COURSE;
2337 } else {
2338 $course = $DB->get_record('course', array('id' => $this->courseid));
2339 }
2340 $this->modinfo = get_fast_modinfo($course);
2341
7a6b7acf 2342 // get course grade tree
2343 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2344
4faf5f99 2345 // collapse the categories if requested
2346 if (!empty($collapsed)) {
2347 grade_tree::category_collapse($this->top_element, $collapsed);
2348 }
2349
aea4df41 2350 // no otucomes if requested
2351 if (!empty($nooutcomes)) {
2352 grade_tree::no_outcomes($this->top_element);
2353 }
2354
4faf5f99 2355 // move category item to last position in category
7a6b7acf 2356 if ($category_grade_last) {
2357 grade_tree::category_grade_last($this->top_element);
2358 }
2359
2360 if ($fillers) {
2361 // inject fake categories == fillers
2362 grade_tree::inject_fillers($this->top_element, 0);
2363 // add colspans to categories and fillers
2364 grade_tree::inject_colspans($this->top_element);
2365 }
2366
2367 grade_tree::fill_levels($this->levels, $this->top_element, 0);
d297269d 2368
7a6b7acf 2369 }
2370
9e313e79
DM
2371 /**
2372 * Old syntax of class constructor. Deprecated in PHP7.
2373 *
2374 * @deprecated since Moodle 3.1
2375 */
2376 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2377 $collapsed=null, $nooutcomes=false) {
2378 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2379 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2380 }
2381
4faf5f99 2382 /**
2383 * Static recursive helper - removes items from collapsed categories
cf72e2dd 2384 *
2385 * @param array &$element The seed of the recursion
4faf5f99 2386 * @param array $collapsed array of collapsed categories
cf72e2dd 2387 *
4faf5f99 2388 * @return void
2389 */
d24832f9 2390 public function category_collapse(&$element, $collapsed) {
4faf5f99 2391 if ($element['type'] != 'category') {
2392 return;
2393 }
2394 if (empty($element['children']) or count($element['children']) < 2) {
2395 return;
2396 }
2397
384960dd 2398 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 2399 $category_item = reset($element['children']); //keep only category item
2400 $element['children'] = array(key($element['children'])=>$category_item);
2401
2402 } else {
384960dd 2403 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2404 reset($element['children']);
2405 $first_key = key($element['children']);
2406 unset($element['children'][$first_key]);
2407 }
2408 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 2409 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2410 }
2411 }
2412 }
7a6b7acf 2413
aea4df41 2414 /**
2415 * Static recursive helper - removes all outcomes
cf72e2dd 2416 *
2417 * @param array &$element The seed of the recursion
2418 *
aea4df41 2419 * @return void
2420 */
d24832f9 2421 public function no_outcomes(&$element) {
aea4df41 2422 if ($element['type'] != 'category') {
2423 return;
2424 }
2425 foreach ($element['children'] as $sortorder=>$child) {
2426 if ($element['children'][$sortorder]['type'] == 'item'
2427 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2428 unset($element['children'][$sortorder]);
2429
d4795a07 2430 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 2431 grade_tree::no_outcomes($element['children'][$sortorder]);
2432 }
2433 }
2434 }
2435
7a6b7acf 2436 /**
2437 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 2438 *
2439 * @param array &$element The seed of the recursion
2440 *
7a6b7acf 2441 * @return void
2442 */
d24832f9 2443 public function category_grade_last(&$element) {
7a6b7acf 2444 if (empty($element['children'])) {
2445 return;
2446 }
2447 if (count($element['children']) < 2) {
2448 return;
2449 }
3e0e2436 2450 $first_item = reset($element['children']);
4a3dfd9a 2451 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 2452 // the category item might have been already removed
2453 $order = key($element['children']);
2454 unset($element['children'][$order]);
2455 $element['children'][$order] =& $first_item;
2456 }
206f9953 2457 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 2458 grade_tree::category_grade_last($element['children'][$sortorder]);
2459 }
2460 }
2461
2462 /**
2463 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
cf72e2dd 2464 *
2465 * @param array &$levels The levels of the grade tree through which to recurse
2466 * @param array &$element The seed of the recursion
2467 * @param int $depth How deep are we?
7a6b7acf 2468 * @return void
2469 */
d24832f9 2470 public function fill_levels(&$levels, &$element, $depth) {
7a6b7acf 2471 if (!array_key_exists($depth, $levels)) {
2472 $levels[$depth] = array();
2473 }
2474
2475 // prepare unique identifier
2476 if ($element['type'] == 'category') {
ddb9c95f 2477 $element['eid'] = 'cg'.$element['object']->id;
7a6b7acf 2478 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
ddb9c95f 2479 $element['eid'] = 'ig'.$element['object']->id;
b89a70ce 2480 $this->items[$element['object']->id] =& $element['object'];
7a6b7acf 2481 }
2482
2483 $levels[$depth][] =& $element;
2484 $depth++;
2485 if (empty($element['children'])) {
2486 return;
2487 }
2488 $prev = 0;
2489 foreach ($element['children'] as $sortorder=>$child) {
2490 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2491 $element['children'][$sortorder]['prev'] = $prev;
2492 $element['children'][$sortorder]['next'] = 0;
2493 if ($prev) {
2494 $element['children'][$prev]['next'] = $sortorder;
2495 }
2496 $prev = $sortorder;
2497 }
2498 }
2499
825a3fa9
JP
2500 /**
2501 * Determines whether the grade tree item can be displayed.
2502 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2503 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2504 * can be output.
2505 *
2506 * @param array $element The grade category element.
2507 * @return bool True if the grade tree item can be displayed. False, otherwise.
2508 */
2509 public static function can_output_item($element) {
2510 $canoutput = true;
2511
2512 if ($element['type'] === 'category') {
2513 $object = $element['object'];
2514 $category = grade_category::fetch(array('id' => $object->id));
2515 // Category has total, we can output this.
2516 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2517 return true;
2518 }
2519
2520 // Category has no total and has no children, no need to output this.
2521 if (empty($element['children'])) {
2522 return false;
2523 }
2524
2525 $canoutput = false;
2526 // Loop over children and make sure at least one child can be output.
2527 foreach ($element['children'] as $child) {
2528 $canoutput = self::can_output_item($child);
2529 if ($canoutput) {
2530 break;
2531 }
2532 }
2533 }
2534
2535 return $canoutput;
2536 }
2537
7a6b7acf 2538 /**
2539 * Static recursive helper - makes full tree (all leafes are at the same level)
cf72e2dd 2540 *
2541 * @param array &$element The seed of the recursion
2542 * @param int $depth How deep are we?
2543 *
2544 * @return int
7a6b7acf 2545 */
d24832f9 2546 public function inject_fillers(&$element, $depth) {
7a6b7acf 2547 $depth++;
2548
2549 if (empty($element['children'])) {
2550 return $depth;
2551 }
2552 $chdepths = array();
2553 $chids = array_keys($element['children']);
2554 $last_child = end($chids);
2555 $first_child = reset($chids);
2556
2557 foreach ($chids as $chid) {
2558 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2559 }
2560 arsort($chdepths);
2561
2562 $maxdepth = reset($chdepths);
2563 foreach ($chdepths as $chid=>$chd) {
2564 if ($chd == $maxdepth) {
2565 continue;
2566 }
825a3fa9
JP
2567 if (!self::can_output_item($element['children'][$chid])) {
2568 continue;
2569 }
7a6b7acf 2570 for ($i=0; $i < $maxdepth-$chd; $i++) {
2571 if ($chid == $first_child) {
2572 $type = 'fillerfirst';
2573 } else if ($chid == $last_child) {
2574 $type = 'fillerlast';
2575 } else {
2576 $type = 'filler';
2577 }
2578 $oldchild =& $element['children'][$chid];
cf72e2dd 2579 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2580 'eid'=>'', 'depth'=>$element['object']->depth,
2581 'children'=>array($oldchild));
7a6b7acf 2582 }
2583 }
2584
2585 return $maxdepth;
2586 }
2587
2588 /**
2589 * Static recursive helper - add colspan information into categories
cf72e2dd 2590 *
2591 * @param array &$element The seed of the recursion
2592 *
2593 * @return int
7a6b7acf 2594 */
d24832f9 2595 public function inject_colspans(&$element) {
7a6b7acf 2596 if (empty($element['children'])) {
2597 return 1;
2598 }
2599 $count = 0;
2600 foreach ($element['children'] as $key=>$child) {
825a3fa9
JP
2601 if (!self::can_output_item($child)) {
2602 continue;
2603 }
7a6b7acf 2604 $count += grade_tree::inject_colspans($element['children'][$key]);
2605 }
2606 $element['colspan'] = $count;
2607 return $count;
2608 }
2609
2610 /**
2611 * Parses the array in search of a given eid and returns a element object with
2612 * information about the element it has found.
cf72e2dd 2613 * @param int $eid Gradetree Element ID
7a6b7acf 2614 * @return object element
2615 */
d24832f9 2616 public function locate_element($eid) {
d3c3da1b 2617 // it is a grade - construct a new object
2618 if (strpos($eid, 'n') === 0) {
2619 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2620 return null;
2621 }
2622
2623 $itemid = $matches[1];
2624 $userid = $matches[2];
2625
2626 //extra security check - the grade item must be in this tree
ddb9c95f 2627 if (!$item_el = $this->locate_element('ig'.$itemid)) {
d3c3da1b 2628 return null;
2629 }
2630
2631 // $gradea->id may be null - means does not exist yet
2632 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2633
2634 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2635 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2636
2637 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 2638 $id = (int) substr($eid, 1);
7a6b7acf 2639 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2640 return null;
2641 }
2642 //extra security check - the grade item must be in this tree
ddb9c95f 2643 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
7a6b7acf 2644 return null;
2645 }
2646 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2647 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2648 }
2649
2650 // it is a category or item
2651 foreach ($this->levels as $row) {
2652 foreach ($row as $element) {
2653 if ($element['type'] == 'filler') {
2654 continue;
2655 }
2656 if ($element['eid'] == $eid) {
2657 return $element;
2658 }
2659 }
2660 }
2661
2662 return null;
2663 }
d24832f9 2664
b244b9b7 2665 /**
2666 * Returns a well-formed XML representation of the grade-tree using recursion.
cf72e2dd 2667 *
2668 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2669 * @param string $tabs The control character to use for tabs
2670 *
b244b9b7 2671 * @return string $xml
2672 */
cf72e2dd 2673 public function exporttoxml($root=null, $tabs="\t") {
b244b9b7 2674 $xml = null;
2675 $first = false;
2676 if (is_null($root)) {
2677 $root = $this->top_element;
2678 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2679 $xml .= "<gradetree>\n";
2680 $first = true;
2681 }
d24832f9 2682
b244b9b7 2683 $type = 'undefined';
2684 if (strpos($root['object']->table, 'grade_categories') !== false) {
2685 $type = 'category';
cf72e2dd 2686 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2687 $type = 'item';
cf72e2dd 2688 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2689 $type = 'outcome';
2690 }
d24832f9 2691
b244b9b7 2692 $xml .= "$tabs<element type=\"$type\">\n";
2693 foreach ($root['object'] as $var => $value) {
2694 if (!is_object($value) && !is_array($value) && !empty($value)) {
2695 $xml .= "$tabs\t<$var>$value</$var>\n";
2696 }
2697 }
2698
2699 if (!empty($root['children'])) {
2700 $xml .= "$tabs\t<children>\n";
2701 foreach ($root['children'] as $sortorder => $child) {
2702 $xml .= $this->exportToXML($child, $tabs."\t\t");
2703 }
2704 $xml .= "$tabs\t</children>\n";
2705 }
d24832f9 2706
b244b9b7 2707 $xml .= "$tabs</element>\n";
2708
2709 if ($first) {
2710 $xml .= "</gradetree>";
2711 }
d24832f9 2712
b244b9b7 2713 return $xml;
2714 }
d24832f9 2715
b244b9b7 2716 /**
2717 * Returns a JSON representation of the grade-tree using recursion.
cf72e2dd 2718 *
b244b9b7 2719 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2720 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
cf72e2dd 2721 *
2722 * @return string
b244b9b7 2723 */
cf72e2dd 2724 public function exporttojson($root=null, $tabs="\t") {
b244b9b7 2725 $json = null;
2726 $first = false;
2727 if (is_null($root)) {
2728 $root = $this->top_element;
2729 $first = true;
2730 }
d24832f9 2731
b244b9b7 2732 $name = '';
2733
2734
2735 if (strpos($root['object']->table, 'grade_categories') !== false) {
2736 $name = $root['object']->fullname;
2737 if ($name == '?') {
d24832f9 2738 $name = $root['object']->get_name();
b244b9b7 2739 }
cf72e2dd 2740 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2741 $name = $root['object']->itemname;
cf72e2dd 2742 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2743 $name = $root['object']->itemname;
2744 }
d24832f9 2745
b244b9b7 2746 $json .= "$tabs {\n";
2747 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2748 $json .= "$tabs\t \"name\": \"$name\",\n";
2749
2750 foreach ($root['object'] as $var => $value) {
2751 if (!is_object($value) && !is_array($value) && !empty($value)) {
2752 $json .= "$tabs\t \"$var\": \"$value\",\n";
2753 }
2754 }
d24832f9 2755
b244b9b7 2756 $json = substr($json, 0, strrpos($json, ','));
d24832f9 2757
b244b9b7 2758 if (!empty($root['children'])) {
2759 $json .= ",\n$tabs\t\"children\": [\n";
2760 foreach ($root['children'] as $sortorder => $child) {
2761 $json .= $this->exportToJSON($child, $tabs."\t\t");
2762 }
2763 $json = substr($json, 0, strrpos($json, ','));
2764 $json .= "\n$tabs\t]\n";
d24832f9 2765 }
b244b9b7 2766
2767 if ($first) {
2768 $json .= "\n}";
2769 } else {
2770 $json .= "\n$tabs},\n";
2771 }
d24832f9 2772
b244b9b7 2773 return $json;
2774 }
d24832f9 2775
cf72e2dd 2776 /**
2777 * Returns the array of levels
2778 *
2779 * @return array
2780 */
d24832f9 2781 public function get_levels() {
2782 return $this->levels;
2783 }
2784
cf72e2dd 2785 /**
2786 * Returns the array of grade items
2787 *
2788 * @return array
2789 */
d24832f9 2790 public function get_items() {
2791 return $this->items;
2792 }
2793
cf72e2dd 2794 /**
2795 * Returns a specific Grade Item
2796 *
2797 * @param int $itemid The ID of the grade_item object
2798 *
2799 * @return grade_item
2800 */
d24832f9 2801 public function get_item($itemid) {
2802 if (array_key_exists($itemid, $this->items)) {
2803 return $this->items[$itemid];
2804 } else {
2805 return false;
2806 }
2807 }
7a6b7acf 2808}
eef00ade 2809
2810/**
2811 * Local shortcut function for creating an edit/delete button for a grade_* object.
4d27bc79 2812 * @param string $type 'edit' or 'delete'
eef00ade 2813 * @param int $courseid The Course ID
2814 * @param grade_* $object The grade_* object
2815 * @return string html
2816 */
2817function grade_button($type, $courseid, $object) {
2818 global $CFG, $OUTPUT;
2819 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2820 $objectidstring = $matches[1] . 'id';
2821 } else {
2822 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2823 }
2824
2825 $strdelete = get_string('delete');
2826 $stredit = get_string('edit');
2827
eef00ade 2828 if ($type == 'delete') {
8ae8bf8a 2829 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
eef00ade 2830 } else if ($type == 'edit') {
8ae8bf8a 2831 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
eef00ade 2832 }
2833
fa9c0aab 2834 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
eef00ade 2835
2836}
4d5059d4
SH
2837
2838/**
2839 * This method adds settings to the settings block for the grade system and its
2840 * plugins
2841 *
2842 * @global moodle_page $PAGE
2843 */
2844function grade_extend_settings($plugininfo, $courseid) {
2845 global $PAGE;
2846
2847 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2848
2849 $strings = array_shift($plugininfo);
2850
2851 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2852 foreach ($reports as $report) {
2853 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2854 }
2855 }
2856
eb84b779
MG
2857 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2858 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2859 foreach ($settings as $setting) {
2860 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2861 }
2862 }
2863
4d5059d4
SH
2864 if ($imports = grade_helper::get_plugins_import($courseid)) {
2865 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2866 foreach ($imports as $import) {
11f87187 2867 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
4d5059d4
SH
2868 }
2869 }
2870
2871 if ($exports = grade_helper::get_plugins_export($courseid)) {
2872 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2873 foreach ($exports as $export) {
11f87187 2874 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
4d5059d4
SH
2875 }
2876 }
2877
4d5059d4
SH
2878 if ($letters = grade_helper::get_info_letters($courseid)) {
2879 $letters = array_shift($letters);
2880 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2881 }
2882
2883 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2884 $outcomes = array_shift($outcomes);
2885 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2886 }
2887
2888 if ($scales = grade_helper::get_info_scales($courseid)) {
2889 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2890 }
2891
4d5059d4
SH
2892 if ($gradenode->contains_active_node()) {
2893 // If the gradenode is active include the settings base node (gradeadministration) in
2894 // the navbar, typcially this is ignored.
2895 $PAGE->navbar->includesettingsbase = true;
2896
2897 // If we can get the course admin node make sure it is closed by default
2898 // as in this case the gradenode will be opened
2899 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2900 $coursenode->make_inactive();
2901 $coursenode->forceopen = false;
2902 }
2903 }
2904}
2905
2906/**
2907 * Grade helper class
2908 *
2909 * This class provides several helpful functions that work irrespective of any
2910 * current state.
2911 *
2912 * @copyright 2010 Sam Hemelryk
2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2914 */
2915abstract class grade_helper {
2916 /**
2917 * Cached manage settings info {@see get_info_settings}
2918 * @var grade_plugin_info|false
2919 */
2920 protected static $managesetting = null;
2921 /**
2922 * Cached grade report plugins {@see get_plugins_reports}
2923 * @var array|false
2924 */
2925 protected static $gradereports = null;
2926 /**
2927 * Cached grade report plugins preferences {@see get_info_scales}
2928 * @var array|false
2929 */
2930 protected static $gradereportpreferences = null;
2931 /**
2932 * Cached scale info {@see get_info_scales}
2933 * @var grade_plugin_info|false
2934 */
2935 protected static $scaleinfo = null;
2936 /**
2937 * Cached outcome info {@see get_info_outcomes}
2938 * @var grade_plugin_info|false
2939 */
2940 protected static $outcomeinfo = null;
4d5059d4
SH
2941 /**
2942 * Cached leftter info {@see get_info_letters}
2943 * @var grade_plugin_info|false
2944 */
2945 protected static $letterinfo = null;
2946 /**
2947 * Cached grade import plugins {@see get_plugins_import}
2948 * @var array|false
2949 */
2950 protected static $importplugins = null;
2951 /**
2952 * Cached grade export plugins {@see get_plugins_export}
2953 * @var array|false
2954 */
2955 protected static $exportplugins = null;
2956 /**
2957 * Cached grade plugin strings
2958 * @var array
2959 */
2960 protected static $pluginstrings = null;
bfe969e8
DW
2961 /**
2962 * Cached grade aggregation strings
2963 * @var array
2964 */
2965 protected static $aggregationstrings = null;
4d5059d4
SH
2966
2967 /**
2968 * Gets strings commonly used by the describe plugins
2969 *
2970 * report => get_string('view'),
4d5059d4
SH
2971 * scale => get_string('scales'),
2972 * outcome => get_string('outcomes', 'grades'),
2973 * letter => get_string('letters', 'grades'),
2974 * export => get_string('export', 'grades'),
2975 * import => get_string('import'),
4d5059d4
SH
2976 * settings => get_string('settings')
2977 *
2978 * @return array
2979 */
2980 public static function get_plugin_strings() {
2981 if (self::$pluginstrings === null) {
2982 self::$pluginstrings = array(
2983 'report' => get_string('view'),
4d5059d4
SH
2984 'scale' => get_string('scales'),
2985 'outcome' => get_string('outcomes', 'grades'),
2986 'letter' => get_string('letters', 'grades'),
2987 'export' => get_string('export', 'grades'),
2988 'import' => get_string('import'),
eb84b779 2989 'settings' => get_string('edittree', 'grades')
4d5059d4
SH
2990 );
2991 }
2992 return self::$pluginstrings;
2993 }
bfe969e8
DW
2994
2995 /**
2996 * Gets strings describing the available aggregation methods.
2997 *
2998 * @return array
2999 */
3000 public static function get_aggregation_strings() {
3001 if (self::$aggregationstrings === null) {
3002 self::$aggregationstrings = array(
3003 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
3004 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
3005 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
3006 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
3007 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
3008 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
3009 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
3010 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
3011 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
3012 );
3013 }
3014 return self::$aggregationstrings;
3015 }
3016
4d5059d4
SH
3017 /**
3018 * Get grade_plugin_info object for managing settings if the user can
3019 *
3020 * @param int $courseid
8faa560c 3021 * @return grade_plugin_info[]
4d5059d4
SH
3022 */
3023 public static function get_info_manage_settings($courseid) {
3024 if (self::$managesetting !== null) {
3025 return self::$managesetting;
3026 }
d4060472 3027 $context = context_course::instance($courseid);
8faa560c
MG
3028 self::$managesetting = array();
3029 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
53914e44 3030 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
eb84b779 3031 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
53914e44 3032 get_string('gradebooksetup', 'grades'));
8faa560c
MG
3033 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3034 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3035 get_string('coursegradesettings', 'grades'));
eb84b779
MG
3036 }
3037 if (self::$gradereportpreferences === null) {
3038 self::get_plugins_reports($courseid);
3039 }
3040 if (self::$gradereportpreferences) {
3041 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
4d5059d4
SH
3042 }
3043 return self::$managesetting;
3044 }
3045 /**
3046 * Returns an array of plugin reports as grade_plugin_info objects
3047 *
3048 * @param int $courseid
3049 * @return array
3050 */
3051 public static function get_plugins_reports($courseid) {
f7fcf4cd 3052 global $SITE;
cf717dc2 3053
4d5059d4
SH
3054 if (self::$gradereports !== null) {
3055 return self::$gradereports;
3056 }
d4060472 3057 $context = context_course::instance($courseid);
4d5059d4
SH
3058 $gradereports = array();
3059 $gradepreferences = array();
bd3b3bba 3060 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
f7fcf4cd
AD
3061 //some reports make no sense if we're not within a course
3062 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
3063 continue;
3064 }
3065
4d5059d4
SH
3066 // Remove ones we can't see
3067 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3068 continue;
3069 }
3070
4ae71e93
DP
3071 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3072 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3073 'moodle/grade:edit'), $context)) {
3074 continue;
3075 }
3076
b5e7b2bf 3077 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
4d5059d4
SH
3078 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3079 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3080
3081 // Add link to preferences tab if such a page exists
3082 if (file_exists($plugindir.'/preferences.php')) {
3083 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
eb84b779 3084 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
4887d152 3085 get_string('preferences', 'grades') . ': ' . $pluginstr);
4d5059d4
SH
3086 }
3087 }
3088 if (count($gradereports) == 0) {
3089 $gradereports = false;
3090 $gradepreferences = false;
3091 } else if (count($gradepreferences) == 0) {
3092 $gradepreferences = false;
3093 asort($gradereports);
3094 } else {
3095 asort($gradereports);
3096 asort($gradepreferences);
3097 }
3098 self::$gradereports = $gradereports;
3099 self::$gradereportpreferences = $gradepreferences;
3100 return self::$gradereports;
3101 }
eb84b779 3102
4d5059d4
SH
3103 /**
3104 * Get information on scales
3105 * @param int $courseid
3106 * @return grade_plugin_info
3107 */
3108 public static function get_info_scales($courseid) {
3109 if (self::$scaleinfo !== null) {
3110 return self::$scaleinfo;
3111 }
d4060472 3112 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
4d5059d4
SH
3113 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3114 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3115 } else {
3116 self::$scaleinfo = false;
3117 }
3118 return self::$scaleinfo;
3119 }
3120 /**
3121 * Get information on outcomes
3122 * @param int $courseid
3123 * @return grade_plugin_info
3124 */
3125 public static function get_info_outcomes($courseid) {
f7fcf4cd 3126 global $CFG, $SITE;
4d5059d4
SH
3127
3128 if (self::$outcomeinfo !== null) {
3129 return self::$outcomeinfo;
3130 }
d4060472 3131 $context = context_course::instance($courseid);
4d5059d4
SH
3132 $canmanage = has_capability('moodle/grade:manage', $context);
3133 $canupdate = has_capability('moodle/course:update', $context);
3134 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3135 $outcomes = array();
3136 if ($canupdate) {
f7fcf4cd
AD
3137 if ($courseid!=$SITE->id) {
3138 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3139 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3140 }
4d5059d4
SH
3141 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3142 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
c46aeeab
DC
3143 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3144 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
4d5059d4 3145 } else {
f7fcf4cd
AD
3146 if ($courseid!=$SITE->id) {
3147 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3148 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3149 }
4d5059d4
SH
3150 }
3151 self::$outcomeinfo = $outcomes;
3152 } else {
3153 self::$outcomeinfo = false;
3154 }
3155 return self::$outcomeinfo;
3156 }
4d5059d4
SH
3157 /**
3158 * Get information on letters
3159 * @param int $courseid
4d27bc79 3160 * @return array
4d5059d4
SH
3161 */
3162 public static function get_info_letters($courseid) {
a8dfc483 3163 global $SITE;
4d5059d4
SH
3164 if (self::$letterinfo !== null) {
3165 return self::$letterinfo;
3166 }
d4060472 3167 $context = context_course::instance($courseid);
4d5059d4
SH
3168 $canmanage = has_capability('moodle/grade:manage', $context);
3169 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3170 if ($canmanage || $canmanageletters) {
a8dfc483
AA
3171 // Redirect to system context when report is accessed from admin settings MDL-31633
3172 if ($context->instanceid == $SITE->id) {
3173 $param = array('edit' => 1);
3174 } else {
3175 $param = array('edit' => 1,'id' => $context->id);
3176 }
4d5059d4 3177 self::$letterinfo = array(
54caa598 3178 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
a8dfc483 3179 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
4d5059d4
SH
3180 );
3181 } else {
3182 self::$letterinfo = false;
3183 }
3184 return self::$letterinfo;
3185 }
3186 /**
3187 * Get information import plugins
3188 * @param int $courseid
3189 * @return array
3190 */
3191 public static function get_plugins_import($courseid) {
3192 global $CFG;
3193
3194 if (self::$importplugins !== null) {
3195 return self::$importplugins;
3196 }
3197 $importplugins = array();
d4060472 3198 $context = context_course::instance($courseid);
4d5059d4
SH
3199
3200 if (has_capability('moodle/grade:import', $context)) {
bd3b3bba 3201 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
4d5059d4
SH
3202 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3203 continue;
3204 }
b5e7b2bf 3205 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
4d5059d4
SH
3206 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3207 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3208 }
3209
ead4d41e
SL
3210 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3211 // XML is the only grade import plugin that has publishing feature.
3212 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
4d5059d4
SH
3213 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3214 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3215 }
3216 }
3217
3218 if (count($importplugins) > 0) {
3219 asort($importplugins);
3220 self::$importplugins = $importplugins;
3221 } else {
3222 self::$importplugins = false;
3223 }
3224 return self::$importplugins;
3225 }
3226 /**
3227 * Get information export plugins
3228 * @param int $courseid
3229 * @return array
3230 */
3231 public static function get_plugins_export($courseid) {
3232 global $CFG;
3233
3234 if (self::$exportplugins !== null) {
3235 return self::$exportplugins;
3236 }
d4060472 3237 $context = context_course::instance($courseid);
4d5059d4 3238 $exportplugins = array();
ead4d41e 3239 $canpublishgrades = 0;
4d5059d4 3240 if (has_capability('moodle/grade:export', $context)) {
bd3b3bba 3241 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
4d5059d4
SH
3242 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3243 continue;
3244 }
ead4d41e
SL
3245 // All the grade export plugins has grade publishing capabilities.
3246 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3247 $canpublishgrades++;
3248 }
3249
b5e7b2bf 3250 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
4d5059d4
SH
3251 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3252 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3253 }
3254
ead4d41e
SL
3255 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3256 if ($CFG->gradepublishing && $canpublishgrades != 0) {
4d5059d4
SH
3257 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3258 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3259 }
3260 }
3261 if (count($exportplugins) > 0) {
3262 asort($exportplugins);
3263 self::$exportplugins = $exportplugins;
3264 } else {
3265 self::$exportplugins = false;
3266 }
3267 return self::$exportplugins;
3268 }
293f42b6 3269
61c8e0d7
FM
3270 /**
3271 * Returns the value of a field from a user record
3272 *
3273 * @param stdClass $user object
3274 * @param stdClass $field object
3275 * @return string value of the field
3276 */
3277 public static function get_user_field_value($user, $field) {
3278 if (!empty($field->customid)) {
1ef14a5a 3279 $fieldname = 'customfield_' . $field->customid;
61c8e0d7
FM
3280 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3281 $fieldvalue = $user->{$fieldname};
3282 } else {
3283 $fieldvalue = $field->default;
3284 }
3285 } else {
3286 $fieldvalue = $user->{$field->shortname};
3287 }
3288 return $fieldvalue;
3289 }
3290
3291 /**
3292 * Returns an array of user profile fields to be included in export
3293 *
3294 * @param int $courseid
3295 * @param bool $includecustomfields
3296 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3297 */
3298 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3299 global $CFG, $DB;
3300
3301 // Gets the fields that have to be hidden
3302 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3303 $context = context_course::instance($courseid);
3304 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3305 if ($canseehiddenfields) {
3306 $hiddenfields = array();
3307 }
3308
3309 $fields = array();
3310 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3311 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3312 $userdefaultfields = user_get_default_fields();
3313
3314 // Sets the list of profile fields
3315 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3316 if (!empty($userprofilefields)) {
3317 foreach ($userprofilefields as $field) {
3318 $field = trim($field);
3319 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3320 continue;
3321 }
293f42b6 3322 $obj = new stdClass();
61c8e0d7 3323 $obj->customid = 0;
293f42b6 3324 $obj->shortname = $field;
61c8e0d7 3325 $obj->fullname = get_string($field);
293f42b6
CF
3326 $fields[] = $obj;
3327 }
3328 }
293f42b6 3329
61c8e0d7
FM
3330 // Sets the list of custom profile fields
3331 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3332 if ($includecustomfields && !empty($customprofilefields)) {
3333 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
3334 $customfields = $DB->get_records_sql("SELECT f.*
3335 FROM {user_info_field} f
3336 JOIN {user_info_category} c ON f.categoryid=c.id
3337 WHERE f.shortname $wherefields
3338 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
61c8e0d7
FM
3339
3340 foreach ($customfields as $field) {
3341 // Make sure we can display this custom field
3342 if (!in_array($field->shortname, $customprofilefields)) {
3343 continue;
3344 } else if (in_array($field->shortname, $hiddenfields)) {
3345 continue;
3346 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3347 continue;
3348 }
3349
3350 $obj = new stdClass();
3351 $obj->customid = $field->id;
3352 $obj->shortname = $field->shortname;
3353 $obj->fullname = format_string($field->name);
3354 $obj->datatype = $field->datatype;
3355 $obj->default = $field->defaultdata;
3356 $fields[] = $obj;
3357 }
3358 }
3359
3360 return $fields;
3361 }
e61f25a4
DW
3362
3363 /**
3364 * This helper method gets a snapshot of all the weights for a course.
3365 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3366 * @param int $courseid
3367 * @return array of itemid -> aggregationcoef2
3368 */
3369 public static function fetch_all_natural_weights_for_course($courseid) {
3370 global $DB;
3371 $result = array();
3372
3373 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');