PageRenderTime 77ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/grade/lib.php

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