Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
  • Differences Between: [Versions 311 and 400]

       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                      role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
     117                  }
     118              }
     119          }
     120  
     121          return true;
     122      }
     123  
     124      /**
     125       * Event processor - cohort deleted.
     126       * @param \core\event\cohort_deleted $event
     127       * @return bool
     128       */
     129      public static function deleted(\core\event\cohort_deleted $event) {
     130          global $DB;
     131  
     132          // Does anything want to sync with this cohort?
     133          if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
     134              return true;
     135          }
     136  
     137          $plugin = enrol_get_plugin('cohort');
     138          $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     139  
     140          foreach ($instances as $instance) {
     141              if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
     142                  $context = context_course::instance($instance->courseid);
     143                  role_unassign_all(array('contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
     144                  $plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
     145              } else {
     146                  $plugin->delete_instance($instance);
     147              }
     148          }
     149  
     150          return true;
     151      }
     152  }
     153  
     154  
     155  /**
     156   * Sync all cohort course links.
     157   * @param progress_trace $trace
     158   * @param int $courseid one course, empty mean all
     159   * @return int 0 means ok, 1 means error, 2 means plugin disabled
     160   */
     161  function enrol_cohort_sync(progress_trace $trace, $courseid = NULL) {
     162      global $CFG, $DB;
     163      require_once("$CFG->dirroot/group/lib.php");
     164  
     165      // Purge all roles if cohort sync disabled, those can be recreated later here by cron or CLI.
     166      if (!enrol_is_enabled('cohort')) {
     167          $trace->output('Cohort sync plugin is disabled, unassigning all plugin roles and stopping.');
     168          role_unassign_all(array('component'=>'enrol_cohort'));
     169          return 2;
     170      }
     171  
     172      // Unfortunately this may take a long time, this script can be interrupted without problems.
     173      core_php_time_limit::raise();
     174      raise_memory_limit(MEMORY_HUGE);
     175  
     176      $trace->output('Starting user enrolment synchronisation...');
     177  
     178      $allroles = get_all_roles();
     179      $instances = array(); //cache
     180  
     181      $plugin = enrol_get_plugin('cohort');
     182      $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
     183  
     184  
     185      // Iterate through all not enrolled yet users.
     186      $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
     187      $sql = "SELECT cm.userid, e.id AS enrolid, ue.status
     188                FROM {cohort_members} cm
     189                JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus $onecourse)
     190                JOIN {user} u ON (u.id = cm.userid AND u.deleted = 0)
     191           LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
     192               WHERE ue.id IS NULL OR ue.status = :suspended";
     193      $params = array();
     194      $params['courseid'] = $courseid;
     195      $params['suspended'] = ENROL_USER_SUSPENDED;
     196      $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
     197      $rs = $DB->get_recordset_sql($sql, $params);
     198      foreach($rs as $ue) {
     199          if (!isset($instances[$ue->enrolid])) {
     200              $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
     201          }
     202          $instance = $instances[$ue->enrolid];
     203          if ($ue->status == ENROL_USER_SUSPENDED) {
     204              $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_ACTIVE);
     205              $trace->output("unsuspending: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
     206          } else {
     207              $plugin->enrol_user($instance, $ue->userid);
     208              $trace->output("enrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
     209          }
     210      }
     211      $rs->close();
     212  
     213  
     214      // Unenrol as necessary.
     215      $sql = "SELECT ue.*, e.courseid
     216                FROM {user_enrolments} ue
     217                JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
     218           LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
     219               WHERE cm.id IS NULL";
     220      $rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
     221      foreach($rs as $ue) {
     222          if (!isset($instances[$ue->enrolid])) {
     223              $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
     224          }
     225          $instance = $instances[$ue->enrolid];
     226          if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
     227              // Remove enrolment together with group membership, grades, preferences, etc.
     228              $plugin->unenrol_user($instance, $ue->userid);
     229              $trace->output("unenrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
     230  
     231          } else { // ENROL_EXT_REMOVED_SUSPENDNOROLES
     232              // Just disable and ignore any changes.
     233              if ($ue->status != ENROL_USER_SUSPENDED) {
     234                  $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
     235                  $context = context_course::instance($instance->courseid);
     236                  role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
     237                  $trace->output("suspending and unsassigning all roles: $ue->userid ==> $instance->courseid", 1);
     238              }
     239          }
     240      }
     241      $rs->close();
     242      unset($instances);
     243  
     244  
     245      // Now assign all necessary roles to enrolled users - skip suspended instances and users.
     246      $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
     247      $sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid, e.courseid
     248                FROM {user_enrolments} ue
     249                JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' AND e.status = :statusenabled $onecourse)
     250                JOIN {role} r ON (r.id = e.roleid)
     251                JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :coursecontext)
     252                JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
     253           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)
     254               WHERE ue.status = :useractive AND ra.id IS NULL";
     255      $params = array();
     256      $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
     257      $params['useractive'] = ENROL_USER_ACTIVE;
     258      $params['coursecontext'] = CONTEXT_COURSE;
     259      $params['courseid'] = $courseid;
     260  
     261      $rs = $DB->get_recordset_sql($sql, $params);
     262      foreach($rs as $ra) {
     263          role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
     264          $trace->output("assigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
     265      }
     266      $rs->close();
     267  
     268  
     269      // Remove unwanted roles - sync role can not be changed, we only remove role when unenrolled.
     270      $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
     271      $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid
     272                FROM {role_assignments} ra
     273                JOIN {context} c ON (c.id = ra.contextid AND c.contextlevel = :coursecontext)
     274                JOIN {enrol} e ON (e.id = ra.itemid AND e.enrol = 'cohort' $onecourse)
     275           LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :useractive)
     276               WHERE ra.component = 'enrol_cohort' AND (ue.id IS NULL OR e.status <> :statusenabled)";
     277      $params = array();
     278      $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
     279      $params['useractive'] = ENROL_USER_ACTIVE;
     280      $params['coursecontext'] = CONTEXT_COURSE;
     281      $params['courseid'] = $courseid;
     282  
     283      $rs = $DB->get_recordset_sql($sql, $params);
     284      foreach($rs as $ra) {
     285          role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
     286          $trace->output("unassigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
     287      }
     288      $rs->close();
     289  
     290  
     291      // Finally sync groups.
     292      $affectedusers = groups_sync_with_enrolment('cohort', $courseid);
     293      foreach ($affectedusers['removed'] as $gm) {
     294          $trace->output("removing user from group: $gm->userid ==> $gm->courseid - $gm->groupname", 1);
     295      }
     296      foreach ($affectedusers['added'] as $ue) {
     297          $trace->output("adding user to group: $ue->userid ==> $ue->courseid - $ue->groupname", 1);
     298      }
     299  
     300      $trace->output('...user enrolment synchronisation finished.');
     301  
     302      return 0;
     303  }