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