[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/course/ -> moodleform_mod.php (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1