PageRenderTime 322ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/course/moodleform_mod.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 994 lines | 686 code | 131 blank | 177 comment | 141 complexity | 2baa6569fd19a90fa328da6e82eaa7ee MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. require_once ($CFG->libdir.'/formslib.php');
  3. require_once($CFG->libdir.'/completionlib.php');
  4. /**
  5. * This class adds extra methods to form wrapper specific to be used for module
  6. * add / update forms mod/{modname}/mod_form.php replaced deprecated mod/{modname}/mod.html
  7. */
  8. abstract class moodleform_mod extends moodleform {
  9. /** Current data */
  10. protected $current;
  11. /**
  12. * Instance of the module that is being updated. This is the id of the {prefix}{modulename}
  13. * record. Can be used in form definition. Will be "" if this is an 'add' form and not an
  14. * update one.
  15. *
  16. * @var mixed
  17. */
  18. protected $_instance;
  19. /**
  20. * Section of course that module instance will be put in or is in.
  21. * This is always the section number itself (column 'section' from 'course_sections' table).
  22. *
  23. * @var mixed
  24. */
  25. protected $_section;
  26. /**
  27. * Course module record of the module that is being updated. Will be null if this is an 'add' form and not an
  28. * update one.
  29. *
  30. * @var mixed
  31. */
  32. protected $_cm;
  33. /**
  34. * List of modform features
  35. */
  36. protected $_features;
  37. /**
  38. * @var array Custom completion-rule elements, if enabled
  39. */
  40. protected $_customcompletionelements;
  41. /**
  42. * @var string name of module
  43. */
  44. protected $_modname;
  45. /** current context, course or module depends if already exists*/
  46. protected $context;
  47. /** a flag indicating whether outcomes are being used*/
  48. protected $_outcomesused;
  49. /**
  50. * @var bool A flag used to indicate that this module should lock settings
  51. * based on admin settings flags in definition_after_data.
  52. */
  53. protected $applyadminlockedflags = false;
  54. /** @var object The course format of the current course. */
  55. protected $courseformat;
  56. function moodleform_mod($current, $section, $cm, $course) {
  57. global $CFG;
  58. $this->current = $current;
  59. $this->_instance = $current->instance;
  60. $this->_section = $section;
  61. $this->_cm = $cm;
  62. if ($this->_cm) {
  63. $this->context = context_module::instance($this->_cm->id);
  64. } else {
  65. $this->context = context_course::instance($course->id);
  66. }
  67. // Set the course format.
  68. require_once($CFG->dirroot . '/course/format/lib.php');
  69. $this->courseformat = course_get_format($course);
  70. // Guess module name
  71. $matches = array();
  72. if (!preg_match('/^mod_([^_]+)_mod_form$/', get_class($this), $matches)) {
  73. debugging('Use $modname parameter or rename form to mod_xx_mod_form, where xx is name of your module');
  74. print_error('unknownmodulename');
  75. }
  76. $this->_modname = $matches[1];
  77. $this->init_features();
  78. parent::moodleform('modedit.php');
  79. }
  80. protected function init_features() {
  81. global $CFG;
  82. $this->_features = new stdClass();
  83. $this->_features->groups = plugin_supports('mod', $this->_modname, FEATURE_GROUPS, true);
  84. $this->_features->groupings = plugin_supports('mod', $this->_modname, FEATURE_GROUPINGS, false);
  85. $this->_features->groupmembersonly = (!empty($CFG->enablegroupmembersonly) and plugin_supports('mod', $this->_modname, FEATURE_GROUPMEMBERSONLY, false));
  86. $this->_features->outcomes = (!empty($CFG->enableoutcomes) and plugin_supports('mod', $this->_modname, FEATURE_GRADE_OUTCOMES, true));
  87. $this->_features->hasgrades = plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false);
  88. $this->_features->idnumber = plugin_supports('mod', $this->_modname, FEATURE_IDNUMBER, true);
  89. $this->_features->introeditor = plugin_supports('mod', $this->_modname, FEATURE_MOD_INTRO, true);
  90. $this->_features->defaultcompletion = plugin_supports('mod', $this->_modname, FEATURE_MODEDIT_DEFAULT_COMPLETION, true);
  91. $this->_features->rating = plugin_supports('mod', $this->_modname, FEATURE_RATE, false);
  92. $this->_features->showdescription = plugin_supports('mod', $this->_modname, FEATURE_SHOW_DESCRIPTION, false);
  93. $this->_features->gradecat = ($this->_features->outcomes or $this->_features->hasgrades);
  94. $this->_features->advancedgrading = plugin_supports('mod', $this->_modname, FEATURE_ADVANCED_GRADING, false);
  95. }
  96. /**
  97. * Only available on moodleform_mod.
  98. *
  99. * @param array $default_values passed by reference
  100. */
  101. function data_preprocessing(&$default_values){
  102. if (empty($default_values['scale'])) {
  103. $default_values['assessed'] = 0;
  104. }
  105. if (empty($default_values['assessed'])){
  106. $default_values['ratingtime'] = 0;
  107. } else {
  108. $default_values['ratingtime']=
  109. ($default_values['assesstimestart'] && $default_values['assesstimefinish']) ? 1 : 0;
  110. }
  111. }
  112. /**
  113. * Each module which defines definition_after_data() must call this method using parent::definition_after_data();
  114. */
  115. function definition_after_data() {
  116. global $CFG, $COURSE;
  117. $mform =& $this->_form;
  118. if ($id = $mform->getElementValue('update')) {
  119. $modulename = $mform->getElementValue('modulename');
  120. $instance = $mform->getElementValue('instance');
  121. if ($this->_features->gradecat) {
  122. $gradecat = false;
  123. if (!empty($CFG->enableoutcomes) and $this->_features->outcomes) {
  124. $outcomes = grade_outcome::fetch_all_available($COURSE->id);
  125. if (!empty($outcomes)) {
  126. $gradecat = true;
  127. }
  128. }
  129. $items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,'iteminstance'=>$instance, 'courseid'=>$COURSE->id));
  130. //will be no items if, for example, this activity supports ratings but rating aggregate type == no ratings
  131. if (!empty($items)) {
  132. foreach ($items as $item) {
  133. if (!empty($item->outcomeid)) {
  134. $elname = 'outcome_'.$item->outcomeid;
  135. if ($mform->elementExists($elname)) {
  136. $mform->hardFreeze($elname); // prevent removing of existing outcomes
  137. }
  138. }
  139. }
  140. foreach ($items as $item) {
  141. if (is_bool($gradecat)) {
  142. $gradecat = $item->categoryid;
  143. continue;
  144. }
  145. if ($gradecat != $item->categoryid) {
  146. //mixed categories
  147. $gradecat = false;
  148. break;
  149. }
  150. }
  151. }
  152. if ($gradecat === false) {
  153. // items and outcomes in different categories - remove the option
  154. // TODO: add a "Mixed categories" text instead of removing elements with no explanation
  155. if ($mform->elementExists('gradecat')) {
  156. $mform->removeElement('gradecat');
  157. if ($this->_features->rating) {
  158. //if supports ratings then the max grade dropdown wasnt added so the grade box can be removed entirely
  159. $mform->removeElement('modstandardgrade');
  160. }
  161. }
  162. }
  163. }
  164. }
  165. if ($COURSE->groupmodeforce) {
  166. if ($mform->elementExists('groupmode')) {
  167. $mform->hardFreeze('groupmode'); // groupmode can not be changed if forced from course settings
  168. }
  169. }
  170. // Don't disable/remove groupingid if it is currently set to something,
  171. // otherwise you cannot turn it off at same time as turning off other
  172. // option (MDL-30764)
  173. if (empty($this->_cm) || !$this->_cm->groupingid) {
  174. if ($mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly') and empty($COURSE->groupmodeforce)) {
  175. $mform->disabledIf('groupingid', 'groupmode', 'eq', NOGROUPS);
  176. } else if (!$mform->elementExists('groupmode') and $mform->elementExists('groupmembersonly')) {
  177. $mform->disabledIf('groupingid', 'groupmembersonly', 'notchecked');
  178. } else if (!$mform->elementExists('groupmode') and !$mform->elementExists('groupmembersonly')) {
  179. // groupings have no use without groupmode or groupmembersonly
  180. if ($mform->elementExists('groupingid')) {
  181. $mform->removeElement('groupingid');
  182. }
  183. }
  184. }
  185. // Completion: If necessary, freeze fields
  186. $completion = new completion_info($COURSE);
  187. if ($completion->is_enabled()) {
  188. // If anybody has completed the activity, these options will be 'locked'
  189. $completedcount = empty($this->_cm)
  190. ? 0
  191. : $completion->count_user_data($this->_cm);
  192. $freeze = false;
  193. if (!$completedcount) {
  194. if ($mform->elementExists('unlockcompletion')) {
  195. $mform->removeElement('unlockcompletion');
  196. }
  197. // Automatically set to unlocked (note: this is necessary
  198. // in order to make it recalculate completion once the option
  199. // is changed, maybe someone has completed it now)
  200. $mform->getElement('completionunlocked')->setValue(1);
  201. } else {
  202. // Has the element been unlocked, either by the button being pressed
  203. // in this request, or the field already being set from a previous one?
  204. if ($mform->exportValue('unlockcompletion') ||
  205. $mform->exportValue('completionunlocked')) {
  206. // Yes, add in warning text and set the hidden variable
  207. $mform->insertElementBefore(
  208. $mform->createElement('static', 'completedunlocked',
  209. get_string('completedunlocked', 'completion'),
  210. get_string('completedunlockedtext', 'completion')),
  211. 'unlockcompletion');
  212. $mform->removeElement('unlockcompletion');
  213. $mform->getElement('completionunlocked')->setValue(1);
  214. } else {
  215. // No, add in the warning text with the count (now we know
  216. // it) before the unlock button
  217. $mform->insertElementBefore(
  218. $mform->createElement('static', 'completedwarning',
  219. get_string('completedwarning', 'completion'),
  220. get_string('completedwarningtext', 'completion', $completedcount)),
  221. 'unlockcompletion');
  222. $freeze = true;
  223. }
  224. }
  225. if ($freeze) {
  226. $mform->freeze('completion');
  227. if ($mform->elementExists('completionview')) {
  228. $mform->freeze('completionview'); // don't use hardFreeze or checkbox value gets lost
  229. }
  230. if ($mform->elementExists('completionusegrade')) {
  231. $mform->freeze('completionusegrade');
  232. }
  233. $mform->freeze($this->_customcompletionelements);
  234. }
  235. }
  236. // Availability conditions
  237. if (!empty($CFG->enableavailability) && $this->_cm) {
  238. $ci = new condition_info($this->_cm);
  239. $fullcm=$ci->get_full_course_module();
  240. $num=0;
  241. foreach($fullcm->conditionsgrade as $gradeitemid=>$minmax) {
  242. $groupelements=$mform->getElement('conditiongradegroup['.$num.']')->getElements();
  243. $groupelements[0]->setValue($gradeitemid);
  244. $groupelements[2]->setValue(is_null($minmax->min) ? '' :
  245. format_float($minmax->min, 5, true, true));
  246. $groupelements[4]->setValue(is_null($minmax->max) ? '' :
  247. format_float($minmax->max, 5, true, true));
  248. $num++;
  249. }
  250. $num = 0;
  251. foreach($fullcm->conditionsfield as $field => $details) {
  252. $groupelements = $mform->getElement('conditionfieldgroup['.$num.']')->getElements();
  253. $groupelements[0]->setValue($field);
  254. $groupelements[1]->setValue(is_null($details->operator) ? '' : $details->operator);
  255. $groupelements[2]->setValue(is_null($details->value) ? '' : $details->value);
  256. $num++;
  257. }
  258. if ($completion->is_enabled()) {
  259. $num=0;
  260. foreach($fullcm->conditionscompletion as $othercmid=>$state) {
  261. $groupelements=$mform->getElement('conditioncompletiongroup['.$num.']')->getElements();
  262. $groupelements[0]->setValue($othercmid);
  263. $groupelements[1]->setValue($state);
  264. $num++;
  265. }
  266. }
  267. }
  268. // Freeze admin defaults if required (and not different from default)
  269. $this->apply_admin_locked_flags();
  270. }
  271. // form verification
  272. function validation($data, $files) {
  273. global $COURSE, $DB;
  274. $errors = parent::validation($data, $files);
  275. $mform =& $this->_form;
  276. $errors = array();
  277. if ($mform->elementExists('name')) {
  278. $name = trim($data['name']);
  279. if ($name == '') {
  280. $errors['name'] = get_string('required');
  281. }
  282. }
  283. $grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$data['modulename'],
  284. 'iteminstance'=>$data['instance'], 'itemnumber'=>0, 'courseid'=>$COURSE->id));
  285. if ($data['coursemodule']) {
  286. $cm = $DB->get_record('course_modules', array('id'=>$data['coursemodule']));
  287. } else {
  288. $cm = null;
  289. }
  290. if ($mform->elementExists('cmidnumber')) {
  291. // verify the idnumber
  292. if (!grade_verify_idnumber($data['cmidnumber'], $COURSE->id, $grade_item, $cm)) {
  293. $errors['cmidnumber'] = get_string('idnumbertaken');
  294. }
  295. }
  296. // Completion: Don't let them choose automatic completion without turning
  297. // on some conditions. Ignore this check when completion settings are
  298. // locked, as the options are then disabled.
  299. if (array_key_exists('completion', $data) &&
  300. $data['completion'] == COMPLETION_TRACKING_AUTOMATIC &&
  301. !empty($data['completionunlocked'])) {
  302. if (empty($data['completionview']) && empty($data['completionusegrade']) &&
  303. !$this->completion_rule_enabled($data)) {
  304. $errors['completion'] = get_string('badautocompletion', 'completion');
  305. }
  306. }
  307. // Conditions: Don't let them set dates which make no sense
  308. if (array_key_exists('availablefrom', $data) &&
  309. $data['availablefrom'] && $data['availableuntil'] &&
  310. $data['availablefrom'] >= $data['availableuntil']) {
  311. $errors['availablefrom'] = get_string('badavailabledates', 'condition');
  312. }
  313. // Conditions: Verify that the grade conditions are numbers, and make sense.
  314. if (array_key_exists('conditiongradegroup', $data)) {
  315. foreach ($data['conditiongradegroup'] as $i => $gradedata) {
  316. if ($gradedata['conditiongrademin'] !== '' &&
  317. !is_numeric(unformat_float($gradedata['conditiongrademin']))) {
  318. $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
  319. continue;
  320. }
  321. if ($gradedata['conditiongrademax'] !== '' &&
  322. !is_numeric(unformat_float($gradedata['conditiongrademax']))) {
  323. $errors["conditiongradegroup[{$i}]"] = get_string('gradesmustbenumeric', 'condition');
  324. continue;
  325. }
  326. if ($gradedata['conditiongrademin'] !== '' && $gradedata['conditiongrademax'] !== '' &&
  327. unformat_float($gradedata['conditiongrademax']) <= unformat_float($gradedata['conditiongrademin'])) {
  328. $errors["conditiongradegroup[{$i}]"] = get_string('badgradelimits', 'condition');
  329. continue;
  330. }
  331. if ($gradedata['conditiongrademin'] === '' && $gradedata['conditiongrademax'] === '' &&
  332. $gradedata['conditiongradeitemid']) {
  333. $errors["conditiongradegroup[{$i}]"] = get_string('gradeitembutnolimits', 'condition');
  334. continue;
  335. }
  336. if (($gradedata['conditiongrademin'] !== '' || $gradedata['conditiongrademax'] !== '') &&
  337. !$gradedata['conditiongradeitemid']) {
  338. $errors["conditiongradegroup[{$i}]"] = get_string('gradelimitsbutnoitem', 'condition');
  339. continue;
  340. }
  341. }
  342. }
  343. // Conditions: Verify that the user profile field has not been declared more than once
  344. if (array_key_exists('conditionfieldgroup', $data)) {
  345. // Array to store the existing fields
  346. $arrcurrentfields = array();
  347. // Error message displayed if any condition is declared more than once. We use lang string because
  348. // this way we don't actually generate the string unless there is an error.
  349. $stralreadydeclaredwarning = new lang_string('fielddeclaredmultipletimes', 'condition');
  350. foreach ($data['conditionfieldgroup'] as $i => $fielddata) {
  351. if ($fielddata['conditionfield'] == 0) { // Don't need to bother if none is selected
  352. continue;
  353. }
  354. if (in_array($fielddata['conditionfield'], $arrcurrentfields)) {
  355. $errors["conditionfieldgroup[{$i}]"] = $stralreadydeclaredwarning->out();
  356. }
  357. // Add the field to the array
  358. $arrcurrentfields[] = $fielddata['conditionfield'];
  359. }
  360. }
  361. return $errors;
  362. }
  363. /**
  364. * Load in existing data as form defaults. Usually new entry defaults are stored directly in
  365. * form definition (new entry form); this function is used to load in data where values
  366. * already exist and data is being edited (edit entry form).
  367. *
  368. * @param mixed $default_values object or array of default values
  369. */
  370. function set_data($default_values) {
  371. if (is_object($default_values)) {
  372. $default_values = (array)$default_values;
  373. }
  374. $this->data_preprocessing($default_values);
  375. parent::set_data($default_values);
  376. }
  377. /**
  378. * Adds all the standard elements to a form to edit the settings for an activity module.
  379. */
  380. function standard_coursemodule_elements(){
  381. global $COURSE, $CFG, $DB;
  382. $mform =& $this->_form;
  383. $this->_outcomesused = false;
  384. if ($this->_features->outcomes) {
  385. if ($outcomes = grade_outcome::fetch_all_available($COURSE->id)) {
  386. $this->_outcomesused = true;
  387. $mform->addElement('header', 'modoutcomes', get_string('outcomes', 'grades'));
  388. foreach($outcomes as $outcome) {
  389. $mform->addElement('advcheckbox', 'outcome_'.$outcome->id, $outcome->get_name());
  390. }
  391. }
  392. }
  393. if ($this->_features->rating) {
  394. require_once($CFG->dirroot.'/rating/lib.php');
  395. $rm = new rating_manager();
  396. $mform->addElement('header', 'modstandardratings', get_string('ratings', 'rating'));
  397. $permission=CAP_ALLOW;
  398. $rolenamestring = null;
  399. if (!empty($this->_cm)) {
  400. $context = context_module::instance($this->_cm->id);
  401. $rolenames = get_role_names_with_caps_in_context($context, array('moodle/rating:rate', 'mod/'.$this->_cm->modname.':rate'));
  402. $rolenamestring = implode(', ', $rolenames);
  403. } else {
  404. $rolenamestring = get_string('capabilitychecknotavailable','rating');
  405. }
  406. $mform->addElement('static', 'rolewarning', get_string('rolewarning','rating'), $rolenamestring);
  407. $mform->addHelpButton('rolewarning', 'rolewarning', 'rating');
  408. $mform->addElement('select', 'assessed', get_string('aggregatetype', 'rating') , $rm->get_aggregate_types());
  409. $mform->setDefault('assessed', 0);
  410. $mform->addHelpButton('assessed', 'aggregatetype', 'rating');
  411. $mform->addElement('modgrade', 'scale', get_string('scale'), false);
  412. $mform->disabledIf('scale', 'assessed', 'eq', 0);
  413. $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'rating'));
  414. $mform->disabledIf('ratingtime', 'assessed', 'eq', 0);
  415. $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
  416. $mform->disabledIf('assesstimestart', 'assessed', 'eq', 0);
  417. $mform->disabledIf('assesstimestart', 'ratingtime');
  418. $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
  419. $mform->disabledIf('assesstimefinish', 'assessed', 'eq', 0);
  420. $mform->disabledIf('assesstimefinish', 'ratingtime');
  421. }
  422. //doing this here means splitting up the grade related settings on the lesson settings page
  423. //$this->standard_grading_coursemodule_elements();
  424. $mform->addElement('header', 'modstandardelshdr', get_string('modstandardels', 'form'));
  425. $mform->addElement('modvisible', 'visible', get_string('visible'));
  426. if (!empty($this->_cm)) {
  427. $context = context_module::instance($this->_cm->id);
  428. if (!has_capability('moodle/course:activityvisibility', $context)) {
  429. $mform->hardFreeze('visible');
  430. }
  431. }
  432. if ($this->_features->idnumber) {
  433. $mform->addElement('text', 'cmidnumber', get_string('idnumbermod'));
  434. $mform->setType('cmidnumber', PARAM_RAW);
  435. $mform->addHelpButton('cmidnumber', 'idnumbermod');
  436. }
  437. if ($this->_features->groups) {
  438. $options = array(NOGROUPS => get_string('groupsnone'),
  439. SEPARATEGROUPS => get_string('groupsseparate'),
  440. VISIBLEGROUPS => get_string('groupsvisible'));
  441. $mform->addElement('select', 'groupmode', get_string('groupmode', 'group'), $options, NOGROUPS);
  442. $mform->addHelpButton('groupmode', 'groupmode', 'group');
  443. }
  444. if ($this->_features->groupings or $this->_features->groupmembersonly) {
  445. //groupings selector - used for normal grouping mode or also when restricting access with groupmembersonly
  446. $options = array();
  447. if ($groupings = $DB->get_records('groupings', array('courseid'=>$COURSE->id))) {
  448. foreach ($groupings as $grouping) {
  449. $options[$grouping->id] = format_string($grouping->name);
  450. }
  451. }
  452. core_collator::asort($options);
  453. $options = array(0 => get_string('none')) + $options;
  454. $mform->addElement('select', 'groupingid', get_string('grouping', 'group'), $options);
  455. $mform->addHelpButton('groupingid', 'grouping', 'group');
  456. }
  457. if ($this->_features->groupmembersonly) {
  458. $mform->addElement('checkbox', 'groupmembersonly', get_string('groupmembersonly', 'group'));
  459. $mform->addHelpButton('groupmembersonly', 'groupmembersonly', 'group');
  460. }
  461. if (!empty($CFG->enableavailability)) {
  462. // String used by conditions
  463. $strnone = get_string('none','condition');
  464. // Conditional availability
  465. // Available from/to defaults to midnight because then the display
  466. // will be nicer where it tells users when they can access it (it
  467. // shows only the date and not time).
  468. $date = usergetdate(time());
  469. $midnight = make_timestamp($date['year'], $date['mon'], $date['mday']);
  470. // From/until controls
  471. $mform->addElement('header', 'availabilityconditionsheader',
  472. get_string('availabilityconditions', 'condition'));
  473. $mform->addElement('date_time_selector', 'availablefrom',
  474. get_string('availablefrom', 'condition'),
  475. array('optional' => true, 'defaulttime' => $midnight));
  476. $mform->addHelpButton('availablefrom', 'availablefrom', 'condition');
  477. $mform->addElement('date_time_selector', 'availableuntil',
  478. get_string('availableuntil', 'condition'),
  479. array('optional' => true, 'defaulttime' => $midnight));
  480. // Conditions based on grades
  481. $gradeoptions = array();
  482. $items = grade_item::fetch_all(array('courseid'=>$COURSE->id));
  483. $items = $items ? $items : array();
  484. foreach($items as $id=>$item) {
  485. // Do not include grades for current item
  486. if (!empty($this->_cm) && $this->_cm->instance == $item->iteminstance
  487. && $this->_cm->modname == $item->itemmodule
  488. && $item->itemtype == 'mod') {
  489. continue;
  490. }
  491. $gradeoptions[$id] = $item->get_name();
  492. }
  493. asort($gradeoptions);
  494. $gradeoptions = array(0 => $strnone) + $gradeoptions;
  495. $grouparray = array();
  496. $grouparray[] =& $mform->createElement('select','conditiongradeitemid','',$gradeoptions);
  497. $grouparray[] =& $mform->createElement('static', '', '',' '.get_string('grade_atleast','condition').' ');
  498. $grouparray[] =& $mform->createElement('text', 'conditiongrademin','',array('size'=>3));
  499. $grouparray[] =& $mform->createElement('static', '', '','% '.get_string('grade_upto','condition').' ');
  500. $grouparray[] =& $mform->createElement('text', 'conditiongrademax','',array('size'=>3));
  501. $grouparray[] =& $mform->createElement('static', '', '','%');
  502. $group = $mform->createElement('group','conditiongradegroup',
  503. get_string('gradecondition', 'condition'),$grouparray);
  504. // Get version with condition info and store it so we don't ask
  505. // twice
  506. if(!empty($this->_cm)) {
  507. $ci = new condition_info($this->_cm, CONDITION_MISSING_EXTRATABLE);
  508. $this->_cm = $ci->get_full_course_module();
  509. $count = count($this->_cm->conditionsgrade)+1;
  510. $fieldcount = count($this->_cm->conditionsfield) + 1;
  511. } else {
  512. $count = 1;
  513. $fieldcount = 1;
  514. }
  515. $this->repeat_elements(array($group), $count, array(
  516. 'conditiongradegroup[conditiongrademin]' => array('type' => PARAM_RAW),
  517. 'conditiongradegroup[conditiongrademax]' => array('type' => PARAM_RAW)
  518. ), 'conditiongraderepeats', 'conditiongradeadds', 2, get_string('addgrades', 'condition'), true);
  519. $mform->addHelpButton('conditiongradegroup[0]', 'gradecondition', 'condition');
  520. // Conditions based on user fields
  521. $operators = condition_info::get_condition_user_field_operators();
  522. $useroptions = condition_info::get_condition_user_fields(
  523. array('context' => $this->context));
  524. asort($useroptions);
  525. $useroptions = array(0 => $strnone) + $useroptions;
  526. $grouparray = array();
  527. $grouparray[] =& $mform->createElement('select', 'conditionfield', '', $useroptions);
  528. $grouparray[] =& $mform->createElement('select', 'conditionfieldoperator', '', $operators);
  529. $grouparray[] =& $mform->createElement('text', 'conditionfieldvalue');
  530. $group = $mform->createElement('group', 'conditionfieldgroup', get_string('userfield', 'condition'), $grouparray);
  531. $this->repeat_elements(array($group), $fieldcount, array(
  532. 'conditionfieldgroup[conditionfieldvalue]' => array('type' => PARAM_RAW)),
  533. 'conditionfieldrepeats', 'conditionfieldadds', 2, get_string('adduserfields', 'condition'), true);
  534. $mform->addHelpButton('conditionfieldgroup[0]', 'userfield', 'condition');
  535. // Conditions based on completion
  536. $completion = new completion_info($COURSE);
  537. if ($completion->is_enabled()) {
  538. $completionoptions = array();
  539. $modinfo = get_fast_modinfo($COURSE);
  540. foreach($modinfo->cms as $id=>$cm) {
  541. // Add each course-module if it:
  542. // (a) has completion turned on
  543. // (b) is not the same as current course-module
  544. if ($cm->completion && (empty($this->_cm) || $this->_cm->id != $id)) {
  545. $completionoptions[$id]=$cm->name;
  546. }
  547. }
  548. asort($completionoptions);
  549. $completionoptions = array(0 => $strnone) + $completionoptions;
  550. $completionvalues=array(
  551. COMPLETION_COMPLETE=>get_string('completion_complete','condition'),
  552. COMPLETION_INCOMPLETE=>get_string('completion_incomplete','condition'),
  553. COMPLETION_COMPLETE_PASS=>get_string('completion_pass','condition'),
  554. COMPLETION_COMPLETE_FAIL=>get_string('completion_fail','condition'));
  555. $grouparray = array();
  556. $grouparray[] =& $mform->createElement('select','conditionsourcecmid','',$completionoptions);
  557. $grouparray[] =& $mform->createElement('select','conditionrequiredcompletion','',$completionvalues);
  558. $group = $mform->createElement('group','conditioncompletiongroup',
  559. get_string('completioncondition', 'condition'),$grouparray);
  560. $count = empty($this->_cm) ? 1 : count($this->_cm->conditionscompletion)+1;
  561. $this->repeat_elements(array($group),$count,array(),
  562. 'conditioncompletionrepeats','conditioncompletionadds',2,
  563. get_string('addcompletions','condition'),true);
  564. $mform->addHelpButton('conditioncompletiongroup[0]', 'completioncondition', 'condition');
  565. }
  566. // Do we display availability info to students?
  567. $mform->addElement('select', 'showavailability', get_string('showavailability', 'condition'),
  568. array(CONDITION_STUDENTVIEW_SHOW=>get_string('showavailability_show', 'condition'),
  569. CONDITION_STUDENTVIEW_HIDE=>get_string('showavailability_hide', 'condition')));
  570. $mform->setDefault('showavailability', CONDITION_STUDENTVIEW_SHOW);
  571. }
  572. // Conditional activities: completion tracking section
  573. if(!isset($completion)) {
  574. $completion = new completion_info($COURSE);
  575. }
  576. if ($completion->is_enabled()) {
  577. $mform->addElement('header', 'activitycompletionheader', get_string('activitycompletion', 'completion'));
  578. // Unlock button for if people have completed it (will
  579. // be removed in definition_after_data if they haven't)
  580. $mform->addElement('submit', 'unlockcompletion', get_string('unlockcompletion', 'completion'));
  581. $mform->registerNoSubmitButton('unlockcompletion');
  582. $mform->addElement('hidden', 'completionunlocked', 0);
  583. $mform->setType('completionunlocked', PARAM_INT);
  584. $trackingdefault = COMPLETION_TRACKING_NONE;
  585. // If system and activity default is on, set it.
  586. if ($CFG->completiondefault && $this->_features->defaultcompletion) {
  587. $trackingdefault = COMPLETION_TRACKING_MANUAL;
  588. }
  589. $mform->addElement('select', 'completion', get_string('completion', 'completion'),
  590. array(COMPLETION_TRACKING_NONE=>get_string('completion_none', 'completion'),
  591. COMPLETION_TRACKING_MANUAL=>get_string('completion_manual', 'completion')));
  592. $mform->setDefault('completion', $trackingdefault);
  593. $mform->addHelpButton('completion', 'completion', 'completion');
  594. // Automatic completion once you view it
  595. $gotcompletionoptions = false;
  596. if (plugin_supports('mod', $this->_modname, FEATURE_COMPLETION_TRACKS_VIEWS, false)) {
  597. $mform->addElement('checkbox', 'completionview', get_string('completionview', 'completion'),
  598. get_string('completionview_desc', 'completion'));
  599. $mform->disabledIf('completionview', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  600. $gotcompletionoptions = true;
  601. }
  602. // Automatic completion once it's graded
  603. if (plugin_supports('mod', $this->_modname, FEATURE_GRADE_HAS_GRADE, false)) {
  604. $mform->addElement('checkbox', 'completionusegrade', get_string('completionusegrade', 'completion'),
  605. get_string('completionusegrade_desc', 'completion'));
  606. $mform->disabledIf('completionusegrade', 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  607. $mform->addHelpButton('completionusegrade', 'completionusegrade', 'completion');
  608. $gotcompletionoptions = true;
  609. // If using the rating system, there is no grade unless ratings are enabled.
  610. if ($this->_features->rating) {
  611. $mform->disabledIf('completionusegrade', 'assessed', 'eq', 0);
  612. }
  613. }
  614. // Automatic completion according to module-specific rules
  615. $this->_customcompletionelements = $this->add_completion_rules();
  616. foreach ($this->_customcompletionelements as $element) {
  617. $mform->disabledIf($element, 'completion', 'ne', COMPLETION_TRACKING_AUTOMATIC);
  618. }
  619. $gotcompletionoptions = $gotcompletionoptions ||
  620. count($this->_customcompletionelements)>0;
  621. // Automatic option only appears if possible
  622. if ($gotcompletionoptions) {
  623. $mform->getElement('completion')->addOption(
  624. get_string('completion_automatic', 'completion'),
  625. COMPLETION_TRACKING_AUTOMATIC);
  626. }
  627. // Completion expected at particular date? (For progress tracking)
  628. $mform->addElement('date_selector', 'completionexpected', get_string('completionexpected', 'completion'), array('optional'=>true));
  629. $mform->addHelpButton('completionexpected', 'completionexpected', 'completion');
  630. $mform->disabledIf('completionexpected', 'completion', 'eq', COMPLETION_TRACKING_NONE);
  631. }
  632. $this->standard_hidden_coursemodule_elements();
  633. }
  634. /**
  635. * Can be overridden to add custom completion rules if the module wishes
  636. * them. If overriding this, you should also override completion_rule_enabled.
  637. * <p>
  638. * Just add elements to the form as needed and return the list of IDs. The
  639. * system will call disabledIf and handle other behaviour for each returned
  640. * ID.
  641. * @return array Array of string IDs of added items, empty array if none
  642. */
  643. function add_completion_rules() {
  644. return array();
  645. }
  646. /**
  647. * Called during validation. Override to indicate, based on the data, whether
  648. * a custom completion rule is enabled (selected).
  649. *
  650. * @param array $data Input data (not yet validated)
  651. * @return bool True if one or more rules is enabled, false if none are;
  652. * default returns false
  653. */
  654. function completion_rule_enabled($data) {
  655. return false;
  656. }
  657. function standard_hidden_coursemodule_elements(){
  658. $mform =& $this->_form;
  659. $mform->addElement('hidden', 'course', 0);
  660. $mform->setType('course', PARAM_INT);
  661. $mform->addElement('hidden', 'coursemodule', 0);
  662. $mform->setType('coursemodule', PARAM_INT);
  663. $mform->addElement('hidden', 'section', 0);
  664. $mform->setType('section', PARAM_INT);
  665. $mform->addElement('hidden', 'module', 0);
  666. $mform->setType('module', PARAM_INT);
  667. $mform->addElement('hidden', 'modulename', '');
  668. $mform->setType('modulename', PARAM_PLUGIN);
  669. $mform->addElement('hidden', 'instance', 0);
  670. $mform->setType('instance', PARAM_INT);
  671. $mform->addElement('hidden', 'add', 0);
  672. $mform->setType('add', PARAM_ALPHA);
  673. $mform->addElement('hidden', 'update', 0);
  674. $mform->setType('update', PARAM_INT);
  675. $mform->addElement('hidden', 'return', 0);
  676. $mform->setType('return', PARAM_BOOL);
  677. $mform->addElement('hidden', 'sr', 0);
  678. $mform->setType('sr', PARAM_INT);
  679. }
  680. public function standard_grading_coursemodule_elements() {
  681. global $COURSE, $CFG;
  682. $mform =& $this->_form;
  683. if ($this->_features->hasgrades) {
  684. if (!$this->_features->rating || $this->_features->gradecat) {
  685. $mform->addElement('header', 'modstandardgrade', get_string('grade'));
  686. }
  687. //if supports grades and grades arent being handled via ratings
  688. if (!$this->_features->rating) {
  689. $mform->addElement('modgrade', 'grade', get_string('grade'));
  690. $mform->setDefault('grade', 100);
  691. }
  692. if ($this->_features->advancedgrading
  693. and !empty($this->current->_advancedgradingdata['methods'])
  694. and !empty($this->current->_advancedgradingdata['areas'])) {
  695. if (count($this->current->_advancedgradingdata['areas']) == 1) {
  696. // if there is just one gradable area (most cases), display just the selector
  697. // without its name to make UI simplier
  698. $areadata = reset($this->current->_advancedgradingdata['areas']);
  699. $areaname = key($this->current->_advancedgradingdata['areas']);
  700. $mform->addElement('select', 'advancedgradingmethod_'.$areaname,
  701. get_string('gradingmethod', 'core_grading'), $this->current->_advancedgradingdata['methods']);
  702. $mform->addHelpButton('advancedgradingmethod_'.$areaname, 'gradingmethod', 'core_grading');
  703. } else {
  704. // the module defines multiple gradable areas, display a selector
  705. // for each of them together with a name of the area
  706. $areasgroup = array();
  707. foreach ($this->current->_advancedgradingdata['areas'] as $areaname => $areadata) {
  708. $areasgroup[] = $mform->createElement('select', 'advancedgradingmethod_'.$areaname,
  709. $areadata['title'], $this->current->_advancedgradingdata['methods']);
  710. $areasgroup[] = $mform->createElement('static', 'advancedgradingareaname_'.$areaname, '', $areadata['title']);
  711. }
  712. $mform->addGroup($areasgroup, 'advancedgradingmethodsgroup', get_string('gradingmethods', 'core_grading'),
  713. array(' ', '<br />'), false);
  714. }
  715. }
  716. if ($this->_features->gradecat) {
  717. $mform->addElement('select', 'gradecat',
  718. get_string('gradecategoryonmodform', 'grades'),
  719. grade_get_categories_menu($COURSE->id, $this->_outcomesused));
  720. $mform->addHelpButton('gradecat', 'gradecategoryonmodform', 'grades');
  721. }
  722. }
  723. }
  724. function add_intro_editor($required=false, $customlabel=null) {
  725. if (!$this->_features->introeditor) {
  726. // intro editor not supported in this module
  727. return;
  728. }
  729. $mform = $this->_form;
  730. $label = is_null($customlabel) ? get_string('moduleintro') : $customlabel;
  731. $mform->addElement('editor', 'introeditor', $label, array('rows' => 10), array('maxfiles' => EDITOR_UNLIMITED_FILES,
  732. 'noclean' => true, 'context' => $this->context, 'subdirs' => true));
  733. $mform->setType('introeditor', PARAM_RAW); // no XSS prevention here, users must be trusted
  734. if ($required) {
  735. $mform->addRule('introeditor', get_string('required'), 'required', null, 'client');
  736. }
  737. // If the 'show description' feature is enabled, this checkbox appears below the intro.
  738. // We want to hide that when using the singleactivity course format because it is confusing.
  739. if ($this->_features->showdescription && $this->courseformat->has_view_page()) {
  740. $mform->addElement('checkbox', 'showdescription', get_string('showdescription'));
  741. $mform->addHelpButton('showdescription', 'showdescription');
  742. }
  743. }
  744. /**
  745. * Overriding formslib's add_action_buttons() method, to add an extra submit "save changes and return" button.
  746. *
  747. * @param bool $cancel show cancel button
  748. * @param string $submitlabel null means default, false means none, string is label text
  749. * @param string $submit2label null means default, false means none, string is label text
  750. * @return void
  751. */
  752. function add_action_buttons($cancel=true, $submitlabel=null, $submit2label=null) {
  753. if (is_null($submitlabel)) {
  754. $submitlabel = get_string('savechangesanddisplay');
  755. }
  756. if (is_null($submit2label)) {
  757. $submit2label = get_string('savechangesandreturntocourse');
  758. }
  759. $mform = $this->_form;
  760. // elements in a row need a group
  761. $buttonarray = array();
  762. // Label for the submit button to return to the course.
  763. // Ignore this button in single activity format because it is confusing.
  764. if ($submit2label !== false && $this->courseformat->has_view_page()) {
  765. $buttonarray[] = &$mform->createElement('submit', 'submitbutton2', $submit2label);
  766. }
  767. if ($submitlabel !== false) {
  768. $buttonarray[] = &$mform->createElement('submit', 'submitbutton', $submitlabel);
  769. }
  770. if ($cancel) {
  771. $buttonarray[] = &$mform->createElement('cancel');
  772. }
  773. $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
  774. $mform->setType('buttonar', PARAM_RAW);
  775. $mform->closeHeaderBefore('buttonar');
  776. }
  777. /**
  778. * Get the list of admin settings for this module and apply any locked settings.
  779. * This cannot happen in apply_admin_defaults because we do not the current values of the settings
  780. * in that function because set_data has not been called yet.
  781. *
  782. * @return void
  783. */
  784. protected function apply_admin_locked_flags() {
  785. global $OUTPUT;
  786. if (!$this->applyadminlockedflags) {
  787. return;
  788. }
  789. $settings = get_config($this->_modname);
  790. $mform = $this->_form;
  791. $lockedicon = html_writer::tag('span',
  792. $OUTPUT->pix_icon('t/locked', get_string('locked', 'admin')),
  793. array('class' => 'action-icon'));
  794. $isupdate = !empty($this->_cm);
  795. foreach ($settings as $name => $value) {
  796. if (strpos('_', $name) !== false) {
  797. continue;
  798. }
  799. if ($mform->elementExists($name)) {
  800. $element = $mform->getElement($name);
  801. $lockedsetting = $name . '_locked';
  802. if (!empty($settings->$lockedsetting)) {
  803. // Always lock locked settings for new modules,
  804. // for updates, only lock them if the current value is the same as the default (or there is no current value).
  805. $value = $settings->$name;
  806. if ($isupdate && isset($this->current->$name)) {
  807. $value = $this->current->$name;
  808. }
  809. if ($value == $settings->$name) {
  810. $mform->setConstant($name, $settings->$name);
  811. $element->setLabel($element->getLabel() . $lockedicon);
  812. // Do not use hardfreeze because we need the hidden input to check dependencies.
  813. $element->freeze();
  814. }
  815. }
  816. }
  817. }
  818. }
  819. /**
  820. * Get the list of admin settings for this module and apply any defaults/advanced/locked settings.
  821. *
  822. * @param $datetimeoffsets array - If passed, this is an array of fieldnames => times that the
  823. * default date/time value should be relative to. If not passed, all
  824. * date/time fields are set relative to the users current midnight.
  825. * @return void
  826. */
  827. public function apply_admin_defaults($datetimeoffsets = array()) {
  828. // This flag triggers the settings to be locked in apply_admin_locked_flags().
  829. $this->applyadminlockedflags = true;
  830. $settings = get_config($this->_modname);
  831. $mform = $this->_form;
  832. $usermidnight = usergetmidnight(time());
  833. $isupdate = !empty($this->_cm);
  834. foreach ($settings as $name => $value) {
  835. if (strpos('_', $name) !== false) {
  836. continue;
  837. }
  838. if ($mform->elementExists($name)) {
  839. $element = $mform->getElement($name);
  840. if (!$isupdate) {
  841. if ($element->getType() == 'date_time_selector') {
  842. $enabledsetting = $name . '_enabled';
  843. if (empty($settings->$enabledsetting)) {
  844. $mform->setDefault($name, 0);
  845. } else {
  846. $relativetime = $usermidnight;
  847. if (isset($datetimeoffsets[$name])) {
  848. $relativetime = $datetimeoffsets[$name];
  849. }
  850. $mform->setDefault($name, $relativetime + $settings->$name);
  851. }
  852. } else {
  853. $mform->setDefault($name, $settings->$name);
  854. }
  855. }
  856. $advancedsetting = $name . '_adv';
  857. if (!empty($settings->$advancedsetting)) {
  858. $mform->setAdvanced($name);
  859. }
  860. }
  861. }
  862. }
  863. }