MDL-59369 enrol: Introduce data-action attribute for enrol action links
[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);
fd0a43be
JP
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,
241 $actionparams);
7cfe6404
PS
242 }
243 return $actions;
244 }
245
94335e5a
PS
246 /**
247 * Restore instance and map settings.
248 *
249 * @param restore_enrolments_structure_step $step
250 * @param stdClass $data
251 * @param stdClass $course
252 * @param int $oldid
253 */
254 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
255 global $DB, $CFG;
256
257 if (!$step->get_task()->is_samesite()) {
258 // No cohort restore from other sites.
259 $step->set_mapping('enrol', $oldid, 0);
260 return;
261 }
262
7881024e
PS
263 if (!empty($data->customint2)) {
264 $data->customint2 = $step->get_mappingid('group', $data->customint2);
265 }
266
94335e5a
PS
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()));
269 if ($instance) {
9549090d 270 $instanceid = $instance->id;
94335e5a
PS
271 } else {
272 $instanceid = $this->add_instance($course, (array)$data);
273 }
274 $step->set_mapping('enrol', $oldid, $instanceid);
275
276 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
277 $trace = new null_progress_trace();
278 enrol_cohort_sync($trace, $course->id);
279 $trace->finished();
94335e5a
PS
280
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()));
284
285 if ($instance) {
9549090d 286 $instanceid = $instance->id;
94335e5a
PS
287 } else {
288 $data->status = ENROL_INSTANCE_DISABLED;
289 $instanceid = $this->add_instance($course, (array)$data);
290 }
291 $step->set_mapping('enrol', $oldid, $instanceid);
df997f84 292
94335e5a 293 require_once("$CFG->dirroot/enrol/cohort/locallib.php");
c6116231
PS
294 $trace = new null_progress_trace();
295 enrol_cohort_sync($trace, $course->id);
296 $trace->finished();
94335e5a
PS
297
298 } else {
299 $step->set_mapping('enrol', $oldid, 0);
300 }
301 }
302
303 /**
304 * Restore user enrolment.
305 *
306 * @param restore_enrolments_structure_step $step
307 * @param stdClass $data
308 * @param stdClass $instance
309 * @param int $oldinstancestatus
310 * @param int $userid
311 */
312 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
313 global $DB;
314
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.
317 return;
318 }
319
320 // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
321 // but without roles and suspended.
322
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);
325 }
326 }
7881024e
PS
327
328 /**
329 * Restore user group membership.
330 * @param stdClass $instance
331 * @param int $groupid
332 * @param int $userid
333 */
334 public function restore_group_member($instance, $groupid, $userid) {
335 // Nothing to do here, the group members are added in $this->restore_group_restored()
336 return;
337 }
b5a289c4
DNA
338
339 /**
340 * Is it possible to hide/show enrol instance via standard UI?
341 *
342 * @param stdClass $instance
343 * @return bool
344 */
345 public function can_hide_show_instance($instance) {
346 $context = context_course::instance($instance->courseid);
347 return has_capability('enrol/cohort:config', $context);
348 }
60010fd6
DW
349
350 /**
351 * Return an array of valid options for the status.
352 *
353 * @return array
354 */
355 protected function get_status_options() {
356 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
357 ENROL_INSTANCE_DISABLED => get_string('no'));
358 return $options;
359 }
360
361 /**
362 * Return an array of valid options for the cohorts.
363 *
364 * @param stdClass $instance
365 * @param context $context
366 * @return array
367 */
368 protected function get_cohort_options($instance, $context) {
369 global $DB, $CFG;
370
371 require_once($CFG->dirroot . '/cohort/lib.php');
372
373 $cohorts = array();
374
375 if ($instance->id) {
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);
379 } else {
380 $cohorts = array($instance->customint1 => get_string('error'));
381 }
382 } else {
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);
387 }
388 }
389 return $cohorts;
390 }
391
392 /**
393 * Return an array of valid options for the roles.
394 *
395 * @param stdClass $instance
396 * @param context $coursecontext
397 * @return array
398 */
399 protected function get_role_options($instance, $coursecontext) {
400 global $DB;
401
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);
409 } else {
410 $roles[$instance->roleid] = get_string('error');
411 }
412 }
413
414 return $roles;
415 }
416
417 /**
418 * Return an array of valid options for the groups.
419 *
420 * @param context $coursecontext
421 * @return array
422 */
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');
427 }
428
429 foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
430 $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
431 }
432
433 return $groups;
434 }
435
436 /**
437 * We are a good plugin and don't invent our own UI/validation code path.
438 *
439 * @return boolean
440 */
441 public function use_standard_editing_ui() {
442 return true;
443 }
444
445 /**
446 * Add elements to the edit instance form.
447 *
448 * @param stdClass $instance
449 * @param MoodleQuickForm $mform
450 * @param context $coursecontext
451 * @return bool
452 */
453 public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
454 global $DB;
455
456 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
457 $mform->setType('name', PARAM_TEXT);
458
459 $options = $this->get_status_options();
460 $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
461
462 $options = $this->get_cohort_options($instance, $coursecontext);
463 $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $options);
464 if ($instance->id) {
465 $mform->setConstant('customint1', $instance->customint1);
466 $mform->hardFreeze('customint1', $instance->customint1);
467 } else {
468 $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
469 }
470
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);
476 }
477
478 /**
479 * Perform custom validation of the data used to edit the instance.
480 *
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.
487 * @return void
488 */
489 public function edit_instance_validation($data, $files, $instance, $context) {
490 global $DB;
491 $errors = array();
492
493 $params = array(
494 'roleid' => $data['roleid'],
495 'customint1' => $data['customint1'],
496 'courseid' => $data['courseid'],
497 'id' => $data['id']
498 );
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');
502 }
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));
507 $tovalidate = array(
508 'name' => PARAM_TEXT,
509 'status' => $validstatus,
510 'customint1' => $validcohorts,
511 'roleid' => $validroles,
512 'customint2' => $validgroups
513 );
514 $typeerrors = $this->validate_param_types($data, $tovalidate);
515 $errors = array_merge($errors, $typeerrors);
516
517 return $errors;
518 }
7881024e
PS
519}
520
521/**
522 * Prevent removal of enrol roles.
523 * @param int $itemid
524 * @param int $groupid
525 * @param int $userid
526 * @return bool
527 */
528function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
529 return false;
94335e5a 530}
73985b14 531
df9dbc9f
AG
532/**
533 * Create a new group with the cohorts name.
534 *
535 * @param int $courseid
536 * @param int $cohortid
537 * @return int $groupid Group ID for this cohort.
538 */
73985b14 539function enrol_cohort_create_new_group($courseid, $cohortid) {
60010fd6
DW
540 global $DB, $CFG;
541
542 require_once($CFG->dirroot . '/group/lib.php');
7efd0c0a
AG
543
544 $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
545 $a = new stdClass();
546 $a->name = $groupname;
547 $a->increment = '';
5894432c 548 $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
42c92eef 549 $inc = 1;
7efd0c0a 550 // Check to see if the cohort group name already exists. Add an incremented number if it does.
42c92eef
MG
551 while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
552 $a->increment = '(' . (++$inc) . ')';
5894432c 553 $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
7efd0c0a 554 $groupname = $newshortname;
73985b14 555 }
7efd0c0a
AG
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);
561
73985b14 562 return $groupid;
32b97a03 563}