/** * Load initial data from CSVs. */ protected function load_csv_data() { $dataset = $this->createCsvDataSet(array('user' => elispm::file('tests/fixtures/mdluser.csv'), 'user_info_field' => elispm::file('tests/fixtures/user_info_field.csv'), 'user_info_data' => elispm::file('tests/fixtures/user_info_data.csv'), user::TABLE => elispm::file('tests/fixtures/pmuser.csv'), usermoodle::TABLE => elispm::file('tests/fixtures/usermoodle.csv'), field::TABLE => elispm::file('tests/fixtures/user_field.csv'), field_owner::TABLE => elispm::file('tests/fixtures/user_field_owner.csv'))); $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset); $dataset->addSubStrReplacement('\\n', "\n"); $this->loadDataSet($dataset); // Load field data next (we need the user context ID and context level). $usercontext = \local_elisprogram\context\user::instance(103); $dataset = $this->createCsvDataSet(array(field_contextlevel::TABLE => elispm::file('tests/fixtures/user_field_contextlevel.csv'), field_category_contextlevel::TABLE => elispm::file('tests/fixtures/user_field_category_contextlevel.csv'), field_data_int::TABLE => elispm::file('tests/fixtures/user_field_data_int.csv'), field_data_char::TABLE => elispm::file('tests/fixtures/user_field_data_char.csv'), field_data_text::TABLE => elispm::file('tests/fixtures/user_field_data_text.csv'))); $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset); $dataset->addFullReplacement('##USERCTXID##', $usercontext->id); $dataset->addFullReplacement('##USERCTXLVL##', CONTEXT_ELIS_USER); $this->loadDataSet($dataset); }
/** * Test that modifying a Moodle user also updates the corresponding PM user. */ public function test_modifyingmoodleuserupdatespmuser() { global $CFG, $DB; require_once $CFG->dirroot . '/admin/tool/uploaduser/locallib.php'; $this->load_csv_data(); // Update a record. $src = new stdClass(); $src->id = 100; $src->firstname = 'Testuser'; $src->lastname = 'One'; $src->profile_field_sometext = 'boo'; $src->profile_field_sometextfrompm = 'bla'; $DB->update_record('user', $src); $mdluser = $DB->get_record('user', array('id' => 100)); $mcopy = clone $src; $mcopy = uu_pre_process_custom_profile_data($mcopy); profile_save_data($mcopy); events_trigger('user_updated', $mdluser); // Read the PM user and compare. $retr = new user(103, null, array(), false, array()); $retr->reset_custom_field_list(); $this->assertEquals($mdluser->firstname, $retr->firstname); $this->assertEquals($mdluser->lastname, $retr->lastname); // Check custom fields. $result = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_int::TABLE, $DB->get_recordset(field_data_int::TABLE, null, '', 'contextid, fieldid, data'))); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_char::TABLE, $DB->get_recordset(field_data_char::TABLE, null, '', 'contextid, fieldid, data'))); $result->addTable(new moodle_recordset_phpunit_datatable(field_data_text::TABLE, $DB->get_recordset(field_data_text::TABLE, null, '', 'contextid, fieldid, data'))); $usercontext = \local_elisprogram\context\user::instance(103); $dataset = new PHPUnit_Extensions_Database_DataSet_CsvDataSet(); $dataset->addTable(field_data_int::TABLE, elispm::file('tests/fixtures/user_field_data_int.csv')); $dataset->addTable(field_data_char::TABLE, elispm::file('tests/fixtures/user_field_data_char.csv')); $dataset->addTable(field_data_text::TABLE, elispm::file('tests/fixtures/user_field_data_text.csv')); $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset); $dataset->addFullReplacement('##USERCTXID##', $usercontext->id); $dataset->addFullReplacement('##USERCTXLVL##', CONTEXT_ELIS_USER); // Only the first text field should be changed; everything else should be the same. $dataset->addFullReplacement('First text entry field', $src->profile_field_sometext); $ret = $dataset->addFullReplacement('Second text entry field', $src->profile_field_sometextfrompm); $this->assertDataSetsEqual($dataset, $result); }
/** * Validate that mappings are applied during the user update action */ public function test_mapping_applied_during_user_update() { global $CFG, $DB; require_once $CFG->dirroot . '/local/eliscore/lib/data/customfield.class.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/data/user.class.php'; $this->init_mapping(); $customfieldid = $this->create_custom_field(); // Clear the cached custom field list. $usertoclearcustomfieldlist = new user(); $usertoclearcustomfieldlist->reset_custom_field_list(); $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); // Run the user update action. $record = new stdClass(); $record->customaction = 'update'; $record->customusername = '******'; $record->custompassword = '******'; $record->customidnumber = 'testuseridnumber'; $record->customfirstname = 'updatedtestuserfirstname'; $record->customlastname = 'updatedtestuserlastname'; $record->custommi = 'updatedtestusermi'; $record->customemail = '*****@*****.**'; $record->customemail2 = '*****@*****.**'; $record->customaddress = 'updatedtestuseraddress'; $record->customaddress2 = 'updatedtestuseraddress2'; $record->customcity = 'updatedtestusercity'; $record->customstate = 'updatedtestuserstate'; $record->custompostalcode = 'updatedtestuserpostalcode'; $record->customcountry = 'FR'; $record->customphone = 'updatedtestuserphone'; $record->customphone2 = 'updatedtestuserphone2'; $record->customfax = 'updatedtestuserfax'; $record->custombirthdate = 'Jan/02/2012'; $record->customgender = 'F'; $record->customlanguage = 'fr'; $record->customtransfercredits = '2'; $record->customcomments = 'updatedtestusercomments'; $record->customnotes = 'updatedtestusernotes'; $record->custominactive = '1'; $record->customtestfieldshortname = '1'; $this->run_user_import((array) $record); // Validation. $data = array('username' => 'testuserusername', 'idnumber' => 'testuseridnumber', 'firstname' => 'updatedtestuserfirstname', 'lastname' => 'updatedtestuserlastname', 'mi' => 'updatedtestusermi', 'email' => '*****@*****.**', 'email2' => '*****@*****.**', 'address' => 'updatedtestuseraddress', 'address2' => 'updatedtestuseraddress2', 'city' => 'updatedtestusercity', 'state' => 'updatedtestuserstate', 'postalcode' => 'updatedtestuserpostalcode', 'country' => 'FR', 'phone' => 'updatedtestuserphone', 'phone2' => 'updatedtestuserphone2', 'fax' => 'updatedtestuserfax', 'birthdate' => '2012/01/02', 'gender' => 'F', 'language' => 'fr', 'transfercredits' => 2, 'inactive' => 1); $this->assertTrue($DB->record_exists(user::TABLE, $data)); // Validate password. $userrec = $DB->get_record('user', array('username' => $data['username'])); $this->assertTrue(validate_internal_user_password($userrec, 'updatedTestpassword!0')); $record = $DB->get_record(user::TABLE, array('username' => 'testuserusername')); $this->assertEquals('updatedtestusercomments', $record->comments); $this->assertEquals('updatedtestusernotes', $record->notes); $instance = \local_elisprogram\context\user::instance(1); $this->assertTrue($DB->record_exists(field_data_int::TABLE, array('fieldid' => $customfieldid, 'contextid' => $instance->id, 'data' => 1))); }
/** * Create data for our test field field. * * @param int $fieldid The database id of the PM custom field * @param array $data The data to set */ protected function create_field_data($fieldid, $data) { global $CFG, $DB; $field = new field($fieldid); $field->load(); $fieldcontext = $DB->get_field(field_contextlevel::TABLE, 'contextlevel', array('fieldid' => $fieldid)); // Obtain the PM user context. switch ($fieldcontext) { case CONTEXT_ELIS_USER: $context = \local_elisprogram\context\user::instance(200); break; case CONTEXT_ELIS_COURSE: $context = \local_elisprogram\context\course::instance(200); break; case CONTEXT_ELIS_CLASS: $context = \local_elisprogram\context\pmclass::instance(200); break; case CONTEXT_ELIS_PROGRAM: $context = \local_elisprogram\context\program::instance(200); break; } field_data_char::set_for_context_and_field($context, $field, $data); }
/** * Test user capability check. */ public function test_usercapabilitycheck() { global $DB, $USER; $role = $DB->get_record('role', array('shortname' => 'editingteacher')); // Assign the test user the editing teacher role on a test cluster. $ctx = \local_elisprogram\context\user::instance($this->tuserid); $this->assertNotEmpty(role_assign($role->id, $this->mdluserid, $ctx->id)); load_role_access_by_context($role->id, $ctx, $USER->access); // We need to force the accesslib cache to refresh. // Validate the return value when looking at the 'user' level. $contextsuser = new pm_context_set(); $contextsuser->contexts = array('user' => array($this->tuserid)); $contextsuser->contextlevel = 'user'; $contexts = pm_context_set::for_user_with_capability('user', 'local/elisprogram:userset_enrol_userset_user', $this->mdluserid); $this->assertEquals($contextsuser, $contexts); // Validate checking for users with the given capability on this context. $users = pm_get_users_by_capability('user', $this->tuserid, 'local/elisprogram:userset_enrol_userset_user'); $this->assertEquals($this->mdluserid, current($users)->id); }
/** * Performs user deletion * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error deleting the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function user_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::user_delete_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); // Get the user we're updating via identifying fields. $idfields = array('idnumber', 'username', 'email'); $userid = null; foreach ($idfields as $field) { if (isset($data[$field])) { $user = $DB->get_record(user::TABLE, array($field => $data[$field])); if (!empty($user)) { if (!empty($userid) && $userid !== $user->id) { // If we already have a userid from a previous field and this user doesn't match that user, throw exception. throw new moodle_exception('ws_user_delete_fail_conflictingidfields', 'local_datahub'); } else { $userid = $user->id; } } } } if (empty($userid)) { // No valid identifying fields found. throw new moodle_exception('ws_user_delete_fail_noidfields', 'local_datahub'); } // Capability checking. require_capability('local/elisprogram:user_delete', \local_elisprogram\context\user::instance($userid)); // Delete the user. $user = new user($userid); $user->delete(); // Verify user deleted & respond if (!$DB->record_exists(user::TABLE, array('id' => $userid))) { return array('messagecode' => get_string('ws_user_delete_success_code', 'local_datahub'), 'message' => get_string('ws_user_delete_success_msg', 'local_datahub')); } else { throw new data_object_exception('ws_user_delete_fail', 'local_datahub'); } }
/** * Performs updating of user identifiers. * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error editing the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function user_update_identifiers(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::user_update_identifiers_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $userparams = array(); $data = (object) $data; $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_user_update_identifiers_fail_invalid_user', 'local_datahub', '', $a); } // Capability checking. require_capability('local/elisprogram:user_edit', \local_elisprogram\context\user::instance($userid)); $user = new user($userid); $user->load(); if (isset($data->username)) { $user->username = $data->username; } if (isset($data->idnumber)) { $user->idnumber = $data->idnumber; } if (isset($data->email)) { $user->email = $data->email; } $user->save(); // Respond. $userrec = (array) $DB->get_record(user::TABLE, array('id' => $user->id)); $userobj = $user->to_array(); // Convert multi-valued custom field arrays to comma-separated listing. $fields = self::get_user_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($userobj[$fullfieldname]) && is_array($userobj[$fullfieldname])) { $userobj[$fullfieldname] = implode(',', $userobj[$fullfieldname]); } } return array('messagecode' => get_string('ws_user_update_identifiers_success_code', 'local_datahub'), 'message' => get_string('ws_user_update_identifiers_success_msg', 'local_datahub'), 'record' => array_merge($userrec, $userobj)); }
/** * ELIS-4749: Test for assigning a user a role on a user context */ public function test_assignuserforuserctx() { global $DB; // Get role to assign (we'll just take the first one returned). $rolesctx = $DB->get_records('role_context_levels', array('contextlevel' => CONTEXT_ELIS_USER)); foreach ($rolesctx as $rolectx) { $roleid = $rolectx->roleid; break; } // Get user to assign role. $user = new user(103); $muser = $user->get_moodleuser(); // Get specific context. $context = \local_elisprogram\context\user::instance($user->id); // Assign role. $this->assertGreaterThan(0, role_assign($roleid, $muser->id, $context->id)); }
/** * Test that a new User context instance can be created and saved to the database. */ public function test_usercontext() { $newobj = $this->inituser(); $newobj->save(); $context = \local_elisprogram\context\user::instance($newobj->id); // Validate that a context record was actually created with correct values. $this->assertGreaterThan(0, $context->id); $this->assertEquals(CONTEXT_ELIS_USER, $context->contextlevel); $this->assertEquals($newobj->id, $context->instanceid); // Create the context path to validate this in the returned context object. $path = '/' . SYSCONTEXTID . '/' . $context->id; $this->assertEquals($path, $context->path); $this->assertEquals(substr_count($path, '/'), $context->depth); }
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(); } }
/** * Create and update user custom fields * * @dataProvider ui_type_provider * @param string $uitype The string value representing a UI type * @param string $data Value for create * @param mixed $expected Expected value after create as a string or int * @param string $updateddata Value for update * @param mixed $updateexpected Expected value after update as string or int * @param string $name The name of the control * @param string $datatype The datatype of the field * @param mixed $maxlength The maxiumum length of the field as int or null * @param mixed $inctime Include time along with the date as string or null * @param mixed $options The options of the field as array or null */ public function test_elis_user_custom_field_import($control, $data, $expected, $updateddata, $updateexpected, $name, $datatype, $maxlength, $inctime, $options) { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::lib('data/user.class.php'); $fieldid = $this->create_test_field($name, $datatype, $control, $inctime, $maxlength, $options, CONTEXT_ELIS_USER); if ($control === 'datetime' && is_array($expected)) { $expected = rlip_timestamp($expected[0], $expected[1], $expected[2], $expected[3], $expected[4], $expected[5]); } if ($control === 'datetime' && is_array($updateexpected)) { $updateexpected = rlip_timestamp($updateexpected[0], $updateexpected[1], $updateexpected[2], $updateexpected[3], $updateexpected[4], $updateexpected[5]); } $temp = new user(); // Prevent caching issues. $temp->reset_custom_field_list(); $record = new stdClass(); $record->action = 'create'; $record->email = '*****@*****.**'; $record->username = '******'; $record->idnumber = 'testuserid'; $record->firstname = 'testuserfirstname'; $record->lastname = 'testuserlastname'; $record->country = 'CA'; $record->{$name} = $data; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->process_record('user', (object) $record, 'bogus'); $usercontext = \local_elisprogram\context\user::instance($DB->get_field(user::TABLE, 'id', array('idnumber' => 'testuserid'))); $this->assert_field_values($datatype, $control, $fieldid, $usercontext->id, $expected); // Update. $record = new stdClass(); $record->action = 'update'; $record->email = '*****@*****.**'; $record->username = '******'; $record->idnumber = 'testuserid'; $record->firstname = 'testuserfirstname'; $record->lastname = 'testuserlastname'; $record->country = 'CA'; $record->{$name} = $updateddata; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->process_record('user', (object) $record, 'bogus'); $this->assert_field_values($datatype, $control, $fieldid, $usercontext->id, $updateexpected); }
/** * Transforms a heading element displayed above the columns into a listing of such heading elements * * @param string array $grouping_current Mapping of field names to current values in the grouping * @param table_report_grouping $grouping Object containing all info about the current level of grouping * being handled * @param stdClass $datum The most recent record encountered * @param string $export_format The format being used to render the report * * @return string array Set of text entries to display */ function transform_grouping_header_label($grouping_current, $grouping, $datum, $export_format) { //TBD: dependencies for custom fields $labels = array(); //user fullname if ($export_format == table_report::$EXPORT_FORMAT_HTML) { //label for this grouping element $text_label = get_string('grouping_name', $this->languagefile); } else { //label for all groupings $text_label = get_string('grouping_name_csv', $this->languagefile); } $fullname_text = php_report::fullname($datum); $labels[] = $this->add_grouping_header($text_label, $fullname_text, $export_format); $filters = php_report_filtering_get_active_filter_values($this->get_report_shortname(), 'filter-detailheaders', $this->filter); $headers = $filters[0]['value']; $this->_userfieldids = array(); if (!empty($headers)) { foreach ($headers as $field => $active) { if ($active && substr($field, 0, 7) == 'custom_') { $fieldid = substr($field, 7); $this->_userfieldids[] = $fieldid; } } } //configured user custom fields if (!empty($this->_userfieldids)) { //only need to obtain the user information once $user = \local_elisprogram\context\user::instance($datum->userid); //add a row for each field foreach ($this->_userfieldids as $userfieldid) { $field = new field($userfieldid); //needed to store just the actual data value $rawdata = array(); if ($customdata = field_data::get_for_context_and_field($user, $field)) { //could potentially have multiple values foreach ($customdata as $customdatum) { if ($field->datatype == 'bool') { //special display handling for boolean values $rawdata[] = !empty($customdatum->data) ? get_string('yes') : get_string('no'); } else { if (isset($field->owners['manual']) && ($manual = new field_owner($field->owners['manual'])) && $manual->param_control == 'datetime') { //special display handling for datetime fields $rawdata[] = $this->userdate($customdatum->data, get_string(!empty($manual->param_inctime) ? 'customfield_datetime_format' : 'customfield_date_format', $this->languagefile)); } else { $rawdata[] = $customdatum->data; } } } } $labels[] = $this->add_grouping_header($field->name . ': ', implode(', ', $rawdata), $export_format); } } //user address if (!empty($headers['user_address'])) { $text_label = get_string('grouping_address', $this->languagefile); $address_text = get_string('grouping_address_format', $this->languagefile, $datum); $labels[] = $this->add_grouping_header($text_label, $address_text, $export_format); } //user city / town if (!empty($headers['user_city'])) { $text_label = get_string('grouping_city', $this->languagefile); $labels[] = $this->add_grouping_header($text_label, $datum->city, $export_format); } //user state / province if (!empty($headers['user_state'])) { $text_label = get_string('grouping_state', $this->languagefile); $labels[] = $this->add_grouping_header($text_label, $datum->state, $export_format); } //user email address if (!empty($headers['user_email'])) { $text_label = get_string('grouping_email', $this->languagefile); $labels[] = $this->add_grouping_header($text_label, $datum->email, $export_format); } // Get the credit total $num_credits = $this->get_total_credits($grouping_current, $grouping, $datum, $export_format); //create the header item $text_label = get_string('grouping_credits', $this->languagefile); $labels[] = $this->add_grouping_header($text_label, $num_credits, $export_format); return $labels; }
/** * Get data for enable fields for a single record. * * @param object $record The current database record for the current row of data. * * @return array An array of additional data, indexed by field. */ public function get_data($record) { global $CFG; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::file('accesslib.php'); $this->init_customfield_data(); $date_format = get_string('date_format', 'dhexport_version1elis'); $datetime_format = get_string('datetime_format', 'dhexport_version1elis'); $extra_data = array(); foreach ($this->customfield_data as $fieldid => $fieldrec) { $fieldkey = 'field_' . $fieldid; if (isset($this->enabled_fields[$fieldkey])) { $field_recparam = 'custom_field_' . $fieldid; if (isset($record->{$field_recparam}) || $record->{$field_recparam} === null) { $field = new field($fieldrec); $value = $record->{$field_recparam}; // Set field to default data if no data present. if ($value === null) { $value = $field->get_default(); } // Handle multivalue fields. if ($this->customfield_multivaluestatus[$field->id] !== static::MULTIVALUE_NONE) { $context = \local_elisprogram\context\user::instance($record->userid); $data = field_data::get_for_context_and_field($context, $field); if ($this->customfield_multivaluestatus[$field->id] == static::MULTIVALUE_ENABLED) { $parts = array(); foreach ($data as $datum) { $parts[] = $datum->data; } $value = implode(' / ', $parts); } else { $value = $data->current()->data; } } // Display datetime fields as formatted date/time. if ($field->owners['manual']->param_control === 'datetime') { if ($value == 0) { // Use a marker to indicate that it's not set. $value = get_string('nodatemarker', 'dhexport_version1elis'); } else { if ($field->owners['manual']->param_inctime) { // Date and time. $value = date($datetime_format, $value); } else { // Just date. $value = date($date_format, $value); } } } // Remove html from text. $control = $field->owners['manual']->param_control; if ($control === 'text' || $control === 'textarea') { $value = trim(html_to_text($value), "\n\r"); } $extra_data[$fieldkey] = $value; } } } return $extra_data; }
/** * Performs user updating * @throws moodle_exception If there was an error in passed parameters. * @throws data_object_exception If there was an error editing the entity. * @param array $data The incoming data parameter. * @return array An array of parameters, if successful. */ public static function user_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::user_update_parameters(), array('data' => $data)); // Context validation. $context = context_user::instance($USER->id); self::validate_context($context); // Initialize version1elis importplugin for utility functions. $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); // Get the user we're updating via identifying fields. $idfields = array('idnumber', 'username', 'email'); $valididfields = array(); $invalididfields = array(); $userid = null; foreach ($idfields as $field) { if (isset($data[$field])) { $users = $DB->get_records(user::TABLE, array($field => $data[$field]), '', 'id', 0, 2); $numusers = count($users); if ($numusers > 1) { throw new moodle_exception('ws_user_update_fail_multipleusersforidentifier', 'local_datahub', '', $field); } else { if ($numusers === 1) { $user = reset($users); if (!empty($userid) && $userid !== $user->id) { // If we already have a userid from a previous field and this user doesn't match that user, throw exception. $a = implode(', ', $valididfields) . ', ' . $field; throw new moodle_exception('ws_user_update_fail_conflictingidfields', 'local_datahub', '', $a); } else { $userid = $user->id; $valididfields[] = $field; } } else { if (!empty($userid)) { // The user has supplied a valid identifying field already, but this one is an invalid field. // This is likely an attempt to update an identifying field, which has to be done elsewhere. throw new moodle_exception('ws_user_update_fail_idfieldsnotallowed', 'local_datahub'); } $invalididfields[] = $field; } } } } if (empty($userid)) { // No valid identifying fields found. throw new moodle_exception('ws_user_update_fail_noidfields', 'local_datahub'); } else { if (!empty($invalididfields)) { // The user has supplied a valid identifying field already, but has also supplied at least one invalid id field. // This is likely an attempt to update an identifying field, which has to be done elsewhere. throw new moodle_exception('ws_user_update_fail_idfieldsnotallowed', 'local_datahub'); } } // Capability checking. require_capability('local/elisprogram:user_edit', \local_elisprogram\context\user::instance($userid)); // Initialize update data. $data = (object) $data; $data = $importplugin->add_custom_field_prefixes($data); $data = $importplugin->initialize_user_fields($data); // Handle password changes. if (isset($data->password)) { $data->newpassword = $data->password; unset($data->password); } // Convert the birthdate field to the proper setup for storage. if (isset($data->birthdate)) { $value = $importplugin->parse_date($data->birthdate); if (!empty($value)) { $data->birthday = gmdate('d', $value); $data->birthmonth = gmdate('m', $value); $data->birthyear = gmdate('Y', $value); } else { throw new moodle_exception('ws_bad_param', 'local_datahub', '', 'birthdate'); } unset($data->birthdate); } // Update the user. $user = new user($userid); $user->load(); $user->set_from_data($data); $user->save(); // Respond. if (!empty($user->id)) { $userrec = (array) $DB->get_record(user::TABLE, array('id' => $user->id)); $userobj = $user->to_array(); // Convert multi-valued custom field arrays to comma-separated listing. $fields = self::get_user_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($userobj[$fullfieldname]) && is_array($userobj[$fullfieldname])) { $userobj[$fullfieldname] = implode(',', $userobj[$fullfieldname]); } } return array('messagecode' => get_string('ws_user_update_success_code', 'local_datahub'), 'message' => get_string('ws_user_update_success_msg', 'local_datahub'), 'record' => array_merge($userrec, $userobj)); } else { throw new data_object_exception('ws_user_update_fail', 'local_datahub'); } }
protected function get_context() { if (!isset($this->_context)) { $id = $this->required_param('id', PARAM_INT); $context_instance = \local_elisprogram\context\user::instance($id); $this->set_context($context_instance); } return $this->_context; }