MDL-52098 enrol: cohort now looks at instance status
[moodle.git] / enrol / cohort / locallib.php
CommitLineData
df997f84 1<?php
df997f84
PS
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 *
e7193380 20 * @package enrol_cohort
465f5088
PS
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
23 */
24
97795859 25defined('MOODLE_INTERNAL') || die();
df997f84 26
e0dd7cb0 27require_once($CFG->dirroot . '/enrol/locallib.php');
80f98467 28require_once($CFG->dirroot . '/cohort/lib.php');
e0dd7cb0
PS
29
30
df997f84
PS
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 */
37class enrol_cohort_handler {
7cfe6404 38 /**
e7193380 39 * Event processor - cohort member added.
05549cc5 40 * @param \core\event\cohort_member_added $event
7cfe6404
PS
41 * @return bool
42 */
05549cc5 43 public static function member_added(\core\event\cohort_member_added $event) {
7881024e
PS
44 global $DB, $CFG;
45 require_once("$CFG->dirroot/group/lib.php");
df997f84
PS
46
47 if (!enrol_is_enabled('cohort')) {
48 return true;
49 }
50
e7193380 51 // Does any enabled cohort instance want to sync with this cohort?
7cfe6404
PS
52 $sql = "SELECT e.*, r.id as roleexists
53 FROM {enrol} e
54 LEFT JOIN {role} r ON (r.id = e.roleid)
a446095f 55 WHERE e.customint1 = :cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus
7fc9433c 56 ORDER BY e.id ASC";
a446095f
MM
57 $params['cohortid'] = $event->objectid;
58 $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
59 if (!$instances = $DB->get_records_sql($sql, $params)) {
df997f84
PS
60 return true;
61 }
62
63 $plugin = enrol_get_plugin('cohort');
7cfe6404
PS
64 foreach ($instances as $instance) {
65 if ($instance->status != ENROL_INSTANCE_ENABLED ) {
e7193380 66 // No roles for disabled instances.
7cfe6404
PS
67 $instance->roleid = 0;
68 } else if ($instance->roleid and !$instance->roleexists) {
e7193380 69 // Invalid role - let's just enrol, they will have to create new sync and delete this one.
7cfe6404
PS
70 $instance->roleid = 0;
71 }
72 unset($instance->roleexists);
e7193380 73 // No problem if already enrolled.
05549cc5 74 $plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE);
7881024e
PS
75
76 // Sync groups.
77 if ($instance->customint2) {
05549cc5 78 if (!groups_is_member($instance->customint2, $event->relateduserid)) {
7881024e 79 if ($group = $DB->get_record('groups', array('id'=>$instance->customint2, 'courseid'=>$instance->courseid))) {
05549cc5 80 groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id);
7881024e
PS
81 }
82 }
83 }
df997f84
PS
84 }
85
86 return true;
87 }
88
7cfe6404 89 /**
e7193380 90 * Event processor - cohort member removed.
05549cc5 91 * @param \core\event\cohort_member_removed $event
7cfe6404
PS
92 * @return bool
93 */
05549cc5 94 public static function member_removed(\core\event\cohort_member_removed $event) {
df997f84
PS
95 global $DB;
96
e7193380 97 // Does anything want to sync with this cohort?
05549cc5 98 if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
df997f84
PS
99 return true;
100 }
101
102 $plugin = enrol_get_plugin('cohort');
7cfe6404
PS
103 $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
104
105 foreach ($instances as $instance) {
05549cc5 106 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$event->relateduserid))) {
7cfe6404
PS
107 continue;
108 }
109 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
05549cc5 110 $plugin->unenrol_user($instance, $event->relateduserid);
7cfe6404
PS
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 }
df997f84
PS
119 }
120
121 return true;
122 }
123
7cfe6404 124 /**
e7193380 125 * Event processor - cohort deleted.
05549cc5 126 * @param \core\event\cohort_deleted $event
7cfe6404
PS
127 * @return bool
128 */
05549cc5 129 public static function deleted(\core\event\cohort_deleted $event) {
df997f84
PS
130 global $DB;
131
e7193380 132 // Does anything want to sync with this cohort?
05549cc5 133 if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
df997f84
PS
134 return true;
135 }
136
137 $plugin = enrol_get_plugin('cohort');
7cfe6404
PS
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 }
df997f84
PS
148 }
149
150 return true;
151 }
152}
153
7cfe6404 154
df997f84
PS
155/**
156 * Sync all cohort course links.
c6116231 157 * @param progress_trace $trace
df997f84 158 * @param int $courseid one course, empty mean all
7cfe6404 159 * @return int 0 means ok, 1 means error, 2 means plugin disabled
df997f84 160 */
c6116231 161function enrol_cohort_sync(progress_trace $trace, $courseid = NULL) {
df997f84 162 global $CFG, $DB;
7881024e 163 require_once("$CFG->dirroot/group/lib.php");
df997f84 164
e7193380 165 // Purge all roles if cohort sync disabled, those can be recreated later here by cron or CLI.
7cfe6404 166 if (!enrol_is_enabled('cohort')) {
c6116231 167 $trace->output('Cohort sync plugin is disabled, unassigning all plugin roles and stopping.');
7cfe6404
PS
168 role_unassign_all(array('component'=>'enrol_cohort'));
169 return 2;
170 }
df997f84 171
e7193380 172 // Unfortunately this may take a long time, this script can be interrupted without problems.
3ef7279f 173 core_php_time_limit::raise();
7cfe6404
PS
174 raise_memory_limit(MEMORY_HUGE);
175
c6116231 176 $trace->output('Starting user enrolment synchronisation...');
7cfe6404
PS
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);
df997f84 183
df997f84 184
e7193380 185 // Iterate through all not enrolled yet users.
7cfe6404
PS
186 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
187 $sql = "SELECT cm.userid, e.id AS enrolid, ue.status
188 FROM {cohort_members} cm
a446095f 189 JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.enrol = 'cohort' AND e.status = :enrolstatus $onecourse)
a23fe90d 190 JOIN {user} u ON (u.id = cm.userid AND u.deleted = 0)
7cfe6404
PS
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;
a446095f 196 $params['enrolstatus'] = ENROL_INSTANCE_ENABLED;
7cfe6404
PS
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));
df997f84 201 }
7cfe6404
PS
202 $instance = $instances[$ue->enrolid];
203 if ($ue->status == ENROL_USER_SUSPENDED) {
204 $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_ACTIVE);
c6116231 205 $trace->output("unsuspending: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
7cfe6404
PS
206 } else {
207 $plugin->enrol_user($instance, $ue->userid);
c6116231 208 $trace->output("enrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
df997f84 209 }
df997f84 210 }
7cfe6404
PS
211 $rs->close();
212
df997f84 213
e7193380 214 // Unenrol as necessary.
7cfe6404 215 $sql = "SELECT ue.*, e.courseid
df997f84
PS
216 FROM {user_enrolments} ue
217 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
7cfe6404 218 LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
df997f84 219 WHERE cm.id IS NULL";
df997f84 220 $rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
df997f84
PS
221 foreach($rs as $ue) {
222 if (!isset($instances[$ue->enrolid])) {
223 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
224 }
7cfe6404
PS
225 $instance = $instances[$ue->enrolid];
226 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
7881024e 227 // Remove enrolment together with group membership, grades, preferences, etc.
7cfe6404 228 $plugin->unenrol_user($instance, $ue->userid);
c6116231 229 $trace->output("unenrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
7cfe6404
PS
230
231 } else { // ENROL_EXT_REMOVED_SUSPENDNOROLES
e7193380 232 // Just disable and ignore any changes.
7cfe6404
PS
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));
c6116231 237 $trace->output("suspending and unsassigning all roles: $ue->userid ==> $instance->courseid", 1);
7cfe6404
PS
238 }
239 }
df997f84
PS
240 }
241 $rs->close();
242 unset($instances);
243
7cfe6404 244
e7193380 245 // Now assign all necessary roles to enrolled users - skip suspended instances and users.
7cfe6404
PS
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)
a23fe90d 252 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
7cfe6404
PS
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);
c6116231 264 $trace->output("assigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
df997f84 265 }
7cfe6404
PS
266 $rs->close();
267
df997f84 268
e7193380 269 // Remove unwanted roles - sync role can not be changed, we only remove role when unenrolled.
7cfe6404
PS
270 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
271 $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid
df997f84 272 FROM {role_assignments} ra
7cfe6404
PS
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;
df997f84
PS
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);
c6116231 286 $trace->output("unassigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
df997f84
PS
287 }
288 $rs->close();
289
7cfe6404 290
7881024e 291 // Finally sync groups.
9c1561ef
MG
292 $affectedusers = groups_sync_with_enrolment('cohort', $courseid);
293 foreach ($affectedusers['removed'] as $gm) {
c6116231 294 $trace->output("removing user from group: $gm->userid ==> $gm->courseid - $gm->groupname", 1);
7881024e 295 }
9c1561ef 296 foreach ($affectedusers['added'] as $ue) {
c6116231 297 $trace->output("adding user to group: $ue->userid ==> $ue->courseid - $ue->groupname", 1);
7881024e 298 }
7881024e 299
c6116231 300 $trace->output('...user enrolment synchronisation finished.');
7cfe6404
PS
301
302 return 0;
df997f84 303}