Moodle release 2.6.2
[moodle.git] / enrol / cohort / locallib.php
blobe07c20bb241e940eea7cbb651a5437b28a638f98
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.
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/>.
17 /**
18 * Local stuff for cohort enrolment plugin.
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
25 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->dirroot . '/enrol/locallib.php');
30 /**
31 * Event handler for cohort enrolment plugin.
33 * We try to keep everything in sync via listening to events,
34 * it may fail sometimes, so we always do a full sync in cron too.
36 class enrol_cohort_handler {
37 /**
38 * Event processor - cohort member added.
39 * @param \core\event\cohort_member_added $event
40 * @return bool
42 public static function member_added(\core\event\cohort_member_added $event) {
43 global $DB, $CFG;
44 require_once("$CFG->dirroot/group/lib.php");
46 if (!enrol_is_enabled('cohort')) {
47 return true;
50 // Does any enabled cohort instance want to sync with this cohort?
51 $sql = "SELECT e.*, r.id as roleexists
52 FROM {enrol} e
53 LEFT JOIN {role} r ON (r.id = e.roleid)
54 WHERE e.customint1 = :cohortid AND e.enrol = 'cohort'
55 ORDER BY e.id ASC";
56 if (!$instances = $DB->get_records_sql($sql, array('cohortid'=>$event->objectid))) {
57 return true;
60 $plugin = enrol_get_plugin('cohort');
61 foreach ($instances as $instance) {
62 if ($instance->status != ENROL_INSTANCE_ENABLED ) {
63 // No roles for disabled instances.
64 $instance->roleid = 0;
65 } else if ($instance->roleid and !$instance->roleexists) {
66 // Invalid role - let's just enrol, they will have to create new sync and delete this one.
67 $instance->roleid = 0;
69 unset($instance->roleexists);
70 // No problem if already enrolled.
71 $plugin->enrol_user($instance, $event->relateduserid, $instance->roleid, 0, 0, ENROL_USER_ACTIVE);
73 // Sync groups.
74 if ($instance->customint2) {
75 if (!groups_is_member($instance->customint2, $event->relateduserid)) {
76 if ($group = $DB->get_record('groups', array('id'=>$instance->customint2, 'courseid'=>$instance->courseid))) {
77 groups_add_member($group->id, $event->relateduserid, 'enrol_cohort', $instance->id);
83 return true;
86 /**
87 * Event processor - cohort member removed.
88 * @param \core\event\cohort_member_removed $event
89 * @return bool
91 public static function member_removed(\core\event\cohort_member_removed $event) {
92 global $DB;
94 // Does anything want to sync with this cohort?
95 if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
96 return true;
99 $plugin = enrol_get_plugin('cohort');
100 $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
102 foreach ($instances as $instance) {
103 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$event->relateduserid))) {
104 continue;
106 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
107 $plugin->unenrol_user($instance, $event->relateduserid);
109 } else {
110 if ($ue->status != ENROL_USER_SUSPENDED) {
111 $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
112 $context = context_course::instance($instance->courseid);
113 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
118 return true;
122 * Event processor - cohort deleted.
123 * @param \core\event\cohort_deleted $event
124 * @return bool
126 public static function deleted(\core\event\cohort_deleted $event) {
127 global $DB;
129 // Does anything want to sync with this cohort?
130 if (!$instances = $DB->get_records('enrol', array('customint1'=>$event->objectid, 'enrol'=>'cohort'), 'id ASC')) {
131 return true;
134 $plugin = enrol_get_plugin('cohort');
135 $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
137 foreach ($instances as $instance) {
138 if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
139 $context = context_course::instance($instance->courseid);
140 role_unassign_all(array('contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
141 $plugin->update_status($instance, ENROL_INSTANCE_DISABLED);
142 } else {
143 $plugin->delete_instance($instance);
147 return true;
153 * Sync all cohort course links.
154 * @param progress_trace $trace
155 * @param int $courseid one course, empty mean all
156 * @return int 0 means ok, 1 means error, 2 means plugin disabled
158 function enrol_cohort_sync(progress_trace $trace, $courseid = NULL) {
159 global $CFG, $DB;
160 require_once("$CFG->dirroot/group/lib.php");
162 // Purge all roles if cohort sync disabled, those can be recreated later here by cron or CLI.
163 if (!enrol_is_enabled('cohort')) {
164 $trace->output('Cohort sync plugin is disabled, unassigning all plugin roles and stopping.');
165 role_unassign_all(array('component'=>'enrol_cohort'));
166 return 2;
169 // Unfortunately this may take a long time, this script can be interrupted without problems.
170 @set_time_limit(0);
171 raise_memory_limit(MEMORY_HUGE);
173 $trace->output('Starting user enrolment synchronisation...');
175 $allroles = get_all_roles();
176 $instances = array(); //cache
178 $plugin = enrol_get_plugin('cohort');
179 $unenrolaction = $plugin->get_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL);
182 // Iterate through all not enrolled yet users.
183 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
184 $sql = "SELECT cm.userid, e.id AS enrolid, ue.status
185 FROM {cohort_members} cm
186 JOIN {enrol} e ON (e.customint1 = cm.cohortid AND e.enrol = 'cohort' $onecourse)
187 JOIN {user} u ON (u.id = cm.userid AND u.deleted = 0)
188 LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = cm.userid)
189 WHERE ue.id IS NULL OR ue.status = :suspended";
190 $params = array();
191 $params['courseid'] = $courseid;
192 $params['suspended'] = ENROL_USER_SUSPENDED;
193 $rs = $DB->get_recordset_sql($sql, $params);
194 foreach($rs as $ue) {
195 if (!isset($instances[$ue->enrolid])) {
196 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
198 $instance = $instances[$ue->enrolid];
199 if ($ue->status == ENROL_USER_SUSPENDED) {
200 $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_ACTIVE);
201 $trace->output("unsuspending: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
202 } else {
203 $plugin->enrol_user($instance, $ue->userid);
204 $trace->output("enrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
207 $rs->close();
210 // Unenrol as necessary.
211 $sql = "SELECT ue.*, e.courseid
212 FROM {user_enrolments} ue
213 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
214 LEFT JOIN {cohort_members} cm ON (cm.cohortid = e.customint1 AND cm.userid = ue.userid)
215 WHERE cm.id IS NULL";
216 $rs = $DB->get_recordset_sql($sql, array('courseid'=>$courseid));
217 foreach($rs as $ue) {
218 if (!isset($instances[$ue->enrolid])) {
219 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
221 $instance = $instances[$ue->enrolid];
222 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
223 // Remove enrolment together with group membership, grades, preferences, etc.
224 $plugin->unenrol_user($instance, $ue->userid);
225 $trace->output("unenrolling: $ue->userid ==> $instance->courseid via cohort $instance->customint1", 1);
227 } else { // ENROL_EXT_REMOVED_SUSPENDNOROLES
228 // Just disable and ignore any changes.
229 if ($ue->status != ENROL_USER_SUSPENDED) {
230 $plugin->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
231 $context = context_course::instance($instance->courseid);
232 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$context->id, 'component'=>'enrol_cohort', 'itemid'=>$instance->id));
233 $trace->output("suspending and unsassigning all roles: $ue->userid ==> $instance->courseid", 1);
237 $rs->close();
238 unset($instances);
241 // Now assign all necessary roles to enrolled users - skip suspended instances and users.
242 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
243 $sql = "SELECT e.roleid, ue.userid, c.id AS contextid, e.id AS itemid, e.courseid
244 FROM {user_enrolments} ue
245 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' AND e.status = :statusenabled $onecourse)
246 JOIN {role} r ON (r.id = e.roleid)
247 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :coursecontext)
248 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
249 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)
250 WHERE ue.status = :useractive AND ra.id IS NULL";
251 $params = array();
252 $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
253 $params['useractive'] = ENROL_USER_ACTIVE;
254 $params['coursecontext'] = CONTEXT_COURSE;
255 $params['courseid'] = $courseid;
257 $rs = $DB->get_recordset_sql($sql, $params);
258 foreach($rs as $ra) {
259 role_assign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
260 $trace->output("assigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
262 $rs->close();
265 // Remove unwanted roles - sync role can not be changed, we only remove role when unenrolled.
266 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
267 $sql = "SELECT ra.roleid, ra.userid, ra.contextid, ra.itemid, e.courseid
268 FROM {role_assignments} ra
269 JOIN {context} c ON (c.id = ra.contextid AND c.contextlevel = :coursecontext)
270 JOIN {enrol} e ON (e.id = ra.itemid AND e.enrol = 'cohort' $onecourse)
271 LEFT JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = ra.userid AND ue.status = :useractive)
272 WHERE ra.component = 'enrol_cohort' AND (ue.id IS NULL OR e.status <> :statusenabled)";
273 $params = array();
274 $params['statusenabled'] = ENROL_INSTANCE_ENABLED;
275 $params['useractive'] = ENROL_USER_ACTIVE;
276 $params['coursecontext'] = CONTEXT_COURSE;
277 $params['courseid'] = $courseid;
279 $rs = $DB->get_recordset_sql($sql, $params);
280 foreach($rs as $ra) {
281 role_unassign($ra->roleid, $ra->userid, $ra->contextid, 'enrol_cohort', $ra->itemid);
282 $trace->output("unassigning role: $ra->userid ==> $ra->courseid as ".$allroles[$ra->roleid]->shortname, 1);
284 $rs->close();
287 // Finally sync groups.
288 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
290 // Remove invalid.
291 $sql = "SELECT gm.*, e.courseid, g.name AS groupname
292 FROM {groups_members} gm
293 JOIN {groups} g ON (g.id = gm.groupid)
294 JOIN {enrol} e ON (e.enrol = 'cohort' AND e.courseid = g.courseid $onecourse)
295 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
296 WHERE gm.component='enrol_cohort' AND gm.itemid = e.id AND g.id <> e.customint2";
297 $params = array();
298 $params['courseid'] = $courseid;
300 $rs = $DB->get_recordset_sql($sql, $params);
301 foreach($rs as $gm) {
302 groups_remove_member($gm->groupid, $gm->userid);
303 $trace->output("removing user from group: $gm->userid ==> $gm->courseid - $gm->groupname", 1);
305 $rs->close();
307 // Add missing.
308 $sql = "SELECT ue.*, g.id AS groupid, e.courseid, g.name AS groupname
309 FROM {user_enrolments} ue
310 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'cohort' $onecourse)
311 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.customint2)
312 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
313 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
314 WHERE gm.id IS NULL";
315 $params = array();
316 $params['courseid'] = $courseid;
318 $rs = $DB->get_recordset_sql($sql, $params);
319 foreach($rs as $ue) {
320 groups_add_member($ue->groupid, $ue->userid, 'enrol_cohort', $ue->enrolid);
321 $trace->output("adding user to group: $ue->userid ==> $ue->courseid - $ue->groupname", 1);
323 $rs->close();
326 $trace->output('...user enrolment synchronisation finished.');
328 return 0;
332 * Enrols all of the users in a cohort through a manual plugin instance.
334 * In order for this to succeed the course must contain a valid manual
335 * enrolment plugin instance that the user has permission to enrol users through.
337 * @global moodle_database $DB
338 * @param course_enrolment_manager $manager
339 * @param int $cohortid
340 * @param int $roleid
341 * @return int
343 function enrol_cohort_enrol_all_users(course_enrolment_manager $manager, $cohortid, $roleid) {
344 global $DB;
345 $context = $manager->get_context();
346 require_capability('moodle/course:enrolconfig', $context);
348 $instance = false;
349 $instances = $manager->get_enrolment_instances();
350 foreach ($instances as $i) {
351 if ($i->enrol == 'manual') {
352 $instance = $i;
353 break;
356 $plugin = enrol_get_plugin('manual');
357 if (!$instance || !$plugin || !$plugin->allow_enrol($instance) || !has_capability('enrol/'.$plugin->get_name().':enrol', $context)) {
358 return false;
360 $sql = "SELECT com.userid
361 FROM {cohort_members} com
362 LEFT JOIN (
363 SELECT *
364 FROM {user_enrolments} ue
365 WHERE ue.enrolid = :enrolid
366 ) ue ON ue.userid=com.userid
367 WHERE com.cohortid = :cohortid AND ue.id IS NULL";
368 $params = array('cohortid' => $cohortid, 'enrolid' => $instance->id);
369 $rs = $DB->get_recordset_sql($sql, $params);
370 $count = 0;
371 foreach ($rs as $user) {
372 $count++;
373 $plugin->enrol_user($instance, $user->userid, $roleid);
375 $rs->close();
376 return $count;
380 * Gets all the cohorts the user is able to view.
382 * @global moodle_database $DB
383 * @param course_enrolment_manager $manager
384 * @return array
386 function enrol_cohort_get_cohorts(course_enrolment_manager $manager) {
387 global $DB;
388 $context = $manager->get_context();
389 $cohorts = array();
390 $instances = $manager->get_enrolment_instances();
391 $enrolled = array();
392 foreach ($instances as $instance) {
393 if ($instance->enrol == 'cohort') {
394 $enrolled[] = $instance->customint1;
397 list($sqlparents, $params) = $DB->get_in_or_equal($context->get_parent_context_ids());
398 $sql = "SELECT id, name, idnumber, contextid
399 FROM {cohort}
400 WHERE contextid $sqlparents
401 ORDER BY name ASC, idnumber ASC";
402 $rs = $DB->get_recordset_sql($sql, $params);
403 foreach ($rs as $c) {
404 $context = context::instance_by_id($c->contextid);
405 if (!has_capability('moodle/cohort:view', $context)) {
406 continue;
408 $cohorts[$c->id] = array(
409 'cohortid'=>$c->id,
410 'name'=>format_string($c->name, true, array('context'=>context::instance_by_id($c->contextid))),
411 'users'=>$DB->count_records('cohort_members', array('cohortid'=>$c->id)),
412 'enrolled'=>in_array($c->id, $enrolled)
415 $rs->close();
416 return $cohorts;
420 * Check if cohort exists and user is allowed to enrol it.
422 * @global moodle_database $DB
423 * @param int $cohortid Cohort ID
424 * @return boolean
426 function enrol_cohort_can_view_cohort($cohortid) {
427 global $DB;
428 $cohort = $DB->get_record('cohort', array('id' => $cohortid), 'id, contextid');
429 if ($cohort) {
430 $context = context::instance_by_id($cohort->contextid);
431 if (has_capability('moodle/cohort:view', $context)) {
432 return true;
435 return false;
439 * Gets cohorts the user is able to view.
441 * @global moodle_database $DB
442 * @param course_enrolment_manager $manager
443 * @param int $offset limit output from
444 * @param int $limit items to output per load
445 * @param string $search search string
446 * @return array Array(more => bool, offset => int, cohorts => array)
448 function enrol_cohort_search_cohorts(course_enrolment_manager $manager, $offset = 0, $limit = 25, $search = '') {
449 global $DB;
450 $context = $manager->get_context();
451 $cohorts = array();
452 $instances = $manager->get_enrolment_instances();
453 $enrolled = array();
454 foreach ($instances as $instance) {
455 if ($instance->enrol == 'cohort') {
456 $enrolled[] = $instance->customint1;
460 list($sqlparents, $params) = $DB->get_in_or_equal($context->get_parent_context_ids());
462 // Add some additional sensible conditions.
463 $tests = array('contextid ' . $sqlparents);
465 // Modify the query to perform the search if required.
466 if (!empty($search)) {
467 $conditions = array(
468 'name',
469 'idnumber',
470 'description'
472 $searchparam = '%' . $DB->sql_like_escape($search) . '%';
473 foreach ($conditions as $key=>$condition) {
474 $conditions[$key] = $DB->sql_like($condition, "?", false);
475 $params[] = $searchparam;
477 $tests[] = '(' . implode(' OR ', $conditions) . ')';
479 $wherecondition = implode(' AND ', $tests);
481 $sql = "SELECT id, name, idnumber, contextid, description
482 FROM {cohort}
483 WHERE $wherecondition
484 ORDER BY name ASC, idnumber ASC";
485 $rs = $DB->get_recordset_sql($sql, $params, $offset);
487 // Produce the output respecting parameters.
488 foreach ($rs as $c) {
489 // Track offset.
490 $offset++;
491 // Check capabilities.
492 $context = context::instance_by_id($c->contextid);
493 if (!has_capability('moodle/cohort:view', $context)) {
494 continue;
496 if ($limit === 0) {
497 // We have reached the required number of items and know that there are more, exit now.
498 $offset--;
499 break;
501 $cohorts[$c->id] = array(
502 'cohortid' => $c->id,
503 'name' => shorten_text(format_string($c->name, true, array('context'=>context::instance_by_id($c->contextid))), 35),
504 'users' => $DB->count_records('cohort_members', array('cohortid'=>$c->id)),
505 'enrolled' => in_array($c->id, $enrolled)
507 // Count items.
508 $limit--;
510 $rs->close();
511 return array('more' => !(bool)$limit, 'offset' => $offset, 'cohorts' => $cohorts);