/** * Test for correct assignment of course permissions */ public function test_coursepermissions() { global $DB, $CFG, $USER; accesslib_clear_all_caches(true); set_config('siteguest', ''); set_config('siteadmins', ''); $this->assertFalse($this->has_program_create_capability()); $this->assertFalse($this->has_associate_and_manage_capability()); $this->assertFalse($this->has_program_view_capability()); $syscontext = context_system::instance(); $assigninguser = new user(array('idnumber' => 'testuserid', 'username' => 'testuser', 'firstname' => 'testuser', 'lastname' => 'testuser', 'email' => '*****@*****.**', 'country' => 'CA')); $assigninguser->save(); $roleid = create_role('userrole', 'userrole', 'userrole'); $usr = $DB->get_record('user', array('username' => 'testuser')); $this->setUser($usr); $USER = $usr; assign_capability('local/elisprogram:associate', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:manage', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_create', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_enrol', CAP_ALLOW, $roleid, $syscontext->id); assign_capability('local/elisprogram:program_view', CAP_ALLOW, $roleid, $syscontext->id); role_assign($roleid, $usr->id, $syscontext->id); $this->assertTrue($this->has_program_create_capability()); $this->assertTrue($this->has_associate_and_manage_capability()); $this->assertTrue($this->has_program_view_capability()); $this->setUser(null); }
/** * Test student save works when $USER object not set */ public function test_student_save_nouserobject() { global $DB, $USER; // Create Moodle course category. $crscat = create_course_category((object) array('name' => 'Test Course category', 'idnumber' => 'MCC-1')); // Create Moodle course. $crsdata = array('category' => $crscat->id, 'fullname' => 'MC-TEST-ELIS-8484', 'shortname' => 'MC-TEST-ELIS-8484', 'idnumber' => 'MC-TEST-ELIS-8484'); $mdlcrs = new stdClass(); $mdlcrs->id = $DB->insert_record('course', (object) $crsdata); $cddata = array('name' => 'CD-ELIS-8484', 'code' => 'CD-ELIS-8484', 'idnumber' => 'CD-ELIS-8484', 'syllabus' => 'syllabus'); $cd = new course($cddata); $cd->save(); $ci = new pmclass(array('idnumber' => 'CI-ELIS-8484', 'courseid' => $cd->id, 'moodlecourseid' => $mdlcrs->id, 'autocreate' => 0)); $ci->save(); $testuser = new user(array('idnumber' => 'testuserelis8484', 'username' => 'testuserelis8484', 'firstname' => 'Test', 'lastname' => 'User-ELIS8484', 'email' => '*****@*****.**', 'city' => 'Waterloo', 'country' => 'CA')); $testuser->save(); $USER = null; $sturec = new stdClass(); $sturec->userid = $testuser->id; $sturec->classid = $ci->id; $sturec->grade = 0; $sturec->enrolmenttime = time(); $student = new student($sturec); $student->save(); $this->assertFalse(empty($student)); if (!empty($student)) { $this->assertFalse(empty($student->id)); } }
function hasPasswordExpired($username) { // if ($syst_generated_pwd == '0'){ // $type='syst'; // }else{ $type = 'user'; // } $current_user = new user(); $usr_id = $current_user->retrieve_user_id($username); $current_user->retrieve($usr_id); if ($current_user->portal_only == '0') { global $mod_strings; $res = $GLOBALS['sugar_config']['passwordsetting']; if ($res[$type . 'expiration'] == '1') { global $timedate; if ($current_user->pwd_last_changed == '') { $current_user->pwd_last_changed = $timedate->to_display_date_time(gmdate($GLOBALS['timedate']->get_db_date_time_format())); $current_user->save(); } $expireday = $res[$type . 'expirationtype'] * $res[$type . 'expirationtime']; $stim = strtotime($current_user->pwd_last_changed); //add day to timestamp $expiretime = date("Y-m-d H:i:s", mktime(date("H", $stim), date("i", $stim), date("s", $stim), date("m", $stim), date("d", $stim) + $expireday, date("Y", $stim))); $timenow = $timedate->to_display_date_time(gmdate($GLOBALS['timedate']->get_db_date_time_format())); if ($timenow < $expiretime) { return false; } else { $_SESSION['expiration_type'] = $mod_strings['LBL_PASSWORD_EXPIRATION_TIME']; return true; } } if ($res[$type . 'expiration'] == '2') { $login = $current_user->getPreference('loginexpiration'); $current_user->setPreference('loginexpiration', $login + 1); $current_user->save(); if ($login >= $res[$type . 'expirationlogin']) { $_SESSION['expiration_type'] = $mod_strings['LBL_PASSWORD_EXPIRATION_LOGIN']; return true; } else { return false; } } if ($res[$type . 'expiration'] == '0') { return false; } } }
/** * Create a test user record * * @return int The id of the user record */ private function create_test_user() { global $CFG; require_once $CFG->dirroot . '/local/elisprogram/lib/data/user.class.php'; $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); return $user->id; }
function approve($id) { if ($_POST) { $users = new user($id); $users->from_array($_POST); $users->save(); } }
/** * Creates a new user model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new user(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } }
/** * Create user for testing */ public function setUp() { parent::setUp(); $user = new user(); $user->id = -1; $user->mail = '*****@*****.**'; $user->save(); $this->user = $user; $this->be($user); }
function newUser($validator) { $email = $validator->getVar("email"); $q = Doctrine_Query::create()->from('user u')->where("u.email='{$email}'"); $rows = $q->execute(); $random = rand(0, 999999999); if (count($rows) == 0) { $random = rand(0, 999999999); $entity = new user(); $entity->email = $email; $entity->password = $validator->getVar("password"); $entity->validation_code = $random; $entity->save(); } else { $validator->addError('The user "' . $email . '" already exists.'); } $idUsuario = mysql_insert_id(); if ($validator->getTotalErrors() == 0) { require_once 'phputils/class.phpmailer.php'; try { $mail = new PHPMailer(true); //New instance, with exceptions enabled //$body = file_get_contents('contents.html'); $body = 'Hi ' . $email . ', Welcome!, your validation code is ' . $random . '. Before you can log into the system you must click on the following link: ' . $GLOBALS["baseURL"] . 'crud.php?public_action=validate&a=' . $random . '&b=' . $entity->id; $body = preg_replace('/\\\\/', '', $body); //Strip backslashes //$mail->IsSMTP(); // tell the class to use SMTP //$mail->SMTPAuth = true; // enable SMTP authentication //$mail->Port = 587; // set the SMTP server port //$mail->Host = "smtp.gmail.com"; // SMTP server //$mail->Username = "******"; // SMTP server username //$mail->Password = ""; // SMTP server password //$mail->IsSendmail(); // tell the class to use Sendmail //$mail->AddReplyTo("*****@*****.**","domain.com"); $mail->From = "*****@*****.**"; $mail->FromName = "Domain.com"; $mail->AddBCC($email); $mail->Subject = "Domain.com Registration"; $mail->AltBody = 'Hi ' . $email . ', welcome!, your validation code is ' . $random . '. Before you can log into the system you must copy the following link into you browser: ' . $GLOBALS["baseURL"] . 'crud.php?public_action=validate&a=' . $random . '&b=' . $entity->id; $mail->WordWrap = 80; // set word wrap $mail->MsgHTML($body); $mail->IsHTML(true); // send as HTML $mail->Send(); $_SESSION['user']->status = 'pending'; $_SESSION['user']->name = $email; } catch (phpmailerException $e) { //$validator->addError("PHPMailer:".$e->errorMessage()); } } return 'controller.php?view=validate'; }
/** * Test block_elisadmin_load_menu_children_course function. */ public function test_block_elisadmin_load_menu_children_course() { global $DB, $USER; accesslib_clear_all_caches(true); // Create test user - ensure the returned user is NOT a site admin. if they are, our capability restrictions won't work. $testuser = new user(); $testuser->username = '******'; $testuser->idnumber = 'testELIS4093'; $testuser->firstname = 'testELIS4093'; $testuser->lastname = 'testELIS4093'; $testuser->email = '*****@*****.**'; $testuser->country = 'CA'; $testuser->save(); $testmuser = $testuser->get_moodleuser(); // Create role with cap: 'local/elisprogram:class_view'. $testrole = new stdClass(); $testrole->name = 'ELIS Class View'; $testrole->shortname = '_test_ELIS_4093'; $testrole->description = 'ELIS Class View'; $testrole->archetype = ''; $testrole->id = create_role($testrole->name, $testrole->shortname, $testrole->description, $testrole->archetype); // Ensure our new role is assignable to ELIS class contexts. set_role_contextlevels($testrole->id, array(CONTEXT_ELIS_CLASS)); // Ensure the role has our required capability assigned. $sitecontext = context_system::instance(); assign_capability('local/elisprogram:class_view', CAP_ALLOW, $testrole->id, $sitecontext->id, true); $sitecontext->mark_dirty(); // Create ELIS Course Description. $testcrs = new course(array('name' => 'CD-ELIS-4093', 'idnumber' => 'CDELIS4093', 'syllabus' => '')); $testcrs->save(); $testcrs->load(); // Create three(3) Class Instances for Course Descrption. $testcls1 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.1')); $testcls1->save(); $testcls1->load(); $testcls2 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.2')); $testcls2->save(); $testcls2->load(); $testcls3 = new pmclass(array('courseid' => $testcrs->id, 'idnumber' => 'CI_ELIS_4093.3')); $testcls3->save(); $testcls3->load(); // Assign testuser new role in one Class Instance. $context = \local_elisprogram\context\pmclass::instance($testcls2->id); role_assign($testrole->id, $testmuser->id, $context->id); // Switch to testuser. $USER = $testmuser; $this->setUser($testmuser); $items = block_elisadmin_load_menu_children_course($testcrs->id, 0, 0, 5, ''); $this->assertEquals(1, count($items)); $this->assertTrue($items[0]->name == 'pmclass_2'); }
/** * Retourne les données de l'utilisateur depuis la base de données. * L'utilisateur sera créé s'il n'existe pas. * @return User */ public function getUserFromDatabase() { $user = Doctrine::getTable('user')->retrieveByLdapId($this->getProfileVar(sfConfig::get('app_profile_var_translation_uid'))); if ($user === null) { // L'utilisateur se connecte pour la première fois $user = new user(); $user->setLdapId($this->getProfileVar(sfConfig::get('app_profile_var_translation_uid'))); $user->setName($this->getProfileVar(sfConfig::get('app_profile_var_translation_name'))); $user->setSurname($this->getProfileVar(sfConfig::get('app_profile_var_translation_surname'))); $user->setMail($this->getProfileVar(sfConfig::get('app_profile_var_translation_mail'))); $user->save(); } return $user; }
public static function check_and_save($session_id, $user_id, $username, $password) { $session = session::get_session($session_id); if ($session != null && $session->is_valid()) { $user = ormlib::get_from_instance(new user(), array("id"), array($session->user_id)); if ($user->has_group(session::GROUP_METADATA) === true) { if ($username != "" && $password != "") { user::save($user_id, $username, $password); return array("response" => "OK"); } else { return array("response" => "error", "message" => "name or password is empty"); } } } return array("response" => "error", "message" => "no privileg"); }
/** * Validate that appropriate fields are synched over to Moodle when PM user is enrolled in a class instance during an import. */ public function test_user_sync_on_pm_user_create() { global $CFG, $DB; require_once $CFG->dirroot . '/course/lib.php'; require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php'; require_once elispm::lib('data/classmoodlecourse.class.php'); require_once elispm::lib('data/course.class.php'); require_once elispm::lib('data/pmclass.class.php'); require_once elispm::lib('data/user.class.php'); // Configure the elis enrolment plugin. $roleid = $DB->get_field('role', 'id', array(), IGNORE_MULTIPLE); set_config('roleid', $roleid, 'enrol_elis'); $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => '')); $course->save(); $class = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber')); $class->save(); $category = new stdClass(); $category->name = 'testcategoryname'; $category->id = $DB->insert_record('course_categories', $category); // Create the associated context. context_coursecat::instance($category->id); $mdlcourse = new stdClass(); $mdlcourse->category = $category->id; $mdlcourse->fullname = 'testcoursefullname'; $mdlcourse = create_course($mdlcourse); // Associate class instance to Moodle course. $classmoodlecourse = new classmoodlecourse(array('classid' => $class->id, 'moodlecourseid' => $mdlcourse->id)); $classmoodlecourse->save(); // Run the enrolment create action. $record = new stdClass(); $record->context = 'class_testclassidnumber'; $record->user_username = '******'; $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis'); $importplugin->fslogger = new silent_fslogger(null); $importplugin->class_enrolment_create($record, 'bogus', 'testclassidnumber'); // Validate the enrolment. $enrolid = $DB->get_field('enrol', 'id', array('enrol' => 'elis', 'courseid' => $mdlcourse->id)); $this->assertNotEquals(false, $enrolid); $mdluserid = $DB->get_field('user', 'id', array('username' => 'testuserusername')); $this->assertNotEquals(false, $mdluserid); $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrolid, 'userid' => $mdluserid))); // Validate the role assignment. $mdlcoursecontext = context_course::instance($mdlcourse->id); $this->assertTrue($DB->record_exists('role_assignments', array('roleid' => $roleid, 'contextid' => $mdlcoursecontext->id, 'userid' => $mdluserid))); }
function register_action() { $name = isset($_POST['name']) ? $_POST['name'] : ''; $email = isset($_POST['email']) ? $_POST['email'] : ''; $password = isset($_POST['password']) ? $_POST['password'] : ''; $cnf_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : ''; if ($name != '' || $email != '' || $password != '') { $user = new user($name, $email, $password); if ($user->save()) { // it successfully saved the user data header("HTTP/1.1 200 ok"); header("Location: " . "http://" . HOST . '/' . APPLICATION . '/index.php?page=login'); } else { header("HTTP/1.1 400 Invalid input"); header("Location: " . "http://" . HOST . 'index.php?page=register'); } } }
/** * авторизует пользователя * если такого пользователя нет, то создает его */ public function action_signup() { try { if (empty($_REQUEST['email']) || empty($_REQUEST['username'])) { throw new Exception('Все поля должны быть заполнены.'); } $user = user::find_by_email($_REQUEST['email']); if ($user != null) { throw new Exception('Пользователь с таким электронным адресом уже зарегистирован.'); } $user = new user(array('name' => $_REQUEST['username'], 'email' => $_REQUEST['email'])); $user->save(); //зарегистрировали, тут же авторизуем $this->action_login(); } catch (Exception $e) { $this->_actions_data['_errors'][] = $e->getMessage(); $this->_actions_data['_ok'] = 0; } }
/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new user(); $user->username = $this->username; $user->dealer = 1; $user->email = $this->email; $user->city = $this->city; $user->firstname = $this->fname; $user->lastname = $this->lname; $user->setPassword($this->password); $user->generateAuthKey(); \Yii::$app->mailer->compose(['html' => 'auth-html'], ['user' => $user])->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])->setTo($this->email)->setSubject('Authenticate your account ' . \Yii::$app->name)->send(); if ($user->save()) { return $user; } } return null; }
function update($params) { if ($params['id'] != null) { $object = user::get($params['id']); } else { $object = new user(); } $oldpwd = $object->password; $object->bind_params($params); if ($oldpwd != $params['password']) { $object->password = md5($params['password']); $object->plain_pwd = $params['password']; } try { $object->save(); print json(array('status' => 'ok', 'id' => $object->id)); return; } catch (\Ammonio\ORM\ValidationException $e) { print json(array('status' => 'error', 'errors' => $object->get_errors())); } }
function setup() { //Grab the user if (isset($_GET['cid'])) { $confirm_id = $_GET['cid']; } else { header("HTTP/1.0 404 Not Found"); exit; } $user = new user(); if ($user->load_from_confirm_id($confirm_id)) { //Update the confirmed flag $user->confirmed = true; //delete any other active alerts for this postcode $user->remove_existing(); $user->save(false); //Grab the postcode and area $this->postcode = $user->postcode; $this->alert_area_size = alert_size_to_meters($user->alert_area_size); } else { header("HTTP/1.0 404 Not Found"); exit; } }
/** * Test sync-ing an ELIS User Profile field to a DELETED Moodle User Profile field */ public function test_syncpmuserfieldtodeletedmoodleprofilefield() { global $CFG, $DB; require_once $CFG->dirroot . '/user/profile/definelib.php'; $this->load_csv_data(); // Set PM Custom User field(s) to Sync to Moodle. $ctxlvl = CONTEXT_ELIS_USER; $fields = field::get_for_context_level($ctxlvl); foreach ($fields as $field) { $fieldobj = new field($field); if (!isset($fieldobj->owners['moodle_profile'])) { $fieldobj->owners['moodle_profile'] = new stdClass(); } $owner = new field_owner($fieldobj->owners['moodle_profile']); $owner->exclude = pm_moodle_profile::sync_from_moodle; $owner->save(); $fieldobj->save(); } // Read a record. $src = new user(103, null, array(), false, array()); $src->reset_custom_field_list(); // Modify the data. $src->firstname = 'Testuser'; $src->lastname = 'One'; $src->field_sometext = 'boo'; $src->field_sometextfrompm = 'bla'; $src->save(); // Delete some custom Moodle Profile field(s) to cause old error (pre ELIS-4499). $fields = field::get_for_context_level($ctxlvl); foreach ($fields as $field) { $fieldobj = new field($field); if ($moodlefield = $DB->get_record('user_info_field', array('shortname' => $fieldobj->shortname))) { profile_delete_field($moodlefield->id); } } // Run the library sync - throws errors not exceptions :(. $CFG->mnet_localhost_id = 1; // ??? $mu = cm_get_moodleuser(103); try { $result = pm_moodle_user_to_pm($mu); $this->assertTrue($result); } catch (Exception $ex) { $this->assertTrue(false, $ex->message); } }
include_once '../../includes/basics/header_public.inc'; //include_once(THEME_DIR . DS. 'header.inc'); ?> <script type='text/javascript' src="user.js" ></script> <?php if (!empty($_POST['newUser'])) { $new_user = new user(); $new_user->username = trim($_POST['username'][0]); $new_user->enteredPassword = trim($_POST['enteredPassword'][0]); $new_user->enteredRePassword = trim($_POST['enteredRePassword'][0]); $new_user->first_name = trim($_POST['first_name'][0]); $new_user->last_name = trim($_POST['last_name'][0]); $new_user->email = trim($_POST['email'][0]); if ($new_user->_before_save() == 1) { $new_user->audit_trial(); $new_user->save(); $new_user->_after_save(); $dbc->confirm(); } if (!empty($new_user->user_id)) { //Assign basic role $user_role = new user_role(); $user_role->user_id = $new_user->user_id; $user_role->role_code = 'BASIC'; $user_role->save(); $dbc->confirm(); $msg .= '<div class="message error"> Account is Successfully created!. Please check your mail box for further details. </div>'; } else { $msg .= '<div class="message error"> Account creation failed!. Contact the admin. </div>'; } }
/** * Migrate a single Moodle user to the Program Management system. Will * only do this for users who have an idnumber set. * * @param object $mu Moodle user object * @return boolean Whether user was synchronized or not */ function pm_moodle_user_to_pm($mu) { global $CFG, $DB; require_once $CFG->dirroot . '/lib/moodlelib.php'; require_once elis::lib('data/customfield.class.php'); require_once elispm::lib('data/user.class.php'); require_once elispm::lib('data/usermoodle.class.php'); require_once elis::lib('data/data_filter.class.php'); require_once $CFG->dirroot . '/user/profile/lib.php'; require_once elis::lib('lib.php'); if (!isset($mu->id)) { return true; } // re-fetch, in case this is from a stale event $mu = $DB->get_record('user', array('id' => $mu->id)); if (user_not_fully_set_up($mu) || !$mu->confirmed) { // Prevent the sync if a bare-bones user record is being created by create_user_record // or Moodle user has not yet been confirmed. return true; } //not going to be concerned with city or password for now if (empty($mu->idnumber) && elis::$config->local_elisprogram->auto_assign_user_idnumber) { //make sure the current user's username does not match up with some other user's //idnumber (necessary since usernames and idnumbers aren't bound to one another) if (!$DB->record_exists('user', array('idnumber' => $mu->username))) { $mu->idnumber = $mu->username; $DB->update_record('user', $mu); } } // skip user if no ID number set if (empty($mu->idnumber)) { return true; } // track whether we're syncing an idnumber change over to the PM system $idnumber_updated = false; // track whether an associated Moodle user is linked to the current PM user $moodle_user_exists = false; // determine if the user is already noted as having been associated to a PM user // this will join to Moodle user and PM user table to ensure data correctness $filters = array(); $filters[] = new join_filter('muserid', 'user', 'id'); $filters[] = new join_filter('cuserid', user::TABLE, 'id'); $filters[] = new field_filter('muserid', $mu->id); if ($um = usermoodle::find($filters)) { if ($um->valid()) { $um = $um->current(); //signal that an associated user already exists $moodle_user_exists = true; // determine if the Moodle user idnumber was updated if ($um->idnumber != $mu->idnumber) { //signal that the idnumber was synced over $idnumber_updated = true; // update the PM user with the new idnumber $cmuser = new user(); $cmuser->id = $um->cuserid; $cmuser->idnumber = $mu->idnumber; $cmuser->save(); // update the association table with the new idnumber $um->idnumber = $mu->idnumber; $um->save(); } } } // find the linked PM user //filter for the basic condition on the Moodle user id $condition_filter = new field_filter('id', $mu->id); //filter for joining the association table $association_filter = new join_filter('muserid', 'user', 'id', $condition_filter); //outermost filter $filter = new join_filter('id', usermoodle::TABLE, 'cuserid', $association_filter); $cu = user::find($filter); if ($cu->valid()) { $cu = $cu->current(); } else { // if a user with the same username but different idnumber exists, // we can't sync over because it will violate PM user uniqueness // constraints $cu = user::find(new field_filter('username', $mu->username)); if ($cu->valid()) { return true; } // if no such PM user exists, create a new one $cu = new user(); $cu->transfercredits = 0; $cu->timecreated = time(); } // synchronize standard fields $cu->username = $mu->username; $cu->password = $mu->password; // only need to update the idnumber if it wasn't handled above if (!$idnumber_updated) { $cu->idnumber = $mu->idnumber; } $cu->firstname = $mu->firstname; $cu->lastname = $mu->lastname; $cu->email = $mu->email; $cu->address = $mu->address; $cu->city = $mu->city; $cu->country = $mu->country; if (!empty($mu->phone1)) { $cu->phone = $mu->phone1; } if (!empty($mu->phone2)) { $cu->phone2 = $mu->phone2; } if (!empty($mu->lang)) { $cu->language = $mu->lang; } $cu->timemodified = time(); // synchronize custom profile fields profile_load_data($mu); fix_moodle_profile_fields($mu); $fields = field::get_for_context_level(CONTEXT_ELIS_USER); $fields = $fields ? $fields : array(); require_once elis::plugin_file('elisfields_moodleprofile', 'custom_fields.php'); foreach ($fields as $field) { $field = new field($field); if (!moodle_profile_can_sync($field->shortname)) { continue; } if (isset($field->owners['moodle_profile']) && isset($mu->{"profile_field_{$field->shortname}"})) { // check if should sync user profile field settings if ($field->owners['moodle_profile']->exclude == pm_moodle_profile::sync_from_moodle) { sync_profile_field_settings_from_moodle($field); } $fieldname = "field_{$field->shortname}"; $cu->{$fieldname} = $mu->{"profile_field_{$field->shortname}"}; } } //specifically tell the user save not to use the local_elisprogram_usr_mdl for syncing //because the record hasn't been inserted yet (see below) try { $cu->save(false); } catch (Exception $ex) { if (in_cron()) { mtrace(get_string('record_not_created_reason', 'local_elisprogram', array('message' => $ex->getMessage() . " [{$mu->id}]"))); return false; } else { throw new Exception($ex->getMessage()); } } // if no user association record exists, create one if (!$moodle_user_exists) { $um = new usermoodle(); $um->cuserid = $cu->id; $um->muserid = $mu->id; $um->idnumber = $mu->idnumber; $um->save(); } return true; }
/** * 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(); } }
/** * Validate that mappings are applied during the user delete action */ public function test_mapping_applied_during_user_delete() { global $CFG, $DB; require_once $CFG->dirroot . '/local/elisprogram/lib/data/user.class.php'; $this->init_mapping(); $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA')); $user->save(); // Run the user delete action. $record = new stdClass(); $record->customaction = 'delete'; $record->customusername = '******'; $record->customidnumber = 'testuseridnumber'; $record->customemail = '*****@*****.**'; $this->run_user_import((array) $record); // Validation. $this->assertEquals(0, $DB->count_records(user::TABLE)); }
} else { $changed = TRUE; $ban->banned = FALSE; } if (isset($_POST['banreason'])) { $changed = TRUE; if (strlen($_POST['banreason']) >= 3 && strlen($_POST['banreason']) <= 150) { $ban->bannedreason = $_POST['banreason']; } elseif ($ban->banned == FALSE && $_POST['banreason'] == "") { $changed = TRUE; $ban->bannedreason = ""; } else { $redmsg .= "<p>You must include a ban reason between 3 and 150 characters long.<p>"; } } if ($ban->save()) { $greenmsg .= "<p>The changes has been saved.</p>"; } else { $redmsg .= "<p>Failed to save changes.</p>"; } } //messages if (isset($greenmsg) && $greenmsg != "") { $greenmsg = '<div class="notification green">' . $greenmsg . '</div>'; } if (isset($redmsg) && $redmsg != "") { $redmsg = '<div class="notification red">' . $redmsg . '</div>'; } //Is banned? Checkbox generated. $banned = '<input type="checkbox" name="isbanned" value="yes"'; if ($ban->banned == TRUE) {
/** * 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)); }
/** * Retourne un object utilisateur (si les information de connection sont valide) * @param string $_login nom d'utilisateur * @param string $_mdp motsz de passe en sha1 * @return user object user */ public static function connect($_login, $_mdp, $_passAlreadyEncode = false) { if ($_passAlreadyEncode) { $sMdp = $_mdp; } else { $sMdp = sha1($_mdp); } if (config::byKey('ldap:enable') == '1') { log::add("connection", "debug", __('Authentification par LDAP', __FILE__)); $ad = self::connectToLDAP(); if ($ad !== false) { log::add("connection", "debug", __('Connection au LDAP OK', __FILE__)); $ad = ldap_connect(config::byKey('ldap:host'), config::byKey('ldap:port')); ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ad, LDAP_OPT_REFERRALS, 0); if (!ldap_bind($ad, 'uid=' . $_login . ',' . config::byKey('ldap:basedn'), $_mdp)) { log::add("connection", "info", __('Mot de passe erroné (', __FILE__) . $_login . ')'); return false; } log::add("connection", "debug", __('Bind user OK', __FILE__)); $result = ldap_search($ad, 'uid=' . $_login . ',' . config::byKey('ldap:basedn'), config::byKey('ldap:filter')); log::add("connection", "info", __('Recherche LDAP (', __FILE__) . $_login . ')'); if ($result) { $entries = ldap_get_entries($ad, $result); if ($entries['count'] > 0) { $user = self::byLogin($_login); if (is_object($user)) { $user->setPassword($sMdp); $user->setOptions('lastConnection', date('Y-m-d H:i:s')); $user->save(); return $user; } $user = new user(); $user->setLogin($_login); $user->setPassword($sMdp); $user->setOptions('lastConnection', date('Y-m-d H:i:s')); $user->save(); log::add("connection", "info", __('Utilisateur créé depuis le LDAP : ', __FILE__) . $_login); jeedom::event('user_connect'); log::add('event', 'event', __('Connexion de l\'utilisateur ', __FILE__) . $_login); return $user; } else { $user = self::byLogin($_login); if (is_object($user)) { $user->remove(); } log::add("connection", "info", __('Utilisateur non autorisé à accéder à Jeedom (', __FILE__) . $_login . ')'); return false; } } else { $user = self::byLogin($_login); if (is_object($user)) { $user->remove(); } log::add("connection", "info", __('Utilisateur non autorisé à accéder à Jeedom (', __FILE__) . $_login . ')'); return false; } return false; } else { log::add("connection", "info", __('Impossible de se connecter au LDAP', __FILE__)); } } $values = array('login' => $_login, 'password' => $sMdp); $sql = 'SELECT ' . DB::buildField(__CLASS__) . ' FROM user WHERE login=:login AND password=:password'; $user = DB::Prepare($sql, $values, DB::FETCH_TYPE_ROW, PDO::FETCH_CLASS, __CLASS__); if (is_object($user)) { $user->setOptions('lastConnection', date('Y-m-d H:i:s')); $user->save(); jeedom::event('user_connect'); log::add('event', 'event', __('Connexion de l\'utilisateur ', __FILE__) . $_login); if ($user->getOptions('validity_limit') != '' && strtotime('now') > strtotime($user->getOptions('validity_limit'))) { $user->remove(); return false; } } return $user; }
/** * Initialize a new user description object */ protected function inituser() { global $CFG, $DB, $USER; $data = array('idnumber' => '__fcH__TESTID001__', 'username' => '__fcH__testuser1__', 'firstname' => 'Test', 'lastname' => 'User1', 'email' => '*****@*****.**', 'country' => 'us'); $newuser = new user($data); $newuser->save(); $this->tuserid = $newuser->id; $usernew = new stdClass(); $usernew->username = '******'; $usernew->idnumber = '__fcH__testuser__'; $usernew->firstname = 'Test'; $usernew->lastname = 'User'; $usernew->email = '*****@*****.**'; $usernew->confirmed = 1; $usernew->auth = 'manual'; $usernew->mnethostid = $CFG->mnet_localhost_id; $usernew->confirmed = 1; $usernew->timecreated = time(); $usernew->password = hash_internal_user_password('testpassword'); $this->mdluserid = $DB->insert_record('user', $usernew); // Setup the global user to be this new test user we have created. $USER = $DB->get_record('user', array('id' => $this->mdluserid)); $USER->access = get_user_accessdata($USER->id); }
function hasPasswordExpired($username) { $current_user = new user(); $usr_id = $current_user->retrieve_user_id($username); $current_user->retrieve($usr_id); $type = ''; if ($current_user->system_generated_password == '1') { $type = 'syst'; } if ($current_user->portal_only == '0') { global $mod_strings, $timedate; $res = $GLOBALS['sugar_config']['passwordsetting']; if ($type != '') { switch ($res[$type . 'expiration']) { case '1': global $timedate; if ($current_user->pwd_last_changed == '') { $current_user->pwd_last_changed = $timedate->nowDb(); $current_user->save(); } $expireday = $res[$type . 'expirationtype'] * $res[$type . 'expirationtime']; $expiretime = $timedate->fromUser($current_user->pwd_last_changed)->get("+{$expireday} days")->ts; if ($timedate->getNow()->ts < $expiretime) { return false; } else { $_SESSION['expiration_type'] = $mod_strings['LBL_PASSWORD_EXPIRATION_TIME']; return true; } break; case '2': $login = $current_user->getPreference('loginexpiration'); $current_user->setPreference('loginexpiration', $login + 1); $current_user->save(); if ($login + 1 >= $res[$type . 'expirationlogin']) { $_SESSION['expiration_type'] = $mod_strings['LBL_PASSWORD_EXPIRATION_LOGIN']; return true; } else { return false; } break; case '0': return false; break; } } } }
public function signup() { if ($this->validate()) { return $user; $user = new user(); $user->username = $this->email; $user->email = $this->email; $user->firstname = $this->fname; $user->lastname = $this->lname; $user->setPassword($this->password); $user->generateAuthKey(); \Yii::$app->mailer->compose(['html' => 'auth-html'], ['user' => $user])->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . 'motormetric'])->setTo($this->email)->setSubject('Authenticate your account ' . \Yii::$app->name)->send(); if ($user->save()) { $query2 = (new Query())->select('username')->from('user')->where('city=:city AND dealer=:deal', array(':city' => $this->city, ':deal' => 1)); $dealer = $query2->all(); $flag = 1; $car = $this->model_name; $use = new User(); $user = $this->email; $val = $use->findByUsername1($user); $color = $this->color; $variant = $this->variant; $city = $this->city; $otherr = $this->otherr; $delivery = $this->delivery; $urequest = new Userrequest(); $urequest->car_model = $car; $urequest->user_id = $val->id; $urequest->username = $val->username; $urequest->color = $color; $urequest->variant = $variant; $urequest->city = $city; $urequest->otherr = $otherr; $urequest->delivery = $delivery; $urequest->save(); \Yii::$app->mailer->compose(['html' => 'request-html'], ['user' => $val, 'req' => $urequest])->setFrom([\Yii::$app->params['supportEmail'] => 'motormetric' . ' robot'])->setTo($val->email)->setSubject('Your Request ' . $urequest->car_model)->send(); foreach ($dealer as $deal) { $request = new Carrequest(); $val1 = $use->findByUsername1($deal['username']); $request->car_model = $car; $request->user_id = $val->id; $request->user_name = $val->username; $request->dealer_name = $deal['username']; $request->color = $color; $request->variant = $variant; $request->city = $city; $request->dealer_id = $val1->id; $request->request_id = $urequest->id; $request->otherr = $urequest->otherr; \Yii::$app->mailer->compose(['html' => 'requestd-html'], ['user' => $val, 'req' => $urequest, 'deal' => $val1])->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name])->setTo($val1->email)->setSubject('New Request ' . $urequest->car_model)->send(); if (!$request->save()) { $flag = 0; } } if ($flag) { $request = new Carrequest(); return $request; } return $user; } } return null; }
/** * Test that a record can be modified, and that the corresponding Moodle * user is modified. */ public function test_canupdaterecordandsynctomoodle() { global $DB; require_once elispm::lib('lib.php'); $this->load_csv_data(); // Read a record. $src = new user(103, null, array(), false, array()); $src->reset_custom_field_list(); // Modify the data. $src->firstname = 'Testuser'; $src->lastname = 'One'; $src->field_sometext = 'boo'; $src->field_sometextfrompm = 'bla'; $src->save(); // Read it back. $retr = new user($src->id, null, array(), false, array()); $this->assertEquals($src->firstname, $retr->firstname); $this->assertEquals($src->lastname, $retr->lastname); // Check the Moodle user. $retr = $DB->get_record('user', array('id' => 100)); profile_load_data($retr); fix_moodle_profile_fields($retr); $this->assertEquals($src->firstname, $retr->firstname); $this->assertEquals($src->lastname, $retr->lastname); // Check custom fields. $result = new moodle_recordset_phpunit_datatable('user_info_data', $DB->get_records('user_info_data', null, '', 'id, userid, fieldid, data')); $dataset = new PHPUnit_Extensions_Database_DataSet_CsvDataSet(); $dataset->addTable('user_info_data', elispm::file('tests/fixtures/user_info_data.csv')); $dataset = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($dataset); // Only the second text field should be changed; everything else should be the same. $dataset->addFullReplacement('Second text entry field', 'bla'); $this->assertTablesEqual($dataset->getTable('user_info_data'), $result); }
} else { $filled['password'] = TRUE; } } $isfilled = TRUE; } else { $error['top'] .= "<p>Both passwords must be identical.</p>"; $error['password2'] = "Both passwords must be identical."; } if ($isfilled == TRUE && $filled['username'] == TRUE && $filled['email'] == TRUE && $filled['password'] == TRUE) { $user = new user($sql, "username", $_POST['username']); $user->email = $_POST['email']; $user->membersince = currentTime(); $user->logLogin(); if ($user->changePW($_POST['password'])) { if ($user->save()) { $user->load(); $_SESSION['userid'] = $user->id; $pagecontent .= ' <div class="notification green"> <p>Your account has been created.</p> </div>'; } else { $pagecontent .= ' <div class="notification red"> <p>Failed to save user.</p> </div>'; } } else { $pagecontent .= ' <div class="notification red">