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