Merge branch 'MDL-73996-master-fix' of https://github.com/junpataleta/moodle
[moodle.git] / enrol / cohort / lib.php
blobb1dcb04459700ee3cbf737e396655778a0895166
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 * 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 /**
28 * COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
30 define('COHORT_CREATE_GROUP', -1);
32 /**
33 * Cohort enrolment plugin implementation.
34 * @author Petr Skoda
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class enrol_cohort_plugin extends enrol_plugin {
39 /**
40 * Is it possible to delete enrol instance via standard UI?
42 * @param stdClass $instance
43 * @return bool
45 public function can_delete_instance($instance) {
46 $context = context_course::instance($instance->courseid);
47 return has_capability('enrol/cohort:config', $context);
50 /**
51 * Returns localised name of enrol instance.
53 * @param stdClass $instance (null is accepted too)
54 * @return string
56 public function get_instance_name($instance) {
57 global $DB;
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));
66 if (!$cohort) {
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), ROLENAME_BOTH);
72 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
73 } else {
74 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
77 } else {
78 return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
82 /**
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
87 * @return bool
89 public function can_add_instance($courseid) {
90 global $CFG;
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)) {
94 return false;
96 return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
99 /**
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) {
106 global $CFG;
108 // Allows multiple cohorts to be set on creation.
109 if (!empty($fields['customint1'])) {
110 $fields2 = $fields;
111 if (!is_array($fields['customint1'])) {
112 $fields['customint1'] = array($fields['customint1']);
114 foreach ($fields['customint1'] as $cid) {
115 $fields2['customint1'] = $cid;
116 if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
117 // Create a new group for the cohort if requested.
118 $context = context_course::instance($course->id);
119 require_capability('moodle/course:managegroups', $context);
120 $groupid = enrol_cohort_create_new_group($course->id, $cid);
121 $fields2['customint2'] = $groupid;
123 $result = parent::add_instance($course, $fields2);
125 } else {
126 $result = parent::add_instance($course, $fields);
128 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
129 $trace = new null_progress_trace();
130 enrol_cohort_sync($trace, $course->id);
131 $trace->finished();
132 return $result;
136 * Update instance of enrol plugin.
137 * @param stdClass $instance
138 * @param stdClass $data modified instance fields
139 * @return boolean
141 public function update_instance($instance, $data) {
142 global $CFG;
144 // NOTE: no cohort changes here!!!
145 $context = context_course::instance($instance->courseid);
146 if ($data->roleid != $instance->roleid) {
147 // The sync script can only add roles, for perf reasons it does not modify them.
148 $params = array(
149 'contextid' => $context->id,
150 'roleid' => $instance->roleid,
151 'component' => 'enrol_cohort',
152 'itemid' => $instance->id
154 role_unassign_all($params);
156 // Create a new group for the cohort if requested.
157 if ($data->customint2 == COHORT_CREATE_GROUP) {
158 require_capability('moodle/course:managegroups', $context);
159 $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
160 $data->customint2 = $groupid;
163 $result = parent::update_instance($instance, $data);
165 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
166 $trace = new null_progress_trace();
167 enrol_cohort_sync($trace, $instance->courseid);
168 $trace->finished();
170 return $result;
174 * Called after updating/inserting course.
176 * @param bool $inserted true if course just inserted
177 * @param stdClass $course
178 * @param stdClass $data form data
179 * @return void
181 public function course_updated($inserted, $course, $data) {
182 // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
186 * Update instance status
188 * @param stdClass $instance
189 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
190 * @return void
192 public function update_status($instance, $newstatus) {
193 global $CFG;
195 parent::update_status($instance, $newstatus);
197 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
198 $trace = new null_progress_trace();
199 enrol_cohort_sync($trace, $instance->courseid);
200 $trace->finished();
204 * Does this plugin allow manual unenrolment of a specific user?
205 * Yes, but only if user suspended...
207 * @param stdClass $instance course enrol instance
208 * @param stdClass $ue record from user_enrolments table
210 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
212 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
213 if ($ue->status == ENROL_USER_SUSPENDED) {
214 return true;
217 return false;
221 * Restore instance and map settings.
223 * @param restore_enrolments_structure_step $step
224 * @param stdClass $data
225 * @param stdClass $course
226 * @param int $oldid
228 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
229 global $DB, $CFG;
231 if (!$step->get_task()->is_samesite()) {
232 // No cohort restore from other sites.
233 $step->set_mapping('enrol', $oldid, 0);
234 return;
237 if (!empty($data->customint2)) {
238 $data->customint2 = $step->get_mappingid('group', $data->customint2);
241 if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
242 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
243 if ($instance) {
244 $instanceid = $instance->id;
245 } else {
246 $instanceid = $this->add_instance($course, (array)$data);
248 $step->set_mapping('enrol', $oldid, $instanceid);
250 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
251 $trace = new null_progress_trace();
252 enrol_cohort_sync($trace, $course->id);
253 $trace->finished();
255 } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
256 $data->customint1 = 0;
257 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
259 if ($instance) {
260 $instanceid = $instance->id;
261 } else {
262 $data->status = ENROL_INSTANCE_DISABLED;
263 $instanceid = $this->add_instance($course, (array)$data);
265 $step->set_mapping('enrol', $oldid, $instanceid);
267 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
268 $trace = new null_progress_trace();
269 enrol_cohort_sync($trace, $course->id);
270 $trace->finished();
272 } else {
273 $step->set_mapping('enrol', $oldid, 0);
278 * Restore user enrolment.
280 * @param restore_enrolments_structure_step $step
281 * @param stdClass $data
282 * @param stdClass $instance
283 * @param int $oldinstancestatus
284 * @param int $userid
286 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
287 global $DB;
289 if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
290 // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
291 return;
294 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
295 // but without roles and suspended.
297 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
298 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
303 * Restore user group membership.
304 * @param stdClass $instance
305 * @param int $groupid
306 * @param int $userid
308 public function restore_group_member($instance, $groupid, $userid) {
309 // Nothing to do here, the group members are added in $this->restore_group_restored()
310 return;
314 * Is it possible to hide/show enrol instance via standard UI?
316 * @param stdClass $instance
317 * @return bool
319 public function can_hide_show_instance($instance) {
320 $context = context_course::instance($instance->courseid);
321 return has_capability('enrol/cohort:config', $context);
325 * Return an array of valid options for the status.
327 * @return array
329 protected function get_status_options() {
330 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
331 ENROL_INSTANCE_DISABLED => get_string('no'));
332 return $options;
336 * Return an array of valid options for the cohorts.
338 * @param stdClass $instance
339 * @param context $context
340 * @return array
342 protected function get_cohort_options($instance, $context) {
343 global $DB, $CFG;
345 require_once($CFG->dirroot . '/cohort/lib.php');
347 $cohorts = array();
349 if ($instance->id) {
350 if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
351 $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
352 $cohorts = array($instance->customint1 => $name);
353 } else {
354 $cohorts = array($instance->customint1 => get_string('error'));
356 } else {
357 $cohorts = array('' => get_string('choosedots'));
358 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
359 foreach ($allcohorts as $c) {
360 $cohorts[$c->id] = format_string($c->name);
363 return $cohorts;
367 * Return an array of valid options for the roles.
369 * @param stdClass $instance
370 * @param context $coursecontext
371 * @return array
373 protected function get_role_options($instance, $coursecontext) {
374 global $DB;
376 $roles = get_assignable_roles($coursecontext, ROLENAME_BOTH);
377 $roles[0] = get_string('none');
378 $roles = array_reverse($roles, true); // Descending default sortorder.
380 // If the instance is already configured, but the configured role is no longer assignable in the course then add it back.
381 if ($instance->id and !isset($roles[$instance->roleid])) {
382 if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
383 $roles[$instance->roleid] = role_get_name($role, $coursecontext, ROLENAME_BOTH);
384 } else {
385 $roles[$instance->roleid] = get_string('error');
389 return $roles;
393 * Return an array of valid options for the groups.
395 * @param context $coursecontext
396 * @return array
398 protected function get_group_options($coursecontext) {
399 $groups = array(0 => get_string('none'));
400 if (has_capability('moodle/course:managegroups', $coursecontext)) {
401 $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
404 foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
405 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
408 return $groups;
412 * We are a good plugin and don't invent our own UI/validation code path.
414 * @return boolean
416 public function use_standard_editing_ui() {
417 return true;
421 * Add elements to the edit instance form.
423 * @param stdClass $instance
424 * @param MoodleQuickForm $mform
425 * @param context $coursecontext
426 * @return bool
428 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
430 $options = $this->get_status_options();
431 $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
433 $options = ['contextid' => $coursecontext->id, 'multiple' => true];
434 $mform->addElement('cohort', 'customint1', get_string('cohort', 'cohort'), $options);
436 if ($instance->id) {
437 $mform->setConstant('customint1', $instance->customint1);
438 $mform->hardFreeze('customint1', $instance->customint1);
439 } else {
440 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
443 $roles = $this->get_role_options($instance, $coursecontext);
444 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
445 $mform->setDefault('roleid', $this->get_config('roleid'));
446 $groups = $this->get_group_options($coursecontext);
447 $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
451 * Perform custom validation of the data used to edit the instance.
453 * @param array $data array of ("fieldname" => value) of submitted data
454 * @param array $files array of uploaded files "element_name" => tmp_file_path
455 * @param object $instance The instance loaded from the DB
456 * @param context $context The context of the instance we are editing
457 * @return array of "element_name" => "error_description" if there are errors,
458 * or an empty array if everything is OK.
459 * @return void
461 public function edit_instance_validation($data, $files, $instance, $context) {
462 global $DB;
463 $errors = array();
464 // Allows multiple cohorts to be selected.
465 list($sql1, $params1) = $DB->get_in_or_equal($data['customint1'], SQL_PARAMS_NAMED);
466 $params = array(
467 'roleid' => $data['roleid'],
468 'courseid' => $data['courseid'],
469 'id' => $data['id']
471 $params = array_merge($params, $params1);
472 $sql = "roleid = :roleid AND customint1 $sql1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
473 if ($DB->record_exists_select('enrol', $sql, $params)) {
474 $errors['customint1'] = get_string('instanceexists', 'enrol_cohort');
476 $validstatus = array_keys($this->get_status_options());
477 $validcohorts = array_keys($this->get_cohort_options($instance, $context));
478 $validroles = array_keys($this->get_role_options($instance, $context));
479 $validgroups = array_keys($this->get_group_options($context));
480 $tovalidate = array(
481 'status' => $validstatus,
482 'roleid' => $validroles,
483 'customint2' => $validgroups
485 $typeerrors = $this->validate_param_types($data, $tovalidate);
486 // When creating a new cohort enrolment, we allow multiple cohorts in just one go.
487 // When editing an existing enrolment, changing the cohort is no allowed, so cohort is a single value.
488 if (is_array($data['customint1'])) {
489 $cohorts = $data['customint1'];
490 } else {
491 $cohorts = [$data['customint1']];
494 $errors = array_merge($errors, $typeerrors);
495 // Check that the cohorts passed are valid.
496 if (!empty(array_diff($cohorts, $validcohorts))) {
497 $errors['customint1'] = get_string('invaliddata', 'error');
499 return $errors;
504 * Prevent removal of enrol roles.
505 * @param int $itemid
506 * @param int $groupid
507 * @param int $userid
508 * @return bool
510 function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
511 return false;
515 * Create a new group with the cohorts name.
517 * @param int $courseid
518 * @param int $cohortid
519 * @return int $groupid Group ID for this cohort.
521 function enrol_cohort_create_new_group($courseid, $cohortid) {
522 global $DB, $CFG;
524 require_once($CFG->dirroot . '/group/lib.php');
526 $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
527 $a = new stdClass();
528 $a->name = $groupname;
529 $a->increment = '';
530 $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
531 $inc = 1;
532 // Check to see if the cohort group name already exists. Add an incremented number if it does.
533 while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
534 $a->increment = '(' . (++$inc) . ')';
535 $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
536 $groupname = $newshortname;
538 // Create a new group for the cohort.
539 $groupdata = new stdClass();
540 $groupdata->courseid = $courseid;
541 $groupdata->name = $groupname;
542 $groupid = groups_create_group($groupdata);
544 return $groupid;