Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

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