/** * Test user_get_user_details_courses */ public function test_user_get_user_details_courses() { global $DB; $this->resetAfterTest(); // Create user and modify user profile. $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $course1 = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course1->id); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->getDataGenerator()->enrol_user($user1->id, $course1->id); $this->getDataGenerator()->enrol_user($user2->id, $course1->id); role_assign($teacherrole->id, $user1->id, $coursecontext->id); role_assign($teacherrole->id, $user2->id, $coursecontext->id); accesslib_clear_all_caches_for_unit_testing(); // Get user2 details as a user with super system capabilities. $result = user_get_user_details_courses($user2); $this->assertEquals($user2->id, $result['id']); $this->assertEquals(fullname($user2), $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); $this->setUser($user1); // Get user2 details as a user who can only see this user in a course. $result = user_get_user_details_courses($user2); $this->assertEquals($user2->id, $result['id']); $this->assertEquals(fullname($user2), $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); }
/** * Test for correct assignment of course permissions */ public function test_coursepermissions() { global $DB, $CFG, $USER; accesslib_clear_all_caches(true); set_config('siteguest', ''); set_config('siteadmins', ''); $this->assertFalse($this->has_program_create_capability()); $this->assertFalse($this->has_associate_and_manage_capability()); $this->assertFalse($this->has_program_view_capability()); $syscontext = context_system::instance(); $assigninguser = new user(array('idnumber' => 'testuserid', 'username' => 'testuser', 'firstname' => 'testuser', 'lastname' => 'testuser', 'email' => '*****@*****.**', 'country' => 'CA')); $assigninguser->save(); $roleid = create_role('userrole', 'userrole', 'userrole'); $usr = $DB->get_record('user', array('username' => 'testuser')); $this->setUser($usr); $USER = $usr; assign_capability('local/elisprogram:associate', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:manage', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_create', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_enrol', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_view', CAP_ALLOW, $roleid, $syscontext->id); role_assign($roleid, $usr->id, $syscontext->id); $this->assertTrue($this->has_program_create_capability()); $this->assertTrue($this->has_associate_and_manage_capability()); $this->assertTrue($this->has_program_view_capability()); $this->setUser(null); }
/** * Set up the database for tests * * This function is needed so that daily_log_provider has the before-test set up from setUp() */ public function setUpDB() { global $DB; if ($DB->record_exists('user', array('username' => 'user1'))) { return; } $datagen = self::getDataGenerator(); $user1 = $datagen->create_user(array('username'=>'user1')); $user2 = $datagen->create_user(array('username'=>'user2')); $course1 = $datagen->create_course(array('shortname'=>'course1')); $success = enrol_try_internal_enrol($course1->id, $user1->id, 5); if (! $success) { trigger_error('User enrollment failed', E_USER_ERROR); } $context = context_system::instance(); role_assign(self::STID, $user2->id, $context->id); $this->generate_replacement_list(); }
/** * Validate that redirection from My Moodle does not happen for admins */ public function test_mymoodleredirectreturnsfalseforadmin() { global $CFG, $USER, $DB; require_once $CFG->dirroot . '/user/lib.php'; // Make sure we're not a guest. set_config('siteguest', ''); // Obtain the system context. $syscontext = context_system::instance(); // Set up the current user global. $user = new stdClass(); $user->username = "******"; $userid = user_create_user($user); $USER = $DB->get_record('user', array('id' => $userid)); // Enable functionaltiy. pm_set_config('mymoodle_redirect', 1); elis::$config = new elis_config(); // Give the admin sufficient permissions. $roleid = create_role('adminrole', 'adminrole', 'adminrole'); assign_capability('moodle/site:config', CAP_ALLOW, $roleid, $syscontext->id); role_assign($roleid, $USER->id, $syscontext->id); // Validate that redirection does not happen for admins. $result = pm_mymoodle_redirect(); // Clear out cached permissions data so we don't affect other tests. accesslib_clear_all_caches(true); $this->assertFalse($result); }
/** * Test get_enrolled_users */ public function test_enrol_users() { global $USER, $CFG; $this->resetAfterTest(true); $course = self::getDataGenerator()->create_course(); $user1 = self::getDataGenerator()->create_user(); $user2 = self::getDataGenerator()->create_user(); // Set the required capabilities by the external function. $context = context_course::instance($course->id); $roleid = $this->assignUserCapability('enrol/manual:enrol', $context->id); $this->assignUserCapability('moodle/course:view', $context->id, $roleid); // Add manager role to $USER. // So $USER is allowed to assign 'manager', 'editingteacher', 'teacher' and 'student'. role_assign(1, $USER->id, context_system::instance()->id); // Call the external function. enrol_manual_external::enrol_users(array(array('roleid' => 3, 'userid' => $user1->id, 'courseid' => $course->id), array('roleid' => 3, 'userid' => $user2->id, 'courseid' => $course->id))); // Check we retrieve the good total number of enrolled users. require_once $CFG->dirroot . '/enrol/externallib.php'; $enrolledusers = core_enrol_external::get_enrolled_users($course->id); $this->assertEquals(2, count($enrolledusers)); // Call without required capability. $this->unassignUserCapability('enrol/manual:enrol', $context->id, $roleid); $this->setExpectedException('moodle_exception'); $categories = enrol_manual_external::enrol_users($course->id); }
/** * Create the fixture * * This method must be safe to call multiple times. * * @return void * @throws moodle_exception */ public function build() { global $DB; if (!$this->exists()) { // Dependents $this->get_role()->build(); $this->get_user()->build(); $raid = role_assign($this->get_role()->get('id'), $this->get_user()->get('id'), $this->get_contextid(), $this->get_option('component', ''), $this->get_option('itemid', 0), $this->get_option('timemodified', '')); $this->set_results($DB->get_record('role_assignments', array('id' => $raid), '*', MUST_EXIST)); } }
public function test_message_get_providers_for_user_more() { global $DB; $this->resetAfterTest(); // Create a course. $course = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course->id); // It would probably be better to use a quiz instance as it has capability controlled messages // however mod_quiz doesn't have a data generator. // Instead we're going to use backup notifications and give and take away the capability at various levels. $assign = $this->getDataGenerator()->create_module('assign', array('course' => $course->id)); $modulecontext = context_module::instance($assign->cmid); // Create and enrol a teacher. $teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'), '*', MUST_EXIST); $teacher = $this->getDataGenerator()->create_user(); role_assign($teacherrole->id, $teacher->id, $coursecontext); $enrolplugin = enrol_get_plugin('manual'); $enrolplugin->add_instance($course); $enrolinstances = enrol_get_instances($course->id, false); foreach ($enrolinstances as $enrolinstance) { if ($enrolinstance->enrol === 'manual') { break; } } $enrolplugin->enrol_user($enrolinstance, $teacher->id); // Make the teacher the current user. $this->setUser($teacher); // Teacher shouldn't have the required capability so they shouldn't be able to see the backup message. $this->assertFalse(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); $this->assertFalse($this->message_type_present('moodle', 'backup', $providers)); // Give the user the required capability in an activity module. // They should now be able to see the backup message. assign_capability('moodle/site:config', CAP_ALLOW, $teacherrole->id, $modulecontext->id, true); accesslib_clear_all_caches_for_unit_testing(); $modulecontext = context_module::instance($assign->cmid); $this->assertTrue(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); $this->assertTrue($this->message_type_present('moodle', 'backup', $providers)); // Prohibit the capability for the user at the course level. // This overrules the CAP_ALLOW at the module level. // They should not be able to see the backup message. assign_capability('moodle/site:config', CAP_PROHIBIT, $teacherrole->id, $coursecontext->id, true); accesslib_clear_all_caches_for_unit_testing(); $modulecontext = context_module::instance($assign->cmid); $this->assertFalse(has_capability('moodle/site:config', $modulecontext)); $providers = message_get_providers_for_user($teacher->id); // Actually, handling PROHIBITs would be too expensive. We do not // care if users with PROHIBITs see a few more preferences than they should. // $this->assertFalse($this->message_type_present('moodle', 'backup', $providers)); }
/** * Assign a capability to $USER * The function creates a student $USER if $USER->id is empty * * @param string $capability capability name * @param int $contextid * @param int $roleid * @return int the role id - mainly returned for creation, so calling function can reuse it */ public static function assignUserCapability($capability, $contextid, $roleid = null) { global $USER; // Create a new student $USER if $USER doesn't exist if (empty($USER->id)) { $user = self::getDataGenerator()->create_user(); self::setUser($user); } if (empty($roleid)) { $roleid = create_role('Dummy role', 'dummyrole', 'dummy role description'); } assign_capability($capability, CAP_ALLOW, $roleid, $contextid); role_assign($roleid, $USER->id, $contextid); accesslib_clear_all_caches_for_unit_testing(); return $roleid; }
/** * Returns a user object and its assigned new role. * * @param testing_data_generator $generator * @param $contextid * @return array The user object and the role ID */ protected function get_user_objects(testing_data_generator $generator, $contextid) { global $USER; if (empty($USER->id)) { $user = $generator->create_user(); $this->setUser($user); } $roleid = create_role('Test role', 'testrole', 'Test role description'); if (!is_array($contextid)) { $contextid = array($contextid); } foreach ($contextid as $cid) { $assignid = role_assign($roleid, $user->id, $cid); } return array($user, $roleid); }
function perform_add($userid) { global $CFG; // Try to add necessary role $context = get_context_instance(CONTEXT_SYSTEM); $roleid = $this->check_role(); // If they were able to obtain the correct Moodle role, then // we will assign them the correct filter role if (role_assign($roleid, $userid, 0, $context->id)) { $assign = new stdClass(); $assign->type = $this->type; $assign->path = $this->path; $assign->usersid = $userid; $this->insert_assignment($assign); } }
public function setUp() { global $DB; $this->setAdminUser(); $gen = $this->getDataGenerator(); $this->eventuser = $gen->create_user(); // Create a user. $course = $gen->create_course(); // Create a course. // Assign manager role, so user can see reports. role_assign(1, $this->eventuser->id, context_course::instance($course->id)); // Add a feedback activity to the created course. $record = new stdClass(); $record->course = $course->id; $feedback = $gen->create_module('feedback', $record); $this->eventfeedback = $DB->get_record('feedback', array('id' => $feedback->id), '*', MUST_EXIST); // Get exact copy. $this->eventcm = get_coursemodule_from_instance('feedback', $this->eventfeedback->id, false, MUST_EXIST); // Create a feedback item. $item = new stdClass(); $item->feedback = $this->eventfeedback->id; $item->type = 'numeric'; $item->presentation = '0|0'; $itemid = $DB->insert_record('feedback_item', $item); $this->eventfeedbackitem = $DB->get_record('feedback_item', array('id' => $itemid), '*', MUST_EXIST); // Create a response from a user. $response = new stdClass(); $response->feedback = $this->eventfeedback->id; $response->userid = $this->eventuser->id; $response->anonymous_response = FEEDBACK_ANONYMOUS_YES; $completedid = $DB->insert_record('feedback_completed', $response); $this->eventfeedbackcompleted = $DB->get_record('feedback_completed', array('id' => $completedid), '*', MUST_EXIST); $value = new stdClass(); $value->course_id = $course->id; $value->item = $this->eventfeedbackitem->id; $value->completed = $this->eventfeedbackcompleted->id; $value->value = 25; // User response value. $valueid = $DB->insert_record('feedback_value', $value); $this->eventfeedbackvalue = $DB->get_record('feedback_value', array('id' => $valueid), '*', MUST_EXIST); // Do this in the end to get correct sortorder and cacherev values. $this->eventcourse = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST); }
public function role_assigned($ra) { global $DB; if (!enrol_is_enabled('meta')) { return true; } // prevent circular dependencies - we can not sync meta roles recursively if ($ra->component === 'enrol_meta') { return true; } //only course level roles are interesting $parentcontext = get_context_instance_by_id($ra->contextid); if ($parentcontext->contextlevel != CONTEXT_COURSE) { return true; } // does anything want to sync with this parent? if (!$enrols = $DB->get_records('enrol', array('customint1'=>$parentcontext->instanceid, 'enrol'=>'meta'), 'id ASC')) { return true; } // make sure the role sync is not prevented $plugin = enrol_get_plugin('meta'); if ($disabled = $plugin->get_config('nosyncroleids')) { if (in_array($ra->roleid, explode(',', $disabled))) { return true; } } foreach ($enrols as $enrol) { // Is the user enrolled? We want to sync only really enrolled users if (!$DB->record_exists('user_enrolments', array('userid'=>$ra->userid, 'enrolid'=>$enrol->id))) { continue; } $context = get_context_instance(CONTEXT_COURSE, $enrol->courseid); // just try to assign role, no problem if role assignment already exists role_assign($ra->roleid, $ra->userid, $context->id, 'enrol_meta', $enrol->id); } return true; }
/** * Set up some base user data */ protected function set_up_users() { global $DB, $USER; // Set up a cluster administrator as a PM user. $clusteradmin = new user(array('idnumber' => 'clusteradmin', 'username' => 'clusteradmin', 'firstname' => 'Cluster', 'lastname' => 'Admin', 'email' => '*****@*****.**', 'country' => 'CA')); $clusteradmin->save(); $USER = $DB->get_record('user', array('username' => 'clusteradmin')); // Set up a user set member as a PM user. $clusteruser = new user(array('idnumber' => 'clusteruser', 'username' => 'clusteruser', 'firstname' => 'Cluster', 'lastname' => 'User', 'email' => '*****@*****.**', 'country' => 'CA')); $clusteruser->save(); // Set up our test role. $syscontext = context_system::instance(); $roleid = create_role('clusteradmin', 'clusteradmin', 'clusteradmin'); assign_capability('local/elisprogram:user_edit', CAP_ALLOW, $roleid, $syscontext->id); // Assign the userset administrator an appropriate role on the userset. $instance = \local_elisprogram\context\userset::instance(1); role_assign($roleid, $USER->id, $instance->id); // Assign the user to the user set. $clusterassignment = new clusterassignment(array('clusterid' => 1, 'userid' => $clusteruser->id)); $clusterassignment->save(); }
/** * Validate that the sync from course role assignment to class instance enrolment works */ public function test_enrolled_course_user_syncstoclass() { global $CFG, $DB; require_once elispm::lib('lib.php'); // Set up import data. $this->load_csv_data(); // Make sure the context is set up. $crsctx = context_course::instance(100); // Set up our test role. $roleid = create_role('gradedrole', 'gradedrole', 'gradedrole'); set_config('gradebookroles', $roleid); // Create role assignments. role_assign($roleid, 100, $crsctx->id); // Attempt the sync. $sync = new \local_elisprogram\moodle\synchronize(); $sync->synchronize_moodle_class_grades(); // Make sure the student record was created. $student = student::find(); $this->assertTrue($student->valid()); // Make sure the student has the right class id. $student = $student->current(); $this->assertEquals(100, $student->classid); }
protected function define_execution() { global $CFG, $DB; if (!($userid = $this->task->get_userid())) { return; } if (empty($CFG->restorernewroleid)) { // Bad luck, no fallback role for restorers specified return; } $courseid = $this->get_courseid(); $context = context_course::instance($courseid); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Current user may access the course (admin, category manager or restored teacher enrolment usually) return; } // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled role_assign($CFG->restorernewroleid, $userid, $context); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Extra role is enough, yay! return; } // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, // hopefully admin selected suitable $CFG->restorernewroleid ... if (!enrol_is_enabled('manual')) { return; } if (!($enrol = enrol_get_plugin('manual'))) { return; } if (!$DB->record_exists('enrol', array('enrol' => 'manual', 'courseid' => $courseid))) { $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); $fields = array('status' => ENROL_INSTANCE_ENABLED, 'enrolperiod' => $enrol->get_config('enrolperiod', 0), 'roleid' => $enrol->get_config('roleid', 0)); $enrol->add_instance($course, $fields); } enrol_try_internal_enrol($courseid, $userid); }
/** * Hook that gets called after a CM entity is added through this page * (Note: this function should only use the id field from the supplied cm entity * as the rest of the data is not guaranteed to be there) * * @param object $cm_entity The CM entity added * @uses $DB * @uses $USER */ function after_cm_entity_add($cm_entity) { global $DB, $USER; //make sure a valid role is set if (!empty(elis::$config->local_elisprogram->default_curriculum_role_id) && $DB->record_exists('role', array('id' => elis::$config->local_elisprogram->default_curriculum_role_id))) { //get the context instance for capability checking $context_instance = \local_elisprogram\context\program::instance($cm_entity->id); //assign the appropriate role if the user does not have the edit capability if (!has_capability('local/elisprogram:program_edit', $context_instance)) { role_assign(elis::$config->local_elisprogram->default_curriculum_role_id, $USER->id, $context_instance->id); } } }
/** * Assign roles * * This has to be called after enrolments processing. * * @param mixed $data * @return void */ public function process_assignment($data) { global $DB; $data = (object)$data; // Check roleid, userid are one of the mapped ones if (!$newroleid = $this->get_mappingid('role', $data->roleid)) { return; } if (!$newuserid = $this->get_mappingid('user', $data->userid)) { return; } if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) { // Only assign roles to not deleted users return; } if (!$contextid = $this->task->get_contextid()) { return; } if (empty($data->component)) { // assign standard manual roles // TODO: role_assign() needs one userid param to be able to specify our restore userid role_assign($newroleid, $newuserid, $contextid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment roles if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($component = $DB->get_field('enrol', 'component', array('id'=>$enrolid))) { //note: we have to verify component because it might have changed if ($component === 'enrol_manual') { // manual is a special case, we do not use components - this owudl happen when converting from other plugin role_assign($newroleid, $newuserid, $contextid); //TODO: do we need modifierid? } else { role_assign($newroleid, $newuserid, $contextid, $component, $enrolid); //TODO: do we need modifierid? } } } } }
/** * Restore role assignment. * * @param stdClass $instance * @param int $roleid * @param int $userid * @param int $contextid */ public function restore_role_assignment($instance, $roleid, $userid, $contextid) { if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_UNENROL or $this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) { // Role assignments were already synchronised in restore_instance(), we do not want any leftovers. return; } role_assign($roleid, $userid, $contextid, 'enrol_' . $this->get_name(), $instance->id); }
/** * Hook that gets called after a CM entity is added through this page * (Note: this function should only use the id field from the supplied cm entity * as the rest of the data is not guaranteed to be there) * * @param object $cm_entity The CM entity added */ function after_cm_entity_add($cm_entity) { global $USER, $CURMAN; //make sure a valid role is set if (!empty($CURMAN->config->default_cluster_role_id) && record_exists('role', 'id', $CURMAN->config->default_cluster_role_id)) { //get the context instance for capability checking $context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin'); $context_instance = get_context_instance($context_level, $cm_entity->id); //assign the appropriate role if the user does not have the edit capability if (!has_capability('block/curr_admin:cluster:edit', $context_instance)) { role_assign($CURMAN->config->default_cluster_role_id, $USER->id, 0, $context_instance->id); } } }
case 3: $timestart = $today; break; case 4: $timestart = $course->enrolstartdate; break; case 5: $timestart = $course->enrolenddate; break; } if ($extendperiod > 0) { $timeend = $timestart + $extendperiod; } else { $timeend = 0; } if (!role_assign($roleid, $adduser, 0, $context->id, $timestart, $timeend, $hidden)) { $errors[] = "Could not add user with id {$adduser} to this role!"; } } } $rolename = get_field('role', 'name', 'id', $roleid); add_to_log($course->id, 'role', 'assign', 'admin/roles/assign.php?contextid=' . $context->id . '&roleid=' . $roleid, $rolename, '', $USER->id); } else { if ($remove and !empty($frm->removeselect) and confirm_sesskey()) { $sitecontext = get_context_instance(CONTEXT_SYSTEM); $topleveladmin = false; // we only worry about this if the role has doanything capability at site level if ($context->id == $sitecontext->id && ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext))) { foreach ($adminroles as $adminrole) { if ($adminrole->id == $roleid) { $topleveladmin = true;
public function test_is_user_access_restricted_by_capability() { global $DB; $this->resetAfterTest(); // Create a course and a mod_assign instance. $course = $this->getDataGenerator()->create_course(); $assign = $this->getDataGenerator()->create_module('assign', array('course' => $course->id)); // Create and enrol a student. $coursecontext = context_course::instance($course->id); $studentrole = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST); $student = $this->getDataGenerator()->create_user(); role_assign($studentrole->id, $student->id, $coursecontext); $enrolplugin = enrol_get_plugin('manual'); $enrolinstance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual')); $enrolplugin->enrol_user($enrolinstance, $student->id); $this->setUser($student); // Make sure student can see the module. $cm = get_fast_modinfo($course->id)->instances['assign'][$assign->id]; $this->assertTrue($cm->uservisible); $this->assertFalse($cm->is_user_access_restricted_by_capability()); // Prohibit student to view mod_assign for the course. role_change_permission($studentrole->id, $coursecontext, 'mod/assign:view', CAP_PROHIBIT); get_fast_modinfo($course->id, 0, true); $cm = get_fast_modinfo($course->id)->instances['assign'][$assign->id]; $this->assertFalse($cm->uservisible); $this->assertTrue($cm->is_user_access_restricted_by_capability()); // Restore permission to student to view mod_assign for the course. role_change_permission($studentrole->id, $coursecontext, 'mod/assign:view', CAP_INHERIT); get_fast_modinfo($course->id, 0, true); $cm = get_fast_modinfo($course->id)->instances['assign'][$assign->id]; $this->assertTrue($cm->uservisible); $this->assertFalse($cm->is_user_access_restricted_by_capability()); // Prohibit student to view mod_assign for the particular module. role_change_permission($studentrole->id, context_module::instance($cm->id), 'mod/assign:view', CAP_PROHIBIT); get_fast_modinfo($course->id, 0, true); $cm = get_fast_modinfo($course->id)->instances['assign'][$assign->id]; $this->assertFalse($cm->uservisible); $this->assertTrue($cm->is_user_access_restricted_by_capability()); // Check calling get_fast_modinfo() for different user: $this->setAdminUser(); $cm = get_fast_modinfo($course->id)->instances['assign'][$assign->id]; $this->assertTrue($cm->uservisible); $this->assertFalse($cm->is_user_access_restricted_by_capability()); $cm = get_fast_modinfo($course->id, $student->id)->instances['assign'][$assign->id]; $this->assertFalse($cm->uservisible); $this->assertTrue($cm->is_user_access_restricted_by_capability()); }
} // Process any incoming role assignments before printing the header. if ($roleid) { // Create the user selector objects. $options = array('context' => $context, 'roleid' => $roleid); $potentialuserselector = roles_get_potential_user_selector($context, 'addselect', $options); $currentuserselector = new existing_role_holders('removeselect', $options); // Process incoming role assignments $errors = array(); if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) { $userstoassign = $potentialuserselector->get_selected_users(); if (!empty($userstoassign)) { foreach ($userstoassign as $adduser) { $allow = true; if ($allow) { role_assign($roleid, $adduser->id, $context->id); } } $potentialuserselector->invalidate_selected_users(); $currentuserselector->invalidate_selected_users(); $rolename = $assignableroles[$roleid]; add_to_log($course->id, 'role', 'assign', 'mod/adobeconnect/participant.php?contextid=' . $context->id . '&roleid=' . $roleid, $rolename, '', $USER->id); // Counts have changed, so reload. list($assignableroles, $assigncounts, $nameswithcounts) = get_assignable_roles($context, ROLENAME_BOTH, true); } } // Process incoming role unassignments if (optional_param('remove', false, PARAM_BOOL) && confirm_sesskey()) { $userstounassign = $currentuserselector->get_selected_users(); if (!empty($userstounassign)) { foreach ($userstounassign as $removeuser) {
/** * Synchronise user enrolments in given instance as fast as possible. * * All roles are removed if the meta plugin disabled. * * @static * @param stdClass $instance * @param int $userid * @return void */ protected static function sync_with_parent_course(stdClass $instance, $userid) { global $DB, $CFG; $plugin = enrol_get_plugin('meta'); if ($instance->customint1 == $instance->courseid) { // can not sync with self!!! return; } $context = context_course::instance($instance->courseid); if (!($parentcontext = context_course::instance($instance->customint1, IGNORE_MISSING))) { // linking to missing course is not possible role_unassign_all(array('userid' => $userid, 'contextid' => $context->id, 'component' => 'enrol_meta')); return; } // list of enrolments in parent course (we ignore meta enrols in parents completely) list($enabled, $params) = $DB->get_in_or_equal(explode(',', $CFG->enrol_plugins_enabled), SQL_PARAMS_NAMED, 'e'); $params['userid'] = $userid; $params['parentcourse'] = $instance->customint1; $sql = "SELECT ue.*\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol <> 'meta' AND e.courseid = :parentcourse AND e.enrol {$enabled})\n WHERE ue.userid = :userid"; $parentues = $DB->get_records_sql($sql, $params); // current enrolments for this instance $ue = $DB->get_record('user_enrolments', array('enrolid' => $instance->id, 'userid' => $userid)); // first deal with users that are not enrolled in parent if (empty($parentues)) { self::user_not_supposed_to_be_here($instance, $ue, $context, $plugin); return; } if (!enrol_is_enabled('meta')) { if ($ue) { role_unassign_all(array('userid' => $userid, 'contextid' => $context->id, 'component' => 'enrol_meta')); } return; } $skiproles = $plugin->get_config('nosyncroleids', ''); $skiproles = empty($skiproles) ? array() : explode(',', $skiproles); $syncall = $plugin->get_config('syncall', 1); // roles in parent course (meta enrols must be ignored!) $parentroles = array(); list($ignoreroles, $params) = $DB->get_in_or_equal($skiproles, SQL_PARAMS_NAMED, 'ri', false, -1); $params['contextid'] = $parentcontext->id; $params['userid'] = $userid; $select = "contextid = :contextid AND userid = :userid AND component <> 'enrol_meta' AND roleid {$ignoreroles}"; foreach ($DB->get_records_select('role_assignments', $select, $params) as $ra) { $parentroles[$ra->roleid] = $ra->roleid; } // roles from this instance $roles = array(); $ras = $DB->get_records('role_assignments', array('contextid' => $context->id, 'userid' => $userid, 'component' => 'enrol_meta', 'itemid' => $instance->id)); foreach ($ras as $ra) { $roles[$ra->roleid] = $ra->roleid; } unset($ras); // do we want users without roles? if (!$syncall and empty($parentroles)) { self::user_not_supposed_to_be_here($instance, $ue, $context, $plugin); return; } // is parent enrol active? (we ignore enrol starts and ends, sorry it would be too complex) $parentstatus = ENROL_USER_SUSPENDED; foreach ($parentues as $pue) { if ($pue->status == ENROL_USER_ACTIVE) { $parentstatus = ENROL_USER_ACTIVE; break; } } // enrol user if not enrolled yet or fix status if ($ue) { if ($parentstatus != $ue->status) { $plugin->update_user_enrol($instance, $userid, $parentstatus); $ue->status = $parentstatus; } } else { $plugin->enrol_user($instance, $userid, NULL, 0, 0, $parentstatus); $ue = new stdClass(); $ue->userid = $userid; $ue->enrolid = $instance->id; $ue->status = $parentstatus; } // only active users in enabled instances are supposed to have roles (we can reassign the roles any time later) if ($ue->status != ENROL_USER_ACTIVE or $instance->status != ENROL_INSTANCE_ENABLED) { if ($roles) { role_unassign_all(array('userid' => $userid, 'contextid' => $context->id, 'component' => 'enrol_meta', 'itemid' => $instance->id)); } return; } // add new roles foreach ($parentroles as $rid) { if (!isset($roles[$rid])) { role_assign($rid, $userid, $context->id, 'enrol_meta', $instance->id); } } // remove roles foreach ($roles as $rid) { if (!isset($parentroles[$rid])) { role_unassign($rid, $userid, $context->id, 'enrol_meta', $instance->id); } } }
public function test_sync() { global $CFG, $DB; $this->resetAfterTest(true); $metalplugin = enrol_get_plugin('meta'); $manplugin = enrol_get_plugin('manual'); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); $user4 = $this->getDataGenerator()->create_user(); $user5 = $this->getDataGenerator()->create_user(); $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $course3 = $this->getDataGenerator()->create_course(); $course4 = $this->getDataGenerator()->create_course(); $manual1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual2 = $DB->get_record('enrol', array('courseid' => $course2->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual3 = $DB->get_record('enrol', array('courseid' => $course3->id, 'enrol' => 'manual'), '*', MUST_EXIST); $manual4 = $DB->get_record('enrol', array('courseid' => $course4->id, 'enrol' => 'manual'), '*', MUST_EXIST); $student = $DB->get_record('role', array('shortname' => 'student')); $teacher = $DB->get_record('role', array('shortname' => 'teacher')); $manager = $DB->get_record('role', array('shortname' => 'manager')); $this->disable_plugin(); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->getDataGenerator()->enrol_user($user2->id, $course1->id, $student->id); $this->getDataGenerator()->enrol_user($user3->id, $course1->id, 0); $this->getDataGenerator()->enrol_user($user4->id, $course1->id, $teacher->id); $this->getDataGenerator()->enrol_user($user5->id, $course1->id, $manager->id); $this->getDataGenerator()->enrol_user($user1->id, $course2->id, $student->id); $this->getDataGenerator()->enrol_user($user2->id, $course2->id, $teacher->id); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); set_config('syncall', 0, 'enrol_meta'); set_config('nosyncroleids', $manager->id, 'enrol_meta'); require_once $CFG->dirroot . '/enrol/meta/locallib.php'; enrol_meta_sync(null, false); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); $this->enable_plugin(); enrol_meta_sync(null, false); $this->assertEquals(7, $DB->count_records('user_enrolments')); $this->assertEquals(6, $DB->count_records('role_assignments')); // Disable the plugin to prevent add_instance from calling enrol_meta_sync. $this->disable_plugin(); $e1 = $metalplugin->add_instance($course3, array('customint1' => $course1->id)); $e2 = $metalplugin->add_instance($course3, array('customint1' => $course2->id)); $e3 = $metalplugin->add_instance($course4, array('customint1' => $course2->id)); $enrol1 = $DB->get_record('enrol', array('id' => $e1)); $enrol2 = $DB->get_record('enrol', array('id' => $e2)); $enrol3 = $DB->get_record('enrol', array('id' => $e3)); $this->enable_plugin(); enrol_meta_sync($course4->id, false); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol3, $teacher)); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(13, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol1, $student)); $this->assertFalse($this->is_meta_enrolled($user3, $enrol1)); $this->assertTrue($this->is_meta_enrolled($user4, $enrol1, $teacher)); $this->assertFalse($this->is_meta_enrolled($user5, $enrol1)); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol2, $teacher)); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($this->is_meta_enrolled($user2, $enrol3, $teacher)); set_config('syncall', 1, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(16, $DB->count_records('user_enrolments')); $this->assertEquals(13, $DB->count_records('role_assignments')); $this->assertTrue($this->is_meta_enrolled($user3, $enrol1, false)); $this->assertTrue($this->is_meta_enrolled($user5, $enrol1, false)); $this->assertEquals(16, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->disable_plugin(); $manplugin->unenrol_user($manual1, $user1->id); $manplugin->unenrol_user($manual2, $user1->id); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(14, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->enable_plugin(); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol3->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(11, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol1->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, $student)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol2->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol3, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol3->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); enrol_meta_sync(null, false); $this->assertEquals(14, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol1->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol2, false)); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrol2->id, 'status' => ENROL_USER_SUSPENDED, 'userid' => $user1->id))); set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL, 'enrol_meta'); enrol_meta_sync($course4->id, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol3)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->assertFalse($this->is_meta_enrolled($user1, $enrol2)); // Now try sync triggered by events. set_config('syncall', 1, 'enrol_meta'); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 0); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); set_config('syncall', 0, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(9, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, 0); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); role_assign($teacher->id, $user1->id, context_course::instance($course1->id)->id); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $teacher)); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $teacher)); role_unassign($teacher->id, $user1->id, context_course::instance($course1->id)->id); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(10, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(10, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(9, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(9, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertFalse($this->is_meta_enrolled($user1, $enrol1)); set_config('syncall', 1, 'enrol_meta'); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(11, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->update_user_enrol($manual1, $user1->id, ENROL_USER_SUSPENDED); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(9, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(9, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); set_config('syncall', 1, 'enrol_meta'); set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); $manplugin->unenrol_user($manual1, $user1->id); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); enrol_meta_sync(null, false); $this->assertEquals(12, $DB->count_records('user_enrolments')); $this->assertEquals(8, $DB->count_records('role_assignments')); $this->assertEquals(11, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, false)); $this->getDataGenerator()->enrol_user($user1->id, $course1->id, $student->id); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); $this->assertTrue($this->is_meta_enrolled($user1, $enrol1, $student)); set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL, 'enrol_meta'); enrol_meta_sync(null, false); $this->assertEquals(13, $DB->count_records('user_enrolments')); $this->assertEquals(10, $DB->count_records('role_assignments')); $this->assertEquals(13, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course1, false); $this->assertEquals(3, $DB->count_records('user_enrolments')); $this->assertEquals(3, $DB->count_records('role_assignments')); $this->assertEquals(3, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); enrol_meta_sync(null, false); $this->assertEquals(3, $DB->count_records('user_enrolments')); $this->assertEquals(3, $DB->count_records('role_assignments')); $this->assertEquals(3, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course2, false); $this->assertEquals(0, $DB->count_records('user_enrolments')); $this->assertEquals(0, $DB->count_records('role_assignments')); $this->assertEquals(0, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); enrol_meta_sync(null, false); $this->assertEquals(0, $DB->count_records('user_enrolments')); $this->assertEquals(0, $DB->count_records('role_assignments')); $this->assertEquals(0, $DB->count_records('user_enrolments', array('status' => ENROL_USER_ACTIVE))); delete_course($course3, false); delete_course($course4, false); }
function sync_enrolments($type, $enrol = false) { global $CFG; // Get the role. If it doesn't exist, that is bad. $role = get_record('role', 'shortname', $type); if (!$role) { notify("No such role: {$type}"); return false; } // Connect to the external database $ldap_connection = $this->enrol_ldap_connect(); if (!$ldap_connection) { @ldap_close($ldap_connection); notify("LDAP-module cannot connect to server: {$CFG->ldap_host_url}"); return false; } // we are connected OK, continue... $this->enrol_ldap_bind($ldap_connection); //get all contexts and look for first matching user $ldap_contexts = explode(";", $CFG->{'enrol_ldap_contexts_role' . $role->id}); // get all the fields we will want for the potential course creation // as they are light. don't get membership -- potentially a lot of data. $ldap_fields_wanted = array('dn', $CFG->enrol_ldap_course_idnumber); if (!empty($CFG->enrol_ldap_course_fullname)) { array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_fullname); } if (!empty($CFG->enrol_ldap_course_shortname)) { array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_shortname); } if (!empty($CFG->enrol_ldap_course_summary)) { array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_summary); } if ($enrol) { array_push($ldap_fields_wanted, $CFG->{'enrol_ldap_memberattribute_role' . $role->id}); } // define the search pattern if (!empty($CFG->enrol_ldap_objectclass)) { $ldap_search_pattern = '(objectclass=' . $CFG->enrol_ldap_objectclass . ')'; } else { $ldap_search_pattern = "(objectclass=*)"; } // first, pack the sortorder... fix_course_sortorder(); foreach ($ldap_contexts as $context) { $context = trim($context); if ($CFG->enrol_ldap_search_sub) { //use ldap_search to find first user from subtree $ldap_result = @ldap_search($ldap_connection, $context, $ldap_search_pattern, $ldap_fields_wanted); } else { //search only in this context $ldap_result = @ldap_list($ldap_connection, $context, $ldap_search_pattern, $ldap_fields_wanted, 0, 0); } // check and push results $records = $ldap_result ? ldap_get_entries($ldap_connection, $ldap_result) : array('count' => 0); // ldap libraries return an odd array, really. fix it: $flat_records = array(); for ($c = 0; $c < $records['count']; $c++) { array_push($flat_records, $records["{$c}"]); } // free mem -- is there a leak? $records = 0; $ldap_result = 0; if (count($flat_records)) { foreach ($flat_records as $course) { $idnumber = $course[$CFG->enrol_ldap_course_idnumber][0]; print "== Synching {$idnumber}\n"; // does the course exist in moodle already? $course_obj = false; $course_obj = get_record('course', $this->enrol_localcoursefield, $idnumber); if (!is_object($course_obj)) { // ok, now then let's create it! print "Creating Course {$idnumber}..."; $newcourseid = $this->create_course($course, true); // we are skipping fix_course_sortorder() $course_obj = get_record('course', 'id', $newcourseid); if (is_object($course_obj)) { print "OK!\n"; } else { print "failed\n"; } } // enrol&unenrol if required if ($enrol && is_object($course_obj)) { // Get a context object. $context = get_context_instance(CONTEXT_COURSE, $course_obj->id); // pull the ldap membership into a nice array // this is an odd array -- mix of hash and array -- $ldapmembers = array(); if (array_key_exists('enrol_ldap_memberattribute_role' . $role->id, $CFG) && !empty($CFG->{'enrol_ldap_memberattribute_role' . $role->id}) && !empty($course[strtolower($CFG->{'enrol_ldap_memberattribute_role' . $role->id})])) { // may have no membership! $ldapmembers = $course[strtolower($CFG->{'enrol_ldap_memberattribute_role' . $role->id})]; unset($ldapmembers['count']); // remove oddity ;) $ldapmembers = addslashes_recursive($ldapmembers); } // prune old ldap enrolments // hopefully they'll fit in the max buffer size for the RDBMS $sql = ' SELECT enr.userid AS user, 1 FROM ' . $CFG->prefix . 'role_assignments enr JOIN ' . $CFG->prefix . 'user usr ON usr.id=enr.userid WHERE enr.roleid = ' . $role->id . ' AND enr.contextid = ' . $context->id . ' AND enr.enrol = \'ldap\' '; if (!empty($ldapmembers)) { $sql .= 'AND usr.idnumber NOT IN (\'' . join('\',\'', $ldapmembers) . '\')'; } else { print "Empty enrolment for {$course_obj->shortname} \n"; } $todelete = get_records_sql($sql); if (!empty($todelete)) { foreach ($todelete as $member) { $member = $member->user; if (role_unassign($role->id, $member, 0, $context->id, 'ldap')) { print "Unassigned {$type} from {$member} for course {$course_obj->id} ({$course_obj->shortname})\n"; } else { print "Failed to unassign {$type} from {$member} for course {$course_obj->id} ({$course_obj->shortname})\n"; } } } // insert current enrolments // bad we can't do INSERT IGNORE with postgres... foreach ($ldapmembers as $ldapmember) { $sql = 'SELECT id,1 FROM ' . $CFG->prefix . 'user ' . " WHERE idnumber='{$ldapmember}'"; $member = get_record_sql($sql); // print "sql: $sql \nidnumber = ".stripslashes($ldapmember)." \n".var_dump($member); if (empty($member) || empty($member->id)) { print "Could not find user " . stripslashes($ldapmember) . ", skipping\n"; continue; } $member = $member->id; if (!get_record('role_assignments', 'roleid', $role->id, 'contextid', $context->id, 'userid', $member, 'enrol', 'ldap')) { if (role_assign($role->id, $member, 0, $context->id, 0, 0, 0, 'ldap')) { print "Assigned role {$type} to {$member} (" . stripslashes($ldapmember) . ") for course {$course_obj->id} ({$course_obj->shortname})\n"; } else { print "Failed to assign role {$type} to {$member} (" . stripslashes($ldapmember) . ") for course {$course_obj->id} ({$course_obj->shortname})\n"; } } } } } } } // we are done now, a bit of housekeeping fix_course_sortorder(); @ldap_close($ldap_connection); return true; }
/** * Restore role assignment. * * @param stdClass $instance * @param int $roleid * @param int $userid * @param int $contextid */ public function restore_role_assignment($instance, $roleid, $userid, $contextid) { // This is necessary only because we may migrate other types to this instance, // we do not use component in manual or self enrol. role_assign($roleid, $userid, $contextid, '', 0); }
/** * Validate that class instance-moodle course associations can be created during a class instance update action. * * @param string $link The link attribute to use in the import, or 'auto' to auto-create from template. * @dataProvider link_course_provider */ public function test_associate_moodle_course_during_class_update($link) { global $CFG, $DB, $USER; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/classmoodlecourse.class.php'); require_once elispm::lib('data/coursetemplate.class.php'); require_once elispm::lib('data/course.class.php'); require_once elispm::lib('data/pmclass.class.php'); // Make sure $USER is set up for backup/restore. $USER->id = $DB->get_field_select('user', 'id', "username != 'guest' AND deleted = 0", array(), IGNORE_MULTIPLE); // Need the moodle/backup:backupcourse capability. $guestroleid = create_role('guestrole', 'guestrole', 'guestrole'); set_config('guestroleid', $guestroleid); set_config('siteguest', ''); $systemcontext = context_system::instance(); $roleid = create_role('testrole', 'testrole', 'testrole'); assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $roleid, $systemcontext->id); role_assign($roleid, $USER->id, $systemcontext->id); $coursecategory = new stdClass(); $coursecategory->name = 'testcoursecategoryname'; $coursecategory->id = $DB->insert_record('course_categories', $coursecategory); $moodlecourse = new stdClass(); $moodlecourse->category = $coursecategory->id; $moodlecourse->shortname = 'testcourseshortname'; $moodlecourse->fullname = 'testcoursefullname'; $moodlecourse = create_course($moodlecourse); $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => '')); $course->save(); $class = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber')); $class->save(); // Need this for the 'auto' case, at the very least. $coursetemplate = new coursetemplate(array('courseid' => $course->id, 'location' => $moodlecourse->id, 'templateclass' => 'moodlecourseurl')); $coursetemplate->save(); // Run the class instance create action. $record = new stdClass(); $record->idnumber = 'testclassidnumber'; $record->assignment = 'testcourseidnumber'; $record->link = $link; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->class_update($record, 'bogus'); // Validation. if ($record->link == 'auto') { $moodlecourseid = $moodlecourse->id + 1; } else { $moodlecourseid = $moodlecourse->id; } $dbautocreated = $record->link == 'auto' ? 1 : 0; $this->assertTrue($DB->record_exists(classmoodlecourse::TABLE, array('classid' => $class->id, 'moodlecourseid' => $moodlecourseid, 'enroltype' => 0, 'enrolplugin' => 'crlm', 'autocreated' => $dbautocreated))); ini_set('max_execution_time', '0'); }
/** * This function is run by admin/cron.php every time if admin has enabled this plugin. * * Everyday at settlement time (default is 00:05), it cleans up some tables * and sends email to admin/teachers about pending orders expiring if manual-capture has enabled. * * If admin set up 'Order review' and 'Capture day', it captures credits cards and enrols students. * * @access public */ function cron() { global $CFG; require_once $CFG->dirroot . '/enrol/authorize/authorizenetlib.php'; $oneday = 86400; $timenow = time(); $settlementtime = authorize_getsettletime($timenow); $timediff30 = $settlementtime - 30 * $oneday; $mconfig = get_config('enrol/authorize'); mtrace("Processing authorize cron..."); if (intval($mconfig->an_dailysettlement) < $settlementtime) { set_config('an_dailysettlement', $settlementtime, 'enrol/authorize'); mtrace(" daily cron; some cleanups and sending email to admins the count of pending orders expiring", ": "); $this->cron_daily(); mtrace("done"); } mtrace(" scheduled capture", ": "); if (empty($CFG->an_review) or !empty($CFG->an_test) or intval($CFG->an_capture_day) < 1 or !check_openssl_loaded()) { mtrace("disabled"); return; // order review disabled or test mode or manual capture or openssl wasn't loaded. } $timediffcnf = $settlementtime - intval($CFG->an_capture_day) * $oneday; $select = "(status = '" . AN_STATUS_AUTH . "') AND (timecreated < '{$timediffcnf}') AND (timecreated > '{$timediff30}')"; if (!($ordercount = count_records_select('enrol_authorize', $select))) { mtrace("no pending orders"); return; } $eachconn = intval($mconfig->an_eachconnsecs); $eachconn = $eachconn > 60 ? 60 : ($eachconn <= 0 ? 3 : $eachconn); if ($ordercount * $eachconn + intval($mconfig->an_lastcron) > $timenow) { mtrace("blocked"); return; } set_config('an_lastcron', $timenow, 'enrol/authorize'); mtrace(" {$ordercount} orders are being processed now", ": "); $faults = ''; $sendem = array(); $elapsed = time(); @set_time_limit(0); $this->log = "AUTHORIZE.NET AUTOCAPTURE CRON: " . userdate($timenow) . "\n"; $lastcourseid = 0; for ($rs = get_recordset_select('enrol_authorize', $select, 'courseid'); $order = rs_fetch_next_record($rs);) { $message = ''; $extra = NULL; if (AN_APPROVED == authorize_action($order, $message, $extra, AN_ACTION_PRIOR_AUTH_CAPTURE)) { if ($lastcourseid != $order->courseid) { $lastcourseid = $order->courseid; $course = get_record('course', 'id', $lastcourseid); $role = get_default_course_role($course); $context = get_context_instance(CONTEXT_COURSE, $lastcourseid); } $timestart = $timeend = 0; if ($course->enrolperiod) { $timestart = $timenow; $timeend = $order->settletime + $course->enrolperiod; } $user = get_record('user', 'id', $order->userid); if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, 'authorize')) { $this->log .= "User({$user->id}) has been enrolled to course({$course->id}).\n"; if (!empty($CFG->enrol_mailstudents)) { $sendem[] = $order->id; } } else { $faults .= "Error while trying to enrol " . fullname($user) . " in '{$course->fullname}' \n"; foreach ($order as $okey => $ovalue) { $faults .= " {$okey} = {$ovalue}\n"; } } } else { $this->log .= "Error, Order# {$order->id}: " . $message . "\n"; } } rs_close($rs); mtrace("processed"); $timenow = time(); $elapsed = $timenow - $elapsed; $eachconn = ceil($elapsed / $ordercount); set_config('an_eachconnsecs', $eachconn, 'enrol/authorize'); $this->log .= "AUTHORIZE.NET CRON FINISHED: " . userdate($timenow); $adminuser = get_admin(); if (!empty($faults)) { email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON FAULTS", $faults); } if (!empty($CFG->enrol_mailadmins)) { email_to_user($adminuser, $adminuser, "AUTHORIZE.NET CRON LOG", $this->log); } // Send emails to students about which courses have enrolled. if (!empty($sendem)) { mtrace(" sending welcome messages to students", ": "); send_welcome_messages($sendem); mtrace("sent"); } }
/** * Assigns a role to a user. * * @param int $roleid * @param int $userid * @return int|false */ public function assign_role_to_user($roleid, $userid) { require_capability('moodle/role:assign', $this->context); if (!array_key_exists($roleid, $this->get_assignable_roles())) { if (defined('AJAX_SCRIPT')) { throw new moodle_exception('invalidrole'); } return false; } return role_assign($roleid, $userid, $this->context->id, '', NULL); }
/** * Adapter to enrol_user() data generator. * @throws Exception * @param array $data * @return void */ protected function process_enrol_user($data) { global $SITE; if (empty($data['roleid'])) { throw new Exception('\'course enrolments\' requires the field \'role\' to be specified'); } if (!isset($data['userid'])) { throw new Exception('\'course enrolments\' requires the field \'user\' to be specified'); } if (!isset($data['courseid'])) { throw new Exception('\'course enrolments\' requires the field \'course\' to be specified'); } if (!isset($data['enrol'])) { $data['enrol'] = 'manual'; } if (!isset($data['timestart'])) { $data['timestart'] = 0; } if (!isset($data['timeend'])) { $data['timeend'] = 0; } if (!isset($data['status'])) { $data['status'] = null; } // If the provided course shortname is the site shortname we consider it a system role assign. if ($data['courseid'] == $SITE->id) { // Frontpage course assign. $context = context_course::instance($data['courseid']); role_assign($data['roleid'], $data['userid'], $context->id); } else { // Course assign. $this->datagenerator->enrol_user($data['userid'], $data['courseid'], $data['roleid'], $data['enrol'], $data['timestart'], $data['timeend'], $data['status']); } }