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