MDL-48362 enrol_cohort: Correct variable naming for course sync
[moodle.git] / enrol / cohort / lib.php
CommitLineData
df997f84 1<?php
df997f84
PS
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.
13//
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/>.
16
17/**
18 * Cohort enrolment plugin.
19 *
e7193380 20 * @package enrol_cohort
465f5088
PS
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
23 */
24
97795859 25defined('MOODLE_INTERNAL') || die();
df997f84 26
7efd0c0a
AG
27/**
28 * COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
29 */
30define('COHORT_CREATE_GROUP', -1);
31
df997f84
PS
32/**
33 * Cohort enrolment plugin implementation.
34 * @author Petr Skoda
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class enrol_cohort_plugin extends enrol_plugin {
ee9e079d
DN
38
39 /**
40 * Is it possible to delete enrol instance via standard UI?
41 *
42 * @param stdClass $instance
43 * @return bool
44 */
45 public function can_delete_instance($instance) {
46 $context = context_course::instance($instance->courseid);
47 return has_capability('enrol/cohort:config', $context);
48 }
49
df997f84 50 /**
e7193380 51 * Returns localised name of enrol instance.
df997f84 52 *
e7193380 53 * @param stdClass $instance (null is accepted too)
df997f84
PS
54 * @return string
55 */
56 public function get_instance_name($instance) {
57 global $DB;
58
59 if (empty($instance)) {
60 $enrol = $this->get_name();
61 return get_string('pluginname', 'enrol_'.$enrol);
7cfe6404 62
df997f84
PS
63 } else if (empty($instance->name)) {
64 $enrol = $this->get_name();
7881024e 65 $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
48391606
PS
66 if (!$cohort) {
67 return get_string('pluginname', 'enrol_'.$enrol);
68 }
7881024e 69 $cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid)));
df997f84 70 if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
55bcef29 71 $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING));
7881024e 72 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
df997f84 73 } else {
7881024e 74 return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
df997f84
PS
75 }
76
df997f84 77 } else {
7881024e 78 return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
df997f84
PS
79 }
80 }
81
b69ca6be 82 /**
e7193380 83 * Given a courseid this function returns true if the user is able to enrol or configure cohorts.
b69ca6be
SH
84 * AND there are cohorts that the user can view.
85 *
86 * @param int $courseid
87 * @return bool
88 */
60010fd6 89 public function can_add_instance($courseid) {
80f98467
MG
90 global $CFG;
91 require_once($CFG->dirroot . '/cohort/lib.php');
55bcef29 92 $coursecontext = context_course::instance($courseid);
465f5088 93 if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
b69ca6be 94 return false;
df997f84 95 }
3e70f579 96 return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
df997f84
PS
97 }
98
60010fd6
DW
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
104 */
105 public function add_instance($course, array $fields = null) {
e3f24ac0 106 global $CFG;
60010fd6
DW
107
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;
114 }
115
e3f24ac0
DW
116 $result = parent::add_instance($course, $fields);
117
118 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
119 $trace = new null_progress_trace();
120 enrol_cohort_sync($trace, $course->id);
121 $trace->finished();
122
123 return $result;
60010fd6
DW
124 }
125
126 /**
127 * Update instance of enrol plugin.
128 * @param stdClass $instance
129 * @param stdClass $data modified instance fields
130 * @return boolean
131 */
132 public function update_instance($instance, $data) {
72fcaae7
DW
133 global $CFG;
134
60010fd6
DW
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.
139 $params = array(
140 'contextid' => $context->id,
141 'roleid' => $instance->roleid,
142 'component' => 'enrol_cohort',
143 'itemid' => $instance->id
144 );
145 role_unassign_all($params);
146 }
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;
152 }
153
e3f24ac0
DW
154 $result = parent::update_instance($instance, $data);
155
156 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
157 $trace = new null_progress_trace();
ebdbc82b 158 enrol_cohort_sync($trace, $instance->courseid);
e3f24ac0
DW
159 $trace->finished();
160
161 return $result;
60010fd6
DW
162 }
163
df997f84
PS
164 /**
165 * Called for all enabled enrol plugins that returned true from is_cron_required().
166 * @return void
167 */
168 public function cron() {
169 global $CFG;
170
df997f84 171 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
172 $trace = new null_progress_trace();
173 enrol_cohort_sync($trace);
174 $trace->finished();
df997f84
PS
175 }
176
177 /**
178 * Called after updating/inserting course.
179 *
180 * @param bool $inserted true if course just inserted
e7193380
PS
181 * @param stdClass $course
182 * @param stdClass $data form data
df997f84
PS
183 * @return void
184 */
185 public function course_updated($inserted, $course, $data) {
d94ef563 186 // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
df997f84 187 }
b69ca6be 188
7cfe6404
PS
189 /**
190 * Update instance status
191 *
192 * @param stdClass $instance
193 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
194 * @return void
195 */
196 public function update_status($instance, $newstatus) {
197 global $CFG;
198
199 parent::update_status($instance, $newstatus);
200
201 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
202 $trace = new null_progress_trace();
203 enrol_cohort_sync($trace, $instance->courseid);
204 $trace->finished();
7cfe6404
PS
205 }
206
207 /**
208 * Does this plugin allow manual unenrolment of a specific user?
209 * Yes, but only if user suspended...
210 *
211 * @param stdClass $instance course enrol instance
212 * @param stdClass $ue record from user_enrolments table
213 *
214 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
215 */
216 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
217 if ($ue->status == ENROL_USER_SUSPENDED) {
218 return true;
219 }
220
221 return false;
222 }
223
224 /**
e7193380 225 * Gets an array of the user enrolment actions.
7cfe6404
PS
226 *
227 * @param course_enrolment_manager $manager
228 * @param stdClass $ue A user enrolment object
229 * @return array An array of user_enrolment_actions
230 */
231 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
232 $actions = array();
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 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url, array('class'=>'unenrollink', 'rel'=>$ue->id));
240 }
241 return $actions;
242 }
243
94335e5a
PS
244 /**
245 * Restore instance and map settings.
246 *
247 * @param restore_enrolments_structure_step $step
248 * @param stdClass $data
249 * @param stdClass $course
250 * @param int $oldid
251 */
252 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
253 global $DB, $CFG;
254
255 if (!$step->get_task()->is_samesite()) {
256 // No cohort restore from other sites.
257 $step->set_mapping('enrol', $oldid, 0);
258 return;
259 }
260
7881024e
PS
261 if (!empty($data->customint2)) {
262 $data->customint2 = $step->get_mappingid('group', $data->customint2);
263 }
264
94335e5a
PS
265 if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
266 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
267 if ($instance) {
9549090d 268 $instanceid = $instance->id;
94335e5a
PS
269 } else {
270 $instanceid = $this->add_instance($course, (array)$data);
271 }
272 $step->set_mapping('enrol', $oldid, $instanceid);
273
274 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
275 $trace = new null_progress_trace();
276 enrol_cohort_sync($trace, $course->id);
277 $trace->finished();
94335e5a
PS
278
279 } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
280 $data->customint1 = 0;
281 $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
282
283 if ($instance) {
9549090d 284 $instanceid = $instance->id;
94335e5a
PS
285 } else {
286 $data->status = ENROL_INSTANCE_DISABLED;
287 $instanceid = $this->add_instance($course, (array)$data);
288 }
289 $step->set_mapping('enrol', $oldid, $instanceid);
df997f84 290
94335e5a 291 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
292 $trace = new null_progress_trace();
293 enrol_cohort_sync($trace, $course->id);
294 $trace->finished();
94335e5a
PS
295
296 } else {
297 $step->set_mapping('enrol', $oldid, 0);
298 }
299 }
300
301 /**
302 * Restore user enrolment.
303 *
304 * @param restore_enrolments_structure_step $step
305 * @param stdClass $data
306 * @param stdClass $instance
307 * @param int $oldinstancestatus
308 * @param int $userid
309 */
310 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
311 global $DB;
312
313 if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
314 // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
315 return;
316 }
317
318 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
319 // but without roles and suspended.
320
321 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
322 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
323 }
324 }
7881024e
PS
325
326 /**
327 * Restore user group membership.
328 * @param stdClass $instance
329 * @param int $groupid
330 * @param int $userid
331 */
332 public function restore_group_member($instance, $groupid, $userid) {
333 // Nothing to do here, the group members are added in $this->restore_group_restored()
334 return;
335 }
b5a289c4
DNA
336
337 /**
338 * Is it possible to hide/show enrol instance via standard UI?
339 *
340 * @param stdClass $instance
341 * @return bool
342 */
343 public function can_hide_show_instance($instance) {
344 $context = context_course::instance($instance->courseid);
345 return has_capability('enrol/cohort:config', $context);
346 }
60010fd6
DW
347
348 /**
349 * Return an array of valid options for the status.
350 *
351 * @return array
352 */
353 protected function get_status_options() {
354 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
355 ENROL_INSTANCE_DISABLED => get_string('no'));
356 return $options;
357 }
358
359 /**
360 * Return an array of valid options for the cohorts.
361 *
362 * @param stdClass $instance
363 * @param context $context
364 * @return array
365 */
366 protected function get_cohort_options($instance, $context) {
367 global $DB, $CFG;
368
369 require_once($CFG->dirroot . '/cohort/lib.php');
370
371 $cohorts = array();
372
373 if ($instance->id) {
374 if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
375 $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
376 $cohorts = array($instance->customint1 => $name);
377 } else {
378 $cohorts = array($instance->customint1 => get_string('error'));
379 }
380 } else {
381 $cohorts = array('' => get_string('choosedots'));
382 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
383 foreach ($allcohorts as $c) {
384 $cohorts[$c->id] = format_string($c->name);
385 }
386 }
387 return $cohorts;
388 }
389
390 /**
391 * Return an array of valid options for the roles.
392 *
393 * @param stdClass $instance
394 * @param context $coursecontext
395 * @return array
396 */
397 protected function get_role_options($instance, $coursecontext) {
398 global $DB;
399
400 $roles = get_assignable_roles($coursecontext);
401 $roles[0] = get_string('none');
402 $roles = array_reverse($roles, true); // Descending default sortorder.
403 if ($instance->id and !isset($roles[$instance->roleid])) {
404 if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
405 $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true);
406 $roles[$instance->roleid] = role_get_name($role, $coursecontext);
407 } else {
408 $roles[$instance->roleid] = get_string('error');
409 }
410 }
411
412 return $roles;
413 }
414
415 /**
416 * Return an array of valid options for the groups.
417 *
418 * @param context $coursecontext
419 * @return array
420 */
421 protected function get_group_options($coursecontext) {
422 $groups = array(0 => get_string('none'));
423 if (has_capability('moodle/course:managegroups', $coursecontext)) {
424 $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
425 }
426
427 foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
428 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
429 }
430
431 return $groups;
432 }
433
434 /**
435 * We are a good plugin and don't invent our own UI/validation code path.
436 *
437 * @return boolean
438 */
439 public function use_standard_editing_ui() {
440 return true;
441 }
442
443 /**
444 * Add elements to the edit instance form.
445 *
446 * @param stdClass $instance
447 * @param MoodleQuickForm $mform
448 * @param context $coursecontext
449 * @return bool
450 */
451 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
452 global $DB;
453
454 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
455 $mform->setType('name', PARAM_TEXT);
456
457 $options = $this->get_status_options();
458 $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
459
460 $options = $this->get_cohort_options($instance, $coursecontext);
461 $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $options);
462 if ($instance->id) {
463 $mform->setConstant('customint1', $instance->customint1);
464 $mform->hardFreeze('customint1', $instance->customint1);
465 } else {
466 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
467 }
468
469 $roles = $this->get_role_options($instance, $coursecontext);
470 $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
471 $mform->setDefault('roleid', $this->get_config('roleid'));
472 $groups = $this->get_group_options($coursecontext);
473 $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
474 }
475
476 /**
477 * Perform custom validation of the data used to edit the instance.
478 *
479 * @param array $data array of ("fieldname" => value) of submitted data
480 * @param array $files array of uploaded files "element_name" => tmp_file_path
481 * @param object $instance The instance loaded from the DB
482 * @param context $context The context of the instance we are editing
483 * @return array of "element_name" => "error_description" if there are errors,
484 * or an empty array if everything is OK.
485 * @return void
486 */
487 public function edit_instance_validation($data, $files, $instance, $context) {
488 global $DB;
489 $errors = array();
490
491 $params = array(
492 'roleid' => $data['roleid'],
493 'customint1' => $data['customint1'],
494 'courseid' => $data['courseid'],
495 'id' => $data['id']
496 );
497 $sql = "roleid = :roleid AND customint1 = :customint1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
498 if ($DB->record_exists_select('enrol', $sql, $params)) {
499 $errors['roleid'] = get_string('instanceexists', 'enrol_cohort');
500 }
501 $validstatus = array_keys($this->get_status_options());
502 $validcohorts = array_keys($this->get_cohort_options($instance, $context));
503 $validroles = array_keys($this->get_role_options($instance, $context));
504 $validgroups = array_keys($this->get_group_options($context));
505 $tovalidate = array(
506 'name' => PARAM_TEXT,
507 'status' => $validstatus,
508 'customint1' => $validcohorts,
509 'roleid' => $validroles,
510 'customint2' => $validgroups
511 );
512 $typeerrors = $this->validate_param_types($data, $tovalidate);
513 $errors = array_merge($errors, $typeerrors);
514
515 return $errors;
516 }
7881024e
PS
517}
518
519/**
520 * Prevent removal of enrol roles.
521 * @param int $itemid
522 * @param int $groupid
523 * @param int $userid
524 * @return bool
525 */
526function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
527 return false;
94335e5a 528}
73985b14 529
df9dbc9f
AG
530/**
531 * Create a new group with the cohorts name.
532 *
533 * @param int $courseid
534 * @param int $cohortid
535 * @return int $groupid Group ID for this cohort.
536 */
73985b14 537function enrol_cohort_create_new_group($courseid, $cohortid) {
60010fd6
DW
538 global $DB, $CFG;
539
540 require_once($CFG->dirroot . '/group/lib.php');
7efd0c0a
AG
541
542 $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
543 $a = new stdClass();
544 $a->name = $groupname;
545 $a->increment = '';
5894432c 546 $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
42c92eef 547 $inc = 1;
7efd0c0a 548 // Check to see if the cohort group name already exists. Add an incremented number if it does.
42c92eef
MG
549 while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
550 $a->increment = '(' . (++$inc) . ')';
5894432c 551 $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
7efd0c0a 552 $groupname = $newshortname;
73985b14 553 }
7efd0c0a
AG
554 // Create a new group for the cohort.
555 $groupdata = new stdClass();
556 $groupdata->courseid = $courseid;
557 $groupdata->name = $groupname;
558 $groupid = groups_create_group($groupdata);
559
73985b14 560 return $groupid;
32b97a03 561}