Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

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