Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 401 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   * Cohort enrolment plugin.
  19   *
  20   * @package    enrol_cohort
  21   * @copyright  2010 Petr Skoda {@link http://skodak.org}
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  /**
  28   * COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
  29   */
  30  define('COHORT_CREATE_GROUP', -1);
  31  
  32  /**
  33   * Cohort enrolment plugin implementation.
  34   * @author Petr Skoda
  35   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class enrol_cohort_plugin extends enrol_plugin {
  38  
  39      /**
  40       * Is it possible to delete enrol instance via standard UI?
  41       *
  42       * @param stdClass $instance
  43       * @return bool
  44       */
  45      public function can_delete_instance($instance) {
  46          $context = context_course::instance($instance->courseid);
  47          return has_capability('enrol/cohort:config', $context);
  48      }
  49  
  50      /**
  51       * Returns localised name of enrol instance.
  52       *
  53       * @param stdClass $instance (null is accepted too)
  54       * @return string
  55       */
  56      public function get_instance_name($instance) {
  57          global $DB;
  58  
  59          if (empty($instance)) {
  60              $enrol = $this->get_name();
  61              return get_string('pluginname', 'enrol_'.$enrol);
  62  
  63          } else if (empty($instance->name)) {
  64              $enrol = $this->get_name();
  65              $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
  66              if (!$cohort) {
  67                  return get_string('pluginname', 'enrol_'.$enrol);
  68              }
  69              $cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid)));
  70              if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
  71                  $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING), ROLENAME_BOTH);
  72                  return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
  73              } else {
  74                  return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
  75              }
  76  
  77          } else {
  78              return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
  79          }
  80      }
  81  
  82      /**
  83       * Given a courseid this function returns true if the user is able to enrol or configure cohorts.
  84       * AND there are cohorts that the user can view.
  85       *
  86       * @param int $courseid
  87       * @return bool
  88       */
  89      public function can_add_instance($courseid) {
  90          global $CFG;
  91          require_once($CFG->dirroot . '/cohort/lib.php');
  92          $coursecontext = context_course::instance($courseid);
  93          if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
  94              return false;
  95          }
  96          return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
  97      }
  98  
  99      /**
 100       * Add new instance of enrol plugin.
 101       * @param object $course
 102       * @param array $fields instance fields
 103       * @return int id of new instance, null if can not be created
 104       */
 105      public function add_instance($course, array $fields = null) {
 106          global $CFG;
 107  
 108          // Allows multiple cohorts to be set on creation.
 109          if (!empty($fields['customint1'])) {
 110              $fields2 = $fields;
 111              if (!is_array($fields['customint1'])) {
 112                  $fields['customint1'] = array($fields['customint1']);
 113              }
 114              foreach ($fields['customint1'] as $cid) {
 115                  $fields2['customint1'] = $cid;
 116                  if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
 117                      // Create a new group for the cohort if requested.
 118                      $context = context_course::instance($course->id);
 119                      require_capability('moodle/course:managegroups', $context);
 120                      $groupid = enrol_cohort_create_new_group($course->id, $cid);
 121                      $fields2['customint2'] = $groupid;
 122                  }
 123                  $result = parent::add_instance($course, $fields2);
 124              }
 125          } else {
 126              $result = parent::add_instance($course, $fields);
 127          }
 128          require_once("$CFG->dirroot/enrol/cohort/locallib.php");
 129          $trace = new null_progress_trace();
 130          enrol_cohort_sync($trace, $course->id);
 131          $trace->finished();
 132          return $result;
 133      }
 134  
 135      /**
 136       * Update instance of enrol plugin.
 137       * @param stdClass $instance
 138       * @param stdClass $data modified instance fields
 139       * @return boolean
 140       */
 141      public function update_instance($instance, $data) {
 142          global $CFG;
 143  
 144          // NOTE: no cohort changes here!!!
 145          $context = context_course::instance($instance->courseid);
 146          if ($data->roleid != $instance->roleid) {
 147              // The sync script can only add roles, for perf reasons it does not modify them.
 148              $params = array(
 149                  'contextid' => $context->id,
 150                  'roleid' => $instance->roleid,
 151                  'component' => 'enrol_cohort',
 152                  'itemid' => $instance->id
 153              );
 154              role_unassign_all($params);
 155          }
 156          // Create a new group for the cohort if requested.
 157          if ($data->customint2 == COHORT_CREATE_GROUP) {
 158              require_capability('moodle/course:managegroups', $context);
 159              $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
 160              $data->customint2 = $groupid;
 161          }
 162  
 163          $result = parent::update_instance($instance, $data);
 164  
 165          require_once("$CFG->dirroot/enrol/cohort/locallib.php");
 166          $trace = new null_progress_trace();
 167          enrol_cohort_sync($trace, $instance->courseid);
 168          $trace->finished();
 169  
 170          return $result;
 171      }
 172  
 173      /**
 174       * Called after updating/inserting course.
 175       *
 176       * @param bool $inserted true if course just inserted
 177       * @param stdClass $course
 178       * @param stdClass $data form data
 179       * @return void
 180       */
 181      public function course_updated($inserted, $course, $data) {
 182          // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
 183      }
 184  
 185      /**
 186       * Update instance status
 187       *
 188       * @param stdClass $instance
 189       * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
 190       * @return void
 191       */
 192      public function update_status($instance, $newstatus) {
 193          global $CFG;
 194  
 195          parent::update_status($instance, $newstatus);
 196  
 197          require_once("$CFG->dirroot/enrol/cohort/locallib.php");
 198          $trace = new null_progress_trace();
 199          enrol_cohort_sync($trace, $instance->courseid);
 200          $trace->finished();
 201      }
 202  
 203      /**
 204       * Does this plugin allow manual unenrolment of a specific user?
 205       * Yes, but only if user suspended...
 206       *
 207       * @param stdClass $instance course enrol instance
 208       * @param stdClass $ue record from user_enrolments table
 209       *
 210       * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
 211       */
 212      public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
 213          if ($ue->status == ENROL_USER_SUSPENDED) {
 214              return true;
 215          }
 216  
 217          return false;
 218      }
 219  
 220      /**
 221       * Restore instance and map settings.
 222       *
 223       * @param restore_enrolments_structure_step $step
 224       * @param stdClass $data
 225       * @param stdClass $course
 226       * @param int $oldid
 227       */
 228      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 229          global $DB, $CFG;
 230  
 231          if (!$step->get_task()->is_samesite()) {
 232              // No cohort restore from other sites.
 233              $step->set_mapping('enrol', $oldid, 0);
 234              return;
 235          }
 236  
 237          if (!empty($data->customint2)) {
 238              $data->customint2 = $step->get_mappingid('group', $data->customint2);
 239          }
 240  
 241          if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
 242              $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
 243              if ($instance) {
 244                  $instanceid = $instance->id;
 245              } else {
 246                  $instanceid = $this->add_instance($course, (array)$data);
 247              }
 248              $step->set_mapping('enrol', $oldid, $instanceid);
 249  
 250              require_once("$CFG->dirroot/enrol/cohort/locallib.php");
 251              $trace = new null_progress_trace();
 252              enrol_cohort_sync($trace, $course->id);
 253              $trace->finished();
 254  
 255          } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
 256              $data->customint1 = 0;
 257              $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
 258  
 259              if ($instance) {
 260                  $instanceid = $instance->id;
 261              } else {
 262                  $data->status = ENROL_INSTANCE_DISABLED;
 263                  $instanceid = $this->add_instance($course, (array)$data);
 264              }
 265              $step->set_mapping('enrol', $oldid, $instanceid);
 266  
 267              require_once("$CFG->dirroot/enrol/cohort/locallib.php");
 268              $trace = new null_progress_trace();
 269              enrol_cohort_sync($trace, $course->id);
 270              $trace->finished();
 271  
 272          } else {
 273              $step->set_mapping('enrol', $oldid, 0);
 274          }
 275      }
 276  
 277      /**
 278       * Restore user enrolment.
 279       *
 280       * @param restore_enrolments_structure_step $step
 281       * @param stdClass $data
 282       * @param stdClass $instance
 283       * @param int $oldinstancestatus
 284       * @param int $userid
 285       */
 286      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 287          global $DB;
 288  
 289          if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
 290              // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
 291              return;
 292          }
 293  
 294          // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
 295          // but without roles and suspended.
 296  
 297          if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
 298              $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
 299          }
 300      }
 301  
 302      /**
 303       * Restore user group membership.
 304       * @param stdClass $instance
 305       * @param int $groupid
 306       * @param int $userid
 307       */
 308      public function restore_group_member($instance, $groupid, $userid) {
 309          // Nothing to do here, the group members are added in $this->restore_group_restored()
 310          return;
 311      }
 312  
 313      /**
 314       * Is it possible to hide/show enrol instance via standard UI?
 315       *
 316       * @param stdClass $instance
 317       * @return bool
 318       */
 319      public function can_hide_show_instance($instance) {
 320          $context = context_course::instance($instance->courseid);
 321          return has_capability('enrol/cohort:config', $context);
 322      }
 323  
 324      /**
 325       * Return an array of valid options for the status.
 326       *
 327       * @return array
 328       */
 329      protected function get_status_options() {
 330          $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
 331                           ENROL_INSTANCE_DISABLED => get_string('no'));
 332          return $options;
 333      }
 334  
 335      /**
 336       * Return an array of valid options for the cohorts.
 337       *
 338       * @param stdClass $instance
 339       * @param context $context
 340       * @return array
 341       */
 342      protected function get_cohort_options($instance, $context) {
 343          global $DB, $CFG;
 344  
 345          require_once($CFG->dirroot . '/cohort/lib.php');
 346  
 347          $cohorts = array();
 348  
 349          if ($instance->id) {
 350              if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
 351                  $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
 352                  $cohorts = array($instance->customint1 => $name);
 353              } else {
 354                  $cohorts = array($instance->customint1 => get_string('error'));
 355              }
 356          } else {
 357              $cohorts = array('' => get_string('choosedots'));
 358              $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
 359              foreach ($allcohorts as $c) {
 360                  $cohorts[$c->id] = format_string($c->name);
 361              }
 362          }
 363          return $cohorts;
 364      }
 365  
 366      /**
 367       * Return an array of valid options for the roles.
 368       *
 369       * @param stdClass $instance
 370       * @param context $coursecontext
 371       * @return array
 372       */
 373      protected function get_role_options($instance, $coursecontext) {
 374          global $DB;
 375  
 376          $roles = get_assignable_roles($coursecontext, ROLENAME_BOTH);
 377          $roles[0] = get_string('none');
 378          $roles = array_reverse($roles, true); // Descending default sortorder.
 379  
 380          // If the instance is already configured, but the configured role is no longer assignable in the course then add it back.
 381          if ($instance->id and !isset($roles[$instance->roleid])) {
 382              if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
 383                  $roles[$instance->roleid] = role_get_name($role, $coursecontext, ROLENAME_BOTH);
 384              } else {
 385                  $roles[$instance->roleid] = get_string('error');
 386              }
 387          }
 388  
 389          return $roles;
 390      }
 391  
 392      /**
 393       * Return an array of valid options for the groups.
 394       *
 395       * @param context $coursecontext
 396       * @return array
 397       */
 398      protected function get_group_options($coursecontext) {
 399          $groups = array(0 => get_string('none'));
 400          if (has_capability('moodle/course:managegroups', $coursecontext)) {
 401              $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
 402          }
 403  
 404          foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
 405              $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
 406          }
 407  
 408          return $groups;
 409      }
 410  
 411      /**
 412       * We are a good plugin and don't invent our own UI/validation code path.
 413       *
 414       * @return boolean
 415       */
 416      public function use_standard_editing_ui() {
 417          return true;
 418      }
 419  
 420      /**
 421       * Add elements to the edit instance form.
 422       *
 423       * @param stdClass $instance
 424       * @param MoodleQuickForm $mform
 425       * @param context $coursecontext
 426       * @return bool
 427       */
 428      public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
 429  
 430          $options = $this->get_status_options();
 431          $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
 432  
 433          $options = ['contextid' => $coursecontext->id, 'multiple' => true];
 434          $mform->addElement('cohort', 'customint1', get_string('cohort', 'cohort'), $options);
 435  
 436          if ($instance->id) {
 437              $mform->setConstant('customint1', $instance->customint1);
 438              $mform->hardFreeze('customint1', $instance->customint1);
 439          } else {
 440              $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
 441          }
 442  
 443          $roles = $this->get_role_options($instance, $coursecontext);
 444          $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
 445          $mform->setDefault('roleid', $this->get_config('roleid'));
 446          $groups = $this->get_group_options($coursecontext);
 447          $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
 448      }
 449  
 450      /**
 451       * Perform custom validation of the data used to edit the instance.
 452       *
 453       * @param array $data array of ("fieldname" => value) of submitted data
 454       * @param array $files array of uploaded files "element_name" => tmp_file_path
 455       * @param object $instance The instance loaded from the DB
 456       * @param context $context The context of the instance we are editing
 457       * @return array of "element_name" => "error_description" if there are errors,
 458       *         or an empty array if everything is OK.
 459       * @return void
 460       */
 461      public function edit_instance_validation($data, $files, $instance, $context) {
 462          global $DB;
 463          $errors = array();
 464          // Allows multiple cohorts to be selected.
 465          list($sql1, $params1) = $DB->get_in_or_equal($data['customint1'], SQL_PARAMS_NAMED);
 466          $params = array(
 467              'roleid' => $data['roleid'],
 468              'courseid' => $data['courseid'],
 469              'id' => $data['id']
 470          );
 471          $params = array_merge($params, $params1);
 472          $sql = "roleid = :roleid AND customint1 $sql1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
 473          if ($DB->record_exists_select('enrol', $sql, $params)) {
 474              $errors['customint1'] = get_string('instanceexists', 'enrol_cohort');
 475          }
 476          $validstatus = array_keys($this->get_status_options());
 477          $validcohorts = array_keys($this->get_cohort_options($instance, $context));
 478          $validroles = array_keys($this->get_role_options($instance, $context));
 479          $validgroups = array_keys($this->get_group_options($context));
 480          $tovalidate = array(
 481              'status' => $validstatus,
 482              'roleid' => $validroles,
 483              'customint2' => $validgroups
 484          );
 485          $typeerrors = $this->validate_param_types($data, $tovalidate);
 486          // When creating a new cohort enrolment, we allow multiple cohorts in just one go.
 487          // When editing an existing enrolment, changing the cohort is no allowed, so cohort is a single value.
 488          if (is_array($data['customint1'])) {
 489              $cohorts = $data['customint1'];
 490          } else {
 491              $cohorts = [$data['customint1']];
 492          }
 493  
 494          $errors = array_merge($errors, $typeerrors);
 495          // Check that the cohorts passed are valid.
 496          if (!empty(array_diff($cohorts, $validcohorts))) {
 497              $errors['customint1'] = get_string('invaliddata', 'error');
 498          }
 499          return $errors;
 500      }
 501  }
 502  
 503  /**
 504   * Prevent removal of enrol roles.
 505   * @param int $itemid
 506   * @param int $groupid
 507   * @param int $userid
 508   * @return bool
 509   */
 510  function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
 511      return false;
 512  }
 513  
 514  /**
 515   * Create a new group with the cohorts name.
 516   *
 517   * @param int $courseid
 518   * @param int $cohortid
 519   * @return int $groupid Group ID for this cohort.
 520   */
 521  function enrol_cohort_create_new_group($courseid, $cohortid) {
 522      global $DB, $CFG;
 523  
 524      require_once($CFG->dirroot . '/group/lib.php');
 525  
 526      $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
 527      $a = new stdClass();
 528      $a->name = $groupname;
 529      $a->increment = '';
 530      $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
 531      $inc = 1;
 532      // Check to see if the cohort group name already exists. Add an incremented number if it does.
 533      while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
 534          $a->increment = '(' . (++$inc) . ')';
 535          $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
 536          $groupname = $newshortname;
 537      }
 538      // Create a new group for the cohort.
 539      $groupdata = new stdClass();
 540      $groupdata->courseid = $courseid;
 541      $groupdata->name = $groupname;
 542      $groupid = groups_create_group($groupdata);
 543  
 544      return $groupid;
 545  }