public function execute() { global $CFG, $DB; require_once $CFG->dirroot . '/cohort/lib.php'; require_once $CFG->dirroot . '/enrol/cohort/locallib.php'; $cohortid = $this->arguments[0]; // Check if cohort exists. if (!($cohort = $DB->get_record('cohort', array('id' => $cohortid)))) { echo "Cohort does not exist\n"; exit(0); } $users = array_slice($this->arguments, 1); foreach ($users as $key => $userid) { cohort_remove_member($cohortid, $userid); echo "User " . $userid . " un-enrolled\n"; } }
// cohort_add_member($cohort->id, $adduser->id); // } //$batches->enrol_course(); $potentialuserselector->invalidate_selected_users(); $existinguserselector->invalidate_selected_users(); } } // Process removing user assignments to the cohort if (optional_param('remove', false, PARAM_BOOL) && confirm_sesskey()) { $userstoremove = $existinguserselector->get_selected_users(); if (!empty($userstoremove)) { foreach ($userstoremove as $removeuser) { cohort_remove_member($cohort->id, $removeuser->id); // $batches->unenrol_user($removeuser->id); } $potentialuserselector->invalidate_selected_users(); $existinguserselector->invalidate_selected_users(); } } // Print the form. ?> <form id="assignform" method="post" action="<?php echo $PAGE->url ?>"><div> <input type="hidden" name="sesskey" value="<?php echo sesskey() ?>" /> <input type="hidden" name="costid" value="<?php echo $costid; ?>" /> <table summary="" class="generaltable generalbox boxaligncenter" cellspacing="0"> <tr>
private function process_cohort_membership_node($membershipnode, $xpath, $subtractive = 0) { global $DB, $CFG; $members = $xpath->evaluate("member", $membershipnode); $idnumber = $xpath->evaluate("sourcedid/id", $membershipnode)->item(0); if ($idnumber) { $ship = new stdClass(); $ship->coursecode = $idnumber->nodeValue; if ($ship->courseid = $DB->get_field('cohort', 'id', array('idnumber' => $ship->coursecode))) { $cohortrec = $DB->get_fieldset_select('cohort_members', 'userid', 'cohortid=' . $ship->courseid); $curlist = array_flip($cohortrec); foreach ($members as $mmember) { $midnumber = new stdClass(); $midnumber = $xpath->evaluate("sourcedid/id", $mmember)->item(0); if ($midnumber) { $member = new stdClass(); $member->idnumber = $midnumber->nodeValue; $userid = $DB->get_field('user', 'id', array('idnumber' => $member->idnumber)); $latestlist[$userid] = $userid; if (!isset($curlist[$userid])) { if ($userid != 0 && $userid != '') { cohort_add_member($ship->courseid, $userid); } } } } if ($subtractive == 1) { foreach ($cohortrec as $curmember) { if (!isset($latestlist[$curmember])) { cohort_remove_member($ship->courseid, $curmember); } } } } } }
public function test_cohort_remove_member_event() { global $USER; $this->resetAfterTest(); // Setup the data. $cohort = $this->getDataGenerator()->create_cohort(); $user = $this->getDataGenerator()->create_user(); cohort_add_member($cohort->id, $user->id); // Capture the events. $sink = $this->redirectEvents(); // Peform the remove operation. cohort_remove_member($cohort->id, $user->id); $events = $sink->get_events(); $sink->close(); // Validate the event. $this->assertCount(1, $events); $event = $events[0]; $this->assertInstanceOf('\\core\\event\\cohort_member_removed', $event); $this->assertEquals('cohort', $event->objecttable); $this->assertEquals($cohort->id, $event->objectid); $this->assertEquals($user->id, $event->relateduserid); $this->assertEquals($USER->id, $event->userid); $url = new moodle_url('/cohort/assign.php', array('id' => $event->objectid)); $this->assertEquals($url, $event->get_url()); $this->assertEventLegacyData((object) array('cohortid' => $cohort->id, 'userid' => $user->id), $event); $this->assertEventContextNotUsed($event); }
/** * cron synchronization script * * @param int $do_updates true to update existing accounts * * @return int */ function sync_users($do_updates = false) { global $CFG, $DB; // process users in Moodle that no longer exist in Drupal $remote_user = $this->config->remote_user; $remote_pw = $this->config->remote_pw; $base_url = $this->config->host_uri; $apiObj = new RemoteAPI($base_url); // Required for authentication, and all other operations: $ret = $apiObj->Login($remote_user, $remote_pw, true); if ($ret->info['http_code'] == 404) { die("ERROR: Login service unreachable!\n"); } if ($ret->info['http_code'] == 401) { die("ERROR: Login failed - check username and password!\n"); } elseif ($ret->info['http_code'] !== 200) { $error = "ERROR: Login to drupal failed with http code " . $ret->info['http_code']; if (!empty($ret->error)) { $error .= PHP_EOL . $ret->error . PHP_EOL; } die($error); } // list external users since last update $vid = isset($this->config->last_vid) ? $this->config->last_vid : 0; $pagesize = $this->config->pagesize; $page = 0; $drupal_users = $apiObj->Index('user', "?vid={$vid},page={$page},pagesize={$pagesize}"); if (is_null($drupal_users) || empty($drupal_users)) { die("ERROR: Problems trying to get index of users!\n"); } // sync users in Drupal with users in Moodle (adding users if needed) print_string('auth_drupalservicesuserstoupdate', 'auth_drupalservices', count($drupal_users)); foreach ($drupal_users as $drupal_user_info) { // get the full user object rather than the prototype from the index service // merge the listing and the full value because if the user is blocked, a full user will not be retrieved $drupal_user = (array) $drupal_user_info + (array) $apiObj->Index("user/{$drupal_user_info->uid}"); // recast drupaluser as an object $drupal_user = (object) $drupal_user; // the drupal services module strips off the mail attribute if the user requested is not // either the user requesting, or a user with administer users permission. // luckily the updates service has the value, so we have to copy it over. $drupal_user->mail = $drupal_user_info->mail; if ($drupal_user_info->uid < 1) { //No anon print "Skipping anon user - uid {$drupal_user->uid}\n"; continue; } print_string('auth_drupalservicesupdateuser', 'auth_drupalservices', array($drupal_user->name . '(' . $drupal_user->uid . ')')); $user = $this->create_update_user($drupal_user); if (empty($user)) { // Something went wrong while creating the user print_error('auth_drupalservicescreateaccount', 'auth_drupalservices', array($drupal_user->name)); continue; //Next user } } // now that all the latest updates have been imported, store the revision point we are at. set_config('last_vid', $drupal_user->vid, 'auth_drupalservices'); // Now do cohorts if ($this->config->cohorts != 0) { $cohort_view = $this->config->cohort_view; print "Updating cohorts using services view - {$cohort_view}\n"; $context = context_system::instance(); //$processed_cohorts_list = array(); $drupal_cohorts = $apiObj->Index($cohort_view); if (is_null($drupal_cohorts)) { print "ERROR: Error retreiving cohorts!\n"; } else { // OK First lets create any Moodle cohorts that are in drupal. foreach ($drupal_cohorts as $drupal_cohort) { if ($drupal_cohort->cohort_name == '') { continue; // We don't want an empty cohort name } $drupal_cohort_list[] = $drupal_cohort->cohort_name; if (!$this->cohort_exists($drupal_cohort->cohort_name)) { $newcohort = new stdClass(); $newcohort->name = $drupal_cohort->cohort_name; $newcohort->idnumber = $drupal_cohort->cohort_id; $newcohort->description = $drupal_cohort->cohort_description; $newcohort->contextid = $context->id; $newcohort->component = 'auth_drupalservices'; $cid = cohort_add_cohort($newcohort); print "Cohort {$drupal_cohort->cohort_name} ({$cid}) created!\n"; } } // Next lets delete any Moodle cohorts that are not in drupal. // Now create a unique array $drupal_cohort_list = array_unique($drupal_cohort_list); //print_r($drupal_cohort_list); $moodle_cohorts = $this->moodle_cohorts(); //print_r($moodle_cohorts); foreach ($moodle_cohorts as $moodle_cohort) { if (array_search($moodle_cohort->name, $drupal_cohort_list) === false) { print "{$moodle_cohort->name} not in drupal - deleteing\n"; cohort_delete_cohort($moodle_cohort); } $moodle_cohorts_list[$moodle_cohort->id] = $moodle_cohort->name; } // Cool. Now lets go through each user and add them to cohorts. // arrays to use? $userlist - list of uids. // $drupal_cohorts - view. $drupal_cohorts_list. Moodle lists. foreach ($userlist as $uid) { $drupal_user_cohort_list = array(); //print "$uid\n"; $user = $DB->get_record('user', array('idnumber' => $uid, 'mnethostid' => $CFG->mnet_localhost_id)); // Get array of cohort names this user belongs to. $drupal_user_cohorts = $this->drupal_user_cohorts($uid, $drupal_cohorts); foreach ($drupal_user_cohorts as $drupal_user_cohort) { //get the cohort id frm the moodle list. $cid = array_search($drupal_user_cohort->cohort_name, $moodle_cohorts_list); //print "$cid\n"; if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) { cohort_add_member($cid, $user->id); print "Added {$user->username} ({$user->id}) to cohort {$drupal_user_cohort->cohort_name}\n"; } // Create a list of enrolled cohorts to use later. $drupal_user_cohort_list[] = $cid; } // Cool. now get this users list of moodle cohorts and compare // with drupal. remove from moodle if needed. $moodle_user_cohorts = $this->moodle_user_cohorts($user); //print_r($moodle_user_cohorts); foreach ($moodle_user_cohorts as $moodle_user_cohort) { if (array_search($moodle_user_cohort->cid, $drupal_user_cohort_list) === false) { cohort_remove_member($moodle_user_cohort->cid, $user->id); print "Removed {$user->username} ({$user->id}) from cohort {$moodle_user_cohort->name}\n"; } } } } } // End of cohorts //LOGOUT if (get_config('auth_drupalservices', 'call_logout_service')) { $ret = $apiObj->Logout(); if (is_null($ret)) { print "ERROR logging out!\n"; } else { print "Logged out from drupal services\n"; } } }
public function test_sync_all_courses() { global $DB; $this->resetAfterTest(); $trace = new null_progress_trace(); // Setup a few courses and categories. $cohortplugin = enrol_get_plugin('cohort'); $manualplugin = enrol_get_plugin('manual'); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->assertNotEmpty($studentrole); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->assertNotEmpty($teacherrole); $managerrole = $DB->get_record('role', array('shortname' => 'manager')); $this->assertNotEmpty($managerrole); $cat1 = $this->getDataGenerator()->create_category(); $cat2 = $this->getDataGenerator()->create_category(); $course1 = $this->getDataGenerator()->create_course(array('category' => $cat1->id)); $course2 = $this->getDataGenerator()->create_course(array('category' => $cat1->id)); $course3 = $this->getDataGenerator()->create_course(array('category' => $cat2->id)); $course4 = $this->getDataGenerator()->create_course(array('category' => $cat2->id)); $maninstance1 = $DB->get_record('enrol', array('courseid' => $course1->id, 'enrol' => 'manual'), '*', MUST_EXIST); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); $user4 = $this->getDataGenerator()->create_user(); $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat1->id)->id)); $cohort2 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat2->id)->id)); $cohort3 = $this->getDataGenerator()->create_cohort(); $this->disable_plugin(); // Prevents event sync. $manualplugin->enrol_user($maninstance1, $user4->id, $teacherrole->id); $manualplugin->enrol_user($maninstance1, $user3->id, $managerrole->id); $this->assertEquals(2, $DB->count_records('role_assignments', array())); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort1->id, 'roleid' => $studentrole->id)); $cohortinstance1 = $DB->get_record('enrol', array('id' => $id)); $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort2->id, 'roleid' => $teacherrole->id)); $cohortinstance2 = $DB->get_record('enrol', array('id' => $id)); $id = $cohortplugin->add_instance($course2, array('customint1' => $cohort2->id, 'roleid' => $studentrole->id)); $cohortinstance3 = $DB->get_record('enrol', array('id' => $id)); cohort_add_member($cohort1->id, $user1->id); cohort_add_member($cohort1->id, $user2->id); cohort_add_member($cohort1->id, $user4->id); cohort_add_member($cohort2->id, $user3->id); cohort_add_member($cohort3->id, $user3->id); $this->assertEquals(2, $DB->count_records('role_assignments', array())); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); // Test sync of one course only. enrol_cohort_sync($trace, null); $this->assertEquals(2, $DB->count_records('role_assignments', array())); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->enable_plugin(); enrol_cohort_sync($trace, null); $this->assertEquals(7, $DB->count_records('user_enrolments', array())); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user1->id))); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user2->id))); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user4->id))); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance2->id, 'userid' => $user3->id))); $this->assertEquals(7, $DB->count_records('role_assignments', array())); $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user1->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user2->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user4->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id))); $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES); $DB->delete_records('cohort_members', array('cohortid' => $cohort2->id, 'userid' => $user3->id)); // Use low level DB api to prevent events! enrol_cohort_sync($trace, $course1->id); $this->assertEquals(7, $DB->count_records('user_enrolments', array())); $this->assertEquals(6, $DB->count_records('role_assignments', array())); $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id))); $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL); $DB->delete_records('cohort_members', array('cohortid' => $cohort1->id, 'userid' => $user1->id)); // Use low level DB api to prevent events! enrol_cohort_sync($trace, $course1->id); $this->assertEquals(5, $DB->count_records('user_enrolments', array())); $this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance2->id, 'userid' => $user3->id))); $this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $cohortinstance1->id, 'userid' => $user1->id))); $this->assertEquals(5, $DB->count_records('role_assignments', array())); $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user3->id, 'roleid' => $teacherrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance2->id))); $this->assertFalse($DB->record_exists('role_assignments', array('contextid' => context_course::instance($course1->id)->id, 'userid' => $user1->id, 'roleid' => $studentrole->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES); $DB->delete_records('cohort_members', array('cohortid' => $cohort1->id)); // Use low level DB api to prevent events! $DB->delete_records('cohort', array('id' => $cohort1->id)); // Use low level DB api to prevent events! enrol_cohort_sync($trace, $course1->id); $this->assertEquals(5, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('role_assignments', array())); $cohortplugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL); enrol_cohort_sync($trace, $course1->id); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('role_assignments', array())); // Test group sync. $this->disable_plugin(); // No event sync // Trigger sync to remove extra role assignments. enrol_cohort_sync($trace, $course1->id); $this->assertEquals(2, $DB->count_records('role_assignments', array())); $id = groups_create_group((object) array('name' => 'Group 1', 'courseid' => $course1->id)); $group1 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST); $id = groups_create_group((object) array('name' => 'Group 2', 'courseid' => $course1->id)); $group2 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST); $id = groups_create_group((object) array('name' => 'Group 2', 'courseid' => $course2->id)); $group3 = $DB->get_record('groups', array('id' => $id), '*', MUST_EXIST); $cohort1 = $this->getDataGenerator()->create_cohort(array('contextid' => context_coursecat::instance($cat1->id)->id)); $id = $cohortplugin->add_instance($course1, array('customint1' => $cohort1->id, 'roleid' => $studentrole->id, 'customint2' => $group1->id)); $cohortinstance1 = $DB->get_record('enrol', array('id' => $id)); $this->assertTrue(groups_add_member($group1, $user4)); $this->assertTrue(groups_add_member($group2, $user4)); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('role_assignments', array())); $this->assertFalse(groups_is_member($group1->id, $user1->id)); cohort_add_member($cohort1->id, $user1->id); cohort_add_member($cohort1->id, $user4->id); cohort_add_member($cohort2->id, $user4->id); cohort_add_member($cohort2->id, $user3->id); $this->enable_plugin(); enrol_cohort_sync($trace, null); $this->assertEquals(8, $DB->count_records('user_enrolments', array())); $this->assertEquals(8, $DB->count_records('role_assignments', array())); $this->assertTrue(groups_is_member($group1->id, $user1->id)); $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user1->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue(is_enrolled(context_course::instance($course1->id), $user4)); $this->assertTrue(groups_is_member($group1->id, $user4->id)); $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue(is_enrolled(context_course::instance($course2->id), $user3)); $this->assertFalse(groups_is_member($group3->id, $user3->id)); $cohortinstance1->customint2 = $group2->id; $DB->update_record('enrol', $cohortinstance1); $cohortinstance3->customint2 = $group3->id; $DB->update_record('enrol', $cohortinstance3); enrol_cohort_sync($trace, null); $this->assertFalse(groups_is_member($group1->id, $user1->id)); $this->assertTrue(groups_is_member($group2->id, $user1->id)); $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group2->id, 'userid' => $user1->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue(groups_is_member($group1->id, $user4->id)); $this->assertTrue(groups_is_member($group2->id, $user4->id)); $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group1->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertFalse($DB->record_exists('groups_members', array('groupid' => $group2->id, 'userid' => $user4->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance1->id))); $this->assertTrue(groups_is_member($group3->id, $user3->id)); $this->assertTrue($DB->record_exists('groups_members', array('groupid' => $group3->id, 'userid' => $user3->id, 'component' => 'enrol_cohort', 'itemid' => $cohortinstance3->id))); cohort_remove_member($cohort1->id, $user1->id); $this->assertFalse(groups_is_member($group1->id, $user1->id)); cohort_remove_member($cohort1->id, $user4->id); $this->assertTrue(groups_is_member($group1->id, $user4->id)); $this->assertTrue(groups_is_member($group2->id, $user4->id)); }
function remove_cohort_member($username, $cohort_id) { global $CFG, $DB; $username = utf8_decode($username); $username = strtolower($username); $conditions = array('username' => $username); $user = $DB->get_record('user', $conditions); if (!$user) { return 0; } $conditions = array('userid' => $user->id, 'cohortid' => $cohort_id); $member = $DB->get_record('cohort_members', $conditions); if (!$member) { return 0; } cohort_remove_member($cohort_id, $user->id); return 1; }
/** * Post authentication hook. * This method is called from authenticate_user_login() for all enabled auth plugins. * * @param object $user user object, later used for $USER * @param string $username (with system magic quotes) * @param string $password plain text password (with system magic quotes) */ function user_authenticated_hook(&$user, $username, $password) { global $DB, $SESSION; $context = context_system::instance(); $uid = $user->id; // Ignore users from don't_touch list $ignore = explode(",", $this->config->donttouchusers); if (!empty($ignore) and array_search($username, $ignore) !== false) { $SESSION->mcautoenrolled = TRUE; return true; } // Ignore guests if ($uid < 2) { $SESSION->mcautoenrolled = TRUE; return true; } // ********************** Get COHORTS data $clause = array('contextid' => $context->id); if ($this->config->enableunenrol == 1) { $clause['component'] = self::COMPONENT_NAME; } $cohorts = $DB->get_records('cohort', $clause); $cohorts_list = array(); foreach ($cohorts as $cohort) { $cid = $cohort->id; $cname = format_string($cohort->name); $cohorts_list[$cid] = $cname; } // Get advanced user data profile_load_data($user); profile_load_custom_fields($user); $user_profile_data = mcae_prepare_profile_data($user, $this->config->secondrule_fld); // Additional values for email list($email_username, $email_domain) = explode("@", $user_profile_data['email']); // email root domain $email_domain_array = explode('.', $email_domain); if (count($email_domain_array) > 2) { $email_rootdomain = $email_domain_array[count($email_domain_array) - 2] . '.' . $email_domain_array[count($email_domain_array) - 1]; } else { $email_rootdomain = $email_domain; } $user_profile_data['email'] = array('full' => $user_profile_data['email'], 'username' => $email_username, 'domain' => $email_domain, 'rootdomain' => $email_rootdomain); // Delimiter $delimiter = $this->config->delim; $delim = strtr($delimiter, array('CR+LF' => chr(13) . chr(10), 'CR' => chr(13), 'LF' => chr(10))); // Calculate a cohort names for user $replacements_tpl = $this->config->replace_arr; $replacements = array(); if (!empty($replacements_tpl)) { $replacements_pre = explode($delim, $replacements_tpl); foreach ($replacements_pre as $rap) { list($key, $val) = explode("|", $rap); $replacements[$key] = $val; } } // Generate cohorts array $main_rule = $this->config->mainrule_fld; $templates_tpl = array(); $templates = array(); if (!empty($main_rule)) { $templates_tpl = explode($delim, $main_rule); } else { $SESSION->mcautoenrolled = TRUE; return; //Empty mainrule } // Find %split function foreach ($templates_tpl as $item) { if (preg_match('/(?<full>%split\\((?<fld>\\w*)\\|(?<delim>.{1,5})\\))/', $item, $split_params)) { // Split! $splitted = explode($split_params['delim'], $user_profile_data[$split_params['fld']]); foreach ($splitted as $key => $val) { $user_profile_data[$split_params['fld'] . "_{$key}"] = $val; $templates[] = strtr($item, array("{$split_params['full']}" => "{{ {$split_params['fld']}_{$key} }}")); } } else { $templates[] = $item; } } $processed = array(); // Process templates with Mustache foreach ($templates as $cohort) { $cohortname = $this->mustache->render($cohort, $user_profile_data); $cohortname = !empty($replacements) ? strtr($cohortname, $replacements) : $cohortname; if ($cohortname == '') { continue; // We don't want an empty cohort name } $cid = array_search($cohortname, $cohorts_list); if ($cid !== false) { if (!$DB->record_exists('cohort_members', array('cohortid' => $cid, 'userid' => $user->id))) { cohort_add_member($cid, $user->id); } } else { // Cohort not exist so create a new one $newcohort = new stdClass(); $newcohort->name = $cohortname; $newcohort->description = "created " . date("d-m-Y"); $newcohort->contextid = $context->id; if ($this->config->enableunenrol == 1) { $newcohort->component = "auth_mcae"; } $cid = cohort_add_cohort($newcohort); cohort_add_member($cid, $user->id); // Prevent creation new cohorts with same names $cohorts_list[$cid] = $cohortname; } $processed[] = $cid; } $SESSION->mcautoenrolled = TRUE; //Unenrol user if ($this->config->enableunenrol == 1) { //List of cohorts where this user enrolled $sql = "SELECT c.id AS cid FROM {cohort} c JOIN {cohort_members} cm ON cm.cohortid = c.id WHERE c.component = 'auth_mcae' AND cm.userid = {$uid}"; $enrolledcohorts = $DB->get_records_sql($sql); foreach ($enrolledcohorts as $ec) { if (array_search($ec->cid, $processed) === false) { cohort_remove_member($ec->cid, $uid); } } } }
// save custom profile fields data profile_save_data($usernew); // reload from db $usernew = $DB->get_record('user', array('id' => $usernew->id)); //if($rolename == 'subadmin') { //Add member to cohort $cohortDetails = $DB->get_record("cohort", array('idnumber' => $usernew->lang)); //var_dump($cohortDetails->id);exit; cohort_add_member($cohortDetails->id, $usernew->id); //} // if($usernew->lang == COUNTER_MANAGER_ISO) { // cohort_add_member(US_ENGLISH, $usernew->id); // } if ($usernew->lang != $userold->lang) { $cohortRemove = $DB->get_record("cohort", array('idnumber' => $userold->lang)); cohort_remove_member($cohortRemove->id, $usernew->id); } // trigger events if ($usercreated) { events_trigger('user_created', $usernew); } else { events_trigger('user_updated', $usernew); } if ($user->id == $USER->id) { // Override old $USER session variable foreach ((array) $usernew as $variable => $value) { $USER->{$variable} = $value; } // preload custom fields profile_load_custom_fields($USER); if (!empty($USER->newadminuser)) {
/** * Delete cohort members * * @param array $members of arrays with keys userid, cohortid * @since Moodle 2.5 */ public static function delete_cohort_members($members) { global $CFG, $DB; require_once "{$CFG->dirroot}/cohort/lib.php"; // Validate parameters. $params = self::validate_parameters(self::delete_cohort_members_parameters(), array('members' => $members)); $transaction = $DB->start_delegated_transaction(); foreach ($params['members'] as $member) { $cohortid = $member['cohortid']; $userid = $member['userid']; $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST); $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST); // Now security checks. $context = context::instance_by_id($cohort->contextid, MUST_EXIST); if ($context->contextlevel != CONTEXT_COURSECAT and $context->contextlevel != CONTEXT_SYSTEM) { throw new invalid_parameter_exception('Invalid context'); } self::validate_context($context); if (!has_any_capability(array('moodle/cohort:manage', 'moodle/cohort:assign'), $context)) { throw new required_capability_exception($context, 'moodle/cohort:assign', 'nopermissions', ''); } cohort_remove_member($cohort->id, $user->id); } $transaction->allow_commit(); }
public function test_sync_plans_from_cohorts_with_templateduedate_task() { $this->resetAfterTest(true); $this->setAdminUser(); $dg = $this->getDataGenerator(); $lpg = $dg->get_plugin_generator('core_competency'); $user1 = $dg->create_user(); $user2 = $dg->create_user(); $user3 = $dg->create_user(); $user4 = $dg->create_user(); $user5 = $dg->create_user(); $cohort = $dg->create_cohort(); $tpl = $lpg->create_template(array('duedate' => time() + 400)); // Add 2 users to the cohort. cohort_add_member($cohort->id, $user1->id); cohort_add_member($cohort->id, $user2->id); // Creating plans from template cohort. $templatecohort = api::create_template_cohort($tpl->get_id(), $cohort->id); $created = api::create_plans_from_template_cohort($tpl->get_id(), $cohort->id); $this->assertEquals(2, $created); $task = \core\task\manager::get_scheduled_task('\\core\\task\\sync_plans_from_template_cohorts_task'); $this->assertInstanceOf('\\core\\task\\sync_plans_from_template_cohorts_task', $task); // Add two more users to the cohort. cohort_add_member($cohort->id, $user3->id); cohort_add_member($cohort->id, $user4->id); $task->execute(); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); // Test if remove user from cohort will affect plans. cohort_remove_member($cohort->id, $user3->id); cohort_remove_member($cohort->id, $user4->id); $task->execute(); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); // The template is now hidden, and I've added a user with a missing plan. Nothing should happen. $tpl->set_visible(false); $tpl->update(); cohort_add_member($cohort->id, $user5->id); $this->assertFalse(plan::record_exists_select('userid = ? AND templateid = ?', array($user5->id, $tpl->get_id()))); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); $task->execute(); $this->assertFalse(plan::record_exists_select('userid = ? AND templateid = ?', array($user5->id, $tpl->get_id()))); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); // Now I set the template as visible again, the plan is created. $tpl->set_visible(true); $tpl->update(); $task->execute(); $this->assertTrue(plan::record_exists_select('userid = ? AND templateid = ?', array($user5->id, $tpl->get_id()))); $this->assertEquals(5, plan::count_records(array('templateid' => $tpl->get_id()))); // Let's unlink the plan and run the task again, it should not be recreated. $plan = plan::get_record(array('userid' => $user5->id, 'templateid' => $tpl->get_id())); \core_competency\api::unlink_plan_from_template($plan); $this->assertTrue(plan::record_exists_select('userid = ?', array($user5->id))); $this->assertFalse(plan::record_exists_select('userid = ? AND templateid = ?', array($user5->id, $tpl->get_id()))); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); $task->execute(); $this->assertTrue(plan::record_exists_select('userid = ?', array($user5->id))); $this->assertFalse(plan::record_exists_select('userid = ? AND templateid = ?', array($user5->id, $tpl->get_id()))); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); // Adding users to cohort that already exist in plans. cohort_add_member($cohort->id, $user3->id); cohort_add_member($cohort->id, $user4->id); $task->execute(); $this->assertEquals(4, plan::count_records(array('templateid' => $tpl->get_id()))); }
public function test_sync_all_cohort_roles() { $this->setAdminUser(); $params = (object) array('userid' => $this->userassignto->id, 'roleid' => $this->roleid, 'cohortid' => $this->cohort->id); $result = api::create_cohort_role_assignment($params); // Verify roles are assigned when users enter the cohort. $sync = api::sync_all_cohort_roles(); $rolesadded = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid)); $rolesremoved = array(); $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved); $this->assertEquals($sync, $expected); // Verify roles are removed when users leave the cohort. cohort_remove_member($this->cohort->id, $this->userassignover->id); $sync = api::sync_all_cohort_roles(); $rolesadded = array(); $rolesremoved = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid)); $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved); $this->assertEquals($sync, $expected); // Verify roles assigned by any other component are not removed. $usercontext = context_user::instance($this->userassignover->id); role_assign($this->roleid, $this->userassignto->id, $usercontext->id); $sync = api::sync_all_cohort_roles(); $rolesadded = array(); $rolesremoved = array(); $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved); $this->assertEquals($sync, $expected); // Remove manual role assignment. role_unassign($this->roleid, $this->userassignto->id, $usercontext->id); // Add someone to the cohort again... cohort_add_member($this->cohort->id, $this->userassignover->id); $sync = api::sync_all_cohort_roles(); $rolesadded = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid)); $rolesremoved = array(); $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved); $this->assertEquals($sync, $expected); // Verify no fatal errors when a cohort is deleted. cohort_delete_cohort($this->cohort); $sync = api::sync_all_cohort_roles(); $rolesadded = array(); $rolesremoved = array(array('useridassignedto' => $this->userassignto->id, 'useridassignedover' => $this->userassignover->id, 'roleid' => $this->roleid)); $expected = array('rolesadded' => $rolesadded, 'rolesremoved' => $rolesremoved); $this->assertEquals($sync, $expected); }
$cohort->description = get_string('cohort_synchronized_with_group', 'local_ldap', $groupname); //print_r($cohort); $cohortid = cohort_add_cohort($cohort); print "creating cohort " . $group . PHP_EOL; } else { $cohortid = $cohort->id; $ldap_members = $plugin->ldap_get_group_members($groupname); } if ($CFG->debug_ldap_groupes) { pp_print_object("members of LDAP group {$groupname} known to Moodle", $ldap_members); } $cohort_members = $plugin->get_cohort_members($cohortid); if ($CFG->debug_ldap_groupes) { pp_print_object("current members of cohort {$groupname}", $cohort_members); } foreach ($cohort_members as $userid => $user) { if (!isset($ldap_members[$userid])) { cohort_remove_member($cohortid, $userid); print "removing " . $user->username . " from cohort " . $groupname . PHP_EOL; } } foreach ($ldap_members as $userid => $username) { if (!$plugin->cohort_is_member($cohortid, $userid)) { cohort_add_member($cohortid, $userid); print "adding " . $username . " to cohort " . $groupname . PHP_EOL; } } //break; } $difftime = microtime_diff($starttime, microtime()); print "Execution took " . $difftime . " seconds" . PHP_EOL;
public function test_cohort_remove_member() { global $DB; $this->resetAfterTest(); $cohort = $this->getDataGenerator()->create_cohort(); $user = $this->getDataGenerator()->create_user(); cohort_add_member($cohort->id, $user->id); $this->assertTrue($DB->record_exists('cohort_members', array('cohortid' => $cohort->id, 'userid' => $user->id))); cohort_remove_member($cohort->id, $user->id); $this->assertFalse($DB->record_exists('cohort_members', array('cohortid' => $cohort->id, 'userid' => $user->id))); }