2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * 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();
28 * COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
30 define('COHORT_CREATE_GROUP', -1);
33 * Cohort enrolment plugin implementation.
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class enrol_cohort_plugin extends enrol_plugin {
40 * Is it possible to delete enrol instance via standard UI?
42 * @param stdClass $instance
45 public function can_delete_instance($instance) {
46 $context = context_course::instance($instance->courseid);
47 return has_capability('enrol/cohort:config', $context);
51 * Returns localised name of enrol instance.
53 * @param stdClass $instance (null is accepted too)
56 public function get_instance_name($instance) {
59 if (empty($instance)) {
60 $enrol = $this->get_name();
61 return get_string('pluginname', 'enrol_'.$enrol);
63 } else if (empty($instance->name)) {
64 $enrol = $this->get_name();
65 $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
67 return get_string('pluginname', 'enrol_'.$enrol);
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));
72 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
74 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
78 return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
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.
86 * @param int $courseid
89 public function can_add_instance($courseid) {
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)) {
96 return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
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
105 public function add_instance($course, array $fields = null) {
108 if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
109 // Create a new group for the cohort if requested.
110 $context = context_course::instance($course->id);
111 require_capability('moodle/course:managegroups', $context);
112 $groupid = enrol_cohort_create_new_group($course->id, $fields['customint1']);
113 $fields['customint2'] = $groupid;
116 $result = parent::add_instance($course, $fields);
118 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
119 $trace = new null_progress_trace();
120 enrol_cohort_sync($trace, $course->id);
127 * Update instance of enrol plugin.
128 * @param stdClass $instance
129 * @param stdClass $data modified instance fields
132 public function update_instance($instance, $data) {
135 // NOTE: no cohort changes here!!!
136 $context = context_course::instance($instance->courseid);
137 if ($data->roleid != $instance->roleid) {
138 // The sync script can only add roles, for perf reasons it does not modify them.
140 'contextid' => $context->id,
141 'roleid' => $instance->roleid,
142 'component' => 'enrol_cohort',
143 'itemid' => $instance->id
145 role_unassign_all($params);
147 // Create a new group for the cohort if requested.
148 if ($data->customint2 == COHORT_CREATE_GROUP) {
149 require_capability('moodle/course:managegroups', $context);
150 $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
151 $data->customint2 = $groupid;
154 $result = parent::update_instance($instance, $data);
156 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
157 $trace = new null_progress_trace();
158 enrol_cohort_sync($trace, $instance->courseid);
165 * Called for all enabled enrol plugins that returned true from is_cron_required().
168 public function cron() {
171 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
172 $trace = new null_progress_trace();
173 enrol_cohort_sync($trace);
178 * Called after updating/inserting course.
180 * @param bool $inserted true if course just inserted
181 * @param stdClass $course
182 * @param stdClass $data form data
185 public function course_updated($inserted, $course, $data) {
186 // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
190 * Update instance status
192 * @param stdClass $instance
193 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
196 public function update_status($instance, $newstatus) {
199 parent::update_status($instance, $newstatus);
201 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
202 $trace = new null_progress_trace();
203 enrol_cohort_sync($trace, $instance->courseid);
208 * Does this plugin allow manual unenrolment of a specific user?
209 * Yes, but only if user suspended...
211 * @param stdClass $instance course enrol instance
212 * @param stdClass $ue record from user_enrolments table
214 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
216 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
217 if ($ue->status == ENROL_USER_SUSPENDED) {
225 * Gets an array of the user enrolment actions.
227 * @param course_enrolment_manager $manager
228 * @param stdClass $ue A user enrolment object
229 * @return array An array of user_enrolment_actions
231 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
233 $context = $manager->get_context();
234 $instance = $ue->enrolmentinstance;
235 $params = $manager->get_moodlepage()->url->params();
236 $params['ue'] = $ue->id;
237 if ($this->allow_unenrol_user($instance, $ue) && has_capability('enrol/cohort:unenrol', $context)) {
238 $url = new moodle_url('/enrol/unenroluser.php', $params);
239 $actionparams = array('class' => 'unenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_UNENROL);
240 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url,
247 * Restore instance and map settings.
249 * @param restore_enrolments_structure_step $step
250 * @param stdClass $data
251 * @param stdClass $course
254 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
257 if (!$step->get_task()->is_samesite()) {
258 // No cohort restore from other sites.
259 $step->set_mapping('enrol', $oldid, 0);
263 if (!empty($data->customint2)) {
264 $data->customint2 = $step->get_mappingid('group', $data->customint2);
267 if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
268 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
270 $instanceid = $instance->id;
272 $instanceid = $this->add_instance($course, (array)$data);
274 $step->set_mapping('enrol', $oldid, $instanceid);
276 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
277 $trace = new null_progress_trace();
278 enrol_cohort_sync($trace, $course->id);
281 } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
282 $data->customint1 = 0;
283 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
286 $instanceid = $instance->id;
288 $data->status = ENROL_INSTANCE_DISABLED;
289 $instanceid = $this->add_instance($course, (array)$data);
291 $step->set_mapping('enrol', $oldid, $instanceid);
293 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
294 $trace = new null_progress_trace();
295 enrol_cohort_sync($trace, $course->id);
299 $step->set_mapping('enrol', $oldid, 0);
304 * Restore user enrolment.
306 * @param restore_enrolments_structure_step $step
307 * @param stdClass $data
308 * @param stdClass $instance
309 * @param int $oldinstancestatus
312 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
315 if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
316 // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
320 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
321 // but without roles and suspended.
323 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
324 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
329 * Restore user group membership.
330 * @param stdClass $instance
331 * @param int $groupid
334 public function restore_group_member($instance, $groupid, $userid) {
335 // Nothing to do here, the group members are added in $this->restore_group_restored()
340 * Is it possible to hide/show enrol instance via standard UI?
342 * @param stdClass $instance
345 public function can_hide_show_instance($instance) {
346 $context = context_course::instance($instance->courseid);
347 return has_capability('enrol/cohort:config', $context);
351 * Return an array of valid options for the status.
355 protected function get_status_options() {
356 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
357 ENROL_INSTANCE_DISABLED => get_string('no'));
362 * Return an array of valid options for the cohorts.
364 * @param stdClass $instance
365 * @param context $context
368 protected function get_cohort_options($instance, $context) {
371 require_once($CFG->dirroot . '/cohort/lib.php');
376 if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
377 $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
378 $cohorts = array($instance->customint1 => $name);
380 $cohorts = array($instance->customint1 => get_string('error'));
383 $cohorts = array('' => get_string('choosedots'));
384 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
385 foreach ($allcohorts as $c) {
386 $cohorts[$c->id] = format_string($c->name);
393 * Return an array of valid options for the roles.
395 * @param stdClass $instance
396 * @param context $coursecontext
399 protected function get_role_options($instance, $coursecontext) {
402 $roles = get_assignable_roles($coursecontext);
403 $roles[0] = get_string('none');
404 $roles = array_reverse($roles, true); // Descending default sortorder.
405 if ($instance->id and !isset($roles[$instance->roleid])) {
406 if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
407 $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true);
408 $roles[$instance->roleid] = role_get_name($role, $coursecontext);
410 $roles[$instance->roleid] = get_string('error');
418 * Return an array of valid options for the groups.
420 * @param context $coursecontext
423 protected function get_group_options($coursecontext) {
424 $groups = array(0 => get_string('none'));
425 if (has_capability('moodle/course:managegroups', $coursecontext)) {
426 $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
429 foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
430 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
437 * We are a good plugin and don't invent our own UI/validation code path.
441 public function use_standard_editing_ui() {
446 * Add elements to the edit instance form.
448 * @param stdClass $instance
449 * @param MoodleQuickForm $mform
450 * @param context $coursecontext
453 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
456 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
457 $mform->setType('name', PARAM_TEXT);
459 $options = $this->get_status_options();
460 $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
462 $options = $this->get_cohort_options($instance, $coursecontext);
463 $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $options);
465 $mform->setConstant('customint1', $instance->customint1);
466 $mform->hardFreeze('customint1', $instance->customint1);
468 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
471 $roles = $this->get_role_options($instance, $coursecontext);
472 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
473 $mform->setDefault('roleid', $this->get_config('roleid'));
474 $groups = $this->get_group_options($coursecontext);
475 $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
479 * Perform custom validation of the data used to edit the instance.
481 * @param array $data array of ("fieldname" => value) of submitted data
482 * @param array $files array of uploaded files "element_name" => tmp_file_path
483 * @param object $instance The instance loaded from the DB
484 * @param context $context The context of the instance we are editing
485 * @return array of "element_name" => "error_description" if there are errors,
486 * or an empty array if everything is OK.
489 public function edit_instance_validation($data, $files, $instance, $context) {
494 'roleid' => $data['roleid'],
495 'customint1' => $data['customint1'],
496 'courseid' => $data['courseid'],
499 $sql = "roleid = :roleid AND customint1 = :customint1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
500 if ($DB->record_exists_select('enrol', $sql, $params)) {
501 $errors['roleid'] = get_string('instanceexists', 'enrol_cohort');
503 $validstatus = array_keys($this->get_status_options());
504 $validcohorts = array_keys($this->get_cohort_options($instance, $context));
505 $validroles = array_keys($this->get_role_options($instance, $context));
506 $validgroups = array_keys($this->get_group_options($context));
508 'name' => PARAM_TEXT,
509 'status' => $validstatus,
510 'customint1' => $validcohorts,
511 'roleid' => $validroles,
512 'customint2' => $validgroups
514 $typeerrors = $this->validate_param_types($data, $tovalidate);
515 $errors = array_merge($errors, $typeerrors);
522 * Prevent removal of enrol roles.
524 * @param int $groupid
528 function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
533 * Create a new group with the cohorts name.
535 * @param int $courseid
536 * @param int $cohortid
537 * @return int $groupid Group ID for this cohort.
539 function enrol_cohort_create_new_group($courseid, $cohortid) {
542 require_once($CFG->dirroot . '/group/lib.php');
544 $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
546 $a->name = $groupname;
548 $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
550 // Check to see if the cohort group name already exists. Add an incremented number if it does.
551 while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
552 $a->increment = '(' . (++$inc) . ')';
553 $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
554 $groupname = $newshortname;
556 // Create a new group for the cohort.
557 $groupdata = new stdClass();
558 $groupdata->courseid = $courseid;
559 $groupdata->name = $groupname;
560 $groupid = groups_create_group($groupdata);