/** * 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); }
/** * method to create test userset * @param string $name the name to use to create userset * @return int|bool the userset DB id or false on error */ public function create_userset($name) { $params = array('name' => $name); $us = new userset($params); $us->save(); return !empty($us->id) ? $us->id : false; }
/** * Move incoming usersets to be a subuset of current userset. * @throws moodle_exception * @param array $elements An array of userset information to assign to the track. * @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, $USER; // The userset that will be the new parent set. $curusersetid = required_param('id', PARAM_INT); // Limit incoming usersets to possible-to-move usersets. $possiblesubsets = cluster_get_possible_sub_clusters($curusersetid); $elements = array_intersect_key($elements, $possiblesubsets); unset($possiblesubsets); // We need edit permissions. $perm = 'local/elisprogram:userset_edit'; $userseteditctx = pm_context_set::for_user_with_capability('cluster', $perm, $USER->id); if ($userseteditctx->context_allowed($curusersetid, 'cluster') !== true) { throw new moodle_exception('not_permitted', 'local_elisprogram'); } // Loop through requested elements to move. Check for permissions and do an sanity check on IDs and parent ID, then move. foreach ($elements as $tomoveusersetid => $label) { // Ensure user has edit perm on $tomoveusersetid. if ($userseteditctx->context_allowed($tomoveusersetid, 'cluster')) { $tomove = new userset($tomoveusersetid); $tomove->load(); // The userset we're moving shouldn't be the userset we're moving below, and it shouldn't already be a child // of the new parent. if ($tomove->id !== $curusersetid && $tomove->parent !== $curusersetid) { $tomove->parent = $curusersetid; $tomove->save(); } } } return array('result' => 'success', 'msg' => 'Success'); }
/** * 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 get_records($filter) { global $DB, $USER; $id = $this->required_param('id', PARAM_INT); $sort = $this->optional_param('sort', 'name', PARAM_ALPHA); $dir = $this->optional_param('dir', 'ASC', PARAM_ALPHA); $pagenum = $this->optional_param('page', 0, PARAM_INT); $perpage = $this->optional_param('perpage', 30, PARAM_INT); $filters = array(); // find users who do not have a manual assignment already $filters[] = new join_filter('id', clusterassignment::TABLE, 'userid', new AND_filter(array(new field_filter('clusterid', $id), new field_filter('plugin', 'manual'))), true); // user-defined filter list($extrasql, $params) = $filter->get_sql_filter(); if ($extrasql) { $filters[] = new select_filter($extrasql, $params); } // TODO: Ugly, this needs to be overhauled $upage = new usersetpage(); if (!$upage->_has_capability('local/elisprogram:userset_enrol')) { //perform SQL filtering for the more "conditional" capability //get the context for the "indirect" capability $context = pm_context_set::for_user_with_capability('cluster', 'local/elisprogram:userset_enrol_userset_user', $USER->id); $allowed_clusters = userset::get_allowed_clusters($id); if (empty($allowed_clusters)) { $filters[] = new select_filter('FALSE'); } else { $filters[] = new join_filter('id', clusterassignment::TABLE, 'userid', new in_list_filter('clusterid', $allowed_clusters)); } } $count = user::count($filters); $users = user::find($filters, array($sort => $dir), $pagenum * $perpage, $perpage); return array($users, $count); }
/** * Set up necessary data * * @param int $numfields The number of custom fields used in auto-association */ private function init_required_data($numfields = 1) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elis::file('eliscore/fields/moodleprofile/custom_fields.php'); require_once elis::lib('data/customfield.class.php'); require_once elispm::file('accesslib.php'); require_once elispm::lib('data/userset.class.php'); require_once $CFG->dirroot . '/user/profile/definelib.php'; require_once $CFG->dirroot . '/user/profile/field/checkbox/define.class.php'; // Set up the category only once. $fieldcategory = new field_category(array('name' => 'testcategoryname')); $fieldcategory->save(); // Ste up the target userset only once. $userset = new userset(array('name' => 'testusersetname')); $userset->save(); for ($i = 1; $i <= $numfields; $i++) { // Custom field. $field = new field(array('categoryid' => $fieldcategory->id, 'shortname' => 'testfieldshortname' . $i, 'name' => 'testfieldname' . $i, '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(); // Ensure moodle profile field owner exists. field_owner::ensure_field_owner_exists($field, 'moodle_profile'); $DB->execute("UPDATE {" . field_owner::TABLE . "} SET exclude = ?", array(pm_moodle_profile::sync_to_moodle)); // Field context level assocation. $fieldcontextlevel = new field_contextlevel(array('fieldid' => $field->id, 'contextlevel' => CONTEXT_ELIS_USER)); $fieldcontextlevel->save(); // The associated Moodle user profile field. $profiledefinecheckbox = new profile_define_checkbox(); $data = new stdClass(); $data->datatype = 'checkbox'; $data->categoryid = 99999; $data->shortname = 'testfieldshortname' . $i; $data->name = 'testfieldname' . $i; $profiledefinecheckbox->define_save($data); $mfield = $DB->get_record('user_info_field', array('shortname' => 'testfieldshortname' . $i)); // The "cluster-profile" association. $usersetprofile = new userset_profile(array('clusterid' => $userset->id, 'fieldid' => $mfield->id, 'value' => 1)); $usersetprofile->save(); } }
/** * A get_filter_sql_permissions_elementuser compatible version of userset::get_allowed_clusters * @param int $usersetid The userset whose parents we care about. */ public static function get_allowed_clusters($usersetid) { global $DB; $ids = userset::get_allowed_clusters($usersetid); if (!empty($ids)) { list($idswhere, $idsparams) = $DB->get_in_or_equal($ids); $sql = 'SELECT id as clusterid FROM {' . userset::TABLE . '} WHERE id ' . $idswhere; return $DB->get_records_sql($sql, $idsparams); } else { return array(); } }
/** * Validate that the provided custom field type and value produce the * specified error message on user set update * * @param string $uitype The input control / UI type * @param string $value The value to use for the custom field * @param string $message The expected error message * @param array $otherparams Other parameters to give to the field owner * @dataProvider type_error_provider */ public function test_userset_update_customfield_message($uitype, $value, $message, $otherparams) { global $CFG; require_once $CFG->dirroot . '/local/elisprogram/accesslib.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/userset.class.php'; $this->create_custom_field(CONTEXT_ELIS_USERSET, $uitype, $otherparams); // Create mapping record. $this->create_mapping_record('course', 'testfieldshortname', 'customtestfieldshortname'); $userset = new userset(array('name' => 'testusersetname')); $userset->save(); $data = array('action' => 'update', 'context' => 'cluster', 'name' => 'testusersetname', 'customtestfieldshortname' => $value); $message = '[course.csv line 2] User set with name "testusersetname" could not be updated. ' . $message . "\n"; $this->assert_data_produces_error($data, $message, 'course'); }
/** * Validate that an appropriate error is logged when max field lengths are * exceeded during a userset update action * @param string $field The identifier for the field we are testing * @param int $length The length we are testing at * @param string $customvalue A custom value to use rather than simply repeating a character, * or null if not applicable * @dataProvider usersetupdatefieldprovider */ public function test_usersetupdatelogserrorwhenfieldstoolong($field, $length, $customvalue) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/data/userset.class.php'; $userset = new userset(array('name' => 'testusersetname')); $userset->save(); $data = array('action' => 'update', 'context' => 'cluster', 'name' => 'testusersetname'); if ($customvalue !== null) { $value = $customvalue; } else { $value = str_repeat('a', $length); } $data[$field] = $value; $maxlength = $length - 1; $expectederror = "{$field} value of \"{$value}\" exceeds the maximum field length of {$maxlength}.\n"; $this->assert_data_produces_error($data, $expectederror, 'course'); }
/** * Test the clustertree. */ public function test_clustertree() { global $CFG; if (!file_exists($CFG->dirroot . '/local/elisreports/php_report_base.php')) { $this->markTestSkipped('Test requires local_elisreports code'); } require_once elispm::lib('filtering/clustertree.php'); $testclusterids = array(); for ($i = 0; $i < 5; $i++) { $userset = new userset(); $userset->name = 'test_userset_' . $i; $userset->save(); $testclusterids[] = $userset->id; } $uniqueid = 'test_clustertree'; $alias = 'test_clustertree'; $name = 'test_clustertree'; $label = 'test_clustertree'; $advanced = false; $field = null; $filter = new generalized_filter_clustertree($uniqueid, $alias, $name, $label, $advanced, $field); // Test context call in get_sql_filter. $data = array('clusterids' => array(), 'clrunexpanded_ids' => array(), 'unexpanded_ids' => array()); $sqlfilter = $filter->get_sql_filter($data); $this->assertNotEmpty($sqlfilter); // Test empty get_label. $data = array(); $label = $filter->get_label($data); $expected = 'test_clustertree: N/A<br/>'; $this->assertEquals($expected, $label); // Test get_label with clusterids. $data = array('clusterids' => $testclusterids); $label = $filter->get_label($data); $clusternames = array(); for ($i = 0; $i < 5; $i++) { $clusternames[] = 'test_userset_' . $i; } $expected = $name . ':<br/>' . implode(', ', $clusternames) . '<br/>'; $this->assertEquals($expected, $label); // Test get_label with unexpanded_ids. $data = array('unexpanded_ids' => $testclusterids); $label = $filter->get_label($data); $clusternames = array(); for ($i = 0; $i < 5; $i++) { $clusternames[] = 'test_userset_' . $i . ' (and all children)'; } $expected = $name . ':<br/>' . implode(', ', $clusternames) . '<br/>'; $this->assertEquals($expected, $label); // Create a subuserset for the next two tests. $subuserset = new userset(); $subuserset->name = 'test_subuserset_1'; $subuserset->parent = $testclusterids[0]; $subuserset->save(); $testclusterids[] = $subuserset->id; // Test get_label with recursively unselected clusters with 'clusterids' param. // Tests that when clrunexpanded_ids contains an ID of a userset with child usersets, the child usersets also // do not show up. $data = array('clusterids' => $testclusterids, 'clrunexpanded_ids' => array($testclusterids[0])); $label = $filter->get_label($data); $clusternames = array(); for ($i = 1; $i <= 4; $i++) { $clusternames[] = 'test_userset_' . $i; } $expected = $name . ':<br/>' . implode(', ', $clusternames) . '<br/>'; $this->assertEquals($expected, $label); // Test get_label with recursively unselected clusters with 'unexpanded_ids'. // Tests that when a subusetset is listed in 'unexpanded_ids', but it's parent is listed in clrunexpanded_ids, // the subuserset does not show up. $unexpandedids = $testclusterids; unset($unexpandedids[0]); $data = array('unexpanded_ids' => $unexpandedids, 'clrunexpanded_ids' => array($testclusterids[0])); $label = $filter->get_label($data); $clusternames = array(); for ($i = 1; $i <= 4; $i++) { $clusternames[] = 'test_userset_' . $i . ' (and all children)'; } $expected = $name . ':<br/>' . implode(', ', $clusternames) . '<br/>'; $this->assertEquals($expected, $label); }
/** * 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))); }
/** * Update a cluster (user set) * @todo: consider factoring this some more once other actions exist * * @param object $record One record of import data * @param string $filename The import file name, used for logging * @return boolean true on success, otherwise false */ function cluster_delete($record, $filename) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/data/userset.class.php'; if (isset($record->name)) { $id = $DB->get_field(userset::TABLE, 'id', array('name' => $record->name)); if (!$id) { $identifier = $this->get_field_mapping('name'); $this->fslogger->log_failure("{$identifier} value of \"{$record->name}\" does not refer to a valid user set.", 0, $filename, $this->linenumber, $record, "cluster"); return false; } } if (isset($record->recursive)) { if (!$this->validate_fixed_list($record, 'recursive', static::$yes_no_field_options)) { $identifier = $this->get_field_mapping('recursive'); $this->fslogger->log_failure("{$identifier} value of \"{$record->recursive}\" is not one of the available options (0, 1).", 0, $filename, $this->linenumber, $record, "cluster"); return false; } else { $record->recursive = (string) $record->recursive == 'yes' || (string) $record->recursive == '1' ? '1' : '0'; } } $data = new userset($id); //handle recursive delete, if necessary if (!empty($record->recursive)) { $data->deletesubs = true; } $data->delete(); //log success $success_message = "User set with name \"{$record->name}\" successfully deleted."; $this->fslogger->log_success($success_message, 0, $filename, $this->linenumber); return true; }
/** * Test failure conditions. * @dataProvider dataprovider_failure * @expectedException moodle_exception * @param array $us The incoming userset data. */ public function test_failure(array $us) { global $DB; $this->give_permissions(array('local/elisprogram:userset_create')); // Setup duplicate userset. $dupus = new userset(array('name' => 'DupUsersetName')); $dupus->save(); $response = local_datahub_elis_userset_create::userset_create($us); }
/** * 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); }
/** * 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); }
/** * Test creating a new userset entity with a default role assignment defined. */ public function test_createusersetwithdefaultroleassignment() { global $USER, $DB; list($rcid, $reid) = $this->create_roles('userset'); // Setup the editor role to be the default role for the userset context. elis::$config->local_elisprogram->default_cluster_role_id = $reid; $sysctx = context_system::instance(); // Assign the test user the creator role. role_assign($rcid, $USER->id, $sysctx->id); // Create a new userset entity. $data = array('idnumber' => 'program100', 'name' => 'program100', 'description' => 'program100'); $obj = new userset($data); $obj->save(); // Initialize a new userset management page and invoke the code that handles default role assignments. $page = new usersetpage(); $page->after_cm_entity_add($obj); $usersetctx = \local_elisprogram\context\userset::instance($obj->id); $params = array('roleid' => $reid, 'userid' => $USER->id, 'contextid' => $usersetctx->id); $this->assertTrue($DB->record_exists('role_assignments', $params)); }
/** * Validate that mappings are applied during the user set delete action */ public function test_mapping_applied_during_userset_delete() { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/accesslib.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/userset.class.php'; $this->init_mapping(); context_helper::reset_caches(); $parentuserset = new userset(array('name' => 'testparentusersetname')); $parentuserset->save(); \local_elisprogram\context\userset::instance($parentuserset->id); $userset = new userset(array('parent' => $parentuserset->id, 'name' => 'testusersetname')); $userset->save(); \local_elisprogram\context\userset::instance($userset->id); // Run the course delete action. $record = new stdClass(); $record->customaction = 'delete'; $record->customcontext = 'cluster'; $record->customname = 'testparentusersetname'; $record->customrecursive = '1'; $this->run_pmentity_import((array) $record); // Validation. $this->assertEquals(0, $DB->count_records(userset::TABLE)); }
/** * Prints a deletion confirmation form. * @param $obj record whose deletion is being confirmed */ function print_delete_form($obj) { global $DB; if ($count = userset::count(new field_filter('parent', $obj->id))) { // cluster has sub-clusters, so ask the user if they want to // promote or delete the sub-clusters $a = new stdClass(); $a->name = $obj; $a->subclusters = $count; $context = \local_elisprogram\context\userset::instance($obj->id); $like = $DB->sql_like('path', '?'); $a->descendants = $DB->count_records_select('context', $DB->sql_like('path', '?'), array("{$context->path}/%")) - $a->subclusters; print_string($a->descendants ? 'confirm_delete_with_usersubsets_and_descendants' : 'confirm_delete_with_usersubsets', 'local_elisprogram', array('name' => $obj->name, 'subclusters' => $count)); $target = $this->get_new_page(array('action' => 'delete', 'confirm' => '1')); $form = new usersetdeleteform($target->url, array('obj' => $obj, 'a' => $a)); $form->display(); } else { parent::print_delete_form($obj); } }
/** * Performs userset delete * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error creating the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function userset_delete(array $data) { global $USER, $DB; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::userset_delete_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); $data = (object) $data; // Validate if (empty($data->name) || !($usid = $DB->get_field(userset::TABLE, 'id', array('name' => $data->name)))) { throw new data_object_exception('ws_userset_delete_fail_invalid_name', 'local_datahub', '', $data); } // Capability checking. require_capability('local/elisprogram:userset_delete', \local_elisprogram\context\userset::instance($usid)); $userset = new userset($usid); if (!empty($data->recursive)) { $userset->deletesubs = true; } $userset->delete(); // Verify deletion & respond. if (!$DB->record_exists(userset::TABLE, array('name' => $data->name))) { return array('messagecode' => get_string('ws_userset_delete_success_code', 'local_datahub', empty($data->recursive) ? '' : get_string('ws_userset_delete_recursive', 'local_datahub')), 'message' => get_string('ws_userset_delete_success_msg', 'local_datahub', empty($data->recursive) ? '' : get_string('ws_userset_delete_subsets', 'local_datahub'))); } else { throw new data_object_exception('ws_userset_delete_fail', 'local_datahub'); } }
/** * Create an ELIS userset. * @param field $field A custom field to set when creating the userset. * @return userset The created userset. */ public function create_userset(field $field) { $data = new stdClass(); $data->name = 'Test User Set 123'; $data->parent = '0'; $data->profile_field1 = '0'; $data->profile_field2 = '0'; $fieldvar = 'field_' . $field->shortname; $data->{$fieldvar} = 'test field data'; $usrset = new userset(); $usrset->set_from_data($data); $usrset->save(); return $usrset; }
/** * Performs useret update * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error creating the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function userset_update(array $data) { global $USER, $DB; if (static::require_elis_dependencies() !== true) { throw new moodle_exception('ws_function_requires_elis', 'local_datahub'); } // Parameter validation. $params = self::validate_parameters(self::userset_update_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); $data = (object) $data; $record = new stdClass(); $record = $data; // need all custom fields, etc. // Validate if (empty($data->name) || !($usersetid = $DB->get_field(userset::TABLE, 'id', array('name' => $data->name)))) { throw new data_object_exception('ws_userset_update_fail_invalid_name', 'local_datahub', '', $data); } // Capability checking. require_capability('local/elisprogram:userset_edit', \local_elisprogram\context\userset::instance($usersetid)); $usid = 0; if (!empty($data->parent) && strtolower($data->parent) != 'top' && !($usid = $DB->get_field(userset::TABLE, 'id', array('name' => $data->parent)))) { throw new data_object_exception('ws_userset_update_fail_invalid_parent', 'local_datahub', '', $data); } if ($usid || strtolower($data->parent) == 'top') { $record->parent = $usid; } $userset = new userset($usersetid); $userset->set_from_data($record); $userset->save(); // Respond. if (!empty($userset->id)) { $usrec = (array) $DB->get_record(userset::TABLE, array('id' => $userset->id)); $usobj = $userset->to_array(); // convert multi-valued custom field arrays to comma-separated listing $fields = self::get_userset_custom_fields(); foreach ($fields as $field) { // Generate name using custom field prefix. $fullfieldname = data_object_with_custom_fields::CUSTOM_FIELD_PREFIX . $field->shortname; if ($field->multivalued && isset($usobj[$fullfieldname]) && is_array($usobj[$fullfieldname])) { $usobj[$fullfieldname] = implode(',', $usobj[$fullfieldname]); } } return array('messagecode' => get_string('ws_userset_update_success_code', 'local_datahub'), 'message' => get_string('ws_userset_update_success_msg', 'local_datahub'), 'record' => array_merge($usrec, $usobj)); } else { throw new data_object_exception('ws_userset_update_fail', 'local_datahub'); } }
/** * Initialize a new user description object */ protected function inituserset() { $data = array('name' => 'Test User Set 1', 'display' => 'We\'re just testing user set creation!'); $newuserset = new userset($data); $newuserset->save(); $this->tusersetid = $newuserset->id; }
/** * 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)); }
/** * Test failure conditions. * @dataProvider dataprovider_failure * @expectedException moodle_exception * @param array $us The incoming userset data. */ public function test_failure(array $us) { global $DB; $this->give_permissions(array('local/elisprogram:userset_delete')); // Setup userset to delete. $userset = new userset(array('name' => 'testuserset')); $userset->save(); $response = local_datahub_elis_userset_delete::userset_delete($us); }
/** * Validate duplicate user set creation */ public function test_duplicate_userset_creation() { if (!self::$haspm) { $this->markTestSkipped('local_elisprogram is required for Userset testing'); } $this->resetAfterTest(true); $this->setup_test_data_xml(); $repo = repository_factory::factory('elisfiles'); $userset = new userset(array('name' => 'testuserset')); $userset->save(); $uuid = $repo->get_userset_store($userset->id); $uuidduplicate = $repo->get_userset_store($userset->id); $this->assertEquals($uuidduplicate, $uuid); }
/** * Test that a child User Set context instance is updated when that User Set is promoted to the top level due to parent * User Set deletion */ public function test_childusersetcontext_onpromotion_duringparentdeletion() { $newobj = $this->inituserset(); $newobj->save(); $ctx1 = \local_elisprogram\context\userset::instance($newobj->id); $data = array('name' => 'Test Sub User Set 1A', 'display' => 'We\'re just testing user set creation with child user sets!', 'parent' => $newobj->id); $subuserset = new userset($data); $subuserset->save(); // Delete the parent user set, promoting the sub-user-set. $newobj->delete(); $context = \local_elisprogram\context\userset::instance($subuserset->id); // Validate that the curent state of the context record is valid. $this->assertGreaterThan(0, $context->id); $this->assertEquals(CONTEXT_ELIS_USERSET, $context->contextlevel); $this->assertEquals($subuserset->id, $context->instanceid); // Create the context path to valid that this in the returned context object. $path = '/' . SYSCONTEXTID . '/' . $context->id; $this->assertEquals($path, $context->path); $this->assertEquals(substr_count($path, '/'), $context->depth); }
/** * 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(); } }
/** * 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); }
/** * Validate the various behaviours of the parent field during userset creation * * @param string $inputvalue The parent value specified * @param int $dbvalue The expected parent value stored in the database * @param int $depth The expected userset depth * @dataProvider parent_provider */ public function test_create_elis_userset_respects_parent_field($inputvalue, $dbvalue, $depth) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/userset.class.php'); // Set up a parent userset. $parent = new userset(array('name' => 'testparentusersetname')); $parent->save(); // Run the import. $data = array('parent' => $inputvalue); $this->run_core_userset_import($data, true); // Validation. $data['name'] = 'testusersetname'; $data['parent'] = $dbvalue; $data['depth'] = $depth; $this->assertTrue($DB->record_exists(userset::TABLE, $data)); }
public function test_deleteparentpromotechildren() { // Load great-grandfather, grandfather, parent, child usersets. ids 5,6,7,8, respectively. $dataset = $this->createCsvDataSet(array(userset::TABLE => elispm::file('tests/fixtures/userset_grandfathers.csv'), 'context' => elispm::file('tests/fixtures/userset_context.csv'))); $this->loadDataSet($dataset); // Delete grandfather userset. $grandfather = new userset(6); $grandfather->load(); $grandfather->deletesubs = 0; $grandfather->delete(); $parent = new userset(7); $parent->load(); $child = new userset(8); $child->load(); $this->assertEquals('0', $parent->parent); $this->assertEquals('1', $parent->depth); $this->assertEquals('7', $child->parent); $this->assertEquals('2', $child->depth); }