. /** * Cohort enrolment plugin. * * @package enrol_cohort * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * COHORT_CREATEGROUP constant for automatically creating a group for a cohort. */ define('COHORT_CREATE_GROUP', -1); /** * Cohort enrolment plugin implementation. * @author Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class enrol_cohort_plugin extends enrol_plugin { /** * Is it possible to delete enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function can_delete_instance($instance) { $context = context_course::instance($instance->courseid); return has_capability('enrol/cohort:config', $context); } /** * Returns localised name of enrol instance. * * @param stdClass $instance (null is accepted too) * @return string */ public function get_instance_name($instance) { global $DB; if (empty($instance)) { $enrol = $this->get_name(); return get_string('pluginname', 'enrol_'.$enrol); } else if (empty($instance->name)) { $enrol = $this->get_name(); $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1)); if (!$cohort) { return get_string('pluginname', 'enrol_'.$enrol); } $cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid))); if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) { $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)); return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')'; } else { return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')'; } } else { return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid))); } } /** * Given a courseid this function returns true if the user is able to enrol or configure cohorts. * AND there are cohorts that the user can view. * * @param int $courseid * @return bool */ public function can_add_instance($courseid) { global $CFG; require_once($CFG->dirroot . '/cohort/lib.php'); $coursecontext = context_course::instance($courseid); if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) { return false; } return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false; } /** * Add new instance of enrol plugin. * @param object $course * @param array $fields instance fields * @return int id of new instance, null if can not be created */ public function add_instance($course, array $fields = null) { global $CFG; if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) { // Create a new group for the cohort if requested. $context = context_course::instance($course->id); require_capability('moodle/course:managegroups', $context); $groupid = enrol_cohort_create_new_group($course->id, $fields['customint1']); $fields['customint2'] = $groupid; } $result = parent::add_instance($course, $fields); require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $course->id); $trace->finished(); return $result; } /** * Update instance of enrol plugin. * @param stdClass $instance * @param stdClass $data modified instance fields * @return boolean */ public function update_instance($instance, $data) { global $CFG; // NOTE: no cohort changes here!!! $context = context_course::instance($instance->courseid); if ($data->roleid != $instance->roleid) { // The sync script can only add roles, for perf reasons it does not modify them. $params = array( 'contextid' => $context->id, 'roleid' => $instance->roleid, 'component' => 'enrol_cohort', 'itemid' => $instance->id ); role_unassign_all($params); } // Create a new group for the cohort if requested. if ($data->customint2 == COHORT_CREATE_GROUP) { require_capability('moodle/course:managegroups', $context); $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1); $data->customint2 = $groupid; } $result = parent::update_instance($instance, $data); require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $instance->courseid); $trace->finished(); return $result; } /** * Called for all enabled enrol plugins that returned true from is_cron_required(). * @return void */ public function cron() { global $CFG; require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace); $trace->finished(); } /** * Called after updating/inserting course. * * @param bool $inserted true if course just inserted * @param stdClass $course * @param stdClass $data form data * @return void */ public function course_updated($inserted, $course, $data) { // It turns out there is no need for cohorts to deal with this hook, see MDL-34870. } /** * Update instance status * * @param stdClass $instance * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED * @return void */ public function update_status($instance, $newstatus) { global $CFG; parent::update_status($instance, $newstatus); require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $instance->courseid); $trace->finished(); } /** * Does this plugin allow manual unenrolment of a specific user? * Yes, but only if user suspended... * * @param stdClass $instance course enrol instance * @param stdClass $ue record from user_enrolments table * * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment */ public function allow_unenrol_user(stdClass $instance, stdClass $ue) { if ($ue->status == ENROL_USER_SUSPENDED) { return true; } return false; } /** * Gets an array of the user enrolment actions. * * @param course_enrolment_manager $manager * @param stdClass $ue A user enrolment object * @return array An array of user_enrolment_actions */ public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) { $actions = array(); $context = $manager->get_context(); $instance = $ue->enrolmentinstance; $params = $manager->get_moodlepage()->url->params(); $params['ue'] = $ue->id; if ($this->allow_unenrol_user($instance, $ue) && has_capability('enrol/cohort:unenrol', $context)) { $url = new moodle_url('/enrol/unenroluser.php', $params); $strunenrol = get_string('unenrol', 'enrol'); $actions[] = new user_enrolment_action(new pix_icon('t/delete', $strunenrol), $strunenrol, $url, array('class' => 'unenrollink', 'rel' => $ue->id)); } return $actions; } /** * Restore instance and map settings. * * @param restore_enrolments_structure_step $step * @param stdClass $data * @param stdClass $course * @param int $oldid */ public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) { global $DB, $CFG; if (!$step->get_task()->is_samesite()) { // No cohort restore from other sites. $step->set_mapping('enrol', $oldid, 0); return; } if (!empty($data->customint2)) { $data->customint2 = $step->get_mappingid('group', $data->customint2); } if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) { $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name())); if ($instance) { $instanceid = $instance->id; } else { $instanceid = $this->add_instance($course, (array)$data); } $step->set_mapping('enrol', $oldid, $instanceid); require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $course->id); $trace->finished(); } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) { $data->customint1 = 0; $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name())); if ($instance) { $instanceid = $instance->id; } else { $data->status = ENROL_INSTANCE_DISABLED; $instanceid = $this->add_instance($course, (array)$data); } $step->set_mapping('enrol', $oldid, $instanceid); require_once("$CFG->dirroot/enrol/cohort/locallib.php"); $trace = new null_progress_trace(); enrol_cohort_sync($trace, $course->id); $trace->finished(); } else { $step->set_mapping('enrol', $oldid, 0); } } /** * Restore user enrolment. * * @param restore_enrolments_structure_step $step * @param stdClass $data * @param stdClass $instance * @param int $oldinstancestatus * @param int $userid */ public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) { global $DB; if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) { // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers. return; } // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored // but without roles and suspended. if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED); } } /** * Restore user group membership. * @param stdClass $instance * @param int $groupid * @param int $userid */ public function restore_group_member($instance, $groupid, $userid) { // Nothing to do here, the group members are added in $this->restore_group_restored() return; } /** * Is it possible to hide/show enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function can_hide_show_instance($instance) { $context = context_course::instance($instance->courseid); return has_capability('enrol/cohort:config', $context); } /** * Return an array of valid options for the status. * * @return array */ protected function get_status_options() { $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'), ENROL_INSTANCE_DISABLED => get_string('no')); return $options; } /** * Return an array of valid options for the cohorts. * * @param stdClass $instance * @param context $context * @return array */ protected function get_cohort_options($instance, $context) { global $DB, $CFG; require_once($CFG->dirroot . '/cohort/lib.php'); $cohorts = array(); if ($instance->id) { if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) { $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid))); $cohorts = array($instance->customint1 => $name); } else { $cohorts = array($instance->customint1 => get_string('error')); } } else { $cohorts = array('' => get_string('choosedots')); $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0); foreach ($allcohorts as $c) { $cohorts[$c->id] = format_string($c->name); } } return $cohorts; } /** * Return an array of valid options for the roles. * * @param stdClass $instance * @param context $coursecontext * @return array */ protected function get_role_options($instance, $coursecontext) { global $DB; $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // Descending default sortorder. if ($instance->id and !isset($roles[$instance->roleid])) { if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true); $roles[$instance->roleid] = role_get_name($role, $coursecontext); } else { $roles[$instance->roleid] = get_string('error'); } } return $roles; } /** * Return an array of valid options for the groups. * * @param context $coursecontext * @return array */ protected function get_group_options($coursecontext) { $groups = array(0 => get_string('none')); if (has_capability('moodle/course:managegroups', $coursecontext)) { $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort'); } foreach (groups_get_all_groups($coursecontext->instanceid) as $group) { $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext)); } return $groups; } /** * We are a good plugin and don't invent our own UI/validation code path. * * @return boolean */ public function use_standard_editing_ui() { return true; } /** * Add elements to the edit instance form. * * @param stdClass $instance * @param MoodleQuickForm $mform * @param context $coursecontext * @return bool */ public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) { global $DB; $mform->addElement('text', 'name', get_string('custominstancename', 'enrol')); $mform->setType('name', PARAM_TEXT); $options = $this->get_status_options(); $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options); $options = $this->get_cohort_options($instance, $coursecontext); $mform->addElement('select', 'customint1', get_string('cohort', 'cohort'), $options); if ($instance->id) { $mform->setConstant('customint1', $instance->customint1); $mform->hardFreeze('customint1', $instance->customint1); } else { $mform->addRule('customint1', get_string('required'), 'required', null, 'client'); } $roles = $this->get_role_options($instance, $coursecontext); $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles); $mform->setDefault('roleid', $this->get_config('roleid')); $groups = $this->get_group_options($coursecontext); $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups); $mform->addElement('advcheckbox', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self')); $mform->setDefault('customint4', $this->get_config('sendcoursewelcomemessage')); $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self'); $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), array('cols'=>'60', 'rows'=>'8')); } /** * Perform custom validation of the data used to edit the instance. * * @param array $data array of ("fieldname" => value) of submitted data * @param array $files array of uploaded files "element_name" => tmp_file_path * @param object $instance The instance loaded from the DB * @param context $context The context of the instance we are editing * @return array of "element_name" => "error_description" if there are errors, * or an empty array if everything is OK. * @return void */ public function edit_instance_validation($data, $files, $instance, $context) { global $DB; $errors = array(); $params = array( 'roleid' => $data['roleid'], 'customint1' => $data['customint1'], 'courseid' => $data['courseid'], 'id' => $data['id'] ); $sql = "roleid = :roleid AND customint1 = :customint1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id"; if ($DB->record_exists_select('enrol', $sql, $params)) { $errors['roleid'] = get_string('instanceexists', 'enrol_cohort'); } $validstatus = array_keys($this->get_status_options()); $validcohorts = array_keys($this->get_cohort_options($instance, $context)); $validroles = array_keys($this->get_role_options($instance, $context)); $validgroups = array_keys($this->get_group_options($context)); $tovalidate = array( 'name' => PARAM_TEXT, 'status' => $validstatus, 'customint1' => $validcohorts, 'roleid' => $validroles, 'customint2' => $validgroups ); $typeerrors = $this->validate_param_types($data, $tovalidate); $errors = array_merge($errors, $typeerrors); return $errors; } /** * @param stdClass $instance * @param int $userid * @param int $roleid optional role id * @param int $timestart 0 means unknown * @param int $timeend 0 means forever * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates * @param bool $recovergrades restore grade history * @return void */ public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL, $recovergrades = null){ global $DB; parent::enrol_user($instance, $userid, $roleid, $timestart, $timeend, $status, $recovergrades = null); $user = $DB->get_record('user', array('id' => $userid)); // Send welcome message. if ($instance->customint4) { $this->email_welcome_message($instance, $user); } } /** * @param stdClass $instance * @param stdClass $user user record * @return void */ protected function email_welcome_message($instance, $user) { global $CFG, $DB; $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST); $context = context_course::instance($course->id); $a = new stdClass(); $a->coursename = format_string($course->fullname, true, array('context'=>$context)); $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id"; if (trim($instance->customtext1) !== '') { $message = $instance->customtext1; $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}'); $value = array($a->coursename, $a->profileurl, fullname($user), $user->email); $message = str_replace($key, $value, $message); if (strpos($message, '<') === false) { // Plain text only. $messagetext = $message; $messagehtml = text_to_html($messagetext, null, false, true); } else { // This is most probably the tag/newline soup known as FORMAT_MOODLE. $messagehtml = format_text($message, FORMAT_MOODLE, array('context'=>$context, 'para'=>false, 'newlines'=>true, 'filter'=>true)); $messagetext = html_to_text($messagehtml); } } else { $messagetext = get_string('welcometocoursetext', 'enrol_self', $a); $messagehtml = text_to_html($messagetext, null, false, true); } $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context))); $sendoption = ENROL_SEND_EMAIL_FROM_NOREPLY; $contact = $this->get_welcome_email_contact($sendoption, $context); // Directly emailing welcome message rather than using messaging. email_to_user($user, $contact, $subject, $messagetext, $messagehtml); } /** * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_* * @param $context context where the user will be fetched * @return mixed|stdClass the contact user object. */ public function get_welcome_email_contact($sendoption, $context) { global $CFG; $contact = null; // Send as the first user assigned as the course contact. if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) { $rusers = array(); if (!empty($CFG->coursecontact)) { $croles = explode(',', $CFG->coursecontact); list($sort, $sortparams) = users_order_by_sql('u'); // We only use the first user. $i = 0; do { $rusers = get_role_users($croles[$i], $context, true, '', 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams); $i++; } while (empty($rusers) && !empty($croles[$i])); } if ($rusers) { $contact = array_values($rusers)[0]; } } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) { // Send as the first user with enrol/self:holdkey capability assigned in the course. list($sort) = users_order_by_sql('u'); $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort); if (!empty($keyholders)) { $contact = array_values($keyholders)[0]; } } // If send welcome email option is set to no reply or if none of the previous options have // returned a contact send welcome message as noreplyuser. if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) { $contact = core_user::get_noreply_user(); } return $contact; } } /** * Prevent removal of enrol roles. * @param int $itemid * @param int $groupid * @param int $userid * @return bool */ function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) { return false; } /** * Create a new group with the cohorts name. * * @param int $courseid * @param int $cohortid * @return int $groupid Group ID for this cohort. */ function enrol_cohort_create_new_group($courseid, $cohortid) { global $DB, $CFG; require_once($CFG->dirroot . '/group/lib.php'); $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST); $a = new stdClass(); $a->name = $groupname; $a->increment = ''; $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a)); $inc = 1; // Check to see if the cohort group name already exists. Add an incremented number if it does. while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) { $a->increment = '(' . (++$inc) . ')'; $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a)); $groupname = $newshortname; } // Create a new group for the cohort. $groupdata = new stdClass(); $groupdata->courseid = $courseid; $groupdata->name = $groupname; $groupid = groups_create_group($groupdata); return $groupid; }