MDL-32978 Gradebook: Fix strict standards notices
[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
7a6b7acf 25require_once $CFG->libdir.'/gradelib.php';
26
0f5660f7 27/**
28 * This class iterates over all users that are graded in a course.
b9f49659 29 * Returns detailed info about users and their grades.
cf72e2dd 30 *
31 * @author Petr Skoda <skodak@moodle.org>
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0f5660f7 33 */
34class graded_users_iterator {
d24832f9 35 public $course;
36 public $grade_items;
37 public $groupid;
38 public $users_rs;
39 public $grades_rs;
40 public $gradestack;
41 public $sortfield1;
42 public $sortorder1;
43 public $sortfield2;
44 public $sortorder2;
0f5660f7 45
78ab98bc
AD
46 /**
47 * Should users whose enrolment has been suspended be ignored?
48 */
49 protected $onlyactive = false;
50
0f5660f7 51 /**
52 * Constructor
cf72e2dd 53 *
54 * @param object $course A course object
55 * @param array $grade_items array of grade items, if not specified only user info returned
56 * @param int $groupid iterate only group users if present
d08bba83 57 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
58 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
59 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
60 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
0f5660f7 61 */
cf72e2dd 62 public function graded_users_iterator($course, $grade_items=null, $groupid=0,
63 $sortfield1='lastname', $sortorder1='ASC',
64 $sortfield2='firstname', $sortorder2='ASC') {
0f5660f7 65 $this->course = $course;
66 $this->grade_items = $grade_items;
67 $this->groupid = $groupid;
d08bba83 68 $this->sortfield1 = $sortfield1;
69 $this->sortorder1 = $sortorder1;
70 $this->sortfield2 = $sortfield2;
71 $this->sortorder2 = $sortorder2;
0f5660f7 72
73 $this->gradestack = array();
74 }
75
76 /**
77 * Initialise the iterator
78 * @return boolean success
79 */
d24832f9 80 public function init() {
81 global $CFG, $DB;
0f5660f7 82
83 $this->close();
84
85 grade_regrade_final_grades($this->course->id);
86 $course_item = grade_item::fetch_course_item($this->course->id);
87 if ($course_item->needsupdate) {
88 // can not calculate all final grades - sorry
89 return false;
90 }
91
656d17c2
AD
92 $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
93 $relatedcontexts = get_related_contexts_string($coursecontext);
94
cf72e2dd 95 list($gradebookroles_sql, $params) =
cf717dc2 96 $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
78ab98bc 97 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
656d17c2
AD
98
99 $params = array_merge($params, $enrolledparams);
0f5660f7 100
101 if ($this->groupid) {
d24832f9 102 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
e58fcb35 103 $groupwheresql = "AND gm.groupid = :groupid";
d24832f9 104 // $params contents: gradebookroles
e58fcb35 105 $params['groupid'] = $this->groupid;
0f5660f7 106 } else {
107 $groupsql = "";
108 $groupwheresql = "";
109 }
110
345674ca 111 if (empty($this->sortfield1)) {
112 // we must do some sorting even if not specified
113 $ofields = ", u.id AS usrt";
114 $order = "usrt ASC";
115
116 } else {
117 $ofields = ", u.$this->sortfield1 AS usrt1";
118 $order = "usrt1 $this->sortorder1";
119 if (!empty($this->sortfield2)) {
0febb12d 120 $ofields .= ", u.$this->sortfield2 AS usrt2";
345674ca 121 $order .= ", usrt2 $this->sortorder2";
122 }
123 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
cf72e2dd 124 // user order MUST be the same in both queries,
125 // must include the only unique user->id if not already present
345674ca 126 $ofields .= ", u.id AS usrt";
127 $order .= ", usrt ASC";
128 }
129 }
130
d24832f9 131 // $params contents: gradebookroles and groupid (for $groupwheresql)
345674ca 132 $users_sql = "SELECT u.* $ofields
d24832f9 133 FROM {user} u
656d17c2 134 JOIN ($enrolledsql) je ON je.id = u.id
0f5660f7 135 $groupsql
656d17c2
AD
136 JOIN (
137 SELECT DISTINCT ra.userid
138 FROM {role_assignments} ra
139 WHERE ra.roleid $gradebookroles_sql
140 AND ra.contextid $relatedcontexts
141 ) rainner ON rainner.userid = u.id
142 WHERE u.deleted = 0
345674ca 143 $groupwheresql
144 ORDER BY $order";
d24832f9 145 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
0f5660f7 146
147 if (!empty($this->grade_items)) {
148 $itemids = array_keys($this->grade_items);
cf717dc2 149 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
d24832f9 150 $params = array_merge($params, $grades_params);
656d17c2 151 // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
0f5660f7 152
345674ca 153 $grades_sql = "SELECT g.* $ofields
d24832f9 154 FROM {grade_grades} g
656d17c2
AD
155 JOIN {user} u ON g.userid = u.id
156 JOIN ($enrolledsql) je ON je.id = u.id
0f5660f7 157 $groupsql
656d17c2
AD
158 JOIN (
159 SELECT DISTINCT ra.userid
160 FROM {role_assignments} ra
161 WHERE ra.roleid $gradebookroles_sql
162 AND ra.contextid $relatedcontexts
4f82032a 163 ) rainner ON rainner.userid = u.id
656d17c2
AD
164 WHERE u.deleted = 0
165 AND g.itemid $itemidsql
166 $groupwheresql
345674ca 167 ORDER BY $order, g.itemid ASC";
d24832f9 168 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
345674ca 169 } else {
170 $this->grades_rs = false;
0f5660f7 171 }
345674ca 172
0f5660f7 173 return true;
174 }
175
176 /**
177 * Returns information about the next user
178 * @return mixed array of user info, all grades and feedback or null when no more users found
179 */
180 function next_user() {
03cedd62 181 if (!$this->users_rs) {
0f5660f7 182 return false; // no users present
183 }
184
5c75a0a3 185 if (!$this->users_rs->valid()) {
345674ca 186 if ($current = $this->_pop()) {
187 // this is not good - user or grades updated between the two reads above :-(
188 }
189
0f5660f7 190 return false; // no more users
5c75a0a3 191 } else {
192 $user = $this->users_rs->current();
193 $this->users_rs->next();
0f5660f7 194 }
195
345674ca 196 // find grades of this user
0f5660f7 197 $grade_records = array();
198 while (true) {
199 if (!$current = $this->_pop()) {
200 break; // no more grades
201 }
202
5c75a0a3 203 if (empty($current->userid)) {
204 break;
205 }
206
345674ca 207 if ($current->userid != $user->id) {
208 // grade of the next user, we have all for this user
0f5660f7 209 $this->_push($current);
210 break;
211 }
212
213 $grade_records[$current->itemid] = $current;
214 }
215
216 $grades = array();
217 $feedbacks = array();
218
d08bba83 219 if (!empty($this->grade_items)) {
345674ca 220 foreach ($this->grade_items as $grade_item) {
6189c7b4
FM
221 if (!isset($feedbacks[$grade_item->id])) {
222 $feedbacks[$grade_item->id] = new stdClass();
223 }
345674ca 224 if (array_key_exists($grade_item->id, $grade_records)) {
225 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
226 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
227 unset($grade_records[$grade_item->id]->feedback);
228 unset($grade_records[$grade_item->id]->feedbackformat);
229 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
230 } else {
231 $feedbacks[$grade_item->id]->feedback = '';
232 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
cf72e2dd 233 $grades[$grade_item->id] =
234 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
345674ca 235 }
0f5660f7 236 }
237 }
238
ace9051c 239 $result = new stdClass();
0f5660f7 240 $result->user = $user;
241 $result->grades = $grades;
242 $result->feedbacks = $feedbacks;
0f5660f7 243 return $result;
244 }
245
246 /**
247 * Close the iterator, do not forget to call this function.
248 * @return void
249 */
250 function close() {
caffc55a 251 if ($this->users_rs) {
d24832f9 252 $this->users_rs->close();
caffc55a 253 $this->users_rs = null;
0f5660f7 254 }
caffc55a 255 if ($this->grades_rs) {
d24832f9 256 $this->grades_rs->close();
caffc55a 257 $this->grades_rs = null;
0f5660f7 258 }
259 $this->gradestack = array();
260 }
261
78ab98bc
AD
262 /**
263 * Should all enrolled users be exported or just those with an active enrolment?
264 *
265 * @param bool $onlyactive True to limit the export to users with an active enrolment
266 */
267 public function require_active_enrolment($onlyactive = true) {
268 if (!empty($this->users_rs)) {
269 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
270 }
271 $this->onlyactive = $onlyactive;
272 }
273
cf72e2dd 274
0f5660f7 275 /**
cf72e2dd 276 * _push
277 *
278 * @param grade_grade $grade Grade object
279 *
280 * @return void
0f5660f7 281 */
282 function _push($grade) {
283 array_push($this->gradestack, $grade);
284 }
285
cf72e2dd 286
0f5660f7 287 /**
cf72e2dd 288 * _pop
289 *
7ce5df86 290 * @return object current grade object
0f5660f7 291 */
292 function _pop() {
d24832f9 293 global $DB;
0f5660f7 294 if (empty($this->gradestack)) {
8de7c8a7 295 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
cf72e2dd 296 return null; // no grades present
0f5660f7 297 }
298
7ce5df86
AD
299 $current = $this->grades_rs->current();
300
301 $this->grades_rs->next();
0f5660f7 302
7ce5df86 303 return $current;
0f5660f7 304 } else {
305 return array_pop($this->gradestack);
306 }
307 }
308}
309
d08bba83 310/**
311 * Print a selection popup form of the graded users in a course.
312 *
4d5059d4
SH
313 * @deprecated since 2.0
314 *
cf72e2dd 315 * @param int $course id of the course
d08bba83 316 * @param string $actionpage The page receiving the data from the popoup form
cf72e2dd 317 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
318 * @param int $groupid id of requested group, 0 means all
319 * @param int $includeall bool include all option
320 * @param bool $return If true, will return the HTML, otherwise, will print directly
d08bba83 321 * @return null
322 */
7ac88172 323function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
714b4745 324 global $CFG, $USER, $OUTPUT;
4d5059d4
SH
325 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
326}
345674ca 327
4d5059d4 328function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
f9510667
PS
329 global $USER;
330
879c99bb 331 if (is_null($userid)) {
332 $userid = $USER->id;
333 }
d08bba83 334
d08bba83 335 $menu = array(); // Will be a list of userid => user name
772229f3 336 $gui = new graded_users_iterator($course, null, $groupid);
d08bba83 337 $gui->init();
10f5c046 338 $label = get_string('selectauser', 'grades');
7ac88172 339 if ($includeall) {
879c99bb 340 $menu[0] = get_string('allusers', 'grades');
10f5c046 341 $label = get_string('selectalloroneuser', 'grades');
d08bba83 342 }
d08bba83 343 while ($userdata = $gui->next_user()) {
344 $user = $userdata->user;
345 $menu[$user->id] = fullname($user);
346 }
d08bba83 347 $gui->close();
348
7ac88172 349 if ($includeall) {
879c99bb 350 $menu[0] .= " (" . (count($menu) - 1) . ")";
351 }
4d5059d4 352 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
f8dab966
PS
353 $select->label = $label;
354 $select->formid = 'choosegradeuser';
4d5059d4 355 return $select;
d08bba83 356}
357
0610812a 358/**
359 * Print grading plugin selection popup form.
360 *
cf72e2dd 361 * @param array $plugin_info An array of plugins containing information for the selector
0610812a 362 * @param boolean $return return as string
cf72e2dd 363 *
0610812a 364 * @return nothing or string if $return true
365 */
f1a3e072 366function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
714b4745 367 global $CFG, $OUTPUT, $PAGE;
dc482cfa 368
369 $menu = array();
370 $count = 0;
371 $active = '';
372
373 foreach ($plugin_info as $plugin_type => $plugins) {
374 if ($plugin_type == 'strings') {
375 continue;
376 }
377
7981d537 378 $first_plugin = reset($plugins);
dc482cfa 379
f1a3e072
PS
380 $sectionname = $plugin_info['strings'][$plugin_type];
381 $section = array();
d4dcfc6b 382
f1a3e072 383 foreach ($plugins as $plugin) {
d4dcfc6b 384 $link = $plugin->link->out(false);
f1a3e072
PS
385 $section[$link] = $plugin->string;
386 $count++;
387 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
388 $active = $link;
dc482cfa 389 }
390 }
f1a3e072
PS
391
392 if ($section) {
393 $menu[] = array($sectionname=>$section);
394 }
dc482cfa 395 }
396
cf72e2dd 397 // finally print/return the popup form
dc482cfa 398 if ($count > 1) {
f1a3e072 399 $select = new url_select($menu, $active, null, 'choosepluginreport');
3211569a 400
7981d537 401 if ($return) {
f1a3e072 402 return $OUTPUT->render($select);
7981d537 403 } else {
f1a3e072 404 echo $OUTPUT->render($select);
7981d537 405 }
dc482cfa 406 } else {
407 // only one option - no plugin selector needed
408 return '';
409 }
410}
411
412/**
413 * Print grading plugin selection tab-based navigation.
414 *
cf72e2dd 415 * @param string $active_type type of plugin on current page - import, export, report or edit
416 * @param string $active_plugin active plugin type - grader, user, cvs, ...
417 * @param array $plugin_info Array of plugins
dc482cfa 418 * @param boolean $return return as string
cf72e2dd 419 *
dc482cfa 420 * @return nothing or string if $return true
421 */
b827784e 422function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
dc482cfa 423 global $CFG, $COURSE;
1c1f64a2 424
e1513ca9 425 if (!isset($currenttab)) { //TODO: this is weird
dc482cfa 426 $currenttab = '';
427 }
428
429 $tabs = array();
430 $top_row = array();
431 $bottom_row = array();
432 $inactive = array($active_plugin);
433 $activated = array();
434
435 $count = 0;
436 $active = '';
437
438 foreach ($plugin_info as $plugin_type => $plugins) {
439 if ($plugin_type == 'strings') {
440 continue;
441 }
442
443 // If $plugins is actually the definition of a child-less parent link:
cf72e2dd 444 if (!empty($plugins->id)) {
445 $string = $plugins->string;
446 if (!empty($plugin_info[$active_type]->parent)) {
447 $string = $plugin_info[$active_type]->parent->string;
27eef3bb 448 }
449
cf72e2dd 450 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
dc482cfa 451 continue;
452 }
453
454 $first_plugin = reset($plugins);
cf72e2dd 455 $url = $first_plugin->link;
dc482cfa 456
457 if ($plugin_type == 'report') {
458 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
459 }
460
461 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
462
463 if ($active_type == $plugin_type) {
464 foreach ($plugins as $plugin) {
cf72e2dd 465 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
466 if ($plugin->id == $active_plugin) {
467 $inactive = array($plugin->id);
dc482cfa 468 }
469 }
470 }
471 }
472
473 $tabs[] = $top_row;
474 $tabs[] = $bottom_row;
475
476 if ($return) {
477 return print_tabs($tabs, $active_type, $inactive, $activated, true);
478 } else {
479 print_tabs($tabs, $active_type, $inactive, $activated);
480 }
481}
482
cf72e2dd 483/**
484 * grade_get_plugin_info
485 *
486 * @param int $courseid The course id
487 * @param string $active_type type of plugin on current page - import, export, report or edit
488 * @param string $active_plugin active plugin type - grader, user, cvs, ...
489 *
490 * @return array
491 */
dc482cfa 492function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
f7fcf4cd 493 global $CFG, $SITE;
cbff94ba 494
3af29899 495 $context = get_context_instance(CONTEXT_COURSE, $courseid);
cbff94ba 496
dc482cfa 497 $plugin_info = array();
6e2f3121 498 $count = 0;
3af29899 499 $active = '';
dc482cfa 500 $url_prefix = $CFG->wwwroot . '/grade/';
501
502 // Language strings
4d5059d4 503 $plugin_info['strings'] = grade_helper::get_plugin_strings();
b827784e 504
4d5059d4
SH
505 if ($reports = grade_helper::get_plugins_reports($courseid)) {
506 $plugin_info['report'] = $reports;
b827784e 507 }
c46aeeab 508
f7fcf4cd
AD
509 //showing grade categories and items make no sense if we're not within a course
510 if ($courseid!=$SITE->id) {
511 if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
512 $plugin_info['edittree'] = $edittree;
513 }
04678d8e 514 }
b827784e 515
4d5059d4
SH
516 if ($scale = grade_helper::get_info_scales($courseid)) {
517 $plugin_info['scale'] = array('view'=>$scale);
cbff94ba 518 }
dc482cfa 519
4d5059d4
SH
520 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
521 $plugin_info['outcome'] = $outcomes;
cbff94ba 522 }
cbff94ba 523
4d5059d4
SH
524 if ($letters = grade_helper::get_info_letters($courseid)) {
525 $plugin_info['letter'] = $letters;
cbff94ba 526 }
4d5059d4
SH
527
528 if ($imports = grade_helper::get_plugins_import($courseid)) {
529 $plugin_info['import'] = $imports;
281ffa4a 530 }
c46aeeab 531
4d5059d4
SH
532 if ($exports = grade_helper::get_plugins_export($courseid)) {
533 $plugin_info['export'] = $exports;
281ffa4a 534 }
281ffa4a 535
4d5059d4
SH
536 foreach ($plugin_info as $plugin_type => $plugins) {
537 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
538 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
539 break;
281ffa4a 540 }
4d5059d4
SH
541 foreach ($plugins as $plugin) {
542 if (is_a($plugin, 'grade_plugin_info')) {
543 if ($active_plugin == $plugin->id) {
544 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
545 }
3af29899 546 }
281ffa4a 547 }
cbff94ba 548 }
c46aeeab 549
f7fcf4cd
AD
550 //hide course settings if we're not in a course
551 if ($courseid!=$SITE->id) {
552 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
553 $plugin_info['settings'] = array('course'=>$setting);
554 }
281ffa4a 555 }
cbff94ba 556
4d5059d4
SH
557 // Put preferences last
558 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
559 $plugin_info['preferences'] = $preferences;
27eef3bb 560 }
561
dc482cfa 562 foreach ($plugin_info as $plugin_type => $plugins) {
cf72e2dd 563 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
564 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
dc482cfa 565 break;
78ad5f3f 566 }
dc482cfa 567 foreach ($plugins as $plugin) {
cf72e2dd 568 if (is_a($plugin, 'grade_plugin_info')) {
569 if ($active_plugin == $plugin->id) {
570 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
571 }
78ad5f3f 572 }
78ad5f3f 573 }
dc482cfa 574 }
78ad5f3f 575
dc482cfa 576 return $plugin_info;
577}
284abb09 578
cf72e2dd 579/**
580 * A simple class containing info about grade plugins.
581 * Can be subclassed for special rules
582 *
a153c9f2 583 * @package core_grades
cf72e2dd 584 * @copyright 2009 Nicolas Connault
585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
586 */
587class grade_plugin_info {
588 /**
589 * A unique id for this plugin
590 *
591 * @var mixed
592 */
593 public $id;
594 /**
595 * A URL to access this plugin
596 *
597 * @var mixed
598 */
599 public $link;
600 /**
601 * The name of this plugin
602 *
603 * @var mixed
604 */
605 public $string;
606 /**
607 * Another grade_plugin_info object, parent of the current one
608 *
609 * @var mixed
610 */
611 public $parent;
612
613 /**
614 * Constructor
615 *
616 * @param int $id A unique id for this plugin
617 * @param string $link A URL to access this plugin
618 * @param string $string The name of this plugin
619 * @param object $parent Another grade_plugin_info object, parent of the current one
620 *
621 * @return void
622 */
623 public function __construct($id, $link, $string, $parent=null) {
624 $this->id = $id;
625 $this->link = $link;
626 $this->string = $string;
627 $this->parent = $parent;
628 }
629}
630
de0300ea 631/**
632 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
633 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
634 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
635 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
636 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
637 *
cf72e2dd 638 * @param int $courseid Course id
639 * @param string $active_type The type of the current page (report, settings,
640 * import, export, scales, outcomes, letters)
641 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
642 * @param string $heading The heading of the page. Tries to guess if none is given
de0300ea 643 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
cf72e2dd 644 * @param string $bodytags Additional attributes that will be added to the <body> tag
645 * @param string $buttons Additional buttons to display on the page
5625d33d 646 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
de0300ea 647 *
648 * @return string HTML code or nothing if $return == false
649 */
cf72e2dd 650function print_grade_page_head($courseid, $active_type, $active_plugin=null,
34a2777c 651 $heading = false, $return=false,
2821c495 652 $buttons=false, $shownavigation=true) {
4d5059d4 653 global $CFG, $OUTPUT, $PAGE;
c46aeeab 654
dc482cfa 655 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
c46aeeab 656
dc482cfa 657 // Determine the string of the active plugin
658 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
659 $stractive_type = $plugin_info['strings'][$active_type];
e0724506 660
cf72e2dd 661 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
4d5059d4
SH
662 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
663 } else {
664 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
c4c97a6d 665 }
666
367a75fa
SH
667 if ($active_type == 'report') {
668 $PAGE->set_pagelayout('report');
669 } else {
670 $PAGE->set_pagelayout('admin');
671 }
4d5059d4 672 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
f3df5e14 673 $PAGE->set_heading($title);
4d5059d4
SH
674 if ($buttons instanceof single_button) {
675 $buttons = $OUTPUT->render($buttons);
676 }
f3df5e14 677 $PAGE->set_button($buttons);
4d5059d4
SH
678 grade_extend_settings($plugin_info, $courseid);
679
f3df5e14 680 $returnval = $OUTPUT->header();
681 if (!$return) {
682 echo $returnval;
683 }
dc482cfa 684
685 // Guess heading if not given explicitly
686 if (!$heading) {
687 $heading = $stractive_plugin;
688 }
689
2821c495
AD
690 if ($shownavigation) {
691 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
692 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
693 }
5625d33d
AD
694
695 if ($return) {
696 $returnval .= $OUTPUT->heading($heading);
697 } else {
e59a1dd6 698 echo $OUTPUT->heading($heading);
5625d33d
AD
699 }
700
2821c495
AD
701 if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
702 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
703 }
8354e716 704 }
dc482cfa 705
706 if ($return) {
707 return $returnval;
6e2f3121 708 }
cbff94ba 709}
710
0610812a 711/**
7a6b7acf 712 * Utility class used for return tracking when using edit and other forms in grade plugins
cf72e2dd 713 *
a153c9f2 714 * @package core_grades
cf72e2dd 715 * @copyright 2009 Nicolas Connault
716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0610812a 717 */
3af29899 718class grade_plugin_return {
d24832f9 719 public $type;
720 public $plugin;
721 public $courseid;
722 public $userid;
723 public $page;
281ffa4a 724
0610812a 725 /**
726 * Constructor
cf72e2dd 727 *
0610812a 728 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
729 */
cf72e2dd 730 public function grade_plugin_return($params = null) {
3af29899 731 if (empty($params)) {
732 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
aff24313 733 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
3af29899 734 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
735 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
736 $this->page = optional_param('gpr_page', null, PARAM_INT);
a983b6ec 737
a983b6ec 738 } else {
3af29899 739 foreach ($params as $key=>$value) {
4cc977a6 740 if (property_exists($this, $key)) {
3af29899 741 $this->$key = $value;
742 }
cbff94ba 743 }
744 }
6cd8c592 745 }
746
0610812a 747 /**
748 * Returns return parameters as options array suitable for buttons.
749 * @return array options
750 */
d24832f9 751 public function get_options() {
7a6b7acf 752 if (empty($this->type)) {
3af29899 753 return array();
865e9a82 754 }
6cd8c592 755
3af29899 756 $params = array();
6cd8c592 757
7a6b7acf 758 if (!empty($this->plugin)) {
759 $params['plugin'] = $this->plugin;
760 }
6cd8c592 761
3af29899 762 if (!empty($this->courseid)) {
763 $params['id'] = $this->courseid;
6cd8c592 764 }
9c61ba4d 765
3af29899 766 if (!empty($this->userid)) {
767 $params['userid'] = $this->userid;
9c61ba4d 768 }
9c61ba4d 769
3af29899 770 if (!empty($this->page)) {
771 $params['page'] = $this->page;
cbff94ba 772 }
865e9a82 773
3af29899 774 return $params;
cbff94ba 775 }
cbff94ba 776
0610812a 777 /**
778 * Returns return url
cf72e2dd 779 *
0610812a 780 * @param string $default default url when params not set
cf72e2dd 781 * @param array $extras Extra URL parameters
782 *
0610812a 783 * @return string url
784 */
d24832f9 785 public function get_return_url($default, $extras=null) {
3af29899 786 global $CFG;
cbff94ba 787
3af29899 788 if (empty($this->type) or empty($this->plugin)) {
789 return $default;
cbff94ba 790 }
791
65dd61bd 792 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
793 $glue = '?';
cbff94ba 794
3af29899 795 if (!empty($this->courseid)) {
796 $url .= $glue.'id='.$this->courseid;
797 $glue = '&amp;';
cbff94ba 798 }
cbff94ba 799
3af29899 800 if (!empty($this->userid)) {
801 $url .= $glue.'userid='.$this->userid;
802 $glue = '&amp;';
cbff94ba 803 }
7e2d7c92 804
3af29899 805 if (!empty($this->page)) {
806 $url .= $glue.'page='.$this->page;
65dd61bd 807 $glue = '&amp;';
808 }
809
810 if (!empty($extras)) {
cf72e2dd 811 foreach ($extras as $key=>$value) {
65dd61bd 812 $url .= $glue.$key.'='.$value;
813 $glue = '&amp;';
7a6b7acf 814 }
cbff94ba 815 }
cbff94ba 816
3af29899 817 return $url;
cbff94ba 818 }
cbff94ba 819
0610812a 820 /**
821 * Returns string with hidden return tracking form elements.
822 * @return string
823 */
d24832f9 824 public function get_form_fields() {
7a6b7acf 825 if (empty($this->type)) {
3af29899 826 return '';
cbff94ba 827 }
cbff94ba 828
3af29899 829 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 830
831 if (!empty($this->plugin)) {
832 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
833 }
0ca5abd6 834
3af29899 835 if (!empty($this->courseid)) {
836 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 837 }
cbff94ba 838
3af29899 839 if (!empty($this->userid)) {
840 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 841 }
cbff94ba 842
3af29899 843 if (!empty($this->page)) {
844 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 845 }
846 }
cbff94ba 847
0610812a 848 /**
849 * Add hidden elements into mform
cf72e2dd 850 *
851 * @param object &$mform moodle form object
852 *
0610812a 853 * @return void
854 */
d24832f9 855 public function add_mform_elements(&$mform) {
7a6b7acf 856 if (empty($this->type)) {
3af29899 857 return;
cbff94ba 858 }
cbff94ba 859
3af29899 860 $mform->addElement('hidden', 'gpr_type', $this->type);
861 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 862
7a6b7acf 863 if (!empty($this->plugin)) {
864 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
aff24313 865 $mform->setType('gpr_plugin', PARAM_PLUGIN);
7a6b7acf 866 }
97033c86 867
3af29899 868 if (!empty($this->courseid)) {
869 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
870 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 871 }
cbff94ba 872
3af29899 873 if (!empty($this->userid)) {
874 $mform->addElement('hidden', 'gpr_userid', $this->userid);
875 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 876 }
cbff94ba 877
3af29899 878 if (!empty($this->page)) {
879 $mform->addElement('hidden', 'gpr_page', $this->page);
880 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 881 }
882 }
281ffa4a 883
0610812a 884 /**
885 * Add return tracking params into url
cf72e2dd 886 *
1c1f64a2 887 * @param moodle_url $url A URL
cf72e2dd 888 *
6ef4878b 889 * @return string $url with return tracking params
0610812a 890 */
1c1f64a2 891 public function add_url_params(moodle_url $url) {
7a6b7acf 892 if (empty($this->type)) {
3af29899 893 return $url;
cbff94ba 894 }
5609f9e6 895
1c1f64a2 896 $url->param('gpr_type', $this->type);
cbff94ba 897
7a6b7acf 898 if (!empty($this->plugin)) {
1c1f64a2 899 $url->param('gpr_plugin', $this->plugin);
7a6b7acf 900 }
cbff94ba 901
3af29899 902 if (!empty($this->courseid)) {
1c1f64a2 903 $url->param('gpr_courseid' ,$this->courseid);
cbff94ba 904 }
cbff94ba 905
3af29899 906 if (!empty($this->userid)) {
1c1f64a2 907 $url->param('gpr_userid', $this->userid);
cbff94ba 908 }
0a8a95c9 909
3af29899 910 if (!empty($this->page)) {
1c1f64a2 911 $url->param('gpr_page', $this->page);
0a8a95c9 912 }
5a412dbf 913
3af29899 914 return $url;
5a412dbf 915 }
5a412dbf 916}
7a6b7acf 917
826c5f86 918/**
919 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
cf72e2dd 920 *
826c5f86 921 * @param string $path The path of the calling script (using __FILE__?)
922 * @param string $pagename The language string to use as the last part of the navigation (non-link)
cf72e2dd 923 * @param mixed $id Either a plain integer (assuming the key is 'id') or
924 * an array of keys and values (e.g courseid => $courseid, itemid...)
925 *
826c5f86 926 * @return string
927 */
928function grade_build_nav($path, $pagename=null, $id=null) {
f3df5e14 929 global $CFG, $COURSE, $PAGE;
826c5f86 930
931 $strgrades = get_string('grades', 'grades');
932
933 // Parse the path and build navlinks from its elements
934 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
935 $path = substr($path, $dirroot_length);
936 $path = str_replace('\\', '/', $path);
937
938 $path_elements = explode('/', $path);
939
940 $path_elements_count = count($path_elements);
941
826c5f86 942 // First link is always 'grade'
a6855934 943 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
826c5f86 944
f3df5e14 945 $link = null;
826c5f86 946 $numberofelements = 3;
947
948 // Prepare URL params string
f3df5e14 949 $linkparams = array();
826c5f86 950 if (!is_null($id)) {
951 if (is_array($id)) {
952 foreach ($id as $idkey => $idvalue) {
f3df5e14 953 $linkparams[$idkey] = $idvalue;
826c5f86 954 }
955 } else {
f3df5e14 956 $linkparams['id'] = $id;
826c5f86 957 }
958 }
959
960 $navlink4 = null;
961
0f78c4de 962 // Remove file extensions from filenames
963 foreach ($path_elements as $key => $filename) {
964 $path_elements[$key] = str_replace('.php', '', $filename);
965 }
966
826c5f86 967 // Second level links
968 switch ($path_elements[1]) {
969 case 'edit': // No link
970 if ($path_elements[3] != 'index.php') {
971 $numberofelements = 4;
972 }
973 break;
974 case 'import': // No link
975 break;
976 case 'export': // No link
977 break;
978 case 'report':
979 // $id is required for this link. Do not print it if $id isn't given
980 if (!is_null($id)) {
a6855934 981 $link = new moodle_url('/grade/report/index.php', $linkparams);
826c5f86 982 }
983
984 if ($path_elements[2] == 'grader') {
985 $numberofelements = 4;
986 }
987 break;
988
989 default:
990 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
cf72e2dd 991 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
992 " as the second path element after 'grade'.");
826c5f86 993 return false;
994 }
f3df5e14 995 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
826c5f86 996
997 // Third level links
998 if (empty($pagename)) {
999 $pagename = get_string($path_elements[2], 'grades');
1000 }
1001
1002 switch ($numberofelements) {
1003 case 3:
f3df5e14 1004 $PAGE->navbar->add($pagename, $link);
826c5f86 1005 break;
1006 case 4:
826c5f86 1007 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
b5e7b2bf 1008 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
826c5f86 1009 }
f3df5e14 1010 $PAGE->navbar->add($pagename);
826c5f86 1011 break;
1012 }
826c5f86 1013
f3df5e14 1014 return '';
d4795a07 1015}
7a6b7acf 1016
e98871a2 1017/**
6cc3e350 1018 * General structure representing grade items in course
cf72e2dd 1019 *
a153c9f2 1020 * @package core_grades
cf72e2dd 1021 * @copyright 2009 Nicolas Connault
1022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e98871a2 1023 */
6cc3e350 1024class grade_structure {
d24832f9 1025 public $context;
e98871a2 1026
d24832f9 1027 public $courseid;
e98871a2 1028
73ca5f01 1029 /**
1030 * Reference to modinfo for current course (for performance, to save
1031 * retrieving it from courseid every time). Not actually set except for
1032 * the grade_tree type.
1033 * @var course_modinfo
1034 */
1035 public $modinfo;
1036
e98871a2 1037 /**
1038 * 1D array of grade items only
1039 */
d24832f9 1040 public $items;
e98871a2 1041
6391ebe7 1042 /**
6cc3e350 1043 * Returns icon of element
cf72e2dd 1044 *
1045 * @param array &$element An array representing an element in the grade_tree
1046 * @param bool $spacerifnone return spacer if no icon found
1047 *
6cc3e350 1048 * @return string icon or spacer
6391ebe7 1049 */
d24832f9 1050 public function get_element_icon(&$element, $spacerifnone=false) {
6b608f8f 1051 global $CFG, $OUTPUT;
6cc3e350 1052
1053 switch ($element['type']) {
1054 case 'item':
1055 case 'courseitem':
1056 case 'categoryitem':
cf72e2dd 1057 $is_course = $element['object']->is_course_item();
1058 $is_category = $element['object']->is_category_item();
1059 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1060 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
0077f571 1061 $is_outcome = !empty($element['object']->outcomeid);
cf72e2dd 1062
6cc3e350 1063 if ($element['object']->is_calculated()) {
dc482cfa 1064 $strcalc = get_string('calculatedgrade', 'grades');
b5d0cafc 1065 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
cf72e2dd 1066 s($strcalc).'" alt="'.s($strcalc).'"/>';
6cc3e350 1067
cf72e2dd 1068 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
6cc3e350 1069 if ($category = $element['object']->get_item_category()) {
1070 switch ($category->aggregation) {
1071 case GRADE_AGGREGATE_MEAN:
1072 case GRADE_AGGREGATE_MEDIAN:
1073 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1426edac 1074 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
6cc3e350 1075 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
dc482cfa 1076 $stragg = get_string('aggregation', 'grades');
b5d0cafc 1077 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
cf72e2dd 1078 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
0758a08e 1079 case GRADE_AGGREGATE_SUM:
dc482cfa 1080 $stragg = get_string('aggregation', 'grades');
b5d0cafc 1081 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
cf72e2dd 1082 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
6cc3e350 1083 }
1084 }
1085
1086 } else if ($element['object']->itemtype == 'mod') {
0077f571
AD
1087 //prevent outcomes being displaying the same icon as the activity they are attached to
1088 if ($is_outcome) {
1089 $stroutcome = s(get_string('outcome', 'grades'));
1090 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1091 'class="icon itemicon" title="'.$stroutcome.
1092 '" alt="'.$stroutcome.'"/>';
1093 } else {
1094 $strmodname = get_string('modulename', $element['object']->itemmodule);
1095 return '<img src="'.$OUTPUT->pix_url('icon',
e63f88c9 1096 $element['object']->itemmodule) . '" ' .
cf72e2dd 1097 'class="icon itemicon" title="' .s($strmodname).
1098 '" alt="' .s($strmodname).'"/>';
0077f571 1099 }
6cc3e350 1100 } else if ($element['object']->itemtype == 'manual') {
1101 if ($element['object']->is_outcome_item()) {
dc482cfa 1102 $stroutcome = get_string('outcome', 'grades');
b5d0cafc 1103 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
cf72e2dd 1104 'class="icon itemicon" title="'.s($stroutcome).
1105 '" alt="'.s($stroutcome).'"/>';
6cc3e350 1106 } else {
dc482cfa 1107 $strmanual = get_string('manualitem', 'grades');
b5d0cafc 1108 return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
cf72e2dd 1109 'class="icon itemicon" title="'.s($strmanual).
1110 '" alt="'.s($strmanual).'"/>';
6cc3e350 1111 }
1112 }
1113 break;
1114
1115 case 'category':
dc482cfa 1116 $strcat = get_string('category', 'grades');
b5d0cafc 1117 return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
cf72e2dd 1118 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
6cc3e350 1119 }
1120
1121 if ($spacerifnone) {
b11681e0 1122 return $OUTPUT->spacer().' ';
6cc3e350 1123 } else {
1124 return '';
1125 }
1126 }
6391ebe7 1127
e98871a2 1128 /**
6cc3e350 1129 * Returns name of element optionally with icon and link
cf72e2dd 1130 *
1131 * @param array &$element An array representing an element in the grade_tree
1132 * @param bool $withlink Whether or not this header has a link
1133 * @param bool $icon Whether or not to display an icon with this header
1134 * @param bool $spacerifnone return spacer if no icon found
1135 *
1136 * @return string header
e98871a2 1137 */
d24832f9 1138 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
6cc3e350 1139 $header = '';
1140
1141 if ($icon) {
1142 $header .= $this->get_element_icon($element, $spacerifnone);
1143 }
1144
dc482cfa 1145 $header .= $element['object']->get_name();
6cc3e350 1146
cf72e2dd 1147 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1148 $element['type'] != 'courseitem') {
6cc3e350 1149 return $header;
1150 }
1151
73ca5f01 1152 if ($withlink) {
1153 $url = $this->get_activity_link($element);
1154 if ($url) {
ace9051c 1155 $a = new stdClass();
45a639d5 1156 $a->name = get_string('modulename', $element['object']->itemmodule);
dc482cfa 1157 $title = get_string('linktoactivity', 'grades', $a);
6cc3e350 1158
73ca5f01 1159 $header = html_writer::link($url, $header, array('title' => $title));
46d1af82 1160 }
6cc3e350 1161 }
1162
1163 return $header;
1164 }
1165
73ca5f01 1166 private function get_activity_link($element) {
1167 global $CFG;
eff314b0
DM
1168 /** @var array static cache of the grade.php file existence flags */
1169 static $hasgradephp = array();
73ca5f01 1170
1171 $itemtype = $element['object']->itemtype;
1172 $itemmodule = $element['object']->itemmodule;
1173 $iteminstance = $element['object']->iteminstance;
25ab1d50 1174 $itemnumber = $element['object']->itemnumber;
73ca5f01 1175
1176 // Links only for module items that have valid instance, module and are
1177 // called from grade_tree with valid modinfo
1178 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1179 return null;
1180 }
1181
1182 // Get $cm efficiently and with visibility information using modinfo
1183 $instances = $this->modinfo->get_instances();
1184 if (empty($instances[$itemmodule][$iteminstance])) {
1185 return null;
1186 }
1187 $cm = $instances[$itemmodule][$iteminstance];
1188
1189 // Do not add link if activity is not visible to the current user
1190 if (!$cm->uservisible) {
1191 return null;
1192 }
1193
eff314b0
DM
1194 if (!array_key_exists($itemmodule, $hasgradephp)) {
1195 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1196 $hasgradephp[$itemmodule] = true;
1197 } else {
1198 $hasgradephp[$itemmodule] = false;
1199 }
1200 }
1201
73ca5f01 1202 // If module has grade.php, link to that, otherwise view.php
eff314b0 1203 if ($hasgradephp[$itemmodule]) {
c97933ff
MG
1204 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1205 if (isset($element['userid'])) {
1206 $args['userid'] = $element['userid'];
1207 }
1208 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
73ca5f01 1209 } else {
1210 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1211 }
1212 }
1213
bb17ac1e
DM
1214 /**
1215 * Returns URL of a page that is supposed to contain detailed grade analysis
1216 *
bb17ac1e
DM
1217 * At the moment, only activity modules are supported. The method generates link
1218 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
eff314b0 1219 * gradeid and userid. If the grade.php does not exist, null is returned.
bb17ac1e
DM
1220 *
1221 * @return moodle_url|null URL or null if unable to construct it
1222 */
1223 public function get_grade_analysis_url(grade_grade $grade) {
eff314b0
DM
1224 global $CFG;
1225 /** @var array static cache of the grade.php file existence flags */
1226 static $hasgradephp = array();
bb17ac1e
DM
1227
1228 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1229 throw new coding_exception('Passed grade without the associated grade item');
1230 }
1231 $item = $grade->grade_item;
1232
1233 if (!$item->is_external_item()) {
1234 // at the moment, only activity modules are supported
1235 return null;
1236 }
1237 if ($item->itemtype !== 'mod') {
1238 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1239 }
1240 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1241 return null;
1242 }
1243
eff314b0
DM
1244 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1245 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1246 $hasgradephp[$item->itemmodule] = true;
1247 } else {
1248 $hasgradephp[$item->itemmodule] = false;
1249 }
1250 }
1251
1252 if (!$hasgradephp[$item->itemmodule]) {
1253 return null;
1254 }
1255
bb17ac1e
DM
1256 $instances = $this->modinfo->get_instances();
1257 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1258 return null;
1259 }
1260 $cm = $instances[$item->itemmodule][$item->iteminstance];
1261 if (!$cm->uservisible) {
1262 return null;
1263 }
1264
1265 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1266 'id' => $cm->id,
1267 'itemid' => $item->id,
1268 'itemnumber' => $item->itemnumber,
1269 'gradeid' => $grade->id,
1270 'userid' => $grade->userid,
1271 ));
1272
1273 return $url;
1274 }
1275
1276 /**
1277 * Returns an action icon leading to the grade analysis page
1278 *
1279 * @param grade_grade $grade
1280 * @return string
1281 */
1282 public function get_grade_analysis_icon(grade_grade $grade) {
1283 global $OUTPUT;
1284
1285 $url = $this->get_grade_analysis_url($grade);
1286 if (is_null($url)) {
1287 return '';
1288 }
1289
c97933ff 1290 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
bb17ac1e
DM
1291 get_string('gradeanalysis', 'core_grades')));
1292 }
1293
6cc3e350 1294 /**
1295 * Returns the grade eid - the grade may not exist yet.
cf72e2dd 1296 *
1297 * @param grade_grade $grade_grade A grade_grade object
1298 *
6cc3e350 1299 * @return string eid
1300 */
d24832f9 1301 public function get_grade_eid($grade_grade) {
6cc3e350 1302 if (empty($grade_grade->id)) {
1303 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1304 } else {
1305 return 'g'.$grade_grade->id;
1306 }
1307 }
1308
1309 /**
1310 * Returns the grade_item eid
cf72e2dd 1311 * @param grade_item $grade_item A grade_item object
6cc3e350 1312 * @return string eid
1313 */
d24832f9 1314 public function get_item_eid($grade_item) {
6cc3e350 1315 return 'i'.$grade_item->id;
1316 }
1317
cf72e2dd 1318 /**
1319 * Given a grade_tree element, returns an array of parameters
1320 * used to build an icon for that element.
1321 *
1322 * @param array $element An array representing an element in the grade_tree
1323 *
1324 * @return array
1325 */
1326 public function get_params_for_iconstr($element) {
9ecd4386 1327 $strparams = new stdClass();
1328 $strparams->category = '';
1329 $strparams->itemname = '';
1330 $strparams->itemmodule = '';
cf72e2dd 1331
9ecd4386 1332 if (!method_exists($element['object'], 'get_name')) {
1333 return $strparams;
1334 }
345674ca 1335
b285c5aa 1336 $strparams->itemname = html_to_text($element['object']->get_name());
9ecd4386 1337
1338 // If element name is categorytotal, get the name of the parent category
1339 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1340 $parent = $element['object']->get_parent_category();
1341 $strparams->category = $parent->get_name() . ' ';
1342 } else {
1343 $strparams->category = '';
1344 }
1345
1346 $strparams->itemmodule = null;
1347 if (isset($element['object']->itemmodule)) {
1348 $strparams->itemmodule = $element['object']->itemmodule;
345674ca 1349 }
9ecd4386 1350 return $strparams;
1351 }
1352
6cc3e350 1353 /**
1354 * Return edit icon for give element
cf72e2dd 1355 *
1356 * @param array $element An array representing an element in the grade_tree
1357 * @param object $gpr A grade_plugin_return object
1358 *
6cc3e350 1359 * @return string
1360 */
d24832f9 1361 public function get_edit_icon($element, $gpr) {
6b608f8f 1362 global $CFG, $OUTPUT;
6cc3e350 1363
1364 if (!has_capability('moodle/grade:manage', $this->context)) {
1365 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1366 // oki - let them override grade
1367 } else {
1368 return '';
1369 }
1370 }
1371
05aba805 1372 static $strfeedback = null;
1373 static $streditgrade = null;
1374 if (is_null($streditgrade)) {
1375 $streditgrade = get_string('editgrade', 'grades');
1376 $strfeedback = get_string('feedback');
6cc3e350 1377 }
1378
9ecd4386 1379 $strparams = $this->get_params_for_iconstr($element);
6ef4878b 1380
6cc3e350 1381 $object = $element['object'];
6cc3e350 1382
1383 switch ($element['type']) {
1384 case 'item':
1385 case 'categoryitem':
1386 case 'courseitem':
9ecd4386 1387 $stredit = get_string('editverbose', 'grades', $strparams);
6cc3e350 1388 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
a6855934 1389 $url = new moodle_url('/grade/edit/tree/item.php',
1c1f64a2 1390 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1391 } else {
a6855934 1392 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1c1f64a2 1393 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1394 }
6cc3e350 1395 break;
1396
1397 case 'category':
9ecd4386 1398 $stredit = get_string('editverbose', 'grades', $strparams);
a6855934 1399 $url = new moodle_url('/grade/edit/tree/category.php',
1c1f64a2 1400 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1401 break;
1402
1403 case 'grade':
05aba805 1404 $stredit = $streditgrade;
6cc3e350 1405 if (empty($object->id)) {
a6855934 1406 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1407 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
6cc3e350 1408 } else {
a6855934 1409 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1410 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1411 }
6cc3e350 1412 if (!empty($object->feedback)) {
1413 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
6cc3e350 1414 }
1415 break;
1416
1417 default:
1418 $url = null;
1419 }
1420
1421 if ($url) {
c63923bd 1422 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
6cc3e350 1423
1424 } else {
1425 return '';
1426 }
1427 }
1428
1429 /**
1430 * Return hiding icon for give element
cf72e2dd 1431 *
1432 * @param array $element An array representing an element in the grade_tree
1433 * @param object $gpr A grade_plugin_return object
1434 *
6cc3e350 1435 * @return string
1436 */
d24832f9 1437 public function get_hiding_icon($element, $gpr) {
5d3b9994 1438 global $CFG, $OUTPUT;
6cc3e350 1439
cf72e2dd 1440 if (!has_capability('moodle/grade:manage', $this->context) and
1441 !has_capability('moodle/grade:hide', $this->context)) {
6cc3e350 1442 return '';
1443 }
1444
345674ca 1445 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1446 $strshow = get_string('showverbose', 'grades', $strparams);
345674ca 1447 $strhide = get_string('hideverbose', 'grades', $strparams);
6cc3e350 1448
a6855934 1449 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 1450 $url = $gpr->add_url_params($url);
1c1f64a2 1451
6cc3e350 1452 if ($element['object']->is_hidden()) {
8ae8bf8a 1453 $type = 'show';
6cc3e350 1454 $tooltip = $strshow;
1455
cf72e2dd 1456 // Change the icon and add a tooltip showing the date
1457 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
8ae8bf8a 1458 $type = 'hiddenuntil';
cf72e2dd 1459 $tooltip = get_string('hiddenuntildate', 'grades',
1460 userdate($element['object']->get_hidden()));
6cc3e350 1461 }
1462
8ae8bf8a 1463 $url->param('action', 'show');
b9cc756e 1464
c63923bd 1465 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
6cc3e350 1466
1467 } else {
8ae8bf8a 1468 $url->param('action', 'hide');
c63923bd 1469 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
6cc3e350 1470 }
1c1f64a2 1471
8ae8bf8a 1472 return $hideicon;
6cc3e350 1473 }
1474
1475 /**
2673c733 1476 * Return locking icon for given element
cf72e2dd 1477 *
1478 * @param array $element An array representing an element in the grade_tree
1479 * @param object $gpr A grade_plugin_return object
1480 *
6cc3e350 1481 * @return string
1482 */
d24832f9 1483 public function get_locking_icon($element, $gpr) {
6b608f8f 1484 global $CFG, $OUTPUT;
6cc3e350 1485
345674ca 1486 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1487 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1488 $strlock = get_string('lockverbose', 'grades', $strparams);
d24832f9 1489
a6855934 1490 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 1491 $url = $gpr->add_url_params($url);
1c1f64a2 1492
2673c733 1493 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1494 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1495 $strparamobj = new stdClass();
1496 $strparamobj->itemname = $element['object']->grade_item->itemname;
1497 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1c1f64a2 1498
000c278c 1499 $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
8ae8bf8a 1500
cf72e2dd 1501 } else if ($element['object']->is_locked()) {
8ae8bf8a 1502 $type = 'unlock';
6cc3e350 1503 $tooltip = $strunlock;
1504
cf72e2dd 1505 // Change the icon and add a tooltip showing the date
1506 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
8ae8bf8a 1507 $type = 'locktime';
cf72e2dd 1508 $tooltip = get_string('locktimedate', 'grades',
1509 userdate($element['object']->get_locktime()));
6cc3e350 1510 }
1511
8ae8bf8a
PS
1512 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1513 $action = '';
1514 } else {
1515 $url->param('action', 'unlock');
c63923bd 1516 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
6cc3e350 1517 }
6cc3e350 1518
1519 } else {
8ae8bf8a
PS
1520 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1521 $action = '';
1522 } else {
1523 $url->param('action', 'lock');
c63923bd 1524 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
6cc3e350 1525 }
6cc3e350 1526 }
8ae8bf8a 1527
6cc3e350 1528 return $action;
1529 }
1530
1531 /**
1532 * Return calculation icon for given element
cf72e2dd 1533 *
1534 * @param array $element An array representing an element in the grade_tree
1535 * @param object $gpr A grade_plugin_return object
1536 *
6cc3e350 1537 * @return string
1538 */
d24832f9 1539 public function get_calculation_icon($element, $gpr) {
666e8458 1540 global $CFG, $OUTPUT;
6cc3e350 1541 if (!has_capability('moodle/grade:manage', $this->context)) {
1542 return '';
1543 }
1544
6cc3e350 1545 $type = $element['type'];
1546 $object = $element['object'];
1547
1548 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
345674ca 1549 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1550 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
6cc3e350 1551
cf72e2dd 1552 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1553 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1554
6cc3e350 1555 // show calculation icon only when calculation possible
cf72e2dd 1556 if (!$object->is_external_item() and ($is_scale or $is_value)) {
6cc3e350 1557 if ($object->is_calculated()) {
666e8458 1558 $icon = 't/calc';
6cc3e350 1559 } else {
666e8458 1560 $icon = 't/calc_off';
6cc3e350 1561 }
cf72e2dd 1562
a6855934 1563 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
8ae8bf8a 1564 $url = $gpr->add_url_params($url);
c63923bd 1565 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
6cc3e350 1566 }
1567 }
1568
1c1f64a2 1569 return '';
6cc3e350 1570 }
1571}
1572
1573/**
1574 * Flat structure similar to grade tree.
cf72e2dd 1575 *
1576 * @uses grade_structure
a153c9f2 1577 * @package core_grades
cf72e2dd 1578 * @copyright 2009 Nicolas Connault
1579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6cc3e350 1580 */
1581class grade_seq extends grade_structure {
1582
6cc3e350 1583 /**
1584 * 1D array of elements
1585 */
d24832f9 1586 public $elements;
e98871a2 1587
1588 /**
1589 * Constructor, retrieves and stores array of all grade_category and grade_item
1590 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1591 *
1592 * @param int $courseid The course id
1593 * @param bool $category_grade_last category grade item is the last child
1594 * @param bool $nooutcomes Whether or not outcomes should be included
e98871a2 1595 */
d24832f9 1596 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
e98871a2 1597 global $USER, $CFG;
1598
1599 $this->courseid = $courseid;
e98871a2 1600 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1601
1602 // get course grade tree
1603 $top_element = grade_category::fetch_course_tree($courseid, true);
1604
6391ebe7 1605 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1606
1607 foreach ($this->elements as $key=>$unused) {
b89a70ce 1608 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
6391ebe7 1609 }
e98871a2 1610 }
1611
1612 /**
1613 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 1614 *
1615 * @param array &$element The seed of the recursion
1616 * @param bool $category_grade_last category grade item is the last child
1617 * @param bool $nooutcomes Whether or not outcomes should be included
1618 *
1619 * @return array
e98871a2 1620 */
d24832f9 1621 public function flatten(&$element, $category_grade_last, $nooutcomes) {
e98871a2 1622 if (empty($element['children'])) {
1623 return array();
1624 }
1625 $children = array();
1626
1627 foreach ($element['children'] as $sortorder=>$unused) {
cf72e2dd 1628 if ($nooutcomes and $element['type'] != 'category' and
1629 $element['children'][$sortorder]['object']->is_outcome_item()) {
e98871a2 1630 continue;
1631 }
1632 $children[] = $element['children'][$sortorder];
1633 }
1634 unset($element['children']);
1635
1636 if ($category_grade_last and count($children) > 1) {
1637 $cat_item = array_shift($children);
1638 array_push($children, $cat_item);
1639 }
1640
1641 $result = array();
1642 foreach ($children as $child) {
e0724506 1643 if ($child['type'] == 'category') {
6391ebe7 1644 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
e98871a2 1645 } else {
1646 $child['eid'] = 'i'.$child['object']->id;
6391ebe7 1647 $result[$child['object']->id] = $child;
e98871a2 1648 }
1649 }
1650
1651 return $result;
1652 }
1653
1654 /**
1655 * Parses the array in search of a given eid and returns a element object with
1656 * information about the element it has found.
cf72e2dd 1657 *
1658 * @param int $eid Gradetree Element ID
1659 *
e98871a2 1660 * @return object element
1661 */
d24832f9 1662 public function locate_element($eid) {
e98871a2 1663 // it is a grade - construct a new object
1664 if (strpos($eid, 'n') === 0) {
1665 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1666 return null;
1667 }
1668
1669 $itemid = $matches[1];
1670 $userid = $matches[2];
1671
1672 //extra security check - the grade item must be in this tree
1673 if (!$item_el = $this->locate_element('i'.$itemid)) {
1674 return null;
1675 }
1676
1677 // $gradea->id may be null - means does not exist yet
1678 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1679
1680 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1681 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1682
1683 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 1684 $id = (int) substr($eid, 1);
e98871a2 1685 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1686 return null;
1687 }
1688 //extra security check - the grade item must be in this tree
1689 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1690 return null;
1691 }
1692 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1693 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1694 }
1695
1696 // it is a category or item
6391ebe7 1697 foreach ($this->elements as $element) {
6cc3e350 1698 if ($element['eid'] == $eid) {
1699 return $element;
1700 }
e98871a2 1701 }
6cc3e350 1702
1703 return null;
e98871a2 1704 }
e98871a2 1705}
1706
7a6b7acf 1707/**
1708 * This class represents a complete tree of categories, grade_items and final grades,
1709 * organises as an array primarily, but which can also be converted to other formats.
1710 * It has simple method calls with complex implementations, allowing for easy insertion,
1711 * deletion and moving of items and categories within the tree.
cf72e2dd 1712 *
1713 * @uses grade_structure
a153c9f2 1714 * @package core_grades
cf72e2dd 1715 * @copyright 2009 Nicolas Connault
1716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7a6b7acf 1717 */
6cc3e350 1718class grade_tree extends grade_structure {
7a6b7acf 1719
1720 /**
1721 * The basic representation of the tree as a hierarchical, 3-tiered array.
1722 * @var object $top_element
1723 */
d24832f9 1724 public $top_element;
7a6b7acf 1725
7a6b7acf 1726 /**
1727 * 2D array of grade items and categories
cf72e2dd 1728 * @var array $levels
7a6b7acf 1729 */
d24832f9 1730 public $levels;
7a6b7acf 1731
b89a70ce 1732 /**
1733 * Grade items
cf72e2dd 1734 * @var array $items
b89a70ce 1735 */
d24832f9 1736 public $items;
b89a70ce 1737
7a6b7acf 1738 /**
1739 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 1740 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1741 *
1742 * @param int $courseid The Course ID
1743 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1744 * @param bool $category_grade_last category grade item is the last child
4faf5f99 1745 * @param array $collapsed array of collapsed categories
cf72e2dd 1746 * @param bool $nooutcomes Whether or not outcomes should be included
7a6b7acf 1747 */
cf72e2dd 1748 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1749 $collapsed=null, $nooutcomes=false) {
73ca5f01 1750 global $USER, $CFG, $COURSE, $DB;
7a6b7acf 1751
1752 $this->courseid = $courseid;
7a6b7acf 1753 $this->levels = array();
2cc773f5 1754 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
7a6b7acf 1755
73ca5f01 1756 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1757 $course = $COURSE;
1758 } else {
1759 $course = $DB->get_record('course', array('id' => $this->courseid));
1760 }
1761 $this->modinfo = get_fast_modinfo($course);
1762
7a6b7acf 1763 // get course grade tree
1764 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1765
4faf5f99 1766 // collapse the categories if requested
1767 if (!empty($collapsed)) {
1768 grade_tree::category_collapse($this->top_element, $collapsed);
1769 }
1770
aea4df41 1771 // no otucomes if requested
1772 if (!empty($nooutcomes)) {
1773 grade_tree::no_outcomes($this->top_element);
1774 }
1775
4faf5f99 1776 // move category item to last position in category
7a6b7acf 1777 if ($category_grade_last) {
1778 grade_tree::category_grade_last($this->top_element);
1779 }
1780
1781 if ($fillers) {
1782 // inject fake categories == fillers
1783 grade_tree::inject_fillers($this->top_element, 0);
1784 // add colspans to categories and fillers
1785 grade_tree::inject_colspans($this->top_element);
1786 }
1787
1788 grade_tree::fill_levels($this->levels, $this->top_element, 0);
d297269d 1789
7a6b7acf 1790 }
1791
4faf5f99 1792 /**
1793 * Static recursive helper - removes items from collapsed categories
cf72e2dd 1794 *
1795 * @param array &$element The seed of the recursion
4faf5f99 1796 * @param array $collapsed array of collapsed categories
cf72e2dd 1797 *
4faf5f99 1798 * @return void
1799 */
d24832f9 1800 public function category_collapse(&$element, $collapsed) {
4faf5f99 1801 if ($element['type'] != 'category') {
1802 return;
1803 }
1804 if (empty($element['children']) or count($element['children']) < 2) {
1805 return;
1806 }
1807
384960dd 1808 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 1809 $category_item = reset($element['children']); //keep only category item
1810 $element['children'] = array(key($element['children'])=>$category_item);
1811
1812 } else {
384960dd 1813 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1814 reset($element['children']);
1815 $first_key = key($element['children']);
1816 unset($element['children'][$first_key]);
1817 }
1818 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 1819 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1820 }
1821 }
1822 }
7a6b7acf 1823
aea4df41 1824 /**
1825 * Static recursive helper - removes all outcomes
cf72e2dd 1826 *
1827 * @param array &$element The seed of the recursion
1828 *
aea4df41 1829 * @return void
1830 */
d24832f9 1831 public function no_outcomes(&$element) {
aea4df41 1832 if ($element['type'] != 'category') {
1833 return;
1834 }
1835 foreach ($element['children'] as $sortorder=>$child) {
1836 if ($element['children'][$sortorder]['type'] == 'item'
1837 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1838 unset($element['children'][$sortorder]);
1839
d4795a07 1840 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 1841 grade_tree::no_outcomes($element['children'][$sortorder]);
1842 }
1843 }
1844 }
1845
7a6b7acf 1846 /**
1847 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 1848 *
1849 * @param array &$element The seed of the recursion
1850 *
7a6b7acf 1851 * @return void
1852 */
d24832f9 1853 public function category_grade_last(&$element) {
7a6b7acf 1854 if (empty($element['children'])) {
1855 return;
1856 }
1857 if (count($element['children']) < 2) {
1858 return;
1859 }
3e0e2436 1860 $first_item = reset($element['children']);
4a3dfd9a 1861 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 1862 // the category item might have been already removed
1863 $order = key($element['children']);
1864 unset($element['children'][$order]);
1865 $element['children'][$order] =& $first_item;
1866 }
206f9953 1867 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 1868 grade_tree::category_grade_last($element['children'][$sortorder]);
1869 }
1870 }
1871
1872 /**
1873 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
cf72e2dd 1874 *
1875 * @param array &$levels The levels of the grade tree through which to recurse
1876 * @param array &$element The seed of the recursion
1877 * @param int $depth How deep are we?
7a6b7acf 1878 * @return void
1879 */
d24832f9 1880 public function fill_levels(&$levels, &$element, $depth) {
7a6b7acf 1881 if (!array_key_exists($depth, $levels)) {
1882 $levels[$depth] = array();
1883 }
1884
1885 // prepare unique identifier
1886 if ($element['type'] == 'category') {
1887 $element['eid'] = 'c'.$element['object']->id;
1888 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1889 $element['eid'] = 'i'.$element['object']->id;
b89a70ce 1890 $this->items[$element['object']->id] =& $element['object'];
7a6b7acf 1891 }
1892
1893 $levels[$depth][] =& $element;
1894 $depth++;
1895 if (empty($element['children'])) {
1896 return;
1897 }
1898 $prev = 0;
1899 foreach ($element['children'] as $sortorder=>$child) {
1900 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1901 $element['children'][$sortorder]['prev'] = $prev;
1902 $element['children'][$sortorder]['next'] = 0;
1903 if ($prev) {
1904 $element['children'][$prev]['next'] = $sortorder;
1905 }
1906 $prev = $sortorder;
1907 }
1908 }
1909
1910 /**
1911 * Static recursive helper - makes full tree (all leafes are at the same level)
cf72e2dd 1912 *
1913 * @param array &$element The seed of the recursion
1914 * @param int $depth How deep are we?
1915 *
1916 * @return int
7a6b7acf 1917 */
d24832f9 1918 public function inject_fillers(&$element, $depth) {
7a6b7acf 1919 $depth++;
1920
1921 if (empty($element['children'])) {
1922 return $depth;
1923 }
1924 $chdepths = array();
1925 $chids = array_keys($element['children']);
1926 $last_child = end($chids);
1927 $first_child = reset($chids);
1928
1929 foreach ($chids as $chid) {
1930 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1931 }
1932 arsort($chdepths);
1933
1934 $maxdepth = reset($chdepths);
1935 foreach ($chdepths as $chid=>$chd) {
1936 if ($chd == $maxdepth) {
1937 continue;
1938 }
1939 for ($i=0; $i < $maxdepth-$chd; $i++) {
1940 if ($chid == $first_child) {
1941 $type = 'fillerfirst';
1942 } else if ($chid == $last_child) {
1943 $type = 'fillerlast';
1944 } else {
1945 $type = 'filler';
1946 }
1947 $oldchild =& $element['children'][$chid];
cf72e2dd 1948 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
1949 'eid'=>'', 'depth'=>$element['object']->depth,
1950 'children'=>array($oldchild));
7a6b7acf 1951 }
1952 }
1953
1954 return $maxdepth;
1955 }
1956
1957 /**
1958 * Static recursive helper - add colspan information into categories
cf72e2dd 1959 *
1960 * @param array &$element The seed of the recursion
1961 *
1962 * @return int
7a6b7acf 1963 */
d24832f9 1964 public function inject_colspans(&$element) {
7a6b7acf 1965 if (empty($element['children'])) {
1966 return 1;
1967 }
1968 $count = 0;
1969 foreach ($element['children'] as $key=>$child) {
1970 $count += grade_tree::inject_colspans($element['children'][$key]);
1971 }
1972 $element['colspan'] = $count;
1973 return $count;
1974 }
1975
1976 /**
1977 * Parses the array in search of a given eid and returns a element object with
1978 * information about the element it has found.
cf72e2dd 1979 * @param int $eid Gradetree Element ID
7a6b7acf 1980 * @return object element
1981 */
d24832f9 1982 public function locate_element($eid) {
d3c3da1b 1983 // it is a grade - construct a new object
1984 if (strpos($eid, 'n') === 0) {
1985 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1986 return null;
1987 }
1988
1989 $itemid = $matches[1];
1990 $userid = $matches[2];
1991
1992 //extra security check - the grade item must be in this tree
1993 if (!$item_el = $this->locate_element('i'.$itemid)) {
1994 return null;
1995 }
1996
1997 // $gradea->id may be null - means does not exist yet
1998 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1999
2000 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2001 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2002
2003 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 2004 $id = (int) substr($eid, 1);
7a6b7acf 2005 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2006 return null;
2007 }
2008 //extra security check - the grade item must be in this tree
2009 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2010 return null;
2011 }
2012 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2013 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2014 }
2015
2016 // it is a category or item
2017 foreach ($this->levels as $row) {
2018 foreach ($row as $element) {
2019 if ($element['type'] == 'filler') {
2020 continue;
2021 }
2022 if ($element['eid'] == $eid) {
2023 return $element;
2024 }
2025 }
2026 }
2027
2028 return null;
2029 }
d24832f9 2030
b244b9b7 2031 /**
2032 * Returns a well-formed XML representation of the grade-tree using recursion.
cf72e2dd 2033 *
2034 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2035 * @param string $tabs The control character to use for tabs
2036 *
b244b9b7 2037 * @return string $xml
2038 */
cf72e2dd 2039 public function exporttoxml($root=null, $tabs="\t") {
b244b9b7 2040 $xml = null;
2041 $first = false;
2042 if (is_null($root)) {
2043 $root = $this->top_element;
2044 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2045 $xml .= "<gradetree>\n";
2046 $first = true;
2047 }
d24832f9 2048
b244b9b7 2049 $type = 'undefined';
2050 if (strpos($root['object']->table, 'grade_categories') !== false) {
2051 $type = 'category';
cf72e2dd 2052 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2053 $type = 'item';
cf72e2dd 2054 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2055 $type = 'outcome';
2056 }
d24832f9 2057
b244b9b7 2058 $xml .= "$tabs<element type=\"$type\">\n";
2059 foreach ($root['object'] as $var => $value) {
2060 if (!is_object($value) && !is_array($value) && !empty($value)) {
2061 $xml .= "$tabs\t<$var>$value</$var>\n";
2062 }
2063 }
2064
2065 if (!empty($root['children'])) {
2066 $xml .= "$tabs\t<children>\n";
2067 foreach ($root['children'] as $sortorder => $child) {
2068 $xml .= $this->exportToXML($child, $tabs."\t\t");
2069 }
2070 $xml .= "$tabs\t</children>\n";
2071 }
d24832f9 2072
b244b9b7 2073 $xml .= "$tabs</element>\n";
2074
2075 if ($first) {
2076 $xml .= "</gradetree>";
2077 }
d24832f9 2078
b244b9b7 2079 return $xml;
2080 }
d24832f9 2081
b244b9b7 2082 /**
2083 * Returns a JSON representation of the grade-tree using recursion.
cf72e2dd 2084 *
b244b9b7 2085 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2086 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
cf72e2dd 2087 *
2088 * @return string
b244b9b7 2089 */
cf72e2dd 2090 public function exporttojson($root=null, $tabs="\t") {
b244b9b7 2091 $json = null;
2092 $first = false;
2093 if (is_null($root)) {
2094 $root = $this->top_element;
2095 $first = true;
2096 }
d24832f9 2097
b244b9b7 2098 $name = '';
2099
2100
2101 if (strpos($root['object']->table, 'grade_categories') !== false) {
2102 $name = $root['object']->fullname;
2103 if ($name == '?') {
d24832f9 2104 $name = $root['object']->get_name();
b244b9b7 2105 }
cf72e2dd 2106 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2107 $name = $root['object']->itemname;
cf72e2dd 2108 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2109 $name = $root['object']->itemname;
2110 }
d24832f9 2111
b244b9b7 2112 $json .= "$tabs {\n";
2113 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2114 $json .= "$tabs\t \"name\": \"$name\",\n";
2115
2116 foreach ($root['object'] as $var => $value) {
2117 if (!is_object($value) && !is_array($value) && !empty($value)) {
2118 $json .= "$tabs\t \"$var\": \"$value\",\n";
2119 }
2120 }
d24832f9 2121
b244b9b7 2122 $json = substr($json, 0, strrpos($json, ','));
d24832f9 2123
b244b9b7 2124 if (!empty($root['children'])) {
2125 $json .= ",\n$tabs\t\"children\": [\n";
2126 foreach ($root['children'] as $sortorder => $child) {
2127 $json .= $this->exportToJSON($child, $tabs."\t\t");
2128 }
2129 $json = substr($json, 0, strrpos($json, ','));
2130 $json .= "\n$tabs\t]\n";
d24832f9 2131 }
b244b9b7 2132
2133 if ($first) {
2134 $json .= "\n}";
2135 } else {
2136 $json .= "\n$tabs},\n";
2137 }
d24832f9 2138
b244b9b7 2139 return $json;
2140 }
d24832f9 2141
cf72e2dd 2142 /**
2143 * Returns the array of levels
2144 *
2145 * @return array
2146 */
d24832f9 2147 public function get_levels() {
2148 return $this->levels;
2149 }
2150
cf72e2dd 2151 /**
2152 * Returns the array of grade items
2153 *
2154 * @return array
2155 */
d24832f9 2156 public function get_items() {
2157 return $this->items;
2158 }
2159
cf72e2dd 2160 /**
2161 * Returns a specific Grade Item
2162 *
2163 * @param int $itemid The ID of the grade_item object
2164 *
2165 * @return grade_item
2166 */
d24832f9 2167 public function get_item($itemid) {
2168 if (array_key_exists($itemid, $this->items)) {
2169 return $this->items[$itemid];
2170 } else {
2171 return false;
2172 }
2173 }
7a6b7acf 2174}
eef00ade 2175
2176/**
2177 * Local shortcut function for creating an edit/delete button for a grade_* object.
4d27bc79 2178 * @param string $type 'edit' or 'delete'
eef00ade 2179 * @param int $courseid The Course ID
2180 * @param grade_* $object The grade_* object
2181 * @return string html
2182 */
2183function grade_button($type, $courseid, $object) {
2184 global $CFG, $OUTPUT;
2185 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2186 $objectidstring = $matches[1] . 'id';
2187 } else {
2188 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2189 }
2190
2191 $strdelete = get_string('delete');
2192 $stredit = get_string('edit');
2193
eef00ade 2194 if ($type == 'delete') {
8ae8bf8a 2195 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
eef00ade 2196 } else if ($type == 'edit') {
8ae8bf8a 2197 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
eef00ade 2198 }
2199
c63923bd 2200 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
eef00ade 2201
2202}
4d5059d4
SH
2203
2204/**
2205 * This method adds settings to the settings block for the grade system and its
2206 * plugins
2207 *
2208 * @global moodle_page $PAGE
2209 */
2210function grade_extend_settings($plugininfo, $courseid) {
2211 global $PAGE;
2212
2213 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2214
2215 $strings = array_shift($plugininfo);
2216
2217 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2218 foreach ($reports as $report) {
2219 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2220 }
2221 }
2222
2223 if ($imports = grade_helper::get_plugins_import($courseid)) {
2224 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2225 foreach ($imports as $import) {
2226 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
2227 }
2228 }
2229
2230 if ($exports = grade_helper::get_plugins_export($courseid)) {
2231 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2232 foreach ($exports as $export) {
2233 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
2234 }
2235 }
2236
2237 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2238 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2239 }
2240
2241 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2242 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2243 foreach ($preferences as $preference) {
2244 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2245 }
2246 }
2247
2248 if ($letters = grade_helper::get_info_letters($courseid)) {
2249 $letters = array_shift($letters);
2250 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2251 }
2252
2253 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2254 $outcomes = array_shift($outcomes);
2255 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2256 }
2257
2258 if ($scales = grade_helper::get_info_scales($courseid)) {
2259 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2260 }
2261
2262 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2263 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2264 foreach ($categories as $category) {
2265 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2266 }
2267 }
2268
2269 if ($gradenode->contains_active_node()) {
2270 // If the gradenode is active include the settings base node (gradeadministration) in
2271 // the navbar, typcially this is ignored.
2272 $PAGE->navbar->includesettingsbase = true;
2273
2274 // If we can get the course admin node make sure it is closed by default
2275 // as in this case the gradenode will be opened
2276 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2277 $coursenode->make_inactive();
2278 $coursenode->forceopen = false;
2279 }
2280 }
2281}
2282
2283/**
2284 * Grade helper class
2285 *
2286 * This class provides several helpful functions that work irrespective of any
2287 * current state.
2288 *
2289 * @copyright 2010 Sam Hemelryk
2290 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2291 */
2292abstract class grade_helper {
2293 /**
2294 * Cached manage settings info {@see get_info_settings}
2295 * @var grade_plugin_info|false
2296 */
2297 protected static $managesetting = null;
2298 /**
2299 * Cached grade report plugins {@see get_plugins_reports}
2300 * @var array|false
2301 */
2302 protected static $gradereports = null;
2303 /**
2304 * Cached grade report plugins preferences {@see get_info_scales}
2305 * @var array|false
2306 */
2307 protected static $gradereportpreferences = null;
2308 /**
2309 * Cached scale info {@see get_info_scales}
2310 * @var grade_plugin_info|false
2311 */
2312 protected static $scaleinfo = null;
2313 /**
2314 * Cached outcome info {@see get_info_outcomes}
2315 * @var grade_plugin_info|false
2316 */
2317 protected static $outcomeinfo = null;
2318 /**
2319 * Cached info on edit structure {@see get_info_edit_structure}
2320 * @var array|false
2321 */
2322 protected static $edittree = null;
2323 /**
2324 * Cached leftter info {@see get_info_letters}
2325 * @var grade_plugin_info|false
2326 */
2327 protected static $letterinfo = null;
2328 /**
2329 * Cached grade import plugins {@see get_plugins_import}
2330 * @var array|false
2331 */
2332 protected static $importplugins = null;
2333 /**
2334 * Cached grade export plugins {@see get_plugins_export}
2335 * @var array|false
2336 */
2337 protected static $exportplugins = null;
2338 /**
2339 * Cached grade plugin strings
2340 * @var array
2341 */
2342 protected static $pluginstrings = null;
2343
2344 /**
2345 * Gets strings commonly used by the describe plugins
2346 *
2347 * report => get_string('view'),
2348 * edittree => get_string('edittree', 'grades'),
2349 * scale => get_string('scales'),
2350 * outcome => get_string('outcomes', 'grades'),
2351 * letter => get_string('letters', 'grades'),
2352 * export => get_string('export', 'grades'),
2353 * import => get_string('import'),
2354 * preferences => get_string('mypreferences', 'grades'),
2355 * settings => get_string('settings')
2356 *
2357 * @return array
2358 */
2359 public static function get_plugin_strings() {
2360 if (self::$pluginstrings === null) {
2361 self::$pluginstrings = array(
2362 'report' => get_string('view'),
2363 'edittree' => get_string('edittree', 'grades'),
2364 'scale' => get_string('scales'),
2365 'outcome' => get_string('outcomes', 'grades'),
2366 'letter' => get_string('letters', 'grades'),
2367 'export' => get_string('export', 'grades'),
2368 'import' => get_string('import'),
2369 'preferences' => get_string('mypreferences', 'grades'),
2370 'settings' => get_string('settings')
2371 );
2372 }
2373 return self::$pluginstrings;
2374 }
2375 /**
2376 * Get grade_plugin_info object for managing settings if the user can
2377 *
2378 * @param int $courseid
2379 * @return grade_plugin_info
2380 */
2381 public static function get_info_manage_settings($courseid) {
2382 if (self::$managesetting !== null) {
2383 return self::$managesetting;
2384 }
2385 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2386 if (has_capability('moodle/course:update', $context)) {
2387 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2388 } else {
2389 self::$managesetting = false;
2390 }
2391 return self::$managesetting;
2392 }
2393 /**
2394 * Returns an array of plugin reports as grade_plugin_info objects
2395 *
2396 * @param int $courseid
2397 * @return array
2398 */
2399 public static function get_plugins_reports($courseid) {
f7fcf4cd 2400 global $SITE;
cf717dc2 2401
4d5059d4
SH
2402 if (self::$gradereports !== null) {
2403 return self::$gradereports;
2404 }
2405 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2406 $gradereports = array();
2407 $gradepreferences = array();
2408 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
f7fcf4cd
AD
2409 //some reports make no sense if we're not within a course
2410 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2411 continue;
2412 }
2413
4d5059d4
SH
2414 // Remove ones we can't see
2415 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2416 continue;
2417 }
2418
b5e7b2bf 2419 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
4d5059d4
SH
2420 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2421 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2422
2423 // Add link to preferences tab if such a page exists
2424 if (file_exists($plugindir.'/preferences.php')) {
2425 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2426 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2427 }
2428 }
2429 if (count($gradereports) == 0) {
2430 $gradereports = false;
2431 $gradepreferences = false;
2432 } else if (count($gradepreferences) == 0) {
2433 $gradepreferences = false;
2434 asort($gradereports);
2435 } else {
2436 asort($gradereports);
2437 asort($gradepreferences);
2438 }
2439 self::$gradereports = $gradereports;
2440 self::$gradereportpreferences = $gradepreferences;
2441 return self::$gradereports;
2442 }
2443 /**
2444 * Returns an array of grade plugin report preferences for plugin reports that
2445 * support preferences
2446 * @param int $courseid
2447 * @return array
2448 */
2449 public static function get_plugins_report_preferences($courseid) {
2450 if (self::$gradereportpreferences !== null) {
2451 return self::$gradereportpreferences;
2452 }
2453 self::get_plugins_reports($courseid);
2454 return self::$gradereportpreferences;
2455 }
2456 /**
2457 * Get information on scales
2458 * @param int $courseid
2459 * @return grade_plugin_info
2460 */
2461 public static function get_info_scales($courseid) {
2462 if (self::$scaleinfo !== null) {
2463 return self::$scaleinfo;
2464 }
2465 if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
2466 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2467 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2468 } else {
2469 self::$scaleinfo = false;
2470 }
2471 return self::$scaleinfo;
2472 }
2473 /**
2474 * Get information on outcomes
2475 * @param int $courseid
2476 * @return grade_plugin_info
2477 */
2478 public static function get_info_outcomes($courseid) {
f7fcf4cd 2479 global $CFG, $SITE;
4d5059d4
SH
2480
2481 if (self::$outcomeinfo !== null) {
2482 return self::$outcomeinfo;
2483 }
2484 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2485 $canmanage = has_capability('moodle/grade:manage', $context);
2486 $canupdate = has_capability('moodle/course:update', $context);
2487 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2488 $outcomes = array();
2489 if ($canupdate) {
f7fcf4cd
AD
2490 if ($courseid!=$SITE->id) {
2491 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2492 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2493 }
4d5059d4
SH
2494 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2495 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
c46aeeab
DC
2496 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2497 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
4d5059d4 2498 } else {
f7fcf4cd
AD
2499 if ($courseid!=$SITE->id) {
2500 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2501 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2502 }
4d5059d4
SH
2503 }
2504 self::$outcomeinfo = $outcomes;
2505 } else {
2506 self::$outcomeinfo = false;
2507 }
2508 return self::$outcomeinfo;
2509 }
2510 /**
2511 * Get information on editing structures
2512 * @param int $courseid
2513 * @return array
2514 */
2515 public static function get_info_edit_structure($courseid) {
2516 if (self::$edittree !== null) {
2517 return self::$edittree;
2518 }
2519 if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
2520 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2521 self::$edittree = array(
2522 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2523 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2524 );
2525 } else {
2526 self::$edittree = false;
2527 }
2528 return self::$edittree;
2529 }
2530 /**
2531 * Get information on letters
2532 * @param int $courseid
4d27bc79 2533 * @return array
4d5059d4
SH
2534 */
2535 public static function get_info_letters($courseid) {
2536 if (self::$letterinfo !== null) {
2537 return self::$letterinfo;
2538 }
2539 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2540 $canmanage = has_capability('moodle/grade:manage', $context);
2541 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2542 if ($canmanage || $canmanageletters) {
2543 self::$letterinfo = array(
54caa598
AD
2544 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2545 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
4d5059d4
SH
2546 );
2547 } else {
2548 self::$letterinfo = false;
2549 }
2550 return self::$letterinfo;
2551 }
2552 /**
2553 * Get information import plugins
2554 * @param int $courseid
2555 * @return array
2556 */
2557 public static function get_plugins_import($courseid) {
2558 global $CFG;
2559
2560 if (self::$importplugins !== null) {
2561 return self::$importplugins;
2562 }
2563 $importplugins = array();
2564 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2565
2566 if (has_capability('moodle/grade:import', $context)) {
2567 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2568 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2569 continue;
2570 }
b5e7b2bf 2571 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
4d5059d4
SH
2572 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2573 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2574 }
2575
2576
2577 if ($CFG->gradepublishing) {
2578 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2579 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2580 }
2581 }
2582
2583 if (count($importplugins) > 0) {
2584 asort($importplugins);
2585 self::$importplugins = $importplugins;
2586 } else {
2587 self::$importplugins = false;
2588 }
2589 return self::$importplugins;
2590 }
2591 /**
2592 * Get information export plugins
2593 * @param int $courseid
2594 * @return array
2595 */
2596 public static function get_plugins_export($courseid) {
2597 global $CFG;
2598
2599 if (self::$exportplugins !== null) {
2600 return self::$exportplugins;
2601 }
2602 $context = get_context_instance(CONTEXT_COURSE, $courseid);
2603 $exportplugins = array();
2604 if (has_capability('moodle/grade:export', $context)) {
2605 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2606 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2607 continue;
2608 }
b5e7b2bf 2609 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
4d5059d4
SH
2610 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2611 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2612 }
2613
2614 if ($CFG->gradepublishing) {
2615 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2616 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2617 }
2618 }
2619 if (count($exportplugins) > 0) {
2620 asort($exportplugins);
2621 self::$exportplugins = $exportplugins;
2622 } else {
2623 self::$exportplugins = false;
2624 }
2625 return self::$exportplugins;
2626 }
d4dcfc6b 2627}