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