PageRenderTime 62ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/course/moodleform_mod.php

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