PageRenderTime 34ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/course/moodleform_mod.php

http://github.com/moodle/moodle
PHP | 1265 lines | 810 code | 157 blank | 298 comment | 166 complexity | a9755dd2ee497c643a4efc83f38211e2 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

Large files files are truncated, but you can click here to view the full file

  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. * Moodleform.
  18. *
  19. * @package core_course
  20. * @copyright Andrew Nicols <andrew@nicols.co.uk>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once($CFG->libdir.'/formslib.php');
  24. require_once($CFG->libdir.'/completionlib.php');
  25. require_once($CFG->libdir.'/gradelib.php');
  26. require_once($CFG->libdir.'/plagiarismlib.php');
  27. use core_grades\component_gradeitems;
  28. /**
  29. * This class adds extra methods to form wrapper specific to be used for module add / update forms
  30. * mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html Moodleform.
  31. *
  32. * @package core_course
  33. * @copyright Andrew Nicols <andrew@nicols.co.uk>
  34. */
  35. abstract class moodleform_mod extends moodleform {
  36. /** Current data */
  37. protected $current;
  38. /**
  39. * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
  40. * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
  41. * update one.
  42. *
  43. * @var mixed
  44. */
  45. protected $_instance;
  46. /**
  47. * Section of course that module instance will be put in or is in.
  48. * This is always the section number itself (column 'section' from 'course_sections' table).
  49. *
  50. * @var int
  51. */
  52. protected $_section;
  53. /**
  54. * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
  55. * update one.
  56. *
  57. * @var mixed
  58. */
  59. protected $_cm;
  60. /**
  61. * Current course.
  62. *
  63. * @var mixed
  64. */
  65. protected $_course;
  66. /**
  67. * List of modform features
  68. */
  69. protected $_features;
  70. /**
  71. * @var array Custom completion-rule elements, if enabled
  72. */
  73. protected $_customcompletionelements;
  74. /**
  75. * @var string name of module.
  76. */
  77. protected $_modname;
  78. /** current context, course or module depends if already exists*/
  79. protected $context;
  80. /** a flag indicating whether outcomes are being used*/
  81. protected $_outcomesused;
  82. /**
  83. * @var bool A flag used to indicate that this module should lock settings
  84. * based on admin settings flags in definition_after_data.
  85. */
  86. protected $applyadminlockedflags = false;
  87. /** @var object The course format of the current course. */
  88. protected $courseformat;
  89. /** @var string Whether this is graded or rated. */
  90. private $gradedorrated = null;
  91. public function __construct($current, $section, $cm, $course) {
  92. global $CFG;
  93. $this->current = $current;
  94. $this->_instance = $current->instance;
  95. $this->_section = $section;
  96. $this->_cm = $cm;
  97. $this->_course = $course;
  98. if ($this->_cm) {
  99. $this->context = context_module::instance($this->_cm->id);
  100. } else {
  101. $this->context = context_course::instance($course->id);
  102. }
  103. // Set the course format.
  104. require_once($CFG->dirroot . '/course/format/lib.php');
  105. $this->courseformat = course_get_format($course);
  106. // Guess module name if not set.
  107. if (is_null($this->_modname)) {
  108. $matches = array();
  109. if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
  110. debugging('Rename form to mod_xx_mod_form, where xx is name of your module');
  111. print_error('unknownmodulename');
  112. }
  113. $this->_modname = $matches[1];
  114. }
  115. $this->init_features();
  116. parent::__construct('modedit.php');
  117. }
  118. /**
  119. * Old syntax of class constructor. Deprecated in PHP7.
  120. *
  121. * @deprecated since Moodle 3.1
  122. */
  123. public function moodleform_mod($current, $section, $cm, $course) {
  124. debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  125. self::__construct($current, $section, $cm, $course);
  126. }
  127. /**
  128. * Get the current data for the form.
  129. * @return stdClass|null
  130. */
  131. public function get_current() {
  132. return $this->current;
  133. }
  134. /**
  135. * Get the DB record for the current instance.
  136. * @return stdClass|null
  137. */
  138. public function get_instance() {
  139. return $this->_instance;
  140. }
  141. /**
  142. * Get the course section number (relative).
  143. * @return int
  144. */
  145. public function get_section() {
  146. return $this->_section;
  147. }
  148. /**
  149. * Get the course id.
  150. * @return int
  151. */
  152. public function get_course() {
  153. return $this->_course;
  154. }
  155. /**
  156. * Get the course module object.
  157. * @return stdClass|null
  158. */
  159. public function get_coursemodule() {
  160. return $this->_cm;
  161. }
  162. /**
  163. * Return the course context for new modules, or the module context for existing modules.
  164. * @return context
  165. */
  166. public function get_context() {
  167. return $this->context;
  168. }
  169. /**
  170. * Return the features this module supports.
  171. * @return stdClass
  172. */
  173. public function get_features() {
  174. return $this->_features;
  175. }
  176. protected function init_features() {
  177. global $CFG;
  178. $this->_features = new stdClass();
  179. $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, false);
  180. $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
  181. $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
  182. $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
  183. $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
  184. $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
  185. $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
  186. $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
  187. $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
  188. $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
  189. $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
  190. $this->_features->canrescale = (component_callback_exists('mod_' . $this->_modname, 'rescale_activity_grades') !== false);
  191. }
  192. /**
  193. * Allows module to modify data returned by get_moduleinfo_data() or prepare_new_moduleinfo_data() before calling set_data()
  194. * This method is also called in the bulk activity completion form.
  195. *
  196. * Only available on moodleform_mod.
  197. *
  198. * @param array $default_values passed by reference
  199. */
  200. function data_preprocessing(&$default_values){
  201. if (empty($default_values['scale'])) {
  202. $default_values['assessed'] = 0;
  203. }
  204. if (empty($default_values['assessed'])){
  205. $default_values['ratingtime'] = 0;
  206. } else {
  207. $default_values['ratingtime']=
  208. ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
  209. }
  210. }
  211. /**
  212. * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
  213. */
  214. function definition_after_data() {
  215. global $CFG, $COURSE;
  216. $mform =& $this->_form;
  217. if ($id = $mform->getElementValue('update')) {
  218. $modulename = $mform->getElementValue('modulename');
  219. $instance = $mform->getElementValue('instance');
  220. $component = "mod_{$modulename}";
  221. if ($this->_features->gradecat) {
  222. $hasgradeitems = false;
  223. $items = grade_item::fetch_all([
  224. 'itemtype' => 'mod',
  225. 'itemmodule' => $modulename,
  226. 'iteminstance' => $instance,
  227. 'courseid' => $COURSE->id,
  228. ]);
  229. $gradecategories = [];
  230. $removecategories = [];
  231. //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
  232. if (!empty($items)) {
  233. foreach ($items as $item) {
  234. if (!empty($item->outcomeid)) {
  235. $elname = 'outcome_'.$item->outcomeid;
  236. if ($mform->elementExists($elname)) {
  237. $mform->hardFreeze($elname); // prevent removing of existing outcomes
  238. }
  239. } else {
  240. $hasgradeitems = true;
  241. }
  242. }
  243. foreach ($items as $item) {
  244. $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber(
  245. $component,
  246. $item->itemnumber,
  247. 'gradecat'
  248. );
  249. if (!isset($gradecategories[$gradecatfieldname])) {
  250. $gradecategories[$gradecatfieldname] = $item->categoryid;
  251. } else if ($gradecategories[$gradecatfieldname] != $item->categoryid) {
  252. $removecategories[$gradecatfieldname] = true;
  253. }
  254. }
  255. }
  256. foreach ($removecategories as $toremove) {
  257. if ($mform->elementExists($toremove)) {
  258. $mform->removeElement($toremove);
  259. }
  260. }
  261. }
  262. }
  263. if ($COURSE->groupmodeforce) {
  264. if ($mform->elementExists('groupmode')) {
  265. // The groupmode can not be changed if forced from course settings.
  266. $mform->hardFreeze('groupmode');
  267. }
  268. }
  269. // Don't disable/remove groupingid if it is currently set to something, otherwise you cannot turn it off at same
  270. // time as turning off other option (MDL-30764).
  271. if (empty($this->_cm) || !$this->_cm->groupingid) {
  272. if ($mform->elementExists('groupmode') && empty($COURSE->groupmodeforce)) {
  273. $mform->hideIf('groupingid', 'groupmode', 'eq', NOGROUPS);
  274. } else if (!$mform->elementExists('groupmode')) {
  275. // Groupings have no use without groupmode.
  276. if ($mform->elementExists('groupingid')) {
  277. $mform->removeElement('groupingid');
  278. }
  279. // Nor does the group restrictions button.
  280. if ($mform->elementExists('restrictgroupbutton')) {
  281. $mform->removeElement('restrictgroupbutton');
  282. }
  283. }
  284. }
  285. // Completion: If necessary, freeze fields
  286. $completion = new completion_info($COURSE);
  287. if ($completion->is_enabled()) {
  288. // If anybody has completed the activity, these options will be 'locked'
  289. $completedcount = empty($this->_cm)
  290. ? 0
  291. : $completion->count_user_data($this->_cm);
  292. $freeze = false;
  293. if (!$completedcount) {
  294. if ($mform->elementExists('unlockcompletion')) {
  295. $mform->removeElement('unlockcompletion');
  296. }
  297. // Automatically set to unlocked (note: this is necessary
  298. // in order to make it recalculate completion once the option
  299. // is changed, maybe someone has completed it now)
  300. $mform->getElement('completionunlocked')->setValue(1);
  301. } else {
  302. // Has the element been unlocked, either by the button being pressed
  303. // in this request, or the field already being set from a previous one?
  304. if ($mform->exportValue('unlockcompletion') ||
  305. $mform->exportValue('completionunlocked')) {
  306. // Yes, add in warning text and set the hidden variable
  307. $mform->insertElementBefore(
  308. $mform->createElement('static', 'completedunlocked',
  309. get_string('completedunlocked', 'completion'),
  310. get_string('completedunlockedtext', 'completion')),
  311. 'unlockcompletion');
  312. $mform->removeElement('unlockcompletion');
  313. $mform->getElement('completionunlocked')->setValue(1);
  314. } else {
  315. // No, add in the warning text with the count (now we know
  316. // it) before the unlock button
  317. $mform->insertElementBefore(
  318. $mform->createElement('static', 'completedwarning',
  319. get_string('completedwarning', 'completion'),
  320. get_string('completedwarningtext', 'completion', $completedcount)),
  321. 'unlockcompletion');
  322. $freeze = true;
  323. }
  324. }
  325. if ($freeze) {
  326. $mform->freeze('completion');
  327. if ($mform->elementExists('completionview')) {
  328. $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
  329. }
  330. if ($mform->elementExists('completionusegrade')) {
  331. $mform->freeze('completionusegrade');
  332. }
  333. if ($mform->elementExists('completiongradeitemnumber')) {
  334. $mform->freeze('completiongradeitemnumber');
  335. }
  336. $mform->freeze($this->_customcompletionelements);
  337. }
  338. }
  339. // Freeze admin defaults if required (and not different from default)
  340. $this->apply_admin_locked_flags();
  341. }
  342. // form verification
  343. function validation($data, $files) {
  344. global $COURSE, $DB, $CFG;
  345. $errors = parent::validation($data, $files);
  346. $mform =& $this->_form;
  347. $errors = array();
  348. if ($mform->elementExists('name')) {
  349. $name = trim($data['name']);
  350. if ($name == '') {
  351. $errors['name'] = get_string('required');
  352. }
  353. }
  354. $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
  355. 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
  356. if ($data['coursemodule']) {
  357. $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
  358. } else {
  359. $cm = null;
  360. }
  361. if ($mform->elementExists('cmidnumber')) {
  362. // verify the idnumber
  363. if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
  364. $errors['cmidnumber'] = get_string('idnumbertaken');
  365. }
  366. }
  367. $component = "mod_{$this->_modname}";
  368. $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
  369. foreach ($itemnames as $itemnumber => $itemname) {
  370. $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
  371. $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
  372. $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
  373. $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
  374. // Ratings: Don't let them select an aggregate type without selecting a scale.
  375. // If the user has selected to use ratings but has not chosen a scale or set max points then the form is
  376. // invalid. If ratings have been selected then the user must select either a scale or max points.
  377. // This matches (horrible) logic in data_preprocessing.
  378. if (isset($data[$assessedfieldname]) && $data[$assessedfieldname] > 0 && empty($data[$scalefieldname])) {
  379. $errors[$assessedfieldname] = get_string('scaleselectionrequired', 'rating');
  380. }
  381. // Check that the grade pass is a valid number.
  382. $gradepassvalid = false;
  383. if (isset($data[$gradepassfieldname])) {
  384. if (unformat_float($data[$gradepassfieldname], true) === false) {
  385. $errors[$gradepassfieldname] = get_string('err_numeric', 'form');
  386. } else {
  387. $gradepassvalid = true;
  388. }
  389. }
  390. // Grade to pass: ensure that the grade to pass is valid for points and scales.
  391. // If we are working with a scale, convert into a positive number for validation.
  392. if ($gradepassvalid && isset($data[$gradepassfieldname]) && (!empty($data[$gradefieldname]) || !empty($data[$scalefieldname]))) {
  393. $scale = !empty($data[$gradefieldname]) ? $data[$gradefieldname] : $data[$scalefieldname];
  394. if ($scale < 0) {
  395. $scalevalues = $DB->get_record('scale', array('id' => -$scale));
  396. $grade = count(explode(',', $scalevalues->scale));
  397. } else {
  398. $grade = $scale;
  399. }
  400. if (unformat_float($data[$gradepassfieldname]) > $grade) {
  401. $errors[$gradepassfieldname] = get_string('gradepassgreaterthangrade', 'grades', $grade);
  402. }
  403. }
  404. // We have a grade if there is a non-falsey value for:
  405. // - the assessedfieldname for Ratings there; or
  406. // - the gradefieldname for Ratings there.
  407. if (empty($data[$assessedfieldname]) && empty($data[$gradefieldname])) {
  408. // There are no grades set therefore completion is not allowed.
  409. if (isset($data['completiongradeitemnumber']) && $data['completiongradeitemnumber'] == (string) $itemnumber) {
  410. $errors['completiongradeitemnumber'] = get_string(
  411. 'badcompletiongradeitemnumber',
  412. 'completion',
  413. get_string("grade_{$itemname}_name", $component)
  414. );
  415. }
  416. }
  417. }
  418. // Completion: Don't let them choose automatic completion without turning
  419. // on some conditions. Ignore this check when completion settings are
  420. // locked, as the options are then disabled.
  421. $automaticcompletion = array_key_exists('completion', $data);
  422. $automaticcompletion = $automaticcompletion && $data['completion'] == COMPLETION_TRACKING_AUTOMATIC;
  423. $automaticcompletion = $automaticcompletion && !empty($data['completionunlocked']);
  424. if ($automaticcompletion) {
  425. // View to complete.
  426. $rulesenabled = !empty($data['completionview']);
  427. // Use grade to complete (only one grade item).
  428. $rulesenabled = $rulesenabled || !empty($data['completionusegrade']);
  429. // Use grade to complete (specific grade item).
  430. if (!$rulesenabled && isset($data['completiongradeitemnumber'])) {
  431. $rulesenabled = $data['completiongradeitemnumber'] != '';
  432. }
  433. // Module-specific completion rules.
  434. $rulesenabled = $rulesenabled || $this->completion_rule_enabled($data);
  435. if (!$rulesenabled) {
  436. // No rules are enabled. Can't set automatically completed without rules.
  437. $errors['completion'] = get_string('badautocompletion', 'completion');
  438. }
  439. }
  440. // Availability: Check availability field does not have errors.
  441. if (!empty($CFG->enableavailability)) {
  442. \core_availability\frontend::report_validation_errors($data, $errors);
  443. }
  444. $pluginerrors = $this->plugin_extend_coursemodule_validation($data);
  445. if (!empty($pluginerrors)) {
  446. $errors = array_merge($errors, $pluginerrors);
  447. }
  448. return $errors;
  449. }
  450. /**
  451. * Extend the validation function from any other plugin.
  452. *
  453. * @param stdClass $data The form data.
  454. * @return array $errors The list of errors keyed by element name.
  455. */
  456. protected function plugin_extend_coursemodule_validation($data) {
  457. $errors = array();
  458. $callbacks = get_plugins_with_function('coursemodule_validation', 'lib.php');
  459. foreach ($callbacks as $type => $plugins) {
  460. foreach ($plugins as $plugin => $pluginfunction) {
  461. // We have exposed all the important properties with public getters - the errors array should be pass by reference.
  462. $pluginerrors = $pluginfunction($this, $data);
  463. if (!empty($pluginerrors)) {
  464. $errors = array_merge($errors, $pluginerrors);
  465. }
  466. }
  467. }
  468. return $errors;
  469. }
  470. /**
  471. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  472. * form definition (new entry form); this function is used to load in data where values
  473. * already exist and data is being edited (edit entry form).
  474. *
  475. * @param mixed $default_values object or array of default values
  476. */
  477. function set_data($default_values) {
  478. if (is_object($default_values)) {
  479. $default_values = (array)$default_values;
  480. }
  481. $this->data_preprocessing($default_values);
  482. parent::set_data($default_values);
  483. }
  484. /**
  485. * Adds all the standard elements to a form to edit the settings for an activity module.
  486. */
  487. protected function standard_coursemodule_elements() {
  488. global $COURSE, $CFG, $DB;
  489. $mform =& $this->_form;
  490. $this->_outcomesused = false;
  491. if ($this->_features->outcomes) {
  492. if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
  493. $this->_outcomesused = true;
  494. $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
  495. foreach($outcomes as $outcome) {
  496. $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
  497. }
  498. }
  499. }
  500. if ($this->_features->rating) {
  501. $this->add_rating_settings($mform, 0);
  502. }
  503. $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
  504. $section = get_fast_modinfo($COURSE)->get_section_info($this->_section);
  505. $allowstealth = !empty($CFG->allowstealth) && $this->courseformat->allow_stealth_module_visibility($this->_cm, $section);
  506. if ($allowstealth && $section->visible) {
  507. $modvisiblelabel = 'modvisiblewithstealth';
  508. } else if ($section->visible) {
  509. $modvisiblelabel = 'modvisible';
  510. } else {
  511. $modvisiblelabel = 'modvisiblehiddensection';
  512. }
  513. $mform->addElement('modvisible', 'visible', get_string($modvisiblelabel), null,
  514. array('allowstealth' => $allowstealth, 'sectionvisible' => $section->visible, 'cm' => $this->_cm));
  515. $mform->addHelpButton('visible', $modvisiblelabel);
  516. if (!empty($this->_cm)) {
  517. $context = context_module::instance($this->_cm->id);
  518. if (!has_capability('moodle/course:activityvisibility', $context)) {
  519. $mform->hardFreeze('visible');
  520. }
  521. }
  522. if ($this->_features->idnumber) {
  523. $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
  524. $mform->setType('cmidnumber', PARAM_RAW);
  525. $mform->addHelpButton('cmidnumber', 'idnumbermod');
  526. }
  527. if ($this->_features->groups) {
  528. $options = array(NOGROUPS => get_string('groupsnone'),
  529. SEPARATEGROUPS => get_string('groupsseparate'),
  530. VISIBLEGROUPS => get_string('groupsvisible'));
  531. $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
  532. $mform->addHelpButton('groupmode', 'groupmode', 'group');
  533. }
  534. if ($this->_features->groupings) {
  535. // Groupings selector - used to select grouping for groups in activity.
  536. $options = array();
  537. if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
  538. foreach ($groupings as $grouping) {
  539. $options[$grouping->id] = format_string($grouping->name);
  540. }
  541. }
  542. core_collator::asort($options);
  543. $options = array(0 => get_string('none')) + $options;
  544. $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
  545. $mform->addHelpButton('groupingid', 'grouping', 'group');
  546. }
  547. if (!empty($CFG->enableavailability)) {
  548. // Add special button to end of previous section if groups/groupings
  549. // are enabled.
  550. if ($this->_features->groups || $this->_features->groupings) {
  551. $mform->addElement('static', 'restrictgroupbutton', '',
  552. html_writer::tag('button', get_string('restrictbygroup', 'availability'),
  553. array('id' => 'restrictbygroup', 'disabled' => 'disabled', 'class' => 'btn btn-secondary')));
  554. }
  555. // Availability field. This is just a textarea; the user interface
  556. // interaction is all implemented in JavaScript.
  557. $mform->addElement('header', 'availabilityconditionsheader',
  558. get_string('restrictaccess', 'availability'));
  559. // Note: This field cannot be named 'availability' because that
  560. // conflicts with fields in existing modules (such as assign).
  561. // So it uses a long name that will not conflict.
  562. $mform->addElement('textarea', 'availabilityconditionsjson',
  563. get_string('accessrestrictions', 'availability'));
  564. // The _cm variable may not be a proper cm_info, so get one from modinfo.
  565. if ($this->_cm) {
  566. $modinfo = get_fast_modinfo($COURSE);
  567. $cm = $modinfo->get_cm($this->_cm->id);
  568. } else {
  569. $cm = null;
  570. }
  571. \core_availability\frontend::include_all_javascript($COURSE, $cm);
  572. }
  573. // Conditional activities: completion tracking section
  574. if(!isset($completion)) {
  575. $completion = new completion_info($COURSE);
  576. }
  577. if ($completion->is_enabled()) {
  578. $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
  579. // Unlock button for if people have completed it (will
  580. // be removed in definition_after_data if they haven't)
  581. $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
  582. $mform->registerNoSubmitButton('unlockcompletion');
  583. $mform->addElement('hidden', 'completionunlocked', 0);
  584. $mform->setType('completionunlocked', PARAM_INT);
  585. $trackingdefault = COMPLETION_TRACKING_NONE;
  586. // If system and activity default is on, set it.
  587. if ($CFG->completiondefault && $this->_features->defaultcompletion) {
  588. $hasrules = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_HAS_RULES, true);
  589. $tracksviews = plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, true);
  590. if ($hasrules || $tracksviews) {
  591. $trackingdefault = COMPLETION_TRACKING_AUTOMATIC;
  592. } else {
  593. $trackingdefault = COMPLETION_TRACKING_MANUAL;
  594. }
  595. }
  596. $mform->addElement('select', 'completion', get_string('completion', 'completion'),
  597. array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
  598. COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
  599. $mform->setDefault('completion', $trackingdefault);
  600. $mform->addHelpButton('completion', 'completion', 'completion');
  601. // Automatic completion once you view it
  602. $gotcompletionoptions = false;
  603. if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
  604. $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
  605. get_string('completionview_desc', 'completion'));
  606. $mform->hideIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  607. // Check by default if automatic completion tracking is set.
  608. if ($trackingdefault == COMPLETION_TRACKING_AUTOMATIC) {
  609. $mform->setDefault('completionview', 1);
  610. }
  611. $gotcompletionoptions = true;
  612. }
  613. if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
  614. // This activity supports grading.
  615. $gotcompletionoptions = true;
  616. $component = "mod_{$this->_modname}";
  617. $itemnames = component_gradeitems::get_itemname_mapping_for_component($component);
  618. if (count($itemnames) === 1) {
  619. // Only one gradeitem in this activity.
  620. // We use the completionusegrade field here.
  621. $mform->addElement(
  622. 'checkbox',
  623. 'completionusegrade',
  624. get_string('completionusegrade', 'completion'),
  625. get_string('completionusegrade_desc', 'completion')
  626. );
  627. $mform->hideIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  628. $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
  629. // The disabledIf logic differs between ratings and other grade items due to different field types.
  630. if ($this->_features->rating) {
  631. // If using the rating system, there is no grade unless ratings are enabled.
  632. $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
  633. } else {
  634. // All other field types use the '$gradefieldname' field's modgrade_type.
  635. $itemnumbers = array_keys($itemnames);
  636. $itemnumber = array_shift($itemnumbers);
  637. $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
  638. $mform->disabledIf('completionusegrade', "{$gradefieldname}[modgrade_type]", 'eq', 'none');
  639. }
  640. } else if (count($itemnames) > 1) {
  641. // There are multiple grade items in this activity.
  642. // Show them all.
  643. $options = [
  644. '' => get_string('activitygradenotrequired', 'completion'),
  645. ];
  646. foreach ($itemnames as $itemnumber => $itemname) {
  647. $options[$itemnumber] = get_string("grade_{$itemname}_name", $component);
  648. }
  649. $mform->addElement(
  650. 'select',
  651. 'completiongradeitemnumber',
  652. get_string('completionusegrade', 'completion'),
  653. $options
  654. );
  655. $mform->hideIf('completiongradeitemnumber', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  656. }
  657. }
  658. // Automatic completion according to module-specific rules
  659. $this->_customcompletionelements = $this->add_completion_rules();
  660. foreach ($this->_customcompletionelements as $element) {
  661. $mform->hideIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  662. }
  663. $gotcompletionoptions = $gotcompletionoptions ||
  664. count($this->_customcompletionelements)>0;
  665. // Automatic option only appears if possible
  666. if ($gotcompletionoptions) {
  667. $mform->getElement('completion')->addOption(
  668. get_string('completion_automatic', 'completion'),
  669. COMPLETION_TRACKING_AUTOMATIC);
  670. }
  671. // Completion expected at particular date? (For progress tracking)
  672. $mform->addElement('date_time_selector', 'completionexpected', get_string('completionexpected', 'completion'),
  673. array('optional' => true));
  674. $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
  675. $mform->hideIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
  676. }
  677. // Populate module tags.
  678. if (core_tag_tag::is_enabled('core', 'course_modules')) {
  679. $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));
  680. $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'course_modules', 'component' => 'core'));
  681. if ($this->_cm) {
  682. $tags = core_tag_tag::get_item_tags_array('core', 'course_modules', $this->_cm->id);
  683. $mform->setDefault('tags', $tags);
  684. }
  685. }
  686. $this->standard_hidden_coursemodule_elements();
  687. $this->plugin_extend_coursemodule_standard_elements();
  688. }
  689. /**
  690. * Add rating settings.
  691. *
  692. * @param moodleform_mod $mform
  693. * @param int $itemnumber
  694. */
  695. protected function add_rating_settings($mform, int $itemnumber) {
  696. global $CFG, $COURSE;
  697. if ($this->gradedorrated && $this->gradedorrated !== 'rated') {
  698. return;
  699. }
  700. $this->gradedorrated = 'rated';
  701. require_once("{$CFG->dirroot}/rating/lib.php");
  702. $rm = new rating_manager();
  703. $component = "mod_{$this->_modname}";
  704. $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
  705. $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
  706. $assessedfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'assessed');
  707. $scalefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'scale');
  708. $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
  709. $isupdate = !empty($this->_cm);
  710. $rolenamestring = null;
  711. if ($isupdate) {
  712. $context = context_module::instance($this->_cm->id);
  713. $capabilities = ['moodle/rating:rate', "mod/{$this->_cm->modname}:rate"];
  714. $rolenames = get_role_names_with_caps_in_context($context, $capabilities);
  715. $rolenamestring = implode(', ', $rolenames);
  716. } else {
  717. $rolenamestring = get_string('capabilitychecknotavailable', 'rating');
  718. }
  719. $mform->addElement('static', 'rolewarning', get_string('rolewarning', 'rating'), $rolenamestring);
  720. $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
  721. $mform->addElement('select', $assessedfieldname, get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
  722. $mform->setDefault($assessedfieldname, 0);
  723. $mform->addHelpButton($assessedfieldname, 'aggregatetype', 'rating');
  724. $gradeoptions = [
  725. 'isupdate' => $isupdate,
  726. 'currentgrade' => false,
  727. 'hasgrades' => false,
  728. 'canrescale' => false,
  729. 'useratings' => true,
  730. ];
  731. if ($isupdate) {
  732. $gradeitem = grade_item::fetch([
  733. 'itemtype' => 'mod',
  734. 'itemmodule' => $this->_cm->modname,
  735. 'iteminstance' => $this->_cm->instance,
  736. 'itemnumber' => $itemnumber,
  737. 'courseid' => $COURSE->id,
  738. ]);
  739. if ($gradeitem) {
  740. $gradeoptions['currentgrade'] = $gradeitem->grademax;
  741. $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
  742. $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
  743. $gradeoptions['hasgrades'] = $gradeitem->has_grades();
  744. }
  745. }
  746. $mform->addElement('modgrade', $scalefieldname, get_string('scale'), $gradeoptions);
  747. $mform->hideIf($scalefieldname, $assessedfieldname, 'eq', 0);
  748. $mform->addHelpButton($scalefieldname, 'modgrade', 'grades');
  749. $mform->setDefault($scalefieldname, $CFG->gradepointdefault);
  750. $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
  751. $mform->hideIf('ratingtime', $assessedfieldname, 'eq', 0);
  752. $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
  753. $mform->hideIf('assesstimestart', $assessedfieldname, 'eq', 0);
  754. $mform->hideIf('assesstimestart', 'ratingtime');
  755. $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
  756. $mform->hideIf('assesstimefinish', $assessedfieldname, 'eq', 0);
  757. $mform->hideIf('assesstimefinish', 'ratingtime');
  758. if ($this->_features->gradecat) {
  759. $mform->addElement(
  760. 'select',
  761. $gradecatfieldname,
  762. get_string('gradecategoryonmodform', 'grades'),
  763. grade_get_categories_menu($COURSE->id, $this->_outcomesused)
  764. );
  765. $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
  766. $mform->hideIf($gradecatfieldname, $assessedfieldname, 'eq', 0);
  767. $mform->hideIf($gradecatfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
  768. }
  769. // Grade to pass.
  770. $mform->addElement('text', $gradepassfieldname, get_string('gradepass', 'grades'));
  771. $mform->addHelpButton($gradepassfieldname, 'gradepass', 'grades');
  772. $mform->setDefault($gradepassfieldname, '');
  773. $mform->setType($gradepassfieldname, PARAM_RAW);
  774. $mform->hideIf($gradepassfieldname, $assessedfieldname, 'eq', '0');
  775. $mform->hideIf($gradepassfieldname, "{$scalefieldname}[modgrade_type]", 'eq', 'none');
  776. }
  777. /**
  778. * Plugins can extend the coursemodule settings form.
  779. */
  780. protected function plugin_extend_coursemodule_standard_elements() {
  781. $callbacks = get_plugins_with_function('coursemodule_standard_elements', 'lib.php');
  782. foreach ($callbacks as $type => $plugins) {
  783. foreach ($plugins as $plugin => $pluginfunction) {
  784. // We have exposed all the important properties with public getters - and the callback can manipulate the mform
  785. // directly.
  786. $pluginfunction($this, $this->_form);
  787. }
  788. }
  789. }
  790. /**
  791. * Can be overridden to add custom completion rules if the module wishes
  792. * them. If overriding this, you should also override completion_rule_enabled.
  793. * <p>
  794. * Just add elements to the form as needed and return the list of IDs. The
  795. * system will call disabledIf and handle other behaviour for each returned
  796. * ID.
  797. * @return array Array of string IDs of added items, empty array if none
  798. */
  799. function add_completion_rules() {
  800. return array();
  801. }
  802. /**
  803. * Called during validation. Override to indicate, based on the data, whether
  804. * a custom completion rule is enabled (selected).
  805. *
  806. * @param array $data Input data (not yet validated)
  807. * @return bool True if one or more rules is enabled, false if none are;
  808. * default returns false
  809. */
  810. function completion_rule_enabled($data) {
  811. return false;
  812. }
  813. function standard_hidden_coursemodule_elements(){
  814. $mform =& $this->_form;
  815. $mform->addElement('hidden', 'course', 0);
  816. $mform->setType('course', PARAM_INT);
  817. $mform->addElement('hidden', 'coursemodule', 0);
  818. $mform->setType('coursemodule', PARAM_INT);
  819. $mform->addElement('hidden', 'section', 0);
  820. $mform->setType('section', PARAM_INT);
  821. $mform->addElement('hidden', 'module', 0);
  822. $mform->setType('module', PARAM_INT);
  823. $mform->addElement('hidden', 'modulename', '');
  824. $mform->setType('modulename', PARAM_PLUGIN);
  825. $mform->addElement('hidden', 'instance', 0);
  826. $mform->setType('instance', PARAM_INT);
  827. $mform->addElement('hidden', 'add', 0);
  828. $mform->setType('add', PARAM_ALPHANUM);
  829. $mform->addElement('hidden', 'update', 0);
  830. $mform->setType('update', PARAM_INT);
  831. $mform->addElement('hidden', 'return', 0);
  832. $mform->setType('return', PARAM_BOOL);
  833. $mform->addElement('hidden', 'sr', 0);
  834. $mform->setType('sr', PARAM_INT);
  835. }
  836. public function standard_grading_coursemodule_elements() {
  837. global $COURSE, $CFG;
  838. if ($this->gradedorrated && $this->gradedorrated !== 'graded') {
  839. return;
  840. }
  841. if ($this->_features->rating) {
  842. return;
  843. }
  844. $this->gradedorrated = 'graded';
  845. $itemnumber = 0;
  846. $component = "mod_{$this->_modname}";
  847. $gradefieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'grade');
  848. $gradecatfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradecat');
  849. $gradepassfieldname = component_gradeitems::get_field_name_for_itemnumber($component, $itemnumber, 'gradepass');
  850. $mform =& $this->_form;
  851. $isupdate = !empty($this->_cm);
  852. $gradeoptions = array('isupdate' => $isupdate,
  853. 'currentgrade' => false,
  854. 'hasgrades' => false,
  855. 'canrescale' => $this->_features->canrescale,
  856. 'useratings' => $this->_features->rating);
  857. if ($this->_features->hasgrades) {
  858. if ($this->_features->gradecat) {
  859. $mform->addElement('header', 'modstandardgrade', get_string('grade'));
  860. }
  861. //if supports grades and grades arent being handled via ratings
  862. if ($isupdate) {
  863. $gradeitem = grade_item::fetch(array('itemtype' => 'mod',
  864. 'itemmodule' => $this->_cm->modname,
  865. 'iteminstance' => $this->_cm->instance,
  866. 'itemnumber' => 0,
  867. 'courseid' => $COURSE->id));
  868. if ($gradeitem) {
  869. $gradeoptions['currentgrade'] = $gradeitem->grademax;
  870. $gradeoptions['currentgradetype'] = $gradeitem->gradetype;
  871. $gradeoptions['currentscaleid'] = $gradeitem->scaleid;
  872. $gradeoptions['hasgrades'] = $gradeitem->has_grades();
  873. }
  874. }
  875. $mform->addElement('modgrade', $gradefieldname, get_string('grade'), $gradeoptions);
  876. $mform->addHelpButton($gradefieldname, 'modgrade', 'grades');
  877. $mform->setDefault($gradefieldname, $CFG->gradepointdefault);
  878. if ($this->_features->advancedgrading
  879. and !empty($this->current->_advancedgradingdata['methods'])
  880. and !empty($this->current->_advancedgradingdata['areas'])) {
  881. if (count($this->current->_advancedgradingdata['areas']) == 1) {
  882. // if there is just one gradable area (most cases), display just the selector
  883. // without its name to make UI simplier
  884. $areadata = reset($this->current->_advancedgradingdata['areas']);
  885. $areaname = key($this->current->_advancedgradingdata['areas']);
  886. $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
  887. get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
  888. $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
  889. $mform->hideIf('advancedgradingmethod_'.$areaname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
  890. } else {
  891. // the module defines multiple gradable areas, display a selector
  892. // for each of them together with a name of the area
  893. $areasgroup = array();
  894. foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
  895. $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
  896. $areadata['title'], $this->current->_advancedgradingdata['methods']);
  897. $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
  898. }
  899. $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
  900. array(' ', '<br />'), false);
  901. }
  902. }
  903. if ($this->_features->gradecat) {
  904. $mform->addElement('select', $gradecatfieldname,
  905. get_string('gradecategoryonmodform', 'grades'),
  906. grade_get_categories_menu($COURSE->id, $this->_outcomesused));
  907. $mform->addHelpButton($gradecatfieldname, 'gradecategoryonmodform', 'grades');
  908. $mform->hideIf($gradecatfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
  909. }
  910. // Grade to pass.
  911. $mform->addElement('text', $gradepassfieldname, get_string($gradepassfieldname, 'grades'));
  912. $mform->addHelpButton($gradepassfieldname, $gradepassfieldname, 'grades');
  913. $mform->setDefault($gradepassfieldname, '');
  914. $mform->setType($gradepassfieldname, PARAM_RAW);
  915. $mform->hideIf($gradepassfieldname, "{$gradefieldname}[modgrade_type]", 'eq', 'none');
  916. }
  917. }
  918. /**
  919. * Add an editor for an activity's introduction field.
  920. * @deprecated since MDL-49101 - use moodleform_mod::standard_intro_elements() instead.
  921. * @param null $required Override system default for requiremodintro
  922. * @param null $customlabel Override default label for editor
  923. * @throws coding_exception
  924. */
  925. protected function add_intro_editor($required=null, $customlabel=null) {
  926. $str = "Function moodleform_mod::add_intro_editor() is deprecated, use moodleform_mod::standard_intro_elements() instead.";
  927. debugging($str, DEBUG_DEVELOPER);
  928. $this->standard_intro_elements($customlabel);
  929. }
  930. /**
  931. * Add an editor for an activity's introduction field.
  932. *
  933. * @param null $customlabel Override default label for editor
  934. * @throws coding_exception
  935. */
  936. protected function standard_intro_elements($customlabel=null) {
  937. global $CFG;
  938. $required = $CFG->requiremodintro;
  939. $mform = $this->_form;
  940. $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
  941. $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
  942. 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
  943. $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
  944. if ($required) {
  945. $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
  946. }
  947. // If the 'show description' feature is enabled, this checkbox appears below the intro.
  948. // We want to hide that when using the singleactivity course format because it is confusing.
  949. if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
  950. $mform->addElement('advcheckbox', 'showdescription', get_string('showdescription'));
  951. $mform->addHelpButton('showdescription', 'showdescription');
  952. }
  953. }
  954. /**
  955. * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
  956. *
  957. * @param bool $cancel show cancel button
  958. * @param string $submitlabel null means default, false means none, string is label text
  959. * @param string $submit2label null means default, false means none, string is label text
  960. * @return void
  961. */
  962. function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
  963. if (is_null($submitlabel)) {
  964. $submitlabel = get_string('savechangesanddisplay');
  965. }
  966. if

Large files files are truncated, but you can click here to view the full file