MDL-36559 usability: Gradebook CSS styling for new icons
[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');
0cddd851 1185 return '<img src="'.$OUTPUT->pix_url('i/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');
0cddd851 1194 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" 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
a377cc53 1542 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
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
0cddd851
FM
1576 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1577 array('class' => 'action-icon'));
8ae8bf8a 1578
cf72e2dd 1579 } else if ($element['object']->is_locked()) {
8ae8bf8a 1580 $type = 'unlock';
6cc3e350 1581 $tooltip = $strunlock;
1582
cf72e2dd 1583 // Change the icon and add a tooltip showing the date
1584 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
8ae8bf8a 1585 $type = 'locktime';
cf72e2dd 1586 $tooltip = get_string('locktimedate', 'grades',
1587 userdate($element['object']->get_locktime()));
6cc3e350 1588 }
1589
8ae8bf8a
PS
1590 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1591 $action = '';
1592 } else {
1593 $url->param('action', 'unlock');
c63923bd 1594 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
6cc3e350 1595 }
6cc3e350 1596
1597 } else {
8ae8bf8a
PS
1598 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1599 $action = '';
1600 } else {
1601 $url->param('action', 'lock');
c63923bd 1602 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
6cc3e350 1603 }
6cc3e350 1604 }
8ae8bf8a 1605
6cc3e350 1606 return $action;
1607 }
1608
1609 /**
1610 * Return calculation icon for given element
cf72e2dd 1611 *
1612 * @param array $element An array representing an element in the grade_tree
1613 * @param object $gpr A grade_plugin_return object
1614 *
6cc3e350 1615 * @return string
1616 */
d24832f9 1617 public function get_calculation_icon($element, $gpr) {
666e8458 1618 global $CFG, $OUTPUT;
6cc3e350 1619 if (!has_capability('moodle/grade:manage', $this->context)) {
1620 return '';
1621 }
1622
6cc3e350 1623 $type = $element['type'];
1624 $object = $element['object'];
1625
1626 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
345674ca 1627 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1628 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
6cc3e350 1629
cf72e2dd 1630 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1631 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1632
6cc3e350 1633 // show calculation icon only when calculation possible
cf72e2dd 1634 if (!$object->is_external_item() and ($is_scale or $is_value)) {
6cc3e350 1635 if ($object->is_calculated()) {
666e8458 1636 $icon = 't/calc';
6cc3e350 1637 } else {
666e8458 1638 $icon = 't/calc_off';
6cc3e350 1639 }
cf72e2dd 1640
a6855934 1641 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
8ae8bf8a 1642 $url = $gpr->add_url_params($url);
0cddd851 1643 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
6cc3e350 1644 }
1645 }
1646
1c1f64a2 1647 return '';
6cc3e350 1648 }
1649}
1650
1651/**
1652 * Flat structure similar to grade tree.
cf72e2dd 1653 *
1654 * @uses grade_structure
a153c9f2 1655 * @package core_grades
cf72e2dd 1656 * @copyright 2009 Nicolas Connault
1657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6cc3e350 1658 */
1659class grade_seq extends grade_structure {
1660
6cc3e350 1661 /**
1662 * 1D array of elements
1663 */
d24832f9 1664 public $elements;
e98871a2 1665
1666 /**
1667 * Constructor, retrieves and stores array of all grade_category and grade_item
1668 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1669 *
1670 * @param int $courseid The course id
1671 * @param bool $category_grade_last category grade item is the last child
1672 * @param bool $nooutcomes Whether or not outcomes should be included
e98871a2 1673 */
d24832f9 1674 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
e98871a2 1675 global $USER, $CFG;
1676
1677 $this->courseid = $courseid;
d4060472 1678 $this->context = context_course::instance($courseid);
e98871a2 1679
1680 // get course grade tree
1681 $top_element = grade_category::fetch_course_tree($courseid, true);
1682
6391ebe7 1683 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1684
1685 foreach ($this->elements as $key=>$unused) {
b89a70ce 1686 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
6391ebe7 1687 }
e98871a2 1688 }
1689
1690 /**
1691 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 1692 *
1693 * @param array &$element The seed of the recursion
1694 * @param bool $category_grade_last category grade item is the last child
1695 * @param bool $nooutcomes Whether or not outcomes should be included
1696 *
1697 * @return array
e98871a2 1698 */
d24832f9 1699 public function flatten(&$element, $category_grade_last, $nooutcomes) {
e98871a2 1700 if (empty($element['children'])) {
1701 return array();
1702 }
1703 $children = array();
1704
1705 foreach ($element['children'] as $sortorder=>$unused) {
cf72e2dd 1706 if ($nooutcomes and $element['type'] != 'category' and
1707 $element['children'][$sortorder]['object']->is_outcome_item()) {
e98871a2 1708 continue;
1709 }
1710 $children[] = $element['children'][$sortorder];
1711 }
1712 unset($element['children']);
1713
1714 if ($category_grade_last and count($children) > 1) {
1715 $cat_item = array_shift($children);
1716 array_push($children, $cat_item);
1717 }
1718
1719 $result = array();
1720 foreach ($children as $child) {
e0724506 1721 if ($child['type'] == 'category') {
6391ebe7 1722 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
e98871a2 1723 } else {
1724 $child['eid'] = 'i'.$child['object']->id;
6391ebe7 1725 $result[$child['object']->id] = $child;
e98871a2 1726 }
1727 }
1728
1729 return $result;
1730 }
1731
1732 /**
1733 * Parses the array in search of a given eid and returns a element object with
1734 * information about the element it has found.
cf72e2dd 1735 *
1736 * @param int $eid Gradetree Element ID
1737 *
e98871a2 1738 * @return object element
1739 */
d24832f9 1740 public function locate_element($eid) {
e98871a2 1741 // it is a grade - construct a new object
1742 if (strpos($eid, 'n') === 0) {
1743 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1744 return null;
1745 }
1746
1747 $itemid = $matches[1];
1748 $userid = $matches[2];
1749
1750 //extra security check - the grade item must be in this tree
1751 if (!$item_el = $this->locate_element('i'.$itemid)) {
1752 return null;
1753 }
1754
1755 // $gradea->id may be null - means does not exist yet
1756 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1757
1758 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1759 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1760
1761 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 1762 $id = (int) substr($eid, 1);
e98871a2 1763 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1764 return null;
1765 }
1766 //extra security check - the grade item must be in this tree
1767 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1768 return null;
1769 }
1770 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1771 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1772 }
1773
1774 // it is a category or item
6391ebe7 1775 foreach ($this->elements as $element) {
6cc3e350 1776 if ($element['eid'] == $eid) {
1777 return $element;
1778 }
e98871a2 1779 }
6cc3e350 1780
1781 return null;
e98871a2 1782 }
e98871a2 1783}
1784
7a6b7acf 1785/**
1786 * This class represents a complete tree of categories, grade_items and final grades,
1787 * organises as an array primarily, but which can also be converted to other formats.
1788 * It has simple method calls with complex implementations, allowing for easy insertion,
1789 * deletion and moving of items and categories within the tree.
cf72e2dd 1790 *
1791 * @uses grade_structure
a153c9f2 1792 * @package core_grades
cf72e2dd 1793 * @copyright 2009 Nicolas Connault
1794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7a6b7acf 1795 */
6cc3e350 1796class grade_tree extends grade_structure {
7a6b7acf 1797
1798 /**
1799 * The basic representation of the tree as a hierarchical, 3-tiered array.
1800 * @var object $top_element
1801 */
d24832f9 1802 public $top_element;
7a6b7acf 1803
7a6b7acf 1804 /**
1805 * 2D array of grade items and categories
cf72e2dd 1806 * @var array $levels
7a6b7acf 1807 */
d24832f9 1808 public $levels;
7a6b7acf 1809
b89a70ce 1810 /**
1811 * Grade items
cf72e2dd 1812 * @var array $items
b89a70ce 1813 */
d24832f9 1814 public $items;
b89a70ce 1815
7a6b7acf 1816 /**
1817 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 1818 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1819 *
1820 * @param int $courseid The Course ID
1821 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1822 * @param bool $category_grade_last category grade item is the last child
4faf5f99 1823 * @param array $collapsed array of collapsed categories
cf72e2dd 1824 * @param bool $nooutcomes Whether or not outcomes should be included
7a6b7acf 1825 */
cf72e2dd 1826 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1827 $collapsed=null, $nooutcomes=false) {
73ca5f01 1828 global $USER, $CFG, $COURSE, $DB;
7a6b7acf 1829
1830 $this->courseid = $courseid;
7a6b7acf 1831 $this->levels = array();
d4060472 1832 $this->context = context_course::instance($courseid);
7a6b7acf 1833
73ca5f01 1834 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1835 $course = $COURSE;
1836 } else {
1837 $course = $DB->get_record('course', array('id' => $this->courseid));
1838 }
1839 $this->modinfo = get_fast_modinfo($course);
1840
7a6b7acf 1841 // get course grade tree
1842 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1843
4faf5f99 1844 // collapse the categories if requested
1845 if (!empty($collapsed)) {
1846 grade_tree::category_collapse($this->top_element, $collapsed);
1847 }
1848
aea4df41 1849 // no otucomes if requested
1850 if (!empty($nooutcomes)) {
1851 grade_tree::no_outcomes($this->top_element);
1852 }
1853
4faf5f99 1854 // move category item to last position in category
7a6b7acf 1855 if ($category_grade_last) {
1856 grade_tree::category_grade_last($this->top_element);
1857 }
1858
1859 if ($fillers) {
1860 // inject fake categories == fillers
1861 grade_tree::inject_fillers($this->top_element, 0);
1862 // add colspans to categories and fillers
1863 grade_tree::inject_colspans($this->top_element);
1864 }
1865
1866 grade_tree::fill_levels($this->levels, $this->top_element, 0);
d297269d 1867
7a6b7acf 1868 }
1869
4faf5f99 1870 /**
1871 * Static recursive helper - removes items from collapsed categories
cf72e2dd 1872 *
1873 * @param array &$element The seed of the recursion
4faf5f99 1874 * @param array $collapsed array of collapsed categories
cf72e2dd 1875 *
4faf5f99 1876 * @return void
1877 */
d24832f9 1878 public function category_collapse(&$element, $collapsed) {
4faf5f99 1879 if ($element['type'] != 'category') {
1880 return;
1881 }
1882 if (empty($element['children']) or count($element['children']) < 2) {
1883 return;
1884 }
1885
384960dd 1886 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 1887 $category_item = reset($element['children']); //keep only category item
1888 $element['children'] = array(key($element['children'])=>$category_item);
1889
1890 } else {
384960dd 1891 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1892 reset($element['children']);
1893 $first_key = key($element['children']);
1894 unset($element['children'][$first_key]);
1895 }
1896 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 1897 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1898 }
1899 }
1900 }
7a6b7acf 1901
aea4df41 1902 /**
1903 * Static recursive helper - removes all outcomes
cf72e2dd 1904 *
1905 * @param array &$element The seed of the recursion
1906 *
aea4df41 1907 * @return void
1908 */
d24832f9 1909 public function no_outcomes(&$element) {
aea4df41 1910 if ($element['type'] != 'category') {
1911 return;
1912 }
1913 foreach ($element['children'] as $sortorder=>$child) {
1914 if ($element['children'][$sortorder]['type'] == 'item'
1915 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1916 unset($element['children'][$sortorder]);
1917
d4795a07 1918 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 1919 grade_tree::no_outcomes($element['children'][$sortorder]);
1920 }
1921 }
1922 }
1923
7a6b7acf 1924 /**
1925 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 1926 *
1927 * @param array &$element The seed of the recursion
1928 *
7a6b7acf 1929 * @return void
1930 */
d24832f9 1931 public function category_grade_last(&$element) {
7a6b7acf 1932 if (empty($element['children'])) {
1933 return;
1934 }
1935 if (count($element['children']) < 2) {
1936 return;
1937 }
3e0e2436 1938 $first_item = reset($element['children']);
4a3dfd9a 1939 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 1940 // the category item might have been already removed
1941 $order = key($element['children']);
1942 unset($element['children'][$order]);
1943 $element['children'][$order] =& $first_item;
1944 }
206f9953 1945 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 1946 grade_tree::category_grade_last($element['children'][$sortorder]);
1947 }
1948 }
1949
1950 /**
1951 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
cf72e2dd 1952 *
1953 * @param array &$levels The levels of the grade tree through which to recurse
1954 * @param array &$element The seed of the recursion
1955 * @param int $depth How deep are we?
7a6b7acf 1956 * @return void
1957 */
d24832f9 1958 public function fill_levels(&$levels, &$element, $depth) {
7a6b7acf 1959 if (!array_key_exists($depth, $levels)) {
1960 $levels[$depth] = array();
1961 }
1962
1963 // prepare unique identifier
1964 if ($element['type'] == 'category') {
1965 $element['eid'] = 'c'.$element['object']->id;
1966 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1967 $element['eid'] = 'i'.$element['object']->id;
b89a70ce 1968 $this->items[$element['object']->id] =& $element['object'];
7a6b7acf 1969 }
1970
1971 $levels[$depth][] =& $element;
1972 $depth++;
1973 if (empty($element['children'])) {
1974 return;
1975 }
1976 $prev = 0;
1977 foreach ($element['children'] as $sortorder=>$child) {
1978 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1979 $element['children'][$sortorder]['prev'] = $prev;
1980 $element['children'][$sortorder]['next'] = 0;
1981 if ($prev) {
1982 $element['children'][$prev]['next'] = $sortorder;
1983 }
1984 $prev = $sortorder;
1985 }
1986 }
1987
1988 /**
1989 * Static recursive helper - makes full tree (all leafes are at the same level)
cf72e2dd 1990 *
1991 * @param array &$element The seed of the recursion
1992 * @param int $depth How deep are we?
1993 *
1994 * @return int
7a6b7acf 1995 */
d24832f9 1996 public function inject_fillers(&$element, $depth) {
7a6b7acf 1997 $depth++;
1998
1999 if (empty($element['children'])) {
2000 return $depth;
2001 }
2002 $chdepths = array();
2003 $chids = array_keys($element['children']);
2004 $last_child = end($chids);
2005 $first_child = reset($chids);
2006
2007 foreach ($chids as $chid) {
2008 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2009 }
2010 arsort($chdepths);
2011
2012 $maxdepth = reset($chdepths);
2013 foreach ($chdepths as $chid=>$chd) {
2014 if ($chd == $maxdepth) {
2015 continue;
2016 }
2017 for ($i=0; $i < $maxdepth-$chd; $i++) {
2018 if ($chid == $first_child) {
2019 $type = 'fillerfirst';
2020 } else if ($chid == $last_child) {
2021 $type = 'fillerlast';
2022 } else {
2023 $type = 'filler';
2024 }
2025 $oldchild =& $element['children'][$chid];
cf72e2dd 2026 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2027 'eid'=>'', 'depth'=>$element['object']->depth,
2028 'children'=>array($oldchild));
7a6b7acf 2029 }
2030 }
2031
2032 return $maxdepth;
2033 }
2034
2035 /**
2036 * Static recursive helper - add colspan information into categories
cf72e2dd 2037 *
2038 * @param array &$element The seed of the recursion
2039 *
2040 * @return int
7a6b7acf 2041 */
d24832f9 2042 public function inject_colspans(&$element) {
7a6b7acf 2043 if (empty($element['children'])) {
2044 return 1;
2045 }
2046 $count = 0;
2047 foreach ($element['children'] as $key=>$child) {
2048 $count += grade_tree::inject_colspans($element['children'][$key]);
2049 }
2050 $element['colspan'] = $count;
2051 return $count;
2052 }
2053
2054 /**
2055 * Parses the array in search of a given eid and returns a element object with
2056 * information about the element it has found.
cf72e2dd 2057 * @param int $eid Gradetree Element ID
7a6b7acf 2058 * @return object element
2059 */
d24832f9 2060 public function locate_element($eid) {
d3c3da1b 2061 // it is a grade - construct a new object
2062 if (strpos($eid, 'n') === 0) {
2063 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2064 return null;
2065 }
2066
2067 $itemid = $matches[1];
2068 $userid = $matches[2];
2069
2070 //extra security check - the grade item must be in this tree
2071 if (!$item_el = $this->locate_element('i'.$itemid)) {
2072 return null;
2073 }
2074
2075 // $gradea->id may be null - means does not exist yet
2076 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2077
2078 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2079 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2080
2081 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 2082 $id = (int) substr($eid, 1);
7a6b7acf 2083 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2084 return null;
2085 }
2086 //extra security check - the grade item must be in this tree
2087 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
2088 return null;
2089 }
2090 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2091 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2092 }
2093
2094 // it is a category or item
2095 foreach ($this->levels as $row) {
2096 foreach ($row as $element) {
2097 if ($element['type'] == 'filler') {
2098 continue;
2099 }
2100 if ($element['eid'] == $eid) {
2101 return $element;
2102 }
2103 }
2104 }
2105
2106 return null;
2107 }
d24832f9 2108
b244b9b7 2109 /**
2110 * Returns a well-formed XML representation of the grade-tree using recursion.
cf72e2dd 2111 *
2112 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2113 * @param string $tabs The control character to use for tabs
2114 *
b244b9b7 2115 * @return string $xml
2116 */
cf72e2dd 2117 public function exporttoxml($root=null, $tabs="\t") {
b244b9b7 2118 $xml = null;
2119 $first = false;
2120 if (is_null($root)) {
2121 $root = $this->top_element;
2122 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2123 $xml .= "<gradetree>\n";
2124 $first = true;
2125 }
d24832f9 2126
b244b9b7 2127 $type = 'undefined';
2128 if (strpos($root['object']->table, 'grade_categories') !== false) {
2129 $type = 'category';
cf72e2dd 2130 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2131 $type = 'item';
cf72e2dd 2132 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2133 $type = 'outcome';
2134 }
d24832f9 2135
b244b9b7 2136 $xml .= "$tabs<element type=\"$type\">\n";
2137 foreach ($root['object'] as $var => $value) {
2138 if (!is_object($value) && !is_array($value) && !empty($value)) {
2139 $xml .= "$tabs\t<$var>$value</$var>\n";
2140 }
2141 }
2142
2143 if (!empty($root['children'])) {
2144 $xml .= "$tabs\t<children>\n";
2145 foreach ($root['children'] as $sortorder => $child) {
2146 $xml .= $this->exportToXML($child, $tabs."\t\t");
2147 }
2148 $xml .= "$tabs\t</children>\n";
2149 }
d24832f9 2150
b244b9b7 2151 $xml .= "$tabs</element>\n";
2152
2153 if ($first) {
2154 $xml .= "</gradetree>";
2155 }
d24832f9 2156
b244b9b7 2157 return $xml;
2158 }
d24832f9 2159
b244b9b7 2160 /**
2161 * Returns a JSON representation of the grade-tree using recursion.
cf72e2dd 2162 *
b244b9b7 2163 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2164 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
cf72e2dd 2165 *
2166 * @return string
b244b9b7 2167 */
cf72e2dd 2168 public function exporttojson($root=null, $tabs="\t") {
b244b9b7 2169 $json = null;
2170 $first = false;
2171 if (is_null($root)) {
2172 $root = $this->top_element;
2173 $first = true;
2174 }
d24832f9 2175
b244b9b7 2176 $name = '';
2177
2178
2179 if (strpos($root['object']->table, 'grade_categories') !== false) {
2180 $name = $root['object']->fullname;
2181 if ($name == '?') {
d24832f9 2182 $name = $root['object']->get_name();
b244b9b7 2183 }
cf72e2dd 2184 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2185 $name = $root['object']->itemname;
cf72e2dd 2186 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2187 $name = $root['object']->itemname;
2188 }
d24832f9 2189
b244b9b7 2190 $json .= "$tabs {\n";
2191 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2192 $json .= "$tabs\t \"name\": \"$name\",\n";
2193
2194 foreach ($root['object'] as $var => $value) {
2195 if (!is_object($value) && !is_array($value) && !empty($value)) {
2196 $json .= "$tabs\t \"$var\": \"$value\",\n";
2197 }
2198 }
d24832f9 2199
b244b9b7 2200 $json = substr($json, 0, strrpos($json, ','));
d24832f9 2201
b244b9b7 2202 if (!empty($root['children'])) {
2203 $json .= ",\n$tabs\t\"children\": [\n";
2204 foreach ($root['children'] as $sortorder => $child) {
2205 $json .= $this->exportToJSON($child, $tabs."\t\t");
2206 }
2207 $json = substr($json, 0, strrpos($json, ','));
2208 $json .= "\n$tabs\t]\n";
d24832f9 2209 }
b244b9b7 2210
2211 if ($first) {
2212 $json .= "\n}";
2213 } else {
2214 $json .= "\n$tabs},\n";
2215 }
d24832f9 2216
b244b9b7 2217 return $json;
2218 }
d24832f9 2219
cf72e2dd 2220 /**
2221 * Returns the array of levels
2222 *
2223 * @return array
2224 */
d24832f9 2225 public function get_levels() {
2226 return $this->levels;
2227 }
2228
cf72e2dd 2229 /**
2230 * Returns the array of grade items
2231 *
2232 * @return array
2233 */
d24832f9 2234 public function get_items() {
2235 return $this->items;
2236 }
2237
cf72e2dd 2238 /**
2239 * Returns a specific Grade Item
2240 *
2241 * @param int $itemid The ID of the grade_item object
2242 *
2243 * @return grade_item
2244 */
d24832f9 2245 public function get_item($itemid) {
2246 if (array_key_exists($itemid, $this->items)) {
2247 return $this->items[$itemid];
2248 } else {
2249 return false;
2250 }
2251 }
7a6b7acf 2252}
eef00ade 2253
2254/**
2255 * Local shortcut function for creating an edit/delete button for a grade_* object.
4d27bc79 2256 * @param string $type 'edit' or 'delete'
eef00ade 2257 * @param int $courseid The Course ID
2258 * @param grade_* $object The grade_* object
2259 * @return string html
2260 */
2261function grade_button($type, $courseid, $object) {
2262 global $CFG, $OUTPUT;
2263 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2264 $objectidstring = $matches[1] . 'id';
2265 } else {
2266 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2267 }
2268
2269 $strdelete = get_string('delete');
2270 $stredit = get_string('edit');
2271
eef00ade 2272 if ($type == 'delete') {
8ae8bf8a 2273 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
eef00ade 2274 } else if ($type == 'edit') {
8ae8bf8a 2275 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
eef00ade 2276 }
2277
fa9c0aab 2278 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
eef00ade 2279
2280}
4d5059d4
SH
2281
2282/**
2283 * This method adds settings to the settings block for the grade system and its
2284 * plugins
2285 *
2286 * @global moodle_page $PAGE
2287 */
2288function grade_extend_settings($plugininfo, $courseid) {
2289 global $PAGE;
2290
2291 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2292
2293 $strings = array_shift($plugininfo);
2294
2295 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2296 foreach ($reports as $report) {
2297 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2298 }
2299 }
2300
2301 if ($imports = grade_helper::get_plugins_import($courseid)) {
2302 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2303 foreach ($imports as $import) {
11f87187 2304 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
4d5059d4
SH
2305 }
2306 }
2307
2308 if ($exports = grade_helper::get_plugins_export($courseid)) {
2309 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2310 foreach ($exports as $export) {
11f87187 2311 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
4d5059d4
SH
2312 }
2313 }
2314
2315 if ($setting = grade_helper::get_info_manage_settings($courseid)) {
2316 $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2317 }
2318
2319 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2320 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2321 foreach ($preferences as $preference) {
2322 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2323 }
2324 }
2325
2326 if ($letters = grade_helper::get_info_letters($courseid)) {
2327 $letters = array_shift($letters);
2328 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2329 }
2330
2331 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2332 $outcomes = array_shift($outcomes);
2333 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2334 }
2335
2336 if ($scales = grade_helper::get_info_scales($courseid)) {
2337 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2338 }
2339
2340 if ($categories = grade_helper::get_info_edit_structure($courseid)) {
2341 $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
2342 foreach ($categories as $category) {
2343 $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
2344 }
2345 }
2346
2347 if ($gradenode->contains_active_node()) {
2348 // If the gradenode is active include the settings base node (gradeadministration) in
2349 // the navbar, typcially this is ignored.
2350 $PAGE->navbar->includesettingsbase = true;
2351
2352 // If we can get the course admin node make sure it is closed by default
2353 // as in this case the gradenode will be opened
2354 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2355 $coursenode->make_inactive();
2356 $coursenode->forceopen = false;
2357 }
2358 }
2359}
2360
2361/**
2362 * Grade helper class
2363 *
2364 * This class provides several helpful functions that work irrespective of any
2365 * current state.
2366 *
2367 * @copyright 2010 Sam Hemelryk
2368 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2369 */
2370abstract class grade_helper {
2371 /**
2372 * Cached manage settings info {@see get_info_settings}
2373 * @var grade_plugin_info|false
2374 */
2375 protected static $managesetting = null;
2376 /**
2377 * Cached grade report plugins {@see get_plugins_reports}
2378 * @var array|false
2379 */
2380 protected static $gradereports = null;
2381 /**
2382 * Cached grade report plugins preferences {@see get_info_scales}
2383 * @var array|false
2384 */
2385 protected static $gradereportpreferences = null;
2386 /**
2387 * Cached scale info {@see get_info_scales}
2388 * @var grade_plugin_info|false
2389 */
2390 protected static $scaleinfo = null;
2391 /**
2392 * Cached outcome info {@see get_info_outcomes}
2393 * @var grade_plugin_info|false
2394 */
2395 protected static $outcomeinfo = null;
2396 /**
2397 * Cached info on edit structure {@see get_info_edit_structure}
2398 * @var array|false
2399 */
2400 protected static $edittree = null;
2401 /**
2402 * Cached leftter info {@see get_info_letters}
2403 * @var grade_plugin_info|false
2404 */
2405 protected static $letterinfo = null;
2406 /**
2407 * Cached grade import plugins {@see get_plugins_import}
2408 * @var array|false
2409 */
2410 protected static $importplugins = null;
2411 /**
2412 * Cached grade export plugins {@see get_plugins_export}
2413 * @var array|false
2414 */
2415 protected static $exportplugins = null;
2416 /**
2417 * Cached grade plugin strings
2418 * @var array
2419 */
2420 protected static $pluginstrings = null;
2421
2422 /**
2423 * Gets strings commonly used by the describe plugins
2424 *
2425 * report => get_string('view'),
2426 * edittree => get_string('edittree', 'grades'),
2427 * scale => get_string('scales'),
2428 * outcome => get_string('outcomes', 'grades'),
2429 * letter => get_string('letters', 'grades'),
2430 * export => get_string('export', 'grades'),
2431 * import => get_string('import'),
2432 * preferences => get_string('mypreferences', 'grades'),
2433 * settings => get_string('settings')
2434 *
2435 * @return array
2436 */
2437 public static function get_plugin_strings() {
2438 if (self::$pluginstrings === null) {
2439 self::$pluginstrings = array(
2440 'report' => get_string('view'),
2441 'edittree' => get_string('edittree', 'grades'),
2442 'scale' => get_string('scales'),
2443 'outcome' => get_string('outcomes', 'grades'),
2444 'letter' => get_string('letters', 'grades'),
2445 'export' => get_string('export', 'grades'),
2446 'import' => get_string('import'),
2447 'preferences' => get_string('mypreferences', 'grades'),
2448 'settings' => get_string('settings')
2449 );
2450 }
2451 return self::$pluginstrings;
2452 }
2453 /**
2454 * Get grade_plugin_info object for managing settings if the user can
2455 *
2456 * @param int $courseid
2457 * @return grade_plugin_info
2458 */
2459 public static function get_info_manage_settings($courseid) {
2460 if (self::$managesetting !== null) {
2461 return self::$managesetting;
2462 }
d4060472 2463 $context = context_course::instance($courseid);
4d5059d4
SH
2464 if (has_capability('moodle/course:update', $context)) {
2465 self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
2466 } else {
2467 self::$managesetting = false;
2468 }
2469 return self::$managesetting;
2470 }
2471 /**
2472 * Returns an array of plugin reports as grade_plugin_info objects
2473 *
2474 * @param int $courseid
2475 * @return array
2476 */
2477 public static function get_plugins_reports($courseid) {
f7fcf4cd 2478 global $SITE;
cf717dc2 2479
4d5059d4
SH
2480 if (self::$gradereports !== null) {
2481 return self::$gradereports;
2482 }
d4060472 2483 $context = context_course::instance($courseid);
4d5059d4
SH
2484 $gradereports = array();
2485 $gradepreferences = array();
2486 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
f7fcf4cd
AD
2487 //some reports make no sense if we're not within a course
2488 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2489 continue;
2490 }
2491
4d5059d4
SH
2492 // Remove ones we can't see
2493 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2494 continue;
2495 }
2496
b5e7b2bf 2497 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
4d5059d4
SH
2498 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2499 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2500
2501 // Add link to preferences tab if such a page exists
2502 if (file_exists($plugindir.'/preferences.php')) {
2503 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2504 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2505 }
2506 }
2507 if (count($gradereports) == 0) {
2508 $gradereports = false;
2509 $gradepreferences = false;
2510 } else if (count($gradepreferences) == 0) {
2511 $gradepreferences = false;
2512 asort($gradereports);
2513 } else {
2514 asort($gradereports);
2515 asort($gradepreferences);
2516 }
2517 self::$gradereports = $gradereports;
2518 self::$gradereportpreferences = $gradepreferences;
2519 return self::$gradereports;
2520 }
2521 /**
2522 * Returns an array of grade plugin report preferences for plugin reports that
2523 * support preferences
2524 * @param int $courseid
2525 * @return array
2526 */
2527 public static function get_plugins_report_preferences($courseid) {
2528 if (self::$gradereportpreferences !== null) {
2529 return self::$gradereportpreferences;
2530 }
2531 self::get_plugins_reports($courseid);
2532 return self::$gradereportpreferences;
2533 }
2534 /**
2535 * Get information on scales
2536 * @param int $courseid
2537 * @return grade_plugin_info
2538 */
2539 public static function get_info_scales($courseid) {
2540 if (self::$scaleinfo !== null) {
2541 return self::$scaleinfo;
2542 }
d4060472 2543 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
4d5059d4
SH
2544 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2545 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2546 } else {
2547 self::$scaleinfo = false;
2548 }
2549 return self::$scaleinfo;
2550 }
2551 /**
2552 * Get information on outcomes
2553 * @param int $courseid
2554 * @return grade_plugin_info
2555 */
2556 public static function get_info_outcomes($courseid) {
f7fcf4cd 2557 global $CFG, $SITE;
4d5059d4
SH
2558
2559 if (self::$outcomeinfo !== null) {
2560 return self::$outcomeinfo;
2561 }
d4060472 2562 $context = context_course::instance($courseid);
4d5059d4
SH
2563 $canmanage = has_capability('moodle/grade:manage', $context);
2564 $canupdate = has_capability('moodle/course:update', $context);
2565 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2566 $outcomes = array();
2567 if ($canupdate) {
f7fcf4cd
AD
2568 if ($courseid!=$SITE->id) {
2569 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2570 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2571 }
4d5059d4
SH
2572 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2573 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
c46aeeab
DC
2574 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2575 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
4d5059d4 2576 } else {
f7fcf4cd
AD
2577 if ($courseid!=$SITE->id) {
2578 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2579 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2580 }
4d5059d4
SH
2581 }
2582 self::$outcomeinfo = $outcomes;
2583 } else {
2584 self::$outcomeinfo = false;
2585 }
2586 return self::$outcomeinfo;
2587 }
2588 /**
2589 * Get information on editing structures
2590 * @param int $courseid
2591 * @return array
2592 */
2593 public static function get_info_edit_structure($courseid) {
2594 if (self::$edittree !== null) {
2595 return self::$edittree;
2596 }
d4060472 2597 if (has_capability('moodle/grade:manage', context_course::instance($courseid))) {
4d5059d4
SH
2598 $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
2599 self::$edittree = array(
2600 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
2601 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
2602 );
2603 } else {
2604 self::$edittree = false;
2605 }
2606 return self::$edittree;
2607 }
2608 /**
2609 * Get information on letters
2610 * @param int $courseid
4d27bc79 2611 * @return array
4d5059d4
SH
2612 */
2613 public static function get_info_letters($courseid) {
a8dfc483 2614 global $SITE;
4d5059d4
SH
2615 if (self::$letterinfo !== null) {
2616 return self::$letterinfo;
2617 }
d4060472 2618 $context = context_course::instance($courseid);
4d5059d4
SH
2619 $canmanage = has_capability('moodle/grade:manage', $context);
2620 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2621 if ($canmanage || $canmanageletters) {
a8dfc483
AA
2622 // Redirect to system context when report is accessed from admin settings MDL-31633
2623 if ($context->instanceid == $SITE->id) {
2624 $param = array('edit' => 1);
2625 } else {
2626 $param = array('edit' => 1,'id' => $context->id);
2627 }
4d5059d4 2628 self::$letterinfo = array(
54caa598 2629 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
a8dfc483 2630 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
4d5059d4
SH
2631 );
2632 } else {
2633 self::$letterinfo = false;
2634 }
2635 return self::$letterinfo;
2636 }
2637 /**
2638 * Get information import plugins
2639 * @param int $courseid
2640 * @return array
2641 */
2642 public static function get_plugins_import($courseid) {
2643 global $CFG;
2644
2645 if (self::$importplugins !== null) {
2646 return self::$importplugins;
2647 }
2648 $importplugins = array();
d4060472 2649 $context = context_course::instance($courseid);
4d5059d4
SH
2650
2651 if (has_capability('moodle/grade:import', $context)) {
2652 foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
2653 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2654 continue;
2655 }
b5e7b2bf 2656 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
4d5059d4
SH
2657 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2658 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2659 }
2660
2661
2662 if ($CFG->gradepublishing) {
2663 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2664 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2665 }
2666 }
2667
2668 if (count($importplugins) > 0) {
2669 asort($importplugins);
2670 self::$importplugins = $importplugins;
2671 } else {
2672 self::$importplugins = false;
2673 }
2674 return self::$importplugins;
2675 }
2676 /**
2677 * Get information export plugins
2678 * @param int $courseid
2679 * @return array
2680 */
2681 public static function get_plugins_export($courseid) {
2682 global $CFG;
2683
2684 if (self::$exportplugins !== null) {
2685 return self::$exportplugins;
2686 }
d4060472 2687 $context = context_course::instance($courseid);
4d5059d4
SH
2688 $exportplugins = array();
2689 if (has_capability('moodle/grade:export', $context)) {
2690 foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
2691 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2692 continue;
2693 }
b5e7b2bf 2694 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
4d5059d4
SH
2695 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2696 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2697 }
2698
2699 if ($CFG->gradepublishing) {
2700 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2701 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2702 }
2703 }
2704 if (count($exportplugins) > 0) {
2705 asort($exportplugins);
2706 self::$exportplugins = $exportplugins;
2707 } else {
2708 self::$exportplugins = false;
2709 }
2710 return self::$exportplugins;
2711 }
293f42b6 2712
61c8e0d7
FM
2713 /**
2714 * Returns the value of a field from a user record
2715 *
2716 * @param stdClass $user object
2717 * @param stdClass $field object
2718 * @return string value of the field
2719 */
2720 public static function get_user_field_value($user, $field) {
2721 if (!empty($field->customid)) {
2722 $fieldname = 'customfield_' . $field->shortname;
2723 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
2724 $fieldvalue = $user->{$fieldname};
2725 } else {
2726 $fieldvalue = $field->default;
2727 }
2728 } else {
2729 $fieldvalue = $user->{$field->shortname};
2730 }
2731 return $fieldvalue;
2732 }
2733
2734 /**
2735 * Returns an array of user profile fields to be included in export
2736 *
2737 * @param int $courseid
2738 * @param bool $includecustomfields
2739 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2740 */
2741 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2742 global $CFG, $DB;
2743
2744 // Gets the fields that have to be hidden
2745 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
2746 $context = context_course::instance($courseid);
2747 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2748 if ($canseehiddenfields) {
2749 $hiddenfields = array();
2750 }
2751
2752 $fields = array();
2753 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
2754 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2755 $userdefaultfields = user_get_default_fields();
2756
2757 // Sets the list of profile fields
2758 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
2759 if (!empty($userprofilefields)) {
2760 foreach ($userprofilefields as $field) {
2761 $field = trim($field);
2762 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
2763 continue;
2764 }
293f42b6 2765 $obj = new stdClass();
61c8e0d7 2766 $obj->customid = 0;
293f42b6 2767 $obj->shortname = $field;
61c8e0d7 2768 $obj->fullname = get_string($field);
293f42b6
CF
2769 $fields[] = $obj;
2770 }
2771 }
293f42b6 2772
61c8e0d7
FM
2773 // Sets the list of custom profile fields
2774 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
2775 if ($includecustomfields && !empty($customprofilefields)) {
2776 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2777 $customfields = $DB->get_records_sql("SELECT f.*
2778 FROM {user_info_field} f
2779 JOIN {user_info_category} c ON f.categoryid=c.id
2780 WHERE f.shortname $wherefields
2781 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2782 if (!is_array($customfields)) {
2783 continue;
2784 }
2785
2786 foreach ($customfields as $field) {
2787 // Make sure we can display this custom field
2788 if (!in_array($field->shortname, $customprofilefields)) {
2789 continue;
2790 } else if (in_array($field->shortname, $hiddenfields)) {
2791 continue;
2792 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
2793 continue;
2794 }
2795
2796 $obj = new stdClass();
2797 $obj->customid = $field->id;
2798 $obj->shortname = $field->shortname;
2799 $obj->fullname = format_string($field->name);
2800 $obj->datatype = $field->datatype;
2801 $obj->default = $field->defaultdata;
2802 $fields[] = $obj;
2803 }
2804 }
2805
2806 return $fields;
2807 }
293f42b6 2808}
61c8e0d7 2809