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