/** * Test custom userset theme assignment. */ public function test_customusersetthemectx() { $this->load_csv_data(); // ELIS user with the associated moodle user. $user = new user(103); $muser = $user->get_moodleuser(); // Userset with a custom theme. $userset = new userset(1); $userset->field__elis_userset_theme = 'formal_white'; $userset->field__elis_userset_themepriority = 1; $userset->save(); // Assign the user to the user set. $usersetassign = new clusterassignment(); $usersetassign->userid = $user->id; $usersetassign->clusterid = $userset->id; $usersetassign->save(); // Pretend to be that user. $this->setUser($muser->id); // Initialize page. $page = new moodle_page(); $page->initialise_theme_and_output(); // Assert we have our theme. $this->assertEquals('formal_white', $page->theme->name); $this->setUser(null); }
/** * Test validation of entries with the same userid and clusterid but different plugin */ public function test_clusterassignment_validationallowsmultipleplugins() { $this->load_csv_data(); $clusterassignment = new clusterassignment(array('clusterid' => 1, 'userid' => 1, 'plugin' => 'moodleprofile')); $clusterassignment->save(); $this->assertEquals(1, 1); }
/** * Determine whether the current can manage the association between a given user and userset. * @param int $userid The ID of a user. * @param int $clustid The ID of a userset. * @return bool Success status. */ public static function can_manage_assoc($userid, $usersetid) { global $USER; $allowedusersets = array(); // TODO: Ugly, this needs to be overhauled. $upage = new usersetpage(); if (!usersetpage::can_enrol_into_cluster($usersetid)) { // The users who satisfty this condition are a superset of those who can manage associations. return false; } else { if ($upage->_has_capability('local/elisprogram:userset_enrol', $usersetid)) { // Current user has the direct capability. return true; } } $allowedusersets = userset::get_allowed_clusters($usersetid); $filter = array(new field_filter('userid', $userid)); // Query to get users associated to at least one enabling userset. if (empty($allowedusersets)) { $filter[] = new select_filter('FALSE'); } else { $filter[] = new in_list_filter('clusterid', $allowedusersets); } // User just needs to be in one of the possible usersets. if (clusterassignment::exists($filter)) { return true; } return false; }
function cluster_manual_deassign_user($clusterid, $userid) { global $CURMAN, $CFG; if (!is_numeric($clusterid) || !is_numeric($userid) || $clusterid <= 0 || $userid <= 0) { return false; } clusterassignment::delete_records(array(new field_filter('userid', $userid), new field_filter('clusterid', $clusterid), new field_filter('plugin', 'manual'))); return true; }
/** * Test successful userset enrolment deletion. */ public function test_success() { global $DB, $USER; $this->give_permissions(array('local/elisprogram:userset_enrol')); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); // Create test userset. $datagen = new elis_program_datagenerator($DB); $userset = $datagen->create_userset(array('name' => 'TestUsersetEnrolmentDelete')); $userid = $DB->get_field(user::TABLE, 'id', array('username' => 'assigninguser')); // Create the userset enrolment record to delete. $clstass = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $userid, 'plugin' => 'manual')); $clstass->save(); $data = array('userset_name' => $userset->name, 'user_username' => 'assigninguser', 'user_email' => '*****@*****.**'); $response = local_datahub_elis_userset_enrolment_delete::userset_enrolment_delete($data); $this->assertNotEmpty($response); $this->assertInternalType('array', $response); $this->assertArrayHasKey('messagecode', $response); $this->assertArrayHasKey('message', $response); $this->assertEquals(get_string('ws_userset_enrolment_delete_success_code', 'local_datahub'), $response['messagecode']); $this->assertEquals(get_string('ws_userset_enrolment_delete_success_msg', 'local_datahub'), $response['message']); $this->assertFalse($DB->record_exists(clusterassignment::TABLE, array('clusterid' => $userset->id, 'userid' => $userid, 'plugin' => 'manual'))); }
/** * Tests contexts in userset data object. * * Covers: * local/elisprogram/lib/data/userset.class.php:334 * local/elisprogram/lib/data/userset.class.php:453 * local/elisprogram/lib/data/userset.class.php:561 * local/elisprogram/lib/data/userset.class.php:595 * local/elisprogram/lib/data/userset.class.php:616 * local/elisprogram/lib/data/userset.class.php:721 * local/elisprogram/lib/data/userset.class.php:755 * local/elisprogram/lib/data/userset.class.php:847 * local/elisprogram/lib/data/userset.class.php:901 */ public function test_usersetcontexts() { global $USER, $DB; require_once elispm::file('plugins/usetclassify/usersetclassification.class.php'); require_once elispm::file('plugins/usetclassify/lib.php'); $this->setup_users(); $this->setup_usersets(); // TEST local/elisprogram/lib/data/userset.class.php:334. $res = userset::get_allowed_clusters(1); // TEST local/elisprogram/lib/data/userset.class.php:453. $ussfilter = new usersubset_filter('id', new field_filter('id', 1)); $res = $ussfilter->get_sql(); // TEST // local/elisprogram/lib/data/userset.class.php:561 // local/elisprogram/lib/data/userset.class.php:595 // local/elisprogram/lib/data/userset.class.php:616 // local/elisprogram/lib/data/userset.class.php:721 // local/elisprogram/lib/data/userset.class.php:755. $field = new field(array('shortname' => USERSET_CLASSIFICATION_FIELD)); $field->load(); $userset = $this->create_userset($field); // Get a role to assign. $rolesctx = $DB->get_records('role_context_levels', array('contextlevel' => CONTEXT_ELIS_USERSET)); foreach ($rolesctx as $i => $rolectx) { $roleid = $rolectx->roleid; } // Add userset_view capability to our role. $usersetcontext = \local_elisprogram\context\userset::instance($userset->id); $rc = new stdClass(); $rc->contextid = $usersetcontext->id; $rc->roleid = $roleid; $rc->capability = 'local/elisprogram:userset_view'; $rc->permission = 1; $rc->timemodified = time(); $rc->modifierid = 0; $DB->insert_record('role_capabilities', $rc); $rc = new stdClass(); $rc->contextid = $usersetcontext->id; $rc->roleid = $roleid; $rc->capability = 'local/elisprogram:userset_enrol_userset_user'; $rc->permission = 1; $rc->timemodified = time(); $rc->modifierid = 0; $DB->insert_record('role_capabilities', $rc); // Assign role. $user = new user(103); $muser = $user->get_moodleuser(); $raid = role_assign($roleid, $muser->id, $usersetcontext->id); $this->setUser(100); // Assign other user to userset. $clst = new clusterassignment(); $clst->clusterid = $userset->id; $clst->userid = 104; $clst->plugin = 'manual'; $clst->save(); // Get cluster listing. $capability = 'local/elisprogram:userset_view'; $contexts = get_contexts_by_capability_for_user('cluster', $capability, 100); $extrafilters = array('contexts' => $contexts, 'classification' => 'test field data'); $res = cluster_get_listing('name', 'ASC', 0, 0, '', '', $extrafilters, 104); $res = cluster_count_records('', '', $extrafilters); // TEST local/elisprogram/lib/data/userset.class.php:847. cluster_get_non_child_clusters(1); // TEST local/elisprogram/lib/data/userset.class.php:901. cluster_get_possible_sub_clusters(1); $this->setUser(null); }
/** * Perform the necessary actions required to "delete" a cluster from the system. * * @param none * @return bool True on success, False otherwise. */ function delete() { require_once elis::lib('data/data_filter.class.php'); if ($this->deletesimple) { //core delete method, not including recursion (entered once for each //individual userset being delete) //clean make the delete cascade into association records $filter = new field_filter('clusterid', $this->id); clustercurriculum::delete_records($filter, $this->_db); clustertrack::delete_records($filter, $this->_db); clusterassignment::delete_records($filter, $this->_db); //cluster plugin cleanup $plugins = get_plugin_list(self::ENROL_PLUGIN_TYPE); foreach ($plugins as $plugin => $plugindir) { require_once elis::plugin_file(self::ENROL_PLUGIN_TYPE . '_' . $plugin, 'lib.php'); call_user_func('cluster_' . $plugin . '_delete_for_cluster', $this->id); } //delete the userset record parent::delete(); //delete this cluster's context //get a new context instance, $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET); $userset_context = $contextclass::instance($this->id); $userset_context->delete(); events_trigger('cluster_deleted', $this->id); return; } $result = true; $children = array(); $delete_ids = array(); $promote_ids = array(); /// Figure out all the sub-clusters $cluster_context_instance = \local_elisprogram\context\userset::instance($this->id); $instance_id = $cluster_context_instance->id; $instance_path = $cluster_context_instance->path; $children = userset::find(new join_filter('id', 'context', 'instanceid', new AND_filter(array(new field_filter('path', "{$instance_path}/%", field_filter::LIKE), new field_filter('contextlevel', CONTEXT_ELIS_USERSET)))), array('depth' => 'ASC'), 0, 0, $this->_db); $children = $children->to_array(); if ($this->deletesubs) { $todelete = $children; $todelete[] = $this; // The specified cluster always gets deleted } else { $todelete = array($this); } foreach ($todelete as $userset) { //delete without recursion $userset->deletesimple = true; $userset->delete(); } if (!$this->deletesubs && !empty($children)) { foreach ($children as $child) { $lower_depth = $child->depth - 1; if (userset::exists(new field_filter('id', $child->parent))) { /// A parent found so lets lower the depth $child->depth = 0; } else { /// Parent not found so this cluster will be top-level $child->parent = 0; $child->depth = 1; } $child->save(); $sql = "UPDATE {context}\n SET depth=0, path=NULL\n WHERE contextlevel=? AND instanceid=?"; $this->_db->execute($sql, array(CONTEXT_ELIS_USERSET, $child->id)); } \local_eliscore\context\helper::build_all_paths(false, array(CONTEXT_ELIS_USERSET)); // Re-build the context table for all sub-clusters } return $result; }
/** * Test available table shows only programs the user has permission to enrol into based on * local/elisprogram:program_enrol_userset_user permission on a parent userset. * * @dataProvider dataprovider_available_permissions_program_enrol_userset_user * @param array $usersetidsforperm An array of userset IDs to assign the local/elisprogram:program_enrol_userset_user on. * @param array $clusterassignments An array of arrays of parameters to construct clusterassignments with. * @param array $clustercurriculums An array of arrays of parameters to construct clustercurriculums with. * @param int $tableuserid The id of the user to manage associations for. * @param array $expectedresults The expected page of results. * @param int $expectedtotal The expected number of total results. */ public function test_available_permissions_program_enrol_userset_user($usersetidsforperm, $clusterassignments, $clustercurriculums, $tableuserid, $expectedresults, $expectedtotal) { global $USER, $DB, $CFG; $userbackup = $USER; // Import usersets. $dataset = $this->createCsvDataSet(array(userset::TABLE => elispm::file('tests/fixtures/deepsight_userset.csv'))); $this->loadDataSet($dataset); // Set up permissions. $USER = $this->setup_permissions_test(); // Initialize userset contexts. for ($i = 1; $i <= 5; $i++) { $ctx = \local_elisprogram\context\userset::instance($i); } accesslib_clear_all_caches(true); // Set up capabilities. $capability = 'local/elisprogram:program_enrol_userset_user'; foreach ($usersetidsforperm as $usersetid) { $this->give_permission_for_context($USER->id, $capability, \local_elisprogram\context\userset::instance($usersetid)); } // Create clusterassignments. foreach ($clusterassignments as $clusterassignment) { $clusterassignment = new clusterassignment($clusterassignment); $clusterassignment->save(); } // Create clustercurriculums. foreach ($clustercurriculums as $clustercurriculum) { $clustercurriculum = new clustercurriculum($clustercurriculum); $clustercurriculum->save(); } // Construct test table. $table = new deepsight_datatable_userprogram_available_mock($DB, 'test', 'http://localhost', 'testuniqid'); $table->set_userid($tableuserid); // Perform test. $actualresults = $table->get_search_results(array(), array(), 0, 20); // Verify. $this->assert_search_results($expectedresults, $expectedtotal, $actualresults); }
/** * Set up data that is needed for testing * * @param boolean $setcustomfielddata Specify whether the userset's custom fields should be set * @param boolean $assignuser Specify whether the user should be directly assigned to the user set * @param boolean $setautoassociatefields Specity whether we should set up fields that allow userset autoassociation */ private function set_up_required_data($setcustomfielddata = true, $assignuser = true, $setautoassociatefields = false) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::file('accesslib.php'); require_once elispm::file('enrol/userset/moodleprofile/userset_profile.class.php'); require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/usermoodle.class.php'); require_once elispm::lib('data/userset.class.php'); $fieldcategoryid = $DB->get_field(field_category::TABLE, 'id', array('name' => 'Associated Group')); $this->assertNotEquals(false, $fieldcategoryid); $fieldcategory = new field_category($fieldcategoryid); $fieldcategory->load(); // Set up the test user. $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); $user->synchronize_moodle_user(); // We need a system-level role assignment. $roleid = create_role('systemrole', 'systemrole', 'systemrole'); $userid = $DB->get_field('user', 'id', array('username' => 'testuserusername')); $context = context_system::instance(); role_assign($roleid, $userid, $context->id); // Set up the userset. $userset = new userset(); $usersetdata = array('name' => 'testusersetname'); if ($setcustomfielddata) { $usersetdata['field_userset_group'] = 1; $usersetdata['field_userset_groupings'] = 1; } $userset->set_from_data((object) $usersetdata); $userset->save(); if ($setautoassociatefields) { // Set up a file we can use to auto-associate users to a userset. $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'autoassociate', 'name' => 'autoassociate', 'datatype' => 'bool')); $field->save(); // Ensure manual field owner exists for syncing. field_owner::ensure_field_owner_exists($field, 'manual'); $ownerid = $DB->get_field(field_owner::TABLE, 'id', array('fieldid' => $field->id, 'plugin' => 'manual')); $owner = new field_owner($ownerid); $owner->param_control = 'checkbox'; $owner->save(); field_owner::ensure_field_owner_exists($field, 'moodle_profile'); $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle)); $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER)); $fieldcontextlevel->save(); // The associated Moodle user profile field. require_once $CFG->dirroot . '/user/profile/definelib.php'; require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php'; $profiledefinecheckbox = new profile_define_checkbox(); $data = new stdClass(); $data->datatype = 'checkbox'; $data->categoryid = 99999; $data->shortname = 'autoassociate'; $data->name = 'autoassociate'; $profiledefinecheckbox->define_save($data); $mfield = $DB->get_record('user_info_field', array('shortname' => 'autoassociate')); // The "cluster-profile" association. $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => 1)); $usersetprofile->save(); } if ($assignuser) { // Assign the user to the user set. $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $user->id, 'plugin' => 'manual')); $clusterassignment->save(); } }
/** * Updates resulting enrolments that are auto-created after users are * assigned to user sets (specifically user-track assignments, user-program * assignments, and class enrolments in a track's default class) * * Note: This is essentially equivalent to cluster_assigned_handler but * runs a fixed number of queries for scalability reasons * * @param int $userid A specific PM user id to filter on for * consideration, or all users if zero * @param int $clusterid A specific cluster / user set id to filter * on for consideration, or all users if zero */ static function update_enrolments($userid = 0, $clusterid = 0) { global $DB; require_once elispm::lib('data/usermoodle.class.php'); // error_log("/local/elisprogram/lib/data/clusterassignment.class.php::update_enrolments({$userid}, {$clusterid})"); // ELIS-7582 @set_time_limit(0); // convert provided parameters to SQL conditions $extraconditions = array(); $extraparams = array(); if (!empty($userid)) { $users = array($userid); $extraconditions[] = 'u.id = ?'; $extraparams[] = $userid; } else { $users = clusterassignment::find(new field_filter('clusterid', $clusterid)); } if (!empty($clusterid)) { $extraconditions[] = 'clu.clusterid = ?'; $extraparams[] = $clusterid; } $extrawhere = ''; if (!empty($extraconditions)) { $extrawhere = ' AND ' . implode(' AND ', $extraconditions); } //use the current time as the time created and modified for curriculum //assignments $timenow = time(); //assign to curricula based on user-cluster and cluster-curriculum //associations $sql = "INSERT INTO {" . curriculumstudent::TABLE . "}\n (userid, curriculumid, timecreated, timemodified)\n SELECT DISTINCT u.id, clucur.curriculumid, {$timenow}, {$timenow}\n FROM {" . clusterassignment::TABLE . "} clu\n JOIN {" . user::TABLE . "} u ON u.id = clu.userid\n JOIN {" . clustercurriculum::TABLE . "} clucur\n ON clucur.clusterid = clu.clusterid\n LEFT JOIN {" . curriculumstudent::TABLE . "} ca\n ON ca.userid = u.id\n AND ca.curriculumid = clucur.curriculumid\n WHERE ca.curriculumid IS NULL\n AND clucur.autoenrol = 1\n {$extrawhere}"; $DB->execute($sql, $extraparams); //assign to curricula based on user-cluster and cluster-track //associations (assigning a user to a track auto-assigns them to //the track's curriculum, track assignment happens below) $sql = "INSERT INTO {" . curriculumstudent::TABLE . "}\n (userid, curriculumid, timecreated, timemodified)\n SELECT DISTINCT u.id, trk.curid, {$timenow}, {$timenow}\n FROM {" . clusterassignment::TABLE . "} clu\n JOIN {" . user::TABLE . "} u\n ON u.id = clu.userid\n JOIN {" . clustertrack::TABLE . "} clutrk\n ON clutrk.clusterid = clu.clusterid\n JOIN {" . track::TABLE . "} trk\n ON clutrk.trackid = trk.id\n LEFT JOIN {" . curriculumstudent::TABLE . "} ca\n ON ca.userid = u.id\n AND ca.curriculumid = trk.curid\n WHERE ca.curriculumid IS NULL\n AND clutrk.autoenrol = 1\n {$extrawhere}"; $DB->execute($sql, $extraparams); //this represents the tracks that users will be assigned to //based on user-cluster and cluster-track associations //(actual assignment happens below) $exists = "EXISTS (SELECT DISTINCT u.id, clutrk.trackid\n FROM {" . clusterassignment::TABLE . "} clu\n JOIN {" . user::TABLE . "} u\n ON u.id = clu.userid\n JOIN {" . clustertrack::TABLE . "} clutrk\n ON clutrk.clusterid = clu.clusterid\n LEFT JOIN {" . usertrack::TABLE . "} ta\n ON ta.userid = u.id\n AND ta.trackid = clutrk.trackid\n WHERE ta.trackid IS NULL\n AND clutrk.autoenrol = 1\n AND outerta.trackid = clutrk.trackid\n\t {$extrawhere})"; /** * Get autoenrollable classes in the track. Classes are autoenrollable * if: * - the autoenrol flag is set * - it is the only class in that course slot for the track */ // group the classes from the same course together // only select the ones that are the only class for that course in // the given track, and if the autoenrol flag is set $sql = "SELECT outerta.classid, outerta.courseid, trk.curid\n FROM {" . trackassignment::TABLE . "} outerta\n JOIN {" . track::TABLE . "} trk ON trk.id = outerta.trackid\n WHERE {$exists}\n GROUP BY courseid\n HAVING COUNT(*) = 1 AND MAX(autoenrol) = 1"; //go through and assign user(s) to the autoenollable classes $classes = $DB->get_records_sql($sql, $extraparams); if (!empty($classes)) { foreach ($users as $user) { $userid = is_object($user) ? $user->userid : $user; foreach ($classes as $class) { // check pre-requisites $curcrs = new curriculumcourse(array('courseid' => $class->courseid, 'curriculumid' => $class->curid)); if (!$curcrs->prerequisites_satisfied($userid)) { continue; } $now = time(); // enrol user in each autoenrolable class $stu_record = new object(); $stu_record->userid = $userid; $stu_record->classid = $class->classid; $stu_record->enrolmenttime = $now; $enrolment = new student($stu_record); // catch enrolment limits try { $enrolment->save(); } catch (pmclass_enrolment_limit_validation_exception $e) { // autoenrol into waitlist $wait_record = new object(); $wait_record->userid = $userid; $wait_record->classid = $class->classid; $wait_record->enrolmenttime = $now; $wait_record->timecreated = $now; $wait_record->position = 0; $wait_list = new waitlist($wait_record); $wait_list->save(); } catch (Exception $e) { $param = array('message' => $e->getMessage()); if (in_cron()) { mtrace(get_string('record_not_created_reason', 'local_elisprogram', $param)); } else { echo cm_error(get_string('record_not_created_reason', 'local_elisprogram', $param)); } } } } } //assign to tracks based on user-cluster and cluster-track //associations $sql = "INSERT INTO {" . usertrack::TABLE . "}\n (userid, trackid)\n SELECT DISTINCT u.id, clutrk.trackid\n FROM {" . clusterassignment::TABLE . "} clu\n JOIN {" . user::TABLE . "} u\n ON u.id = clu.userid\n JOIN {" . clustertrack::TABLE . "} clutrk\n ON clutrk.clusterid = clu.clusterid\n LEFT JOIN {" . usertrack::TABLE . "} ta\n ON ta.userid = u.id\n AND ta.trackid = clutrk.trackid\n WHERE ta.trackid IS NULL\n AND clutrk.autoenrol = 1\n {$extrawhere}"; $DB->execute($sql, $extraparams); //update site-level "cluster groups" //TODO: make sure all "cluster groups" scenarios are handled here, and look at //performance in more detal if (!empty($userid) && file_exists(elispm::file('plugins/usetgroups/lib.php'))) { require_once elispm::file('plugins/usetgroups/lib.php'); //need the Moodle user id $mdluserid = $DB->get_field(usermoodle::TABLE, 'muserid', array('cuserid' => $userid)); if ($mdluserid) { //find all assignments for this user $assignments = $DB->get_recordset(clusterassignment::TABLE, array('userid' => $userid)); foreach ($assignments as $assignment) { //update site-level group assignments userset_groups_update_site_course($assignment->clusterid, true, $mdluserid); } } //update course-level group assignment userset_groups_update_groups(array('mdlusr.cuserid' => $userid)); } }
public function delete() { global $CFG; $result = false; $muser = cm_get_moodleuserid($this->id); if (empty($muser) || !is_primary_admin($muser)) { $level = context_level_base::get_custom_context_level('user', 'block_curr_admin'); $result = attendance::delete_for_user($this->id); $result = $result && curriculumstudent::delete_for_user($this->id); $result = $result && instructor::delete_for_user($this->id); $result = $result && student::delete_for_user($this->id); $result = $result && student_grade::delete_for_user($this->id); $result = $result && usertrack::delete_for_user($this->id); $result = $result && usercluster::delete_for_user($this->id); $result = $result && clusterassignment::delete_for_user($this->id); $result = $result && waitlist::delete_for_user($this->id); $result = $result && delete_context($level, $this->id); // Delete Moodle user. if ($muser = get_record('user', 'idnumber', $this->idnumber, 'mnethostid', $CFG->mnet_localhost_id, 'deleted', 0)) { $result = $result && delete_user($muser); } $result = $result && parent::delete(); } return $result; }
/** * Test available table shows only usersets the user has permission to enrol into based on * local/elisprogram:userset_enrol_userset_user permission on a parent userset. * * @dataProvider dataprovider_available_permissions_userset_enrol_userset_user * @param array $usersetidsforperm An array of userset IDs to assign the local/elisprogram:userset_enrol_userset_user on. * @param array $clusterassignments An array of arrays of parameters to construct clusterassignments with. * @param int $tableuserid The id of the user to manage associations for. * @param array $expectedresults The expected page of results. * @param int $expectedtotal The expected number of total results. */ public function test_available_permissions_userset_enrol_userset_user($usersetidsforperm, $clusterassignments, $tableuserid, $expectedresults, $expectedtotal) { global $USER, $DB, $CFG; $userbackup = $USER; // Set up permissions. $USER = $this->setup_permissions_test(); // Set up userset contexts. for ($i = 1; $i <= 6; $i++) { $ctx = \local_elisprogram\context\userset::instance($i); } accesslib_clear_all_caches(true); // Assign capabilities. $capability = 'local/elisprogram:userset_enrol_userset_user'; foreach ($usersetidsforperm as $usersetid) { $this->give_permission_for_context($USER->id, $capability, \local_elisprogram\context\userset::instance($usersetid)); } // Create clusterassignments. foreach ($clusterassignments as $clusterassignment) { $clusterassignment = new clusterassignment($clusterassignment); $clusterassignment->save(); } // Construct test table. $table = new deepsight_datatable_useruserset_available_mock($DB, 'test', 'http://localhost', 'testuniqid'); $table->set_userid($tableuserid); // Perform test. $actualresults = $table->get_search_results(array(), array(), 0, 20); // Verify. $this->assert_search_results($expectedresults, $expectedtotal, $actualresults); }
/** * Test the basic functionality of the methods for fetching users as a * recordset when applying userset permissions and an appropriate SQL filter */ public function test_usermanagementgetsusersrecordsetrespectsfilters() { global $USER, $DB; require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('lib.php'); // Make sure we don't hit corner-cases with permissions. set_config('siteguest', ''); set_config('siteadmins', ''); // Prevent accesslib caching. accesslib_clear_all_caches(true); // Data setup. $this->load_csv_data(); $this->set_up_users(); // Assign a second user to the user set. $secondclusteruser = new user(array('idnumber' => 'secondclusteruser', 'username' => 'secondclusteruser', 'firstname' => 'Secondcluster', 'lastname' => 'User', 'email' => '*****@*****.**', 'country' => 'CA')); $secondclusteruser->save(); $clusterassignment = new clusterassignment(array('clusterid' => 1, 'userid' => $secondclusteruser->id)); $clusterassignment->save(); // The context set our user set administrator has access to. $contextset = pm_context_set::for_user_with_capability('cluster', 'local/elisprogram:user_edit', $USER->id); // Add a filter to filter down to only our first test user. $extrasql = array('username = :testusername', array('testusername' => 'clusteruser')); // Validate record. $users = usermanagement_get_users_recordset('name', 'ASC', 0, 0, $extrasql, $contextset); $this->assertTrue($users->valid()); $user = $users->current(); $this->assertEquals('clusteruser', $user->idnumber); $this->assertNull($users->next()); }
/** * Test available table obeys track_enrol_userset_users permission. * * Test available table shows only users that are in clusters where: * - the assigner is also in the cluster * - the assigner has the local/elisprogram:track_enrol_userset_user permission * - the current track is associated with the cluster. * * @dataProvider dataprovider_available_permissions_track_enrol_userset_user * @param array $usersetidsforperm An array of userset IDs to assign the local/elisprogram:track_enrol_userset_user on. * @param array $clusterassignments An array of arrays of parameters to construct clusterassignments with. * @param array $clustertracks An array of arrays of parameters to construct clustertracks with. * @param int $tabletrackid The id of the track to manage associations for. * @param array $expectedresults The expected page of results. * @param int $expectedtotal The expected number of total results. */ public function test_available_permissions_track_enrol_userset_user($usersetidsforperm, $clusterassignments, $clustertracks, $tabletrackid, $expectedresults, $expectedtotal) { global $USER, $DB, $CFG; $userbackup = $USER; // Import usersets. $dataset = $this->createCsvDataSet(array(userset::TABLE => elispm::file('tests/fixtures/deepsight_userset.csv'))); $this->loadDataSet($dataset); // Set up permissions. $USER = $this->setup_permissions_test(); $capability = 'local/elisprogram:track_enrol_userset_user'; foreach ($usersetidsforperm as $usersetid) { $this->give_permission_for_context($USER->id, $capability, \local_elisprogram\context\userset::instance($usersetid)); } // Create clusterassignments. foreach ($clusterassignments as $clusterassignment) { $clusterassignment = new clusterassignment($clusterassignment); $clusterassignment->save(); } // Create clustertracks. foreach ($clustertracks as $clustertrack) { $clustertrack = new clustertrack($clustertrack); $clustertrack->save(); } // Construct test table. $table = new deepsight_datatable_trackuser_available_mock($DB, 'test', 'http://localhost', 'testuniqid'); $table->set_trackid($tabletrackid); // Perform test. $actualresults = $table->get_search_results(array(), array(), 0, 20); // Verify. $this->assert_search_results($expectedresults, $expectedtotal, $actualresults); // Restore user. $USER = $userbackup; }
/** * Test user with view and edit permissions on a userset. * This test only rund when local/elisprogram/setuplib.php exists. */ public function test_manual_field_is_view_or_editable_with_view_edit_permissions_on_userset() { global $DB, $CFG; // Skip test if local/elisprogram doesn't exist. if (!file_exists($CFG->dirroot . '/local/elisprogram/lib/setup.php')) { $this->markTestSkipped('Requires local/elisprogram to be installed.'); } $this->resetAfterTest(true); $this->load_libraries_for_additional_tests(); // Load CSV data. $this->load_csv_data(); // Setup place holders for capabilities. $editcap = 'local/elisprogram:user_edit'; $viewcap = 'local/elisprogram:user_view'; // Retrieve the PM user id to be assigned to a userset $param = array('id' => 103); $pmuserinusersetid = $DB->get_field('local_elisprogram_usr', 'id', $param); // Retrieve the user who will be assigned a role in the user set. $param = array('id' => 101); $userroleinuserset = $DB->get_record('user', $param); // Set user with role as logged in user $this->setUser($userroleinuserset); // Get the userset context. $usersetcontext = \local_elisprogram\context\userset::instance(1); // System context. $syscontext = context_system::instance(); // Create role and assign capabilites to it. $roleid = create_role('testrole', 'testrole', 'testrole'); assign_capability($editcap, CAP_ALLOW, $roleid, $syscontext->id); assign_capability($viewcap, CAP_ALLOW, $roleid, $syscontext->id); // Assin role to user in the userset context. role_assign($roleid, $userroleinuserset->id, $usersetcontext->id); // Add user to cluster/userset. $usersetassign = new clusterassignment(array('clusterid' => 1, 'userid' => $pmuserinusersetid, 'plugin' => 'manual')); $usersetassign->save(); $field = new field(array('id' => 101)); $field->load(); $result = manual_field_is_view_or_editable($field, $syscontext, $editcap, $viewcap, 'user', $pmuserinusersetid); $this->assertEquals(MANUAL_FIELD_EDITABLE, $result); }
function cluster_profile_update_handler($userdata) { global $DB, $CFG; if (!empty($userdata->deleted)) { return true; } // make sure a CM user exists pm_moodle_user_to_pm($userdata); if (!isset($userdata->id)) { return true; } $cuid = pm_get_crlmuserid($userdata->id); if (empty($cuid)) { // not a curriculum user -- (guest?) return true; } // the cluster assignments that the plugin wants to exist // we figure this out by counting the number of profile fields that the // user has that matches the values for the cluster, and comparing that // with the number of profile values set for the cluster $new_assignments = "(SELECT DISTINCT ? as userid, cp.clusterid\n FROM {" . userset_profile::TABLE . "} cp\n WHERE (SELECT COUNT(*)\n FROM {" . userset_profile::TABLE . "} cp1\n JOIN (SELECT i.fieldid, i.data FROM {user_info_data} i\n WHERE i.userid = ?\n UNION\n SELECT uif.id as fieldid, uif.defaultdata as data\n FROM {user_info_field} uif\n LEFT JOIN {user_info_data} i ON i.userid = ? AND uif.id = i.fieldid\n WHERE i.id IS NULL\n ) inf ON inf.fieldid = cp1.fieldid AND inf.data = cp1.value\n WHERE cp.clusterid=cp1.clusterid)\n = (SELECT COUNT(*) FROM {" . userset_profile::TABLE . "} cp1 WHERE cp.clusterid = cp1.clusterid))"; $new_assignments_params = array($cuid, $userdata->id, $userdata->id); // delete existing assignments that should not be there any more if ($CFG->dbfamily == 'postgres') { $delete = "DELETE FROM {" . clusterassignment::TABLE . "}\n WHERE id IN (\n SELECT id FROM {" . clusterassignment::TABLE . "} a\n LEFT OUTER JOIN {$new_assignments} b ON a.clusterid = b.clusterid AND a.userid = b.userid\n WHERE a.userid = ? AND b.clusterid IS NULL\n ) AND plugin='moodleprofile'"; } else { $delete = "DELETE a FROM {" . clusterassignment::TABLE . "} a\n LEFT OUTER JOIN {$new_assignments} b ON a.clusterid = b.clusterid AND a.userid = b.userid\n WHERE a.userid = ? AND b.clusterid IS NULL AND a.plugin='moodleprofile'"; } $DB->execute($delete, array_merge($new_assignments_params, array($cuid))); // add new assignments $insert = "INSERT INTO {" . clusterassignment::TABLE . "}\n (clusterid, userid, plugin)\n SELECT a.clusterid, a.userid, 'moodleprofile'\n FROM {$new_assignments} a\n LEFT OUTER JOIN {" . clusterassignment::TABLE . "} b ON a.clusterid = b.clusterid AND a.userid = b.userid AND b.plugin='moodleprofile'\n WHERE a.userid = ? AND b.clusterid IS NULL"; $DB->execute($insert, array_merge($new_assignments_params, array($cuid))); clusterassignment::update_enrolments($cuid); return true; }
/** * Validate that user unenrolment from user sets only happens for the manual * userset ("cluster") plugin */ public function test_elis_user_userset_unenrolment_respects_userset_plugin() { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/userset.class.php'); $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); $userset = new userset(array('name' => 'testusersetname')); $userset->save(); $clusterassignment = new clusterassignment(array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'manual', 'autoenrol' => 0)); $clusterassignment->save(); $clusterassignment = new clusterassignment(array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'another', 'autoenrol' => 0)); $clusterassignment->save(); // Validate setup. $this->assertTrue($DB->record_exists(clusterassignment::TABLE, array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'manual', 'autoenrol' => 0))); $this->assertTrue($DB->record_exists(clusterassignment::TABLE, array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'another', 'autoenrol' => 0))); // Run the userset enrolment delete action. $record = new stdClass(); $record->context = 'cluster_testusersetname'; $record->user_username = '******'; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->cluster_enrolment_delete($record, 'bogus', 'testusersetname'); // Validation. $this->assertEquals(1, $DB->count_records(clusterassignment::TABLE)); $this->assertTrue($DB->record_exists(clusterassignment::TABLE, array('userid' => $user->id, 'clusterid' => $userset->id, 'plugin' => 'another', 'autoenrol' => 0))); }
/** * Performs userset_enrolment deletion * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error deleting the association. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function userset_enrolment_delete(array $data) { global $DB, $USER; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::userset_enrolment_delete_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); $data = (object) $data; // Parse Userset if (empty($data->userset_name) || !($clstid = $DB->get_field(userset::TABLE, 'id', array('name' => $data->userset_name)))) { throw new data_object_exception('ws_userset_enrolment_delete_fail_invalid_userset', 'local_datahub', '', $data); } if (empty($data->plugin)) { $data->plugin = 'manual'; } // Capability checking. require_capability('local/elisprogram:userset_enrol', \local_elisprogram\context\userset::instance($clstid)); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $userparams = array(); $userid = $importplugin->get_userid_from_record($data, '', $userparams); if ($userid == false) { $a = new stdClass(); if (empty($userparams)) { $a->userparams = '{empty}'; } else { $a->userparams = ''; foreach ($userparams as $userfield => $uservalue) { $subfield = strpos($userfield, '_'); $userfield = substr($userfield, $subfield === false ? 0 : $subfield + 1); if (!empty($a->userparams)) { $a->userparams .= ', '; } $a->userparams .= "{$userfield}: '{$uservalue}'"; } } throw new data_object_exception('ws_userset_enrolment_delete_fail_invalid_user', 'local_datahub', '', $a); } $id = $DB->get_field(clusterassignment::TABLE, 'id', array('clusterid' => $clstid, 'userid' => $userid, 'plugin' => $data->plugin)); // Respond. if (!empty($id) && ($clstass = new clusterassignment($id))) { $clstass->delete(); return array('messagecode' => get_string('ws_userset_enrolment_delete_success_code', 'local_datahub'), 'message' => get_string('ws_userset_enrolment_delete_success_msg', 'local_datahub')); } else { throw new data_object_exception('ws_userset_enrolment_delete_fail', 'local_datahub'); } }
public function delete() { global $CFG; $muser = $this->get_moodleuser(); if (empty($muser) || !is_primary_admin($muser->id)) { // delete associated data require_once elis::lib('data/data_filter.class.php'); $filter = new field_filter('userid', $this->id); curriculumstudent::delete_records($filter, $this->_db); student::delete_records($filter, $this->_db); student_grade::delete_records($filter, $this->_db); waitlist::delete_records($filter, $this->_db); instructor::delete_records($filter, $this->_db); usertrack::delete_records($filter, $this->_db); clusterassignment::delete_records($filter, $this->_db); //delete association to Moodle user, if applicable require_once elispm::lib('data/usermoodle.class.php'); $filter = new field_filter('cuserid', $this->id); usermoodle::delete_records($filter, $this->_db); // Delete Moodle user. if (!empty($muser)) { delete_user($muser); } parent::delete(); $context = \local_elisprogram\context\user::instance($this->id); $context->delete(); } }
/** * Validate that the listing respects the local/elisprogram:track_enrol_userset_user * capability as long as the appropriate userset and track are associated to * one another and the target user is in the userset */ public function test_availableusersrespectsindirectusersetpermissions() { global $DB, $USER; $this->load_csv_data(); set_config('siteguest', ''); set_config('siteadmins', ''); accesslib_clear_all_caches_for_unit_testing(); // Create a test user to be in the userset. $usersetmember = new user(array('idnumber' => 'usersetmember', 'username' => 'usersetmember', 'firstname' => 'usersetmember', 'lastname' => 'usersetmember', 'email' => '*****@*****.**', 'country' => 'CA')); $usersetmember->save(); // Our test userset. $userset = new userset(array('name' => 'userset')); $userset->save(); // Assign the test user to the test userset. $clusterassignment = new clusterassignment(array('userid' => $usersetmember->id, 'clusterid' => $userset->id)); $clusterassignment->save(); // Assign the userset to our track. $clustertrack = new clustertrack(array('clusterid' => $userset->id, 'trackid' => 1)); $clustertrack->save(); // Set up a db record for the active user for permissions reasons. // (i.e. so they are not treated as an admin). $activeuser = new user(array('idnumber' => 'activeuser', 'username' => 'activeuser', 'firstname' => 'activeuser', 'lastname' => 'activeuser', 'email' => '*****@*****.**', 'country' => 'CA')); $activeuser->save(); // Set up our test role. $roleid = create_role('testrole', 'testrole', 'testrole'); $syscontext = context_system::instance(); assign_capability('local/elisprogram:track_enrol_userset_user', CAP_ALLOW, $roleid, $syscontext->id); // Perform the role necessary assignment. $moodleuser = $DB->get_record('user', array('username' => 'activeuser')); // Make sure all the contexts are created, so that we can find the children. $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET); $instance = $contextclass::instance($userset->id); role_assign($roleid, $moodleuser->id, $instance->id); // Assume the role of the user with the role assignment. $USER = $moodleuser; $usersrecset = usertrack::get_available_users(1); $users = array(); foreach ($usersrecset as $key => $user) { $users[$key] = $user; } unset($usersrecset); $this->assertEquals(1, count($users)); // Validate user. $this->assertArrayHasKey($usersetmember->id, $users); $user = $users[$usersetmember->id]; $this->assertEquals($usersetmember->username, 'usersetmember'); // Validate count. $count = usertrack::count_available_users(1); $this->assertEquals(1, $count); }
/** * Unassign the usersets from the user. * * @param array $elements An array containing information on usersets to unassign from the user. * @param bool $bulkaction Whether this is a bulk-action or not. * @return array An array to format as JSON and return to the Javascript. */ protected function _respond_to_js(array $elements, $bulkaction) { global $DB; $userid = required_param('id', PARAM_INT); // Permissions. $upage = new userpage(); if ($upage->_has_capability('local/elisprogram:user_view', $userid) !== true) { return array('result' => 'fail', 'msg' => get_string('not_permitted', 'local_elisprogram')); } foreach ($elements as $usersetid => $label) { if ($this->can_unassign($userid, $usersetid) === true) { $assignrec = $DB->get_record(clusterassignment::TABLE, array('userid' => $userid, 'clusterid' => $usersetid)); if (!empty($assignrec) && $assignrec->plugin === 'manual') { $usertrack = new clusterassignment($assignrec); $usertrack->delete(); } } } return array('result' => 'success', 'msg' => 'Success'); }
/** * Delete a cluster (user set) enrolment * * @param object $record One record of import data * @param string $filename The import file name, used for logging * @param string $name The name of the cluster / user set * * @return boolean true on success, otherwise false */ function cluster_enrolment_delete($record, $filename, $name) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/userset.class.php'); if (!($clusterid = $DB->get_field(userset::TABLE, 'id', array('name' => $name)))) { $this->fslogger->log_failure("instance value of \"{$name}\" does not refer to a valid instance of a user set context.", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } $userid = $this->get_userid_from_record($record, $filename); //string to describe the user $user_descriptor = $this->get_user_descriptor($record, false, 'user_'); if (!$DB->record_exists(clusterassignment::TABLE, array('clusterid' => $clusterid, 'userid' => $userid))) { $this->fslogger->log_failure("User with {$user_descriptor} is not enrolled in user set \"{$name}\".", 0, $filename, $this->linenumber, $record, "enrolment"); return false; } if (!$this->validate_cluster_enrolment_data('delete', $record, $filename)) { return false; } //obtain the cluster / userset id $clusterid = $DB->get_field(userset::TABLE, 'id', array('name' => $name)); //delete the association $clusterassignmentid = $DB->get_field(clusterassignment::TABLE, 'id', array('userid' => $userid, 'clusterid' => $clusterid, 'plugin' => 'manual')); $clusterassignment = new clusterassignment($clusterassignmentid); $clusterassignment->delete(); //log success $success_message = "User with {$user_descriptor} successfully unenrolled from user set \"{$name}\"."; $this->fslogger->log_success($success_message, 0, $filename, $this->linenumber); return true; }
/** * Validate that counting the number of role assignments on a particular * cluster for a particular role respects special userset permissions */ public function test_clusterrolepagecountroleusersrespectsusersetpermissions() { global $CFG, $USER, $DB; require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/userset.class.php'); accesslib_clear_all_caches(true); // Create a user record so that Moodle and PM ids don't match by fluke. set_config('auto_assign_user_idnumber', 0, 'local_elisprogram'); elis::$config = new elis_config(); create_user_record('bogususer', 'Bogususer!0'); // Create our test userset. $userset = new userset(array('name' => 'testuserset')); $userset->save(); // The user who is assigned to the user set. $assigneduser = new user(array('idnumber' => 'assigned', 'username' => 'assigned', 'firstname' => 'assigned', 'lastname' => 'assigned', 'email' => '*****@*****.**', 'country' => 'CA')); $assigneduser->save(); // Userset assignment. $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $assigneduser->id)); $clusterassignment->save(); // User who is potentially assigning the userset member a new role within the userset. $assigninguser = new user(array('idnumber' => 'assigning', 'username' => 'assigning', 'firstname' => 'assigning', 'lastname' => 'assigning', 'email' => '*****@*****.**', 'country' => 'CA')); $assigninguser->save(); // Need the system context for role assignments. $systemcontext = context_system::instance(); // Set up the role that allows a user to assign roles but only to userset members. $permissionsroleid = create_role('permissionsrole', 'permissionsrole', 'permissionsrole'); // Enable the appropriate capabilities. assign_capability('moodle/role:assign', CAP_ALLOW, $permissionsroleid, $systemcontext->id); assign_capability('local/elisprogram:userset_role_assign_userset_users', CAP_ALLOW, $permissionsroleid, $systemcontext->id); // Perform the role assignment. $moodleuserid = $DB->get_field('user', 'id', array('username' => 'assigning')); role_assign($permissionsroleid, $moodleuserid, $systemcontext->id); // Imitate the user assigned the role which allows for further role assignments only on userset members. $USER = $DB->get_record('user', array('id' => $moodleuserid)); // Test role for potential assignment to userset members. $roleid = create_role('targetrole', 'targetrole', 'targetrole'); // Assign the both users to the userset role. $contextclass = \local_eliscore\context\helper::get_class_for_level(CONTEXT_ELIS_USERSET); $usersetcontext = $contextclass::instance($userset->id); role_assign($roleid, $moodleuserid, $usersetcontext->id); $moodleuserid = $DB->get_field('user', 'id', array('username' => 'assigned')); role_assign($roleid, $moodleuserid, $usersetcontext->id); // Obtain the count of assigned users. $page = new cluster_rolepage(array('id' => $userset->id)); $count = $page->count_role_users($roleid, $usersetcontext); // List should only contain the userset member. $this->assertEquals(1, $count); }
/** * Returns an array of cluster ids that are associated to the supplied class through tracks and * the current user has access to enrol users into * * @param int $clsid The class whose association ids we care about * @return int array The array of accessible cluster ids */ public static function get_allowed_clusters($clsid) { global $USER; $context = pm_context_set::for_user_with_capability('cluster', 'local/elisprogram:assign_userset_user_class_instructor', $USER->id); $allowed_clusters = array(); // TODO: Ugly, this needs to be overhauled $cpage = new pmclasspage(); if ($cpage->_has_capability('local/elisprogram:assign_userset_user_class_instructor', $clsid)) { require_once elispm::lib('data/clusterassignment.class.php'); $cmuserid = pm_get_crlmuserid($USER->id); $userclusters = clusterassignment::find(new field_filter('userid', $cmuserid)); foreach ($userclusters as $usercluster) { $allowed_clusters[] = $usercluster->clusterid; } } //we first need to go through tracks to get to clusters $track_listing = new trackassignment(array('classid' => $clsid)); $tracks = $track_listing->get_assigned_tracks(); //iterate over the track ides, which are the keys of the array if (!empty($tracks)) { foreach (array_keys($tracks) as $track) { //get the clusters and check the context against them $clusters = clustertrack::get_clusters($track); $allowed_track_clusters = $context->get_allowed_instances($clusters, 'cluster', 'clusterid'); //append all clusters that are allowed by the available clusters contexts foreach ($allowed_track_clusters as $allowed_track_cluster) { $allowed_clusters[] = $allowed_track_cluster; } } } return $allowed_clusters; }
function _user_allowed($id) { global $DB; if (isset($this->contexts['cluster']) && clusterassignment::exists(array(new field_filter('userid', $id), new in_list_filter('clusterid', $this->contexts['cluster'])))) { return true; } if (isset($this->contexts['cluster'])) { $filter = $this->get_filter('clusterid', 'cluster'); return clusterassignment::count(array(new field_filter('userid', $id), $filter)); } return false; }
/** * Enrol the test user in the provided context * * @param string $contextlevel The string descriptor of the context level * @param string $role The shortname of the import record's role column */ private function create_enrolment($contextlevel, $role) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; switch ($contextlevel) { case 'curriculum': // Program enrolment. require_once elispm::lib('data/curriculumstudent.class.php'); $data = array('curriculumid' => 1, 'userid' => 1); $curriculumstudent = new curriculumstudent($data); $curriculumstudent->save(); break; case 'track': // Track enrolment. require_once elispm::lib('data/usertrack.class.php'); $data = array('trackid' => 1, 'userid' => 1); $usertrack = new usertrack($data); $usertrack->save(); break; case 'cluster': // User set enrolment. require_once elispm::lib('data/clusterassignment.class.php'); $data = array('clusterid' => 1, 'userid' => 1); $clusterassignment = new clusterassignment($data); $clusterassignment->save(); break; case 'class': if ($role == 'instructor') { // Class instance instructor enrolment. require_once elispm::lib('data/instructor.class.php'); $data = array('classid' => 1, 'userid' => 1); $instructor = new instructor($data); $instructor->save(); } else { // Class instance student enrolment. require_once elispm::lib('data/student.class.php'); $data = array('classid' => 1, 'userid' => 1); $student = new student($data); $student->save(); } break; case 'user': // Moodle user role assignment. $roleid = $DB->get_field('role', 'id', array('shortname' => $role)); $userid = $DB->get_field('user', 'id', array('idnumber' => 'testuseridnumber')); $context = context_user::instance($userid); role_assign($roleid, $userid, $context->id); break; default: break; } }
/** * Validate that mappings are applied during the user set enrolment delete action */ public function test_mapping_applied_during_userset_enrolment_delete() { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/data/clusterassignment.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/userset.class.php'; $this->init_mapping(); $userid = $this->create_test_user(); $userset = new userset(array('name' => 'testusersetname')); $userset->save(); $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $userid, 'plugin' => 'manual')); $clusterassignment->save(); // Run the user set enrolment delete action. $record = new stdClass(); $record->customaction = 'delete'; $record->customcontext = 'cluster_testusersetname'; $record->customuser_username = '******'; $record->customuser_email = '*****@*****.**'; $record->customuser_idnumber = 'testuseridnumber'; $this->run_enrolment_import((array) $record); // Validation. $this->assertEquals(0, $DB->count_records(clusterassignment::TABLE)); }
/** * Perform the necessary actions required to "delete" a cluster from the system. * * @uses CURMAN * @uses CFG * @param none * @return bool True on success, False otherwise. */ function delete($deletesubs = 0) { global $CURMAN, $CFG; require_once CURMAN_DIRLOCATION . '/cluster/profile/lib.php'; $result = true; $delete_ids = array(); $promote_ids = array(); $cluster_context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin'); if ($deletesubs > 0) { /// Figure out all the sub-cluster ids and whether to delete or promote them $LIKE = $CURMAN->db->sql_compare(); $cluster_context_instance = get_context_instance($cluster_context_level, $this->id); $instance_id = $cluster_context_instance->id; $instance_path = $cluster_context_instance->path; $sql = "SELECT instanceid FROM {$CFG->prefix}context\n WHERE path {$LIKE} '{$instance_path}/%' ORDER BY instanceid DESC"; $clusters = get_records_sql($sql); foreach ($clusters as $cluster) { if ($deletesubs == 1) { // This sub-cluster will be deleted $delete_ids[] = $cluster->instanceid; } else { // This sub-cluster will be promoted $promote_ids[] = $cluster->instanceid; } } } $delete_ids[] = $this->id; // The specified cluster always gets deleted foreach ($delete_ids as $delete_id) { // Cascade to regular datarecords $result = $result && clustercurriculum::delete_for_cluster($delete_id); // in clustercurriculum $result = $result && clustertrack::delete_for_cluster($delete_id); // in clustercurriculum $result = $result && clusterassignment::delete_for_cluster($delete_id); $result = $result && usercluster::delete_for_cluster($delete_id); $result = $result && delete_context($cluster_context_level, $delete_id); // Cascade to all plugins $plugins = $this->get_plugins(); foreach ($plugins as $plugin) { require_once CURMAN_DIRLOCATION . '/cluster/' . $plugin . '/lib.php'; $result = $result && call_user_func('cluster_' . $plugin . '_delete_for_cluster', $delete_id); } $result = $result && datarecord::data_delete_record($delete_id); // this record } if (count($promote_ids) > 0) { foreach ($promote_ids as $promote_id) { $cluster_data = get_record(CLSTTABLE, 'id', $promote_id); $lower_depth = $cluster_data->depth - 1; $select = "id='{$cluster_data->parent}'"; $parent_cnt = $CURMAN->db->count_records_select(CLSTTABLE, $select); $newclusterdata = new stdClass(); $newclusterdata->id = $promote_id; if ($parent_cnt < 1) { /// Parent not found so this cluster will be top-level $newclusterdata->parent = 0; $newclusterdata->depth = 1; } else { /// A child cluster found so lets lower the depth $newclusterdata->depth = $lower_depth; } $result = update_record(CLSTTABLE, $newclusterdata); $cluster_context_level = context_level_base::get_custom_context_level('cluster', 'block_curr_admin'); $sql = "UPDATE {$CFG->prefix}context\n SET depth=0, path=NULL\n WHERE contextlevel='{$cluster_context_level}' AND instanceid='{$promote_id}'"; $feedback = ""; execute_sql($sql, $feedback); } build_context_path(); // Re-build the context table for all sub-clusters } return $result; }
/** * Validate that deleting a userset deletes all appropriate associations */ public function test_delete_elis_userset_deletes_associations() { global $CFG, $DB; // Entities. require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/userset.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/curriculum.class.php'); require_once elispm::lib('data/track.class.php'); require_once elis::lib('data/customfield.class.php'); // Associations. require_once elispm::lib('data/clusterassignment.class.php'); require_once elispm::lib('data/clustercurriculum.class.php'); require_once elispm::lib('data/clustertrack.class.php'); require_once elispm::file('enrol/userset/moodleprofile/userset_profile.class.php'); // For context level access. require_once elispm::file('accesslib.php'); $origfieldcount = $DB->count_records(field::TABLE); // Set up user set. $userset = new userset(array('name' => 'testusersetname')); $userset->save(); // Set up other entities and associations. // Cluster enrolment. $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); $clusterassignment = new clusterassignment(array('clusterid' => $userset->id, 'userid' => $user->id)); $clusterassignment->save(); // Cluster-curriculum assignment. $curriculum = new curriculum(array('idnumber' => 'testcurriculumidnumber')); $curriculum->save(); $clustercurriculum = new clustercurriculum(array('clusterid' => $userset->id, 'curriculumid' => $curriculum->id)); $clustercurriculum->save(); // Cluster-track assignment. $track = new track(array('curid' => $curriculum->id, 'idnumber' => 'testtrackidnumber')); $track->save(); $clustertrack = new clustertrack(array('clusterid' => $userset->id, 'trackid' => $track->id)); $clustertrack->save(); // Custom field. $field = new field(array('name' => 'testfieldname', 'categoryid' => 9999)); $field->save(); $context = \local_elisprogram\context\userset::instance($userset->id); $data = new field_data_int(array('contextid' => $context->id, 'fieldid' => $field->id, 'data' => 1)); $data->save(); // Cluster profile criteria. $clusterprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $field->id, 'value' => 0)); $clusterprofile->save(); // Validate setup. $this->assertEquals(1, $DB->count_records(userset::TABLE)); $this->assertEquals(1, $DB->count_records(user::TABLE)); $this->assertEquals(1, $DB->count_records(clusterassignment::TABLE)); $this->assertEquals(1, $DB->count_records(curriculum::TABLE)); $this->assertEquals(1, $DB->count_records(clustercurriculum::TABLE)); $this->assertEquals(1, $DB->count_records(track::TABLE)); $this->assertEquals(1, $DB->count_records(clustertrack::TABLE)); $this->assertEquals(1 + $origfieldcount, $DB->count_records(field::TABLE)); $this->assertEquals(1, $DB->count_records(field_data_int::TABLE)); $this->assertEquals(1, $DB->count_records(userset_profile::TABLE)); // Run the import. $data = array('action' => 'delete'); $this->run_core_userset_import($data, true); // Validation. $this->assertEquals(0, $DB->count_records(userset::TABLE)); $this->assertEquals(1, $DB->count_records(user::TABLE)); $this->assertEquals(0, $DB->count_records(clusterassignment::TABLE)); $this->assertEquals(1, $DB->count_records(curriculum::TABLE)); $this->assertEquals(0, $DB->count_records(clustercurriculum::TABLE)); $this->assertEquals(1, $DB->count_records(track::TABLE)); $this->assertEquals(0, $DB->count_records(clustertrack::TABLE)); $this->assertEquals(1 + $origfieldcount, $DB->count_records(field::TABLE)); $this->assertEquals(0, $DB->count_records(field_data_int::TABLE)); $this->assertEquals(0, $DB->count_records(userset_profile::TABLE)); }
/** * Unassign the user from the userset. * * @param array $elements An array of elements to perform the action on. * @param bool $bulkaction Whether this is a bulk-action or not. * @return array An array to format as JSON and return to the Javascript. */ protected function _respond_to_js(array $elements, $bulkaction) { global $DB; $usersetid = required_param('id', PARAM_INT); $userset = new userset($usersetid); // Permissions. if (usersetpage::can_enrol_into_cluster($userset->id) !== true) { return array('result' => 'fail', 'msg' => get_string('not_permitted', 'local_elisprogram')); } $unassignnotpermitted = false; foreach ($elements as $userid => $label) { if ($this->can_unassign($usersetid, $userid)) { $assignrec = $DB->get_record(clusterassignment::TABLE, array('userid' => $userid, 'clusterid' => $usersetid)); if (!empty($assignrec) && $assignrec->plugin === 'manual') { $curstu = new clusterassignment($assignrec); $curstu->delete(); } } else { $unassignnotpermitted = true; } } if ($unassignnotpermitted) { return array('result' => 'fail', 'msg' => get_string('not_permitted', 'local_elisprogram')); } else { return array('result' => 'success', 'msg' => 'Success'); } }