MDL-80599 core: Refactor enrol methods
[moodle.git] / enrol / cohort / lib.php
blobeba1675ea64f33db09f0ffbf6bad63723ae509e7
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_NOGROUP constant for using no group for a cohort.
35 define('COHORT_NOGROUP', 0);
38 /**
39 * Cohort enrolment plugin implementation.
40 * @author Petr Skoda
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class enrol_cohort_plugin extends enrol_plugin {
45 /**
46 * Is it possible to delete enrol instance via standard UI?
48 * @param stdClass $instance
49 * @return bool
51 public function can_delete_instance($instance) {
52 $context = context_course::instance($instance->courseid);
53 return has_capability('enrol/cohort:config', $context);
56 /**
57 * Returns localised name of enrol instance.
59 * @param stdClass $instance (null is accepted too)
60 * @return string
62 public function get_instance_name($instance) {
63 global $DB;
65 if (empty($instance)) {
66 $enrol = $this->get_name();
67 return get_string('pluginname', 'enrol_'.$enrol);
69 } else if (empty($instance->name)) {
70 $enrol = $this->get_name();
71 $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
72 if (!$cohort) {
73 return get_string('pluginname', 'enrol_'.$enrol);
75 $cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid)));
76 if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
77 $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING), ROLENAME_BOTH);
78 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
79 } else {
80 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
83 } else {
84 return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
88 /**
89 * Given a courseid this function returns true if the user is able to enrol or configure cohorts.
90 * AND there are cohorts that the user can view.
92 * @param int $courseid
93 * @return bool
95 public function can_add_instance($courseid) {
96 global $CFG;
97 require_once($CFG->dirroot . '/cohort/lib.php');
98 $coursecontext = context_course::instance($courseid);
99 if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
100 return false;
102 return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
106 * Add new instance of enrol plugin.
107 * @param object $course
108 * @param array $fields instance fields
109 * @return int id of new instance, null if can not be created
111 public function add_instance($course, array $fields = null) {
112 global $CFG;
114 // Allows multiple cohorts to be set on creation.
115 if (!empty($fields['customint1'])) {
116 $fields2 = $fields;
117 if (!is_array($fields['customint1'])) {
118 $fields['customint1'] = array($fields['customint1']);
120 foreach ($fields['customint1'] as $cid) {
121 $fields2['customint1'] = $cid;
122 if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
123 // Create a new group for the cohort if requested.
124 $context = context_course::instance($course->id);
125 require_capability('moodle/course:managegroups', $context);
126 $groupid = enrol_cohort_create_new_group($course->id, $cid);
127 $fields2['customint2'] = $groupid;
129 $result = parent::add_instance($course, $fields2);
131 } else {
132 $result = parent::add_instance($course, $fields);
134 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
135 $trace = new null_progress_trace();
136 enrol_cohort_sync($trace, $course->id);
137 $trace->finished();
138 return $result;
142 * Update instance of enrol plugin.
143 * @param stdClass $instance
144 * @param stdClass $data modified instance fields
145 * @return boolean
147 public function update_instance($instance, $data) {
148 global $CFG;
150 // NOTE: no cohort changes here!!!
151 $context = context_course::instance($instance->courseid);
152 if ($data->roleid != $instance->roleid) {
153 // The sync script can only add roles, for perf reasons it does not modify them.
154 $params = array(
155 'contextid' => $context->id,
156 'roleid' => $instance->roleid,
157 'component' => 'enrol_cohort',
158 'itemid' => $instance->id
160 role_unassign_all($params);
162 // Create a new group for the cohort if requested.
163 if ($data->customint2 == COHORT_CREATE_GROUP) {
164 require_capability('moodle/course:managegroups', $context);
165 $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
166 $data->customint2 = $groupid;
169 $result = parent::update_instance($instance, $data);
171 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
172 $trace = new null_progress_trace();
173 enrol_cohort_sync($trace, $instance->courseid);
174 $trace->finished();
176 return $result;
180 * Called after updating/inserting course.
182 * @param bool $inserted true if course just inserted
183 * @param stdClass $course
184 * @param stdClass $data form data
185 * @return void
187 public function course_updated($inserted, $course, $data) {
188 // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
192 * Update instance status
194 * @param stdClass $instance
195 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
196 * @return void
198 public function update_status($instance, $newstatus) {
199 global $CFG;
201 parent::update_status($instance, $newstatus);
203 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
204 $trace = new null_progress_trace();
205 enrol_cohort_sync($trace, $instance->courseid);
206 $trace->finished();
210 * Does this plugin allow manual unenrolment of a specific user?
211 * Yes, but only if user suspended...
213 * @param stdClass $instance course enrol instance
214 * @param stdClass $ue record from user_enrolments table
216 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
218 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
219 if ($ue->status == ENROL_USER_SUSPENDED) {
220 return true;
223 return false;
227 * Restore instance and map settings.
229 * @param restore_enrolments_structure_step $step
230 * @param stdClass $data
231 * @param stdClass $course
232 * @param int $oldid
234 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
235 global $DB, $CFG;
237 if (!$step->get_task()->is_samesite()) {
238 // No cohort restore from other sites.
239 $step->set_mapping('enrol', $oldid, 0);
240 return;
243 if (!empty($data->customint2)) {
244 $data->customint2 = $step->get_mappingid('group', $data->customint2);
247 if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
248 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
249 if ($instance) {
250 $instanceid = $instance->id;
251 } else {
252 $instanceid = $this->add_instance($course, (array)$data);
254 $step->set_mapping('enrol', $oldid, $instanceid);
256 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
257 $trace = new null_progress_trace();
258 enrol_cohort_sync($trace, $course->id);
259 $trace->finished();
261 } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
262 $data->customint1 = 0;
263 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
265 if ($instance) {
266 $instanceid = $instance->id;
267 } else {
268 $data->status = ENROL_INSTANCE_DISABLED;
269 $instanceid = $this->add_instance($course, (array)$data);
271 $step->set_mapping('enrol', $oldid, $instanceid);
273 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
274 $trace = new null_progress_trace();
275 enrol_cohort_sync($trace, $course->id);
276 $trace->finished();
278 } else {
279 $step->set_mapping('enrol', $oldid, 0);
284 * Restore user enrolment.
286 * @param restore_enrolments_structure_step $step
287 * @param stdClass $data
288 * @param stdClass $instance
289 * @param int $oldinstancestatus
290 * @param int $userid
292 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
293 global $DB;
295 if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
296 // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
297 return;
300 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
301 // but without roles and suspended.
303 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
304 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
309 * Restore user group membership.
310 * @param stdClass $instance
311 * @param int $groupid
312 * @param int $userid
314 public function restore_group_member($instance, $groupid, $userid) {
315 // Nothing to do here, the group members are added in $this->restore_group_restored()
316 return;
320 * Is it possible to hide/show enrol instance via standard UI?
322 * @param stdClass $instance
323 * @return bool
325 public function can_hide_show_instance($instance) {
326 $context = context_course::instance($instance->courseid);
327 return has_capability('enrol/cohort:config', $context);
331 * Return an array of valid options for the status.
333 * @return array
335 protected function get_status_options() {
336 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
337 ENROL_INSTANCE_DISABLED => get_string('no'));
338 return $options;
342 * Return an array of valid options for the cohorts.
344 * @param stdClass $instance
345 * @param context $context
346 * @return array
348 protected function get_cohort_options($instance, $context) {
349 global $DB, $CFG;
351 require_once($CFG->dirroot . '/cohort/lib.php');
353 $cohorts = array();
355 if ($instance->id) {
356 if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
357 $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
358 $cohorts = array($instance->customint1 => $name);
359 } else {
360 $cohorts = array($instance->customint1 => get_string('error'));
362 } else {
363 $cohorts = array('' => get_string('choosedots'));
364 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
365 foreach ($allcohorts as $c) {
366 $cohorts[$c->id] = format_string($c->name);
369 return $cohorts;
373 * Return an array of valid options for the roles.
375 * @param stdClass $instance
376 * @param context $coursecontext
377 * @return array
379 protected function get_role_options($instance, $coursecontext) {
380 global $DB;
382 $roles = get_assignable_roles($coursecontext, ROLENAME_BOTH);
383 $roles[0] = get_string('none');
384 $roles = array_reverse($roles, true); // Descending default sortorder.
386 // If the instance is already configured, but the configured role is no longer assignable in the course then add it back.
387 if ($instance->id and !isset($roles[$instance->roleid])) {
388 if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
389 $roles[$instance->roleid] = role_get_name($role, $coursecontext, ROLENAME_BOTH);
390 } else {
391 $roles[$instance->roleid] = get_string('error');
395 return $roles;
399 * Return an array of valid options for the groups.
401 * @param context $coursecontext
402 * @return array
404 protected function get_group_options($coursecontext) {
405 $groups = array(0 => get_string('none'));
406 if (has_capability('moodle/course:managegroups', $coursecontext)) {
407 $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
410 foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
411 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
414 return $groups;
418 * We are a good plugin and don't invent our own UI/validation code path.
420 * @return boolean
422 public function use_standard_editing_ui() {
423 return true;
427 * Add elements to the edit instance form.
429 * @param stdClass $instance
430 * @param MoodleQuickForm $mform
431 * @param context $coursecontext
432 * @return bool
434 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
436 $options = $this->get_status_options();
437 $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
439 $options = ['contextid' => $coursecontext->id, 'multiple' => true];
440 $mform->addElement('cohort', 'customint1', get_string('cohort', 'cohort'), $options);
442 if ($instance->id) {
443 $mform->setConstant('customint1', $instance->customint1);
444 $mform->hardFreeze('customint1', $instance->customint1);
445 } else {
446 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
449 $roles = $this->get_role_options($instance, $coursecontext);
450 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
451 $mform->setDefault('roleid', $this->get_config('roleid'));
452 $groups = $this->get_group_options($coursecontext);
453 $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
457 * Perform custom validation of the data used to edit the instance.
459 * @param array $data array of ("fieldname" => value) of submitted data
460 * @param array $files array of uploaded files "element_name" => tmp_file_path
461 * @param object $instance The instance loaded from the DB
462 * @param context $context The context of the instance we are editing
463 * @return array of "element_name" => "error_description" if there are errors,
464 * or an empty array if everything is OK.
465 * @return void
467 public function edit_instance_validation($data, $files, $instance, $context) {
468 global $DB;
469 $errors = array();
470 // Allows multiple cohorts to be selected.
471 list($sql1, $params1) = $DB->get_in_or_equal($data['customint1'], SQL_PARAMS_NAMED);
472 $params = array(
473 'roleid' => $data['roleid'],
474 'courseid' => $data['courseid'],
475 'id' => $data['id']
477 $params = array_merge($params, $params1);
478 $sql = "roleid = :roleid AND customint1 $sql1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
479 if ($DB->record_exists_select('enrol', $sql, $params)) {
480 $errors['customint1'] = get_string('instanceexists', 'enrol_cohort');
482 $validstatus = array_keys($this->get_status_options());
483 $validcohorts = array_keys($this->get_cohort_options($instance, $context));
484 $validroles = array_keys($this->get_role_options($instance, $context));
485 $validgroups = array_keys($this->get_group_options($context));
486 $tovalidate = array(
487 'status' => $validstatus,
488 'roleid' => $validroles,
489 'customint2' => $validgroups
491 $typeerrors = $this->validate_param_types($data, $tovalidate);
492 // When creating a new cohort enrolment, we allow multiple cohorts in just one go.
493 // When editing an existing enrolment, changing the cohort is no allowed, so cohort is a single value.
494 if (is_array($data['customint1'])) {
495 $cohorts = $data['customint1'];
496 } else {
497 $cohorts = [$data['customint1']];
500 $errors = array_merge($errors, $typeerrors);
501 // Check that the cohorts passed are valid.
502 if (!empty(array_diff($cohorts, $validcohorts))) {
503 $errors['customint1'] = get_string('invaliddata', 'error');
505 return $errors;
509 * Check if data is valid for a given enrolment plugin
511 * @param array $enrolmentdata enrolment data to validate.
512 * @param int|null $courseid Course ID.
513 * @return array Errors
515 public function validate_enrol_plugin_data(array $enrolmentdata, ?int $courseid = null): array {
516 global $DB;
518 $errors = parent::validate_enrol_plugin_data($enrolmentdata, $courseid);
520 if (isset($enrolmentdata['addtogroup'])) {
521 $addtogroup = $enrolmentdata['addtogroup'];
522 if (($addtogroup == - COHORT_CREATE_GROUP) || $addtogroup == COHORT_NOGROUP) {
523 if (isset($enrolmentdata['groupname'])) {
524 $errors['erroraddtogroupgroupname'] =
525 new lang_string('erroraddtogroupgroupname', 'group');
527 } else {
528 $errors['erroraddtogroup'] =
529 new lang_string('erroraddtogroup', 'group');
533 if ($courseid) {
534 $enrolmentdata = $this->fill_enrol_custom_fields($enrolmentdata, $courseid);
535 $error = $this->validate_plugin_data_context($enrolmentdata, $courseid);
536 if ($error) {
537 $errors['contextnotallowed'] = $error;
540 if (isset($enrolmentdata['groupname']) && $enrolmentdata['groupname']) {
541 $groupname = $enrolmentdata['groupname'];
542 if (!groups_get_group_by_name($courseid, $groupname)) {
543 $errors['errorinvalidgroup'] =
544 new lang_string('errorinvalidgroup', 'group', $groupname);
549 if (!isset($enrolmentdata['cohortidnumber'])) {
550 $missingmandatoryfields = 'cohortidnumber';
551 } else {
552 $cohortidnumber = $enrolmentdata['cohortidnumber'];
553 // Cohort idnumber is unique.
554 $cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $cohortidnumber]);
556 if (!$cohortid) {
557 $errors['unknowncohort'] =
558 new lang_string('unknowncohort', 'cohort', $cohortidnumber);
562 if (!isset($enrolmentdata['role'])) {
563 // We require role since we need it to identify enrol instance.
564 if (isset($missingmandatoryfields)) {
565 $missingmandatoryfields .= ', role';
566 } else {
567 $missingmandatoryfields = 'role';
569 $errors['missingmandatoryfields'] =
570 new lang_string('missingmandatoryfields', 'tool_uploadcourse',
571 $missingmandatoryfields);
572 } else {
573 $roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
574 if (!$roleid) {
575 $errors['unknownrole'] =
576 new lang_string('unknownrole', 'error', s($enrolmentdata['role']));
580 return $errors;
584 * Fill custom fields data for a given enrolment plugin.
586 * @param array $enrolmentdata enrolment data.
587 * @param int $courseid Course ID.
588 * @return array Updated enrolment data with custom fields info.
590 public function fill_enrol_custom_fields(array $enrolmentdata, int $courseid): array {
591 global $DB;
593 if (isset($enrolmentdata['cohortidnumber'])) {
594 // Cohort idnumber is unique.
595 $enrolmentdata['customint1'] =
596 $DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
599 if (isset($enrolmentdata['addtogroup'])) {
600 if ($enrolmentdata['addtogroup'] == COHORT_NOGROUP) {
601 $enrolmentdata['customint2'] = COHORT_NOGROUP;
602 } else if ($enrolmentdata['addtogroup'] == - COHORT_CREATE_GROUP) {
603 $enrolmentdata['customint2'] = COHORT_CREATE_GROUP;
605 } else if (isset($enrolmentdata['groupname'])) {
606 $enrolmentdata['customint2'] = groups_get_group_by_name($courseid, $enrolmentdata['groupname']);
608 return $enrolmentdata;
612 * Check if plugin custom data is allowed in relevant context.
614 * @param array $enrolmentdata enrolment data to validate.
615 * @param int|null $courseid Course ID.
616 * @return lang_string|null Error
618 public function validate_plugin_data_context(array $enrolmentdata, ?int $courseid = null): ?lang_string {
619 $error = null;
620 if (isset($enrolmentdata['customint1'])) {
621 $cohortid = $enrolmentdata['customint1'];
622 $coursecontext = \context_course::instance($courseid);
623 if (!cohort_get_cohort($cohortid, $coursecontext)) {
624 $error = new lang_string('contextcohortnotallowed', 'cohort', $enrolmentdata['cohortidnumber']);
627 return $error;
631 * Add new instance of enrol plugin with custom settings,
632 * called when adding new instance manually or when adding new course.
633 * Used for example on course upload.
635 * Not all plugins support this.
637 * @param stdClass $course Course object
638 * @param array|null $fields instance fields
639 * @return int|null id of new instance or null if not supported
641 public function add_custom_instance(stdClass $course, ?array $fields = null): ?int {
642 return $this->add_instance($course, $fields);
647 * Check if enrolment plugin is supported in csv course upload.
649 * @return bool
651 public function is_csv_upload_supported(): bool {
652 return true;
656 * Finds matching instances for a given course.
658 * @param array $enrolmentdata enrolment data.
659 * @param int $courseid Course ID.
660 * @return stdClass|null Matching instance
662 public function find_instance(array $enrolmentdata, int $courseid): ?stdClass {
663 global $DB;
664 $instances = enrol_get_instances($courseid, false);
666 $instance = null;
667 if (isset($enrolmentdata['cohortidnumber']) && isset($enrolmentdata['role'])) {
668 $cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
669 $roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
670 if ($cohortid && $roleid) {
671 foreach ($instances as $i) {
672 if ($i->enrol == 'cohort' && $i->customint1 == $cohortid && $i->roleid == $roleid) {
673 $instance = $i;
674 break;
679 return $instance;
684 * Prevent removal of enrol roles.
685 * @param int $itemid
686 * @param int $groupid
687 * @param int $userid
688 * @return bool
690 function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
691 return false;
695 * Create a new group with the cohorts name.
697 * @param int $courseid
698 * @param int $cohortid
699 * @return int $groupid Group ID for this cohort.
701 function enrol_cohort_create_new_group($courseid, $cohortid) {
702 global $DB, $CFG;
704 require_once($CFG->dirroot . '/group/lib.php');
706 $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
707 $a = new stdClass();
708 $a->name = $groupname;
709 $a->increment = '';
710 $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
711 $inc = 1;
712 // Check to see if the cohort group name already exists. Add an incremented number if it does.
713 while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
714 $a->increment = '(' . (++$inc) . ')';
715 $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
716 $groupname = $newshortname;
718 // Create a new group for the cohort.
719 $groupdata = new stdClass();
720 $groupdata->courseid = $courseid;
721 $groupdata->name = $groupname;
722 $groupid = groups_create_group($groupdata);
724 return $groupid;