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]

   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   * Local stuff for 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  require_once($CFG->dirroot . '/enrol/locallib.php');
  28  require_once($CFG->dirroot . '/cohort/lib.php');
  29  
  30  
  31  /**
  32   * Event handler for cohort enrolment plugin.
  33   *
  34   * We try to keep everything in sync via listening to events,
  35   * it may fail sometimes, so we always do a full sync in cron too.
  36   */
  37  class enrol_cohort_handler {
  38      /**
  39       * Event processor - cohort member added.
  40       * @param \core\event\cohort_member_added $event
  41       * @return bool
  42       */
  43      public static function member_added(\core\event\cohort_member_added $event) {
  44          global $DB, $CFG;
  45          require_once("$CFG->dirroot/group/lib.php");
  46  
  47          if (!enrol_is_enabled('cohort')) {
  48              return true;
  49          }
  50  
  51          // Does any enabled cohort instance want to sync with this cohort?
  52          $sql = "SELECT e.*, r.id as roleexists
  53                    FROM {enrol} e
  54               LEFT JOIN {role} r ON (r.id = e.roleid)
  55                   WHERE e.customint1 = :cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus
  56                ORDER BY e.id ASC";
  57          $params['cohortid'] = $event->objectid;
  58          $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
  59          if (!$instances = $DB->get_records_sql($sql, $params)) {
  60              return true;
  61          }
  62  
  63          $plugin = enrol_get_plugin('cohort');
  64          foreach ($instances as $instance) {
  65              if ($instance->status != ENROL_INSTANCE_ENABLED ) {
  66                  // No roles for disabled instances.
  67                  $instance->roleid = 0;
  68              } else if ($instance->roleid and !$instance->roleexists) {
  69                  // Invalid role - let's just enrol, they will have to create new sync and delete this one.
  70                  $instance->roleid = 0;
  71              }
  72              unset($instance->roleexists);
  73              // No problem if already enrolled.
  74              $plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE);
  75  
  76              // Sync groups.
  77              if ($instance->customint2) {
  78                  if (!groups_is_member($instance->customint2, $event->relateduserid)) {
  79                      if ($group = $DB->get_record('groups', array('id'=>$instance->customint2, 'courseid'=>$instance->courseid))) {
  80                          groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id);
  81                      }
  82                  }
  83              }
  84          }
  85  
  86          return true;
  87      }
  88  
  89      /**
  90       * Event processor - cohort member removed.
  91       * @param \core\event\cohort_member_removed $event
  92       * @return bool
  93       */
  94      public static function member_removed(\core\event\cohort_member_removed $event) {
  95          global $DB;
  96  
  97          // Does anything want to sync with this cohort?
  98          if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
  99              return true;
 100          }
 101  
 102          $plugin = enrol_get_plugin('cohort');
 103          $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
 104  
 105          foreach ($instances as $instance) {
 106              if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$event->relateduserid))) {
 107                  continue;
 108              }
 109              if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
 110                  $plugin->unenrol_user($instance, $event->relateduserid);
 111  
 112              } else {
 113                  if ($ue->status != ENROL_USER_SUSPENDED) {
 114                      $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
 115                      $context = context_course::instance($instance->courseid);
 116                      if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
 117                          role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id,
 118                              'component' => 'enrol_cohort', 'itemid' => $instance->id));
 119                      }
 120                  }
 121              }
 122          }
 123  
 124          return true;
 125      }
 126  
 127      /**
 128       * Event processor - cohort deleted.
 129       * @param \core\event\cohort_deleted $event
 130       * @return bool
 131       */
 132      public static function deleted(\core\event\cohort_deleted $event) {
 133          global $DB;
 134  
 135          // Does anything want to sync with this cohort?
 136          if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
 137              return true;
 138          }
 139  
 140          $plugin = enrol_get_plugin('cohort');
 141          $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
 142  
 143          foreach ($instances as $instance) {
 144              if ($unenrolaction != ENROL_EXT_REMOVED_UNENROL) {
 145                  $context = context_course::instance($instance->courseid);
 146                  if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
 147                      role_unassign_all(array('contextid' => $context->id, 'component' => 'enrol_cohort',
 148                          'itemid' => $instance->id));
 149                  }
 150                  $plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
 151              } else {
 152                  $plugin->delete_instance($instance);
 153              }
 154          }
 155  
 156          return true;
 157      }
 158  }
 159  
 160  
 161  /**
 162   * Sync all cohort course links.
 163   * @param progress_trace $trace
 164   * @param int $courseid one course, empty mean all
 165   * @return int 0 means ok, 1 means error, 2 means plugin disabled
 166   */
 167  function enrol_cohort_sync(progress_trace $trace, $courseid = NULL) {
 168      global $CFG, $DB;
 169      require_once("$CFG->dirroot/group/lib.php");
 170  
 171      // Purge all roles if cohort sync disabled, those can be recreated later here by cron or CLI.
 172      if (!enrol_is_enabled('cohort')) {
 173          $trace->output('Cohort sync plugin is disabled, unassigning all plugin roles and stopping.');
 174          role_unassign_all(array('component'=>'enrol_cohort'));
 175          return 2;
 176      }
 177  
 178      // Unfortunately this may take a long time, this script can be interrupted without problems.
 179      core_php_time_limit::raise();
 180      raise_memory_limit(MEMORY_HUGE);
 181  
 182      $trace->output('Starting user enrolment synchronisation...');
 183  
 184      $allroles = get_all_roles();
 185      $instances = array(); //cache
 186  
 187      $plugin = enrol_get_plugin('cohort');
 188      $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
 189  
 190  
 191      // Iterate through all not enrolled yet users.
 192      $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
 193      $sql = "SELECT cm.userid, e.id AS enrolid, ue.status
 194                FROM {cohort_members} cm
 195                JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus $onecourse)
 196                JOIN {user} u ON (u.id = cm.userid AND u.deleted = 0)
 197           LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
 198               WHERE ue.id IS NULL OR ue.status = :suspended";
 199      $params = array();
 200      $params['courseid'] = $courseid;
 201      $params['suspended'] = ENROL_USER_SUSPENDED;
 202      $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
 203      $rs = $DB->get_recordset_sql($sql, $params);
 204      foreach($rs as $ue) {
 205          if (!isset($instances[$ue->enrolid])) {
 206              $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
 207          }
 208          $instance = $instances[$ue->enrolid];
 209          if ($ue->status == ENROL_USER_SUSPENDED) {
 210              $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_ACTIVE);
 211              $trace->output("unsuspending: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
 212          } else {
 213              $plugin->enrol_user($instance, $ue->userid);
 214              $trace->output("enrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
 215          }
 216      }
 217      $rs->close();
 218  
 219  
 220      // Unenrol as necessary.
 221      $sql = "SELECT ue.*, e.courseid
 222                FROM {user_enrolments} ue
 223                JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
 224           LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
 225               WHERE cm.id IS NULL";
 226      $rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
 227      foreach($rs as $ue) {
 228          if (!isset($instances[$ue->enrolid])) {
 229              $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
 230          }
 231          $instance = $instances[$ue->enrolid];
 232          if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
 233              // Remove enrolment together with group membership, grades, preferences, etc.
 234              $plugin->unenrol_user($instance, $ue->userid);
 235              $trace->output("unenrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
 236  
 237          } else { // ENROL_EXT_REMOVED_SUSPENDNOROLES
 238              // Just disable and ignore any changes.
 239              if ($ue->status != ENROL_USER_SUSPENDED) {
 240                  $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
 241                  $context = context_course::instance($instance->courseid);
 242                  if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
 243                      role_unassign_all(array('userid' => $ue->userid, 'contextid' => $context->id,
 244                          'component' => 'enrol_cohort', 'itemid' => $instance->id));
 245                      $trace->output("unsassigning all roles: $ue->userid ==> $instance->courseid", 1);
 246                  }
 247                  $trace->output("suspending: $ue->userid ==> $instance->courseid", 1);
 248              }
 249          }
 250      }
 251      $rs->close();
 252      unset($instances);
 253  
 254  
 255      // Now assign all necessary roles to enrolled users - skip suspended instances and users.
 256      $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
 257      $sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid, e.courseid
 258                FROM {user_enrolments} ue
 259                JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' AND e.status = :statusenabled $onecourse)
 260                JOIN {role} r ON (r.id = e.roleid)
 261                JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :coursecontext)
 262                JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
 263           LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid AND ra.itemid = e.id AND ra.component = 'enrol_cohort' AND e.roleid = ra.roleid)
 264               WHERE ue.status = :useractive AND ra.id IS NULL";
 265      $params = array();
 266      $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
 267      $params['useractive'] = ENROL_USER_ACTIVE;
 268      $params['coursecontext'] = CONTEXT_COURSE;
 269      $params['courseid'] = $courseid;
 270  
 271      $rs = $DB->get_recordset_sql($sql, $params);
 272      foreach($rs as $ra) {
 273          role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
 274          $trace->output("assigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
 275      }
 276      $rs->close();
 277  
 278      if ($unenrolaction != ENROL_EXT_REMOVED_SUSPEND) {
 279          // Remove unwanted roles - sync role can not be changed, we only remove role when unenrolled.
 280          $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
 281          $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid
 282                    FROM {role_assignments} ra
 283                    JOIN {context} c ON (c.id = ra.contextid AND c.contextlevel = :coursecontext)
 284                    JOIN {enrol} e ON (e.id = ra.itemid AND e.enrol = 'cohort' $onecourse)
 285               LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :useractive)
 286                   WHERE ra.component = 'enrol_cohort' AND (ue.id IS NULL OR e.status <> :statusenabled)";
 287          $params = array();
 288          $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
 289          $params['useractive'] = ENROL_USER_ACTIVE;
 290          $params['coursecontext'] = CONTEXT_COURSE;
 291          $params['courseid'] = $courseid;
 292  
 293          $rs = $DB->get_recordset_sql($sql, $params);
 294          foreach ($rs as $ra) {
 295              role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
 296              $trace->output("unassigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
 297          }
 298          $rs->close();
 299      }
 300  
 301      // Finally sync groups.
 302      $affectedusers = groups_sync_with_enrolment('cohort', $courseid);
 303      foreach ($affectedusers['removed'] as $gm) {
 304          $trace->output("removing user from group: $gm->userid ==> $gm->courseid - $gm->groupname", 1);
 305      }
 306      foreach ($affectedusers['added'] as $ue) {
 307          $trace->output("adding user to group: $ue->userid ==> $ue->courseid - $ue->groupname", 1);
 308      }
 309  
 310      $trace->output('...user enrolment synchronisation finished.');
 311  
 312      return 0;
 313  }