PageRenderTime 35ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/grade/lib.php

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