Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

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