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