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