Merge branch 'MDL-65584-37' of https://github.com/paulholden/moodle into MOODLE_37_STABLE
[moodle.git] / enrol / meta / lib.php
blobb64817b714042f356289935e90071fe1396fccfd
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 * Meta course enrolment plugin.
20 * @package enrol_meta
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 * ENROL_META_CREATE_GROUP constant for automatically creating a group for a meta course.
30 define('ENROL_META_CREATE_GROUP', -1);
32 /**
33 * Meta course enrolment plugin.
34 * @author Petr Skoda
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class enrol_meta_plugin extends enrol_plugin {
39 /**
40 * Returns localised name of enrol instance
42 * @param stdClass $instance (null is accepted too)
43 * @return string
45 public function get_instance_name($instance) {
46 global $DB;
48 if (empty($instance)) {
49 $enrol = $this->get_name();
50 return get_string('pluginname', 'enrol_'.$enrol);
51 } else if (empty($instance->name)) {
52 $enrol = $this->get_name();
53 $course = $DB->get_record('course', array('id'=>$instance->customint1));
54 if ($course) {
55 $coursename = format_string(get_course_display_name_for_list($course));
56 } else {
57 // Use course id, if course is deleted.
58 $coursename = $instance->customint1;
60 return get_string('pluginname', 'enrol_' . $enrol) . ' (' . $coursename . ')';
61 } else {
62 return format_string($instance->name);
66 /**
67 * Returns true if we can add a new instance to this course.
69 * @param int $courseid
70 * @return boolean
72 public function can_add_instance($courseid) {
73 $context = context_course::instance($courseid, MUST_EXIST);
74 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/meta:config', $context)) {
75 return false;
77 // Multiple instances supported - multiple parent courses linked.
78 return true;
81 /**
82 * Does this plugin allow manual unenrolment of a specific user?
83 * Yes, but only if user suspended...
85 * @param stdClass $instance course enrol instance
86 * @param stdClass $ue record from user_enrolments table
88 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
90 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
91 if ($ue->status == ENROL_USER_SUSPENDED) {
92 return true;
95 return false;
98 /**
99 * Called after updating/inserting course.
101 * @param bool $inserted true if course just inserted
102 * @param stdClass $course
103 * @param stdClass $data form data
104 * @return void
106 public function course_updated($inserted, $course, $data) {
107 // Meta sync updates are slow, if enrolments get out of sync teacher will have to wait till next cron.
108 // We should probably add some sync button to the course enrol methods overview page.
112 * Add new instance of enrol plugin.
113 * @param object $course
114 * @param array $fields instance fields
115 * @return int id of last instance, null if can not be created
117 public function add_instance($course, array $fields = null) {
118 global $CFG;
120 require_once("$CFG->dirroot/enrol/meta/locallib.php");
122 // Support creating multiple at once.
123 if (is_array($fields['customint1'])) {
124 $courses = array_unique($fields['customint1']);
125 } else {
126 $courses = array($fields['customint1']);
128 foreach ($courses as $courseid) {
129 if (!empty($fields['customint2']) && $fields['customint2'] == ENROL_META_CREATE_GROUP) {
130 $context = context_course::instance($course->id);
131 require_capability('moodle/course:managegroups', $context);
132 $groupid = enrol_meta_create_new_group($course->id, $courseid);
133 $fields['customint2'] = $groupid;
136 $fields['customint1'] = $courseid;
137 $result = parent::add_instance($course, $fields);
140 enrol_meta_sync($course->id);
142 return $result;
146 * Update instance of enrol plugin.
147 * @param stdClass $instance
148 * @param stdClass $data modified instance fields
149 * @return boolean
151 public function update_instance($instance, $data) {
152 global $CFG;
154 require_once("$CFG->dirroot/enrol/meta/locallib.php");
156 if (!empty($data->customint2) && $data->customint2 == ENROL_META_CREATE_GROUP) {
157 $context = context_course::instance($instance->courseid);
158 require_capability('moodle/course:managegroups', $context);
159 $groupid = enrol_meta_create_new_group($instance->courseid, $data->customint1);
160 $data->customint2 = $groupid;
163 $result = parent::update_instance($instance, $data);
165 enrol_meta_sync($instance->courseid);
167 return $result;
171 * Update instance status
173 * @param stdClass $instance
174 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
175 * @return void
177 public function update_status($instance, $newstatus) {
178 global $CFG;
180 parent::update_status($instance, $newstatus);
182 require_once("$CFG->dirroot/enrol/meta/locallib.php");
183 enrol_meta_sync($instance->courseid);
187 * Is it possible to delete enrol instance via standard UI?
189 * @param stdClass $instance
190 * @return bool
192 public function can_delete_instance($instance) {
193 $context = context_course::instance($instance->courseid);
194 return has_capability('enrol/meta:config', $context);
198 * Is it possible to hide/show enrol instance via standard UI?
200 * @param stdClass $instance
201 * @return bool
203 public function can_hide_show_instance($instance) {
204 $context = context_course::instance($instance->courseid);
205 return has_capability('enrol/meta:config', $context);
209 * We are a good plugin and don't invent our own UI/validation code path.
211 * @return boolean
213 public function use_standard_editing_ui() {
214 return true;
218 * Return an array of valid options for the courses.
220 * @param stdClass $instance
221 * @param context $coursecontext
222 * @return array
224 protected function get_course_options($instance, $coursecontext) {
225 global $DB;
227 if ($instance->id) {
228 $where = 'WHERE c.id = :courseid';
229 $params = array('courseid' => $instance->customint1);
230 $existing = array();
231 } else {
232 $where = '';
233 $params = array();
234 $instanceparams = array('enrol' => 'meta', 'courseid' => $instance->courseid);
235 $existing = $DB->get_records('enrol', $instanceparams, '', 'customint1, id');
238 // TODO: this has to be done via ajax or else it will fail very badly on large sites!
239 $courses = array();
240 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
241 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
243 $sortorder = 'c.' . $this->get_config('coursesort', 'sortorder') . ' ASC';
245 $sql = "SELECT c.id, c.fullname, c.shortname, c.visible $select FROM {course} c $join $where ORDER BY $sortorder";
246 $rs = $DB->get_recordset_sql($sql, array('contextlevel' => CONTEXT_COURSE) + $params);
247 foreach ($rs as $c) {
248 if ($c->id == SITEID or $c->id == $instance->courseid or isset($existing[$c->id])) {
249 continue;
251 context_helper::preload_from_record($c);
252 $coursecontext = context_course::instance($c->id);
253 if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
254 continue;
256 if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) {
257 continue;
259 $courses[$c->id] = $coursecontext->get_context_name(false);
261 $rs->close();
262 return $courses;
266 * Return an array of valid options for the groups.
268 * @param context $coursecontext
269 * @return array
271 protected function get_group_options($coursecontext) {
272 $groups = array(0 => get_string('none'));
273 $courseid = $coursecontext->instanceid;
274 if (has_capability('moodle/course:managegroups', $coursecontext)) {
275 $groups[ENROL_META_CREATE_GROUP] = get_string('creategroup', 'enrol_meta');
277 foreach (groups_get_all_groups($courseid) as $group) {
278 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
280 return $groups;
284 * Add elements to the edit instance form.
286 * @param stdClass $instance
287 * @param MoodleQuickForm $mform
288 * @param context $coursecontext
289 * @return bool
291 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
292 global $DB;
294 $groups = $this->get_group_options($coursecontext);
295 $existing = $DB->get_records('enrol', array('enrol' => 'meta', 'courseid' => $coursecontext->instanceid), '', 'customint1, id');
297 $excludelist = array($coursecontext->instanceid);
298 foreach ($existing as $existinginstance) {
299 $excludelist[] = $existinginstance->customint1;
302 $options = array(
303 'requiredcapabilities' => array('enrol/meta:selectaslinked'),
304 'multiple' => empty($instance->id), // We only accept multiple values on creation.
305 'exclude' => $excludelist
307 $mform->addElement('course', 'customint1', get_string('linkedcourse', 'enrol_meta'), $options);
308 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
309 if (!empty($instance->id)) {
310 $mform->freeze('customint1');
313 $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_meta'), $groups);
317 * Perform custom validation of the data used to edit the instance.
319 * @param array $data array of ("fieldname"=>value) of submitted data
320 * @param array $files array of uploaded files "element_name"=>tmp_file_path
321 * @param object $instance The instance loaded from the DB
322 * @param context $context The context of the instance we are editing
323 * @return array of "element_name"=>"error_description" if there are errors,
324 * or an empty array if everything is OK.
325 * @return void
327 public function edit_instance_validation($data, $files, $instance, $context) {
328 global $DB;
329 $errors = array();
330 $thiscourseid = $context->instanceid;
331 $c = false;
333 if (!empty($data['customint1'])) {
334 $courses = is_array($data['customint1']) ? $data['customint1'] : [$data['customint1']];
335 foreach ($courses as $courseid) {
336 $c = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
337 $coursecontext = context_course::instance($c->id);
339 $sqlexists = 'enrol = :meta AND courseid = :currentcourseid AND customint1 = :courseid AND id != :id';
340 $existing = $DB->record_exists_select('enrol', $sqlexists, [
341 'meta' => 'meta',
342 'currentcourseid' => $thiscourseid,
343 'courseid' => $c->id,
344 'id' => $instance->id
347 if (!$c->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
348 $errors['customint1'] = get_string('error');
349 } else if (!has_capability('enrol/meta:selectaslinked', $coursecontext)) {
350 $errors['customint1'] = get_string('error');
351 } else if ($c->id == SITEID or $c->id == $thiscourseid or $existing) {
352 $errors['customint1'] = get_string('error');
355 } else {
356 $errors['customint1'] = get_string('required');
359 $validgroups = array_keys($this->get_group_options($context));
361 $tovalidate = array(
362 'customint2' => $validgroups
364 $typeerrors = $this->validate_param_types($data, $tovalidate);
365 $errors = array_merge($errors, $typeerrors);
367 return $errors;
372 * Restore instance and map settings.
374 * @param restore_enrolments_structure_step $step
375 * @param stdClass $data
376 * @param stdClass $course
377 * @param int $oldid
379 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
380 global $DB, $CFG;
382 if (!$step->get_task()->is_samesite()) {
383 // No meta restore from other sites.
384 $step->set_mapping('enrol', $oldid, 0);
385 return;
388 if (!empty($data->customint2)) {
389 $data->customint2 = $step->get_mappingid('group', $data->customint2);
392 if ($DB->record_exists('course', array('id' => $data->customint1))) {
393 $instance = $DB->get_record('enrol', array('roleid' => $data->roleid, 'customint1' => $data->customint1,
394 'courseid' => $course->id, 'enrol' => $this->get_name()));
395 if ($instance) {
396 $instanceid = $instance->id;
397 } else {
398 $instanceid = $this->add_instance($course, (array)$data);
400 $step->set_mapping('enrol', $oldid, $instanceid);
402 require_once("$CFG->dirroot/enrol/meta/locallib.php");
403 enrol_meta_sync($data->customint1);
405 } else {
406 $step->set_mapping('enrol', $oldid, 0);
411 * Restore user enrolment.
413 * @param restore_enrolments_structure_step $step
414 * @param stdClass $data
415 * @param stdClass $instance
416 * @param int $userid
417 * @param int $oldinstancestatus
419 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
420 global $DB;
422 if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
423 // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
424 return;
427 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
428 // but without roles and suspended.
430 if (!$DB->record_exists('user_enrolments', array('enrolid' => $instance->id, 'userid' => $userid))) {
431 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
432 if ($instance->customint2) {
433 groups_add_member($instance->customint2, $userid, 'enrol_meta', $instance->id);
439 * Restore user group membership.
440 * @param stdClass $instance
441 * @param int $groupid
442 * @param int $userid
444 public function restore_group_member($instance, $groupid, $userid) {
445 // Nothing to do here, the group members are added in $this->restore_group_restored().
446 return;