Merge branch 'MDL-62144-master' of git://github.com/damyon/moodle
[moodle.git] / enrol / manual / lib.php
bloba346a08a8b5212f5f95010fec6bd0d6244411949
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 * Manual enrolment plugin main library file.
20 * @package enrol_manual
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 class enrol_manual_plugin extends enrol_plugin {
29 protected $lasternoller = null;
30 protected $lasternollerinstanceid = 0;
32 public function roles_protected() {
33 // Users may tweak the roles later.
34 return false;
37 public function allow_enrol(stdClass $instance) {
38 // Users with enrol cap may unenrol other users manually manually.
39 return true;
42 public function allow_unenrol(stdClass $instance) {
43 // Users with unenrol cap may unenrol other users manually manually.
44 return true;
47 public function allow_manage(stdClass $instance) {
48 // Users with manage cap may tweak period and status.
49 return true;
52 /**
53 * Returns link to manual enrol UI if exists.
54 * Does the access control tests automatically.
56 * @param stdClass $instance
57 * @return moodle_url
59 public function get_manual_enrol_link($instance) {
60 $name = $this->get_name();
61 if ($instance->enrol !== $name) {
62 throw new coding_exception('invalid enrol instance!');
65 if (!enrol_is_enabled($name)) {
66 return NULL;
69 $context = context_course::instance($instance->courseid, MUST_EXIST);
71 if (!has_capability('enrol/manual:enrol', $context)) {
72 // Note: manage capability not used here because it is used for editing
73 // of existing enrolments which is not possible here.
74 return NULL;
77 return new moodle_url('/enrol/manual/manage.php', array('enrolid'=>$instance->id, 'id'=>$instance->courseid));
80 /**
81 * Return true if we can add a new instance to this course.
83 * @param int $courseid
84 * @return boolean
86 public function can_add_instance($courseid) {
87 global $DB;
89 $context = context_course::instance($courseid, MUST_EXIST);
90 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/manual:config', $context)) {
91 return false;
94 if ($DB->record_exists('enrol', array('courseid'=>$courseid, 'enrol'=>'manual'))) {
95 // Multiple instances not supported.
96 return false;
99 return true;
103 * Returns edit icons for the page with list of instances.
104 * @param stdClass $instance
105 * @return array
107 public function get_action_icons(stdClass $instance) {
108 global $OUTPUT;
110 $context = context_course::instance($instance->courseid);
112 $icons = array();
113 if (has_capability('enrol/manual:enrol', $context) or has_capability('enrol/manual:unenrol', $context)) {
114 $managelink = new moodle_url("/enrol/manual/manage.php", array('enrolid'=>$instance->id));
115 $icons[] = $OUTPUT->action_icon($managelink, new pix_icon('t/enrolusers', get_string('enrolusers', 'enrol_manual'), 'core', array('class'=>'iconsmall')));
117 $parenticons = parent::get_action_icons($instance);
118 $icons = array_merge($icons, $parenticons);
120 return $icons;
124 * Add new instance of enrol plugin with default settings.
125 * @param stdClass $course
126 * @return int id of new instance, null if can not be created
128 public function add_default_instance($course) {
129 $expirynotify = $this->get_config('expirynotify', 0);
130 if ($expirynotify == 2) {
131 $expirynotify = 1;
132 $notifyall = 1;
133 } else {
134 $notifyall = 0;
136 $fields = array(
137 'status' => $this->get_config('status'),
138 'roleid' => $this->get_config('roleid', 0),
139 'enrolperiod' => $this->get_config('enrolperiod', 0),
140 'expirynotify' => $expirynotify,
141 'notifyall' => $notifyall,
142 'expirythreshold' => $this->get_config('expirythreshold', 86400),
144 return $this->add_instance($course, $fields);
148 * Add new instance of enrol plugin.
149 * @param stdClass $course
150 * @param array instance fields
151 * @return int id of new instance, null if can not be created
153 public function add_instance($course, array $fields = NULL) {
154 global $DB;
156 if ($DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
157 // only one instance allowed, sorry
158 return NULL;
161 return parent::add_instance($course, $fields);
165 * Update instance of enrol plugin.
166 * @param stdClass $instance
167 * @param stdClass $data modified instance fields
168 * @return boolean
170 public function update_instance($instance, $data) {
171 global $DB;
173 // Delete all other instances, leaving only one.
174 if ($instances = $DB->get_records('enrol', array('courseid' => $instance->courseid, 'enrol' => 'manual'), 'id ASC')) {
175 foreach ($instances as $anotherinstance) {
176 if ($anotherinstance->id != $instance->id) {
177 $this->delete_instance($anotherinstance);
181 return parent::update_instance($instance, $data);
185 * Returns a button to manually enrol users through the manual enrolment plugin.
187 * By default the first manual enrolment plugin instance available in the course is used.
188 * If no manual enrolment instances exist within the course then false is returned.
190 * This function also adds a quickenrolment JS ui to the page so that users can be enrolled
191 * via AJAX.
193 * @param course_enrolment_manager $manager
194 * @return enrol_user_button
196 public function get_manual_enrol_button(course_enrolment_manager $manager) {
197 global $CFG, $PAGE;
198 require_once($CFG->dirroot.'/cohort/lib.php');
200 $instance = null;
201 $instances = array();
202 foreach ($manager->get_enrolment_instances() as $tempinstance) {
203 if ($tempinstance->enrol == 'manual') {
204 if ($instance === null) {
205 $instance = $tempinstance;
207 $instances[] = array('id' => $tempinstance->id, 'name' => $this->get_instance_name($tempinstance));
210 if (empty($instance)) {
211 return false;
214 $link = $this->get_manual_enrol_link($instance);
215 if (!$link) {
216 return false;
219 $button = new enrol_user_button($link, get_string('enrolusers', 'enrol_manual'), 'get');
220 $button->class .= ' enrol_manual_plugin';
222 $context = context_course::instance($instance->courseid);
223 $arguments = array('contextid' => $context->id);
225 $PAGE->requires->js_call_amd('enrol_manual/quickenrolment', 'init', array($arguments));
227 return $button;
231 * Sync all meta course links.
233 * @param progress_trace $trace
234 * @param int $courseid one course, empty mean all
235 * @return int 0 means ok, 1 means error, 2 means plugin disabled
237 public function sync(progress_trace $trace, $courseid = null) {
238 global $DB;
240 if (!enrol_is_enabled('manual')) {
241 $trace->finished();
242 return 2;
245 // Unfortunately this may take a long time, execution can be interrupted safely here.
246 core_php_time_limit::raise();
247 raise_memory_limit(MEMORY_HUGE);
249 $trace->output('Verifying manual enrolment expiration...');
251 $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
252 $coursesql = "";
253 if ($courseid) {
254 $coursesql = "AND e.courseid = :courseid";
255 $params['courseid'] = $courseid;
258 // Deal with expired accounts.
259 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
261 if ($action == ENROL_EXT_REMOVED_UNENROL) {
262 $instances = array();
263 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
264 FROM {user_enrolments} ue
265 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')
266 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
267 WHERE ue.timeend > 0 AND ue.timeend < :now
268 $coursesql";
269 $rs = $DB->get_recordset_sql($sql, $params);
270 foreach ($rs as $ue) {
271 if (empty($instances[$ue->enrolid])) {
272 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
274 $instance = $instances[$ue->enrolid];
275 // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
276 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
277 $this->unenrol_user($instance, $ue->userid);
278 $trace->output("unenrolling expired user $ue->userid from course $instance->courseid", 1);
280 $rs->close();
281 unset($instances);
283 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
284 $instances = array();
285 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
286 FROM {user_enrolments} ue
287 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')
288 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
289 WHERE ue.timeend > 0 AND ue.timeend < :now
290 AND ue.status = :useractive
291 $coursesql";
292 $rs = $DB->get_recordset_sql($sql, $params);
293 foreach ($rs as $ue) {
294 if (empty($instances[$ue->enrolid])) {
295 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
297 $instance = $instances[$ue->enrolid];
298 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
299 // Remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
300 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
301 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
302 $trace->output("suspending expired user $ue->userid in course $instance->courseid, roles unassigned", 1);
303 } else {
304 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
305 $trace->output("suspending expired user $ue->userid in course $instance->courseid, roles kept", 1);
308 $rs->close();
309 unset($instances);
311 } else {
312 // ENROL_EXT_REMOVED_KEEP means no changes.
315 $trace->output('...manual enrolment updates finished.');
316 $trace->finished();
318 return 0;
322 * Returns the user who is responsible for manual enrolments in given instance.
324 * Usually it is the first editing teacher - the person with "highest authority"
325 * as defined by sort_by_roleassignment_authority() having 'enrol/manual:manage'
326 * capability.
328 * @param int $instanceid enrolment instance id
329 * @return stdClass user record
331 protected function get_enroller($instanceid) {
332 global $DB;
334 if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
335 return $this->lasternoller;
338 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
339 $context = context_course::instance($instance->courseid);
341 if ($users = get_enrolled_users($context, 'enrol/manual:manage')) {
342 $users = sort_by_roleassignment_authority($users, $context);
343 $this->lasternoller = reset($users);
344 unset($users);
345 } else {
346 $this->lasternoller = parent::get_enroller($instanceid);
349 $this->lasternollerinstanceid = $instanceid;
351 return $this->lasternoller;
355 * The manual plugin has several bulk operations that can be performed.
356 * @param course_enrolment_manager $manager
357 * @return array
359 public function get_bulk_operations(course_enrolment_manager $manager) {
360 global $CFG;
361 require_once($CFG->dirroot.'/enrol/manual/locallib.php');
362 $context = $manager->get_context();
363 $bulkoperations = array();
364 if (has_capability("enrol/manual:manage", $context)) {
365 $bulkoperations['editselectedusers'] = new enrol_manual_editselectedusers_operation($manager, $this);
367 if (has_capability("enrol/manual:unenrol", $context)) {
368 $bulkoperations['deleteselectedusers'] = new enrol_manual_deleteselectedusers_operation($manager, $this);
370 return $bulkoperations;
374 * Restore instance and map settings.
376 * @param restore_enrolments_structure_step $step
377 * @param stdClass $data
378 * @param stdClass $course
379 * @param int $oldid
381 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
382 global $DB;
383 // There is only I manual enrol instance allowed per course.
384 if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
385 $instance = reset($instances);
386 $instanceid = $instance->id;
387 } else {
388 $instanceid = $this->add_instance($course, (array)$data);
390 $step->set_mapping('enrol', $oldid, $instanceid);
394 * Restore user enrolment.
396 * @param restore_enrolments_structure_step $step
397 * @param stdClass $data
398 * @param stdClass $instance
399 * @param int $oldinstancestatus
400 * @param int $userid
402 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
403 global $DB;
405 // Note: this is a bit tricky because other types may be converted to manual enrolments,
406 // and manual is restricted to one enrolment per user.
408 $ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid));
409 $enrol = false;
410 if ($ue and $ue->status == ENROL_USER_ACTIVE) {
411 // We do not want to restrict current active enrolments, let's kind of merge the times only.
412 // This prevents some teacher lockouts too.
413 if ($data->status == ENROL_USER_ACTIVE) {
414 if ($data->timestart > $ue->timestart) {
415 $data->timestart = $ue->timestart;
416 $enrol = true;
419 if ($data->timeend == 0) {
420 if ($ue->timeend != 0) {
421 $enrol = true;
423 } else if ($ue->timeend == 0) {
424 $data->timeend = 0;
425 } else if ($data->timeend < $ue->timeend) {
426 $data->timeend = $ue->timeend;
427 $enrol = true;
430 } else {
431 if ($instance->status == ENROL_INSTANCE_ENABLED and $oldinstancestatus != ENROL_INSTANCE_ENABLED) {
432 // Make sure that user enrolments are not activated accidentally,
433 // we do it only here because it is not expected that enrolments are migrated to other plugins.
434 $data->status = ENROL_USER_SUSPENDED;
436 $enrol = true;
439 if ($enrol) {
440 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
445 * Restore role assignment.
447 * @param stdClass $instance
448 * @param int $roleid
449 * @param int $userid
450 * @param int $contextid
452 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
453 // This is necessary only because we may migrate other types to this instance,
454 // we do not use component in manual or self enrol.
455 role_assign($roleid, $userid, $contextid, '', 0);
459 * Restore user group membership.
460 * @param stdClass $instance
461 * @param int $groupid
462 * @param int $userid
464 public function restore_group_member($instance, $groupid, $userid) {
465 global $CFG;
466 require_once("$CFG->dirroot/group/lib.php");
468 // This might be called when forcing restore as manual enrolments.
470 groups_add_member($groupid, $userid);
474 * Is it possible to delete enrol instance via standard UI?
476 * @param object $instance
477 * @return bool
479 public function can_delete_instance($instance) {
480 $context = context_course::instance($instance->courseid);
481 return has_capability('enrol/manual:config', $context);
485 * Is it possible to hide/show enrol instance via standard UI?
487 * @param stdClass $instance
488 * @return bool
490 public function can_hide_show_instance($instance) {
491 $context = context_course::instance($instance->courseid);
492 return has_capability('enrol/manual:config', $context);
496 * Enrol all not enrolled cohort members into course via enrol instance.
498 * @param stdClass $instance
499 * @param int $cohortid
500 * @param int $roleid optional role id
501 * @param int $timestart 0 means unknown
502 * @param int $timeend 0 means forever
503 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
504 * @param bool $recovergrades restore grade history
506 public function enrol_cohort(stdClass $instance, $cohortid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
507 global $DB;
508 $context = context_course::instance($instance->courseid);
509 list($esql, $params) = get_enrolled_sql($context);
510 $sql = "SELECT cm.userid FROM {cohort_members} cm LEFT JOIN ($esql) u ON u.id = cm.userid ".
511 "WHERE cm.cohortid = :cohortid AND u.id IS NULL";
512 $params['cohortid'] = $cohortid;
513 $members = $DB->get_fieldset_sql($sql, $params);
514 foreach ($members as $userid) {
515 $this->enrol_user($instance, $userid, $roleid, $timestart, $timeend, $status, $recovergrades);
520 * We are a good plugin and don't invent our own UI/validation code path.
522 * @return boolean
524 public function use_standard_editing_ui() {
525 return true;
529 * Return an array of valid options for the status.
531 * @return array
533 protected function get_status_options() {
534 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
535 ENROL_INSTANCE_DISABLED => get_string('no'));
536 return $options;
540 * Return an array of valid options for the roleid.
542 * @param stdClass $instance
543 * @param context $context
544 * @return array
546 protected function get_roleid_options($instance, $context) {
547 if ($instance->id) {
548 $roles = get_default_enrol_roles($context, $instance->roleid);
549 } else {
550 $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
552 return $roles;
556 * Return an array of valid options for the expirynotify.
558 * @return array
560 protected function get_expirynotify_options() {
561 $options = array(
562 0 => get_string('no'),
563 1 => get_string('expirynotifyenroller', 'core_enrol'),
564 2 => get_string('expirynotifyall', 'core_enrol')
566 return $options;
570 * Add elements to the edit instance form.
572 * @param stdClass $instance
573 * @param MoodleQuickForm $mform
574 * @param context $context
575 * @return bool
577 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
579 $options = $this->get_status_options();
580 $mform->addElement('select', 'status', get_string('status', 'enrol_manual'), $options);
581 $mform->addHelpButton('status', 'status', 'enrol_manual');
582 $mform->setDefault('status', $this->get_config('status'));
584 $roles = $this->get_roleid_options($instance, $context);
585 $mform->addElement('select', 'roleid', get_string('defaultrole', 'role'), $roles);
586 $mform->setDefault('roleid', $this->get_config('roleid'));
588 $options = array('optional' => true, 'defaultunit' => 86400);
589 $mform->addElement('duration', 'enrolperiod', get_string('defaultperiod', 'enrol_manual'), $options);
590 $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
591 $mform->addHelpButton('enrolperiod', 'defaultperiod', 'enrol_manual');
593 $options = $this->get_expirynotify_options();
594 $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
595 $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
597 $options = array('optional' => false, 'defaultunit' => 86400);
598 $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
599 $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
600 $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
602 if (enrol_accessing_via_instance($instance)) {
603 $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
604 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
609 * Perform custom validation of the data used to edit the instance.
611 * @param array $data array of ("fieldname"=>value) of submitted data
612 * @param array $files array of uploaded files "element_name"=>tmp_file_path
613 * @param object $instance The instance loaded from the DB
614 * @param context $context The context of the instance we are editing
615 * @return array of "element_name"=>"error_description" if there are errors,
616 * or an empty array if everything is OK.
617 * @return void
619 public function edit_instance_validation($data, $files, $instance, $context) {
620 $errors = array();
622 if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
623 $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
626 $validstatus = array_keys($this->get_status_options());
627 $validroles = array_keys($this->get_roleid_options($instance, $context));
628 $validexpirynotify = array_keys($this->get_expirynotify_options());
630 $tovalidate = array(
631 'status' => $validstatus,
632 'roleid' => $validroles,
633 'enrolperiod' => PARAM_INT,
634 'expirynotify' => $validexpirynotify,
635 'expirythreshold' => PARAM_INT
638 $typeerrors = $this->validate_param_types($data, $tovalidate);
639 $errors = array_merge($errors, $typeerrors);
641 return $errors;
647 * Serve the manual enrol users form as a fragment.
649 * @param array $args List of named arguments for the fragment loader.
650 * @return string
652 function enrol_manual_output_fragment_enrol_users_form($args) {
653 $args = (object) $args;
654 $context = $args->context;
655 $o = '';
657 require_capability('enrol/manual:enrol', $context);
658 $mform = new enrol_manual_enrol_users_form(null, $args);
660 ob_start();
661 $mform->display();
662 $o .= ob_get_contents();
663 ob_end_clean();
665 return $o;