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