public function __construct($username, $realname = 'Real Name', $email = 'sample@example.com', $groups = array())
{
$this->assertNotReal();
$this->username = $username;
$this->password = 'TestUser';
$this->user = User::newFromName($this->username);
$this->user->load();
// In an ideal world we'd have a new wiki (or mock data store) for every single test.
// But for now, we just need to create or update the user with the desired properties.
// we particularly need the new password, since we just generated it randomly.
// In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
if (!$this->user->isLoggedIn()) {
// create the user
$this->user = User::createNew($this->username, array("email" => $email, "real_name" => $realname));
if (!$this->user) {
throw new MWException("Error creating TestUser " . $username);
}
}
// Update the user to use the password and other details
$change = $this->setPassword($this->password) || $this->setEmail($email) || $this->setRealName($realname);
// Adjust groups by adding any missing ones and removing any extras
$currentGroups = $this->user->getGroups();
foreach (array_diff($groups, $currentGroups) as $group) {
$this->user->addGroup($group);
}
foreach (array_diff($currentGroups, $groups) as $group) {
$this->user->removeGroup($group);
}
if ($change) {
$this->user->saveSettings();
}
}
protected function setUp()
{
parent::setUp();
$this->setMwGlobals(array('wgGroupPermissions' => array(), 'wgRevokePermissions' => array()));
$this->setUpPermissionGlobals();
$this->user = new User();
$this->user->addGroup('unittesters');
}
public function testGroup()
{
$groupTest = new Group("TEST_GROUP");
$groupTest2 = new Group("TEST_GROUP_2");
$this->assertEmpty($this->user->getGroup());
$this->user->addGroup($groupTest);
$this->assertEquals($groupTest, $this->user->getGroup()->first());
$this->user->addGroup($groupTest2);
$this->assertEquals(2, $this->user->getGroup()->count());
$this->user->removeGroup($groupTest);
$this->assertEquals(1, $this->user->getGroup()->count());
$this->assertEquals($groupTest2, $this->user->getGroup()->first());
}
public static function provideAssert()
{
$anon = new User();
$bot = new User();
$bot->setName('Bot');
$bot->addToDatabase();
$bot->addGroup('bot');
$user = new User();
$user->setName('User');
$user->addToDatabase();
return array(array($anon, 'user', 'assertuserfailed'), array($user, 'user', false), array($user, 'bot', 'assertbotfailed'), array($bot, 'user', false), array($bot, 'bot', false));
}
public function __construct($username, $realname = 'Real Name', $email = 'sample@example.com', $groups = [])
{
$this->assertNotReal();
$this->username = $username;
$this->password = 'TestUser';
$this->user = User::newFromName($this->username);
$this->user->load();
// In an ideal world we'd have a new wiki (or mock data store) for every single test.
// But for now, we just need to create or update the user with the desired properties.
// we particularly need the new password, since we just generated it randomly.
// In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
if (!$this->user->isLoggedIn()) {
// create the user
$this->user = User::createNew($this->username, ["email" => $email, "real_name" => $realname]);
if (!$this->user) {
throw new MWException("Error creating TestUser " . $username);
}
}
// Update the user to use the password and other details
$this->setPassword($this->password);
$change = $this->setEmail($email) || $this->setRealName($realname);
// Adjust groups by adding any missing ones and removing any extras
$currentGroups = $this->user->getGroups();
foreach (array_diff($groups, $currentGroups) as $group) {
$this->user->addGroup($group);
}
foreach (array_diff($currentGroups, $groups) as $group) {
$this->user->removeGroup($group);
}
if ($change) {
// Disable CAS check before saving. The User object may have been initialized from cached
// information that may be out of whack with the database during testing. If tests were
// perfectly isolated, this would not happen. But if it does happen, let's just ignore the
// inconsistency, and just write the data we want - during testing, we are not worried
// about data loss.
$this->user->mTouched = '';
$this->user->saveSettings();
}
}
/**
* @covers User::getRights
*/
public function testUserGetRightsHooks()
{
$user = new User();
$user->addGroup('unittesters');
$user->addGroup('testwriters');
$userWrapper = TestingAccessWrapper::newFromObject($user);
$rights = $user->getRights();
$this->assertContains('test', $rights, 'sanity check');
$this->assertContains('runtest', $rights, 'sanity check');
$this->assertContains('writetest', $rights, 'sanity check');
$this->assertNotContains('nukeworld', $rights, 'sanity check');
// Add a hook manipluating the rights
$this->mergeMwGlobalArrayValue('wgHooks', ['UserGetRights' => [function ($user, &$rights) {
$rights[] = 'nukeworld';
$rights = array_diff($rights, ['writetest']);
}]]);
$userWrapper->mRights = null;
$rights = $user->getRights();
$this->assertContains('test', $rights);
$this->assertContains('runtest', $rights);
$this->assertNotContains('writetest', $rights);
$this->assertContains('nukeworld', $rights);
// Add a Session that limits rights
$mock = $this->getMockBuilder(stdclass::class)->setMethods(['getAllowedUserRights', 'deregisterSession', 'getSessionId'])->getMock();
$mock->method('getAllowedUserRights')->willReturn(['test', 'writetest']);
$mock->method('getSessionId')->willReturn(new MediaWiki\Session\SessionId(str_repeat('X', 32)));
$session = MediaWiki\Session\TestUtils::getDummySession($mock);
$mockRequest = $this->getMockBuilder(FauxRequest::class)->setMethods(['getSession'])->getMock();
$mockRequest->method('getSession')->willReturn($session);
$userWrapper->mRequest = $mockRequest;
$userWrapper->mRights = null;
$rights = $user->getRights();
$this->assertContains('test', $rights);
$this->assertNotContains('runtest', $rights);
$this->assertNotContains('writetest', $rights);
$this->assertNotContains('nukeworld', $rights);
}
public function testSerialize()
{
$group = new Group();
$group->setName('Developers');
$user = new User();
$user->setEmail('foobar@example.com');
$user->setPassword('123456');
$user->addGroup($group);
$user->save();
$userId = $user->getId();
$this->assertInternalType('int', $userId);
$serialized = serialize($user);
UserPeer::clearInstancePool();
$this->assertCount(0, UserPeer::$instances);
$unserialized = unserialize($serialized);
$fetchedUser = UserQuery::create()->findOneById($userId);
$this->assertInstanceOf('FOS\\UserBundle\\Propel\\User', $unserialized);
$this->assertCount(1, UserPeer::$instances);
$this->assertTrue($fetchedUser->equals($unserialized));
$this->assertCount(1, $unserialized->getGroups());
}
private function setUpUser()
{
$this->user = new User();
$this->user->addGroup('unittesters');
}
/**
* Add given user to group
*
* @param User $user
*/
public function addUser(User $user)
{
$user->addGroup($this);
$this->users[] = $user;
}
/**
* @covers WikiPage::doRollback
*/
public function testDoRollbackFailureSameContent()
{
$admin = new User();
$admin->setName("Admin");
$admin->addGroup("sysop");
#XXX: make the test user a sysop...
$text = "one";
$page = $this->newPage("WikiPageTest_testDoRollback");
$page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "section one", EDIT_NEW, false, $admin);
$rev1 = $page->getRevision();
$user1 = new User();
$user1->setName("127.0.1.11");
$user1->addGroup("sysop");
#XXX: make the test user a sysop...
$text .= "\n\ntwo";
$page = new WikiPage($page->getTitle());
$page->doEditContent(ContentHandler::makeContent($text, $page->getTitle(), CONTENT_MODEL_WIKITEXT), "adding section two", 0, false, $user1);
# now, do a the rollback from the same user was doing the edit before
$resultDetails = array();
$token = $user1->getEditToken(array($page->getTitle()->getPrefixedText(), $user1->getName()), null);
$errors = $page->doRollback($user1->getName(), "testing revert same user", $token, false, $resultDetails, $admin);
$this->assertEquals(array(), $errors, "Rollback failed same user");
# now, try the rollback
$resultDetails = array();
$token = $admin->getEditToken(array($page->getTitle()->getPrefixedText(), $user1->getName()), null);
$errors = $page->doRollback($user1->getName(), "testing revert", $token, false, $resultDetails, $admin);
$this->assertEquals(array(array('alreadyrolled', 'WikiPageTest testDoRollback', '127.0.1.11', 'Admin')), $errors, "Rollback not failed");
$page = new WikiPage($page->getTitle());
$this->assertEquals($rev1->getSha1(), $page->getRevision()->getSha1(), "rollback did not revert to the correct revision");
$this->assertEquals("one", $page->getContent()->getNativeData());
}
/**
* Helper function for updateUser() and initUser(). Adds users into MediaWiki security groups
* based upon groups retreived from LDAP.
*
* @param User $user
* @access private
*/
function setGroups(&$user)
{
global $wgGroupPermissions;
// TODO: this is *really* ugly code. clean it up!
$this->printDebug("Entering setGroups.", NONSENSITIVE);
# Add ldap groups as local groups
if ($this->getConf('GroupsPrevail')) {
$this->printDebug("Adding all groups to wgGroupPermissions: ", SENSITIVE, $this->allLDAPGroups);
foreach ($this->allLDAPGroups["short"] as $ldapgroup) {
if (!array_key_exists($ldapgroup, $wgGroupPermissions)) {
$wgGroupPermissions[$ldapgroup] = array();
}
}
}
# add groups permissions
$localAvailGrps = $user->getAllGroups();
$localUserGrps = $user->getEffectiveGroups();
$defaultLocallyManagedGrps = array('bot', 'sysop', 'bureaucrat');
$locallyManagedGrps = $this->getConf('LocallyManagedGroups');
if ($locallyManagedGrps) {
$locallyManagedGrps = array_unique(array_merge($defaultLocallyManagedGrps, $locallyManagedGrps));
$this->printDebug("Locally managed groups: ", SENSITIVE, $locallyManagedGrps);
} else {
$locallyManagedGrps = $defaultLocallyManagedGrps;
$this->printDebug("Locally managed groups is unset, using defaults: ", SENSITIVE, $locallyManagedGrps);
}
$this->printDebug("Available groups are: ", NONSENSITIVE, $localAvailGrps);
$this->printDebug("Effective groups are: ", NONSENSITIVE, $localUserGrps);
# note: $localUserGrps does not need to be updated with $cGroup added,
# as $localAvailGrps contains $cGroup only once.
foreach ($localAvailGrps as $cGroup) {
# did we once add the user to the group?
if (in_array($cGroup, $localUserGrps)) {
$this->printDebug("Checking to see if we need to remove user from: {$cGroup}", NONSENSITIVE);
if (!$this->hasLDAPGroup($cGroup) && !in_array($cGroup, $locallyManagedGrps)) {
$this->printDebug("Removing user from: {$cGroup}", NONSENSITIVE);
# the ldap group overrides the local group
# so as the user is currently not a member of the ldap group, he shall be removed from the local group
$user->removeGroup($cGroup);
}
} else {
# no, but maybe the user has recently been added to the ldap group?
$this->printDebug("Checking to see if user is in: {$cGroup}", NONSENSITIVE);
if ($this->hasLDAPGroup($cGroup)) {
$this->printDebug("Adding user to: {$cGroup}", NONSENSITIVE);
$user->addGroup($cGroup);
}
}
}
}
public function register()
{
// POST: user_name, display_name, email, title, password, passwordc, captcha, spiderbro, csrf_token
$post = $this->_app->request->post();
// Get the alert message stream
$ms = $this->_app->alerts;
// Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
$ms->addMessage("danger", "Aww hellllls no!");
$this->_app->halt(500);
// Don't let on about why the request failed ;-)
}
// Load the request schema
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
// Set up Fortress to process the request
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
// Security measure: do not allow registering new users until the master account has been created.
if (!UserLoader::exists($this->_app->config('user_id_master'))) {
$ms->addMessageTranslated("danger", "MASTER_ACCOUNT_NOT_EXISTS");
$this->_app->halt(403);
}
// Check if registration is currently enabled
if (!$this->_app->site->can_register) {
$ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_DISABLED");
$this->_app->halt(403);
}
// Prevent the user from registering if he/she is already logged in
if (!$this->_app->user->isGuest()) {
$ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_LOGOUT");
$this->_app->halt(200);
}
// Sanitize data
$rf->sanitize();
// Validate, and halt on validation errors.
$error = !$rf->validate(true);
// Get the filtered data
$data = $rf->data();
// Check captcha, if required
if ($this->_app->site->enable_captcha == "1") {
if (!$data['captcha'] || md5($data['captcha']) != $_SESSION['userfrosting']['captcha']) {
$ms->addMessageTranslated("danger", "CAPTCHA_FAIL");
$error = true;
}
}
// Remove captcha, password confirmation from object data
$rf->removeFields(['captcha', 'passwordc']);
// Perform desired data transformations. Is this a feature we could add to Fortress?
$data['user_name'] = strtolower(trim($data['user_name']));
$data['display_name'] = trim($data['display_name']);
$data['email'] = strtolower(trim($data['email']));
$data['locale'] = $this->_app->site->default_locale;
if ($this->_app->site->require_activation) {
$data['active'] = 0;
} else {
$data['active'] = 1;
}
// Check if username or email already exists
if (UserLoader::exists($data['user_name'], 'user_name')) {
$ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
$error = true;
}
if (UserLoader::exists($data['email'], 'email')) {
$ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
$error = true;
}
// Halt on any validation errors
if ($error) {
$this->_app->halt(400);
}
// Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
$primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
$data['primary_group_id'] = $primaryGroup->id;
// Set default title for new users
$data['title'] = $primaryGroup->new_user_title;
// Hash password
$data['password'] = Authentication::hashPassword($data['password']);
// Create the user
$user = new User($data);
// Add user to default groups, including default primary group
$defaultGroups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
$user->addGroup($primaryGroup->id);
foreach ($defaultGroups as $group_id => $group) {
$user->addGroup($group_id);
}
// Store new user to database
$user->store();
if ($this->_app->site->require_activation) {
// Create and send activation email
$mail = new \PHPMailer();
$mail->From = $this->_app->site->admin_email;
$mail->FromName = $this->_app->site->site_title;
$mail->addAddress($user->email);
// Add a recipient
$mail->addReplyTo($this->_app->site->admin_email, $this->_app->site->site_title);
$mail->Subject = $this->_app->site->site_title . " - please activate your account";
$mail->Body = $this->_app->view()->render("common/mail/activate-new.html", ["user" => $user]);
$mail->isHTML(true);
// Set email format to HTML
if (!$mail->send()) {
$ms->addMessageTranslated("danger", "MAIL_ERROR");
error_log('Mailer Error: ' . $mail->ErrorInfo);
$this->_app->halt(500);
}
// Activation required
$ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
// No activation required
$ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
/**
* When a user logs in, optionally fill in preferences and such.
* For instance, you might pull the email address or real name from the
* external user database.
*
* The User object is passed by reference so it can be modified; don't
* forget the & on your function declaration.
*
* @param User $user
* @access public
*/
function updateUser(&$user)
{
if (!is_resource($this->db)) {
$this->openDB();
}
$query = mysql_query("SELECT username,email,usergroup,additionalgroups FROM {$this->table_prefix}users WHERE username='" . $this->escape_string($user->mName) . "'", $this->db);
$res = mysql_fetch_array($query);
if ($res) {
if (in_array($res['usergroup'], $this->admin_usergroups)) {
$is_admin = true;
}
$memberships = explode(",", $res['additionalgroups']);
for ($i = 0; $i < count($memberships); $i++) {
if (in_array($memberships[$x], $this->admin_usergroups)) {
$is_admin = true;
}
}
if ($is_admin == true) {
// If a user is not a sysop, make them a sysop
if (!in_array("sysop", $user->getEffectiveGroups())) {
$user->addGroup('sysop');
}
} else {
if (in_array("sysop", $user->getEffectiveGroups())) {
$user->removeGroup('sysop');
return TRUE;
}
}
$user->setEmail($res['email']);
$user->setRealName($res['username']);
return TRUE;
}
return false;
}
/**
* Processes the request to create a new user (from the admin controls).
*
* Processes the request from the user creation form, checking that:
* 1. The username and email are not already in use;
* 2. The logged-in user has the necessary permissions to update the posted field(s);
* 3. The submitted data is valid.
* This route requires authentication.
* Request type: POST
* @see formUserCreate
*/
public function createUser()
{
$post = $this->_app->request->post();
// Load the request schema
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/user-create.json");
// Get the alert message stream
$ms = $this->_app->alerts;
// Access-controlled resource
if (!$this->_app->user->checkAccess('create_account')) {
$ms->addMessageTranslated("danger", "ACCESS_DENIED");
$this->_app->halt(403);
}
// Set up Fortress to process the request
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
// Sanitize data
$rf->sanitize();
// Validate, and halt on validation errors.
$error = !$rf->validate(true);
// Get the filtered data
$data = $rf->data();
// Remove csrf_token from object data
$rf->removeFields(['csrf_token']);
// Perform desired data transformations on required fields. Is this a feature we could add to Fortress?
$data['display_name'] = trim($data['display_name']);
$data['email'] = strtolower(trim($data['email']));
$data['flag_verified'] = 1;
// Set password as empty on initial creation. We will then send email so new user can set it themselves via secret token
$data['password'] = "";
// Check if username or email already exists
if (UserLoader::exists($data['user_name'], 'user_name')) {
$ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
$error = true;
}
if (UserLoader::exists($data['email'], 'email')) {
$ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
$error = true;
}
// Halt on any validation errors
if ($error) {
$this->_app->halt(400);
}
// Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
$primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
// Set default values if not specified or not authorized
if (!isset($data['locale']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "locale"])) {
$data['locale'] = $this->_app->site->default_locale;
}
if (!isset($data['title']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "title"])) {
// Set default title for new users
$data['title'] = $primaryGroup->new_user_title;
}
if (!isset($data['primary_group_id']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "primary_group_id"])) {
$data['primary_group_id'] = $primaryGroup->id;
}
// Set groups to default groups if not specified or not authorized to set groups
if (!isset($data['groups']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "groups"])) {
$default_groups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
$data['groups'] = [];
foreach ($default_groups as $group_id => $group) {
$data['groups'][$group_id] = "1";
}
}
// Create the user
$user = new User($data);
// Add user to groups, including selected primary group
$user->addGroup($data['primary_group_id']);
foreach ($data['groups'] as $group_id => $is_member) {
if ($is_member == "1") {
$user->addGroup($group_id);
}
}
// Create events - account creation and password reset
$user->newEventSignUp($this->_app->user);
$user->newEventPasswordReset();
// Save user again after creating events
$user->save();
// Send an email to the user's email address to set up password
$twig = $this->_app->view()->getEnvironment();
$template = $twig->loadTemplate("mail/password-create.twig");
$notification = new Notification($template);
$notification->fromWebsite();
// Automatically sets sender and reply-to
$notification->addEmailRecipient($user->email, $user->display_name, ['user' => $user, 'create_password_expiration' => $this->_app->site->create_password_expiration / 3600 . " hours"]);
try {
$notification->send();
} catch (\Exception\phpmailerException $e) {
$ms->addMessageTranslated("danger", "MAIL_ERROR");
error_log('Mailer Error: ' . $e->errorMessage());
$this->_app->halt(500);
}
// Success message
$ms->addMessageTranslated("success", "ACCOUNT_CREATION_COMPLETE", $data);
}
/**
* Add groups based on the existence of attributes in the SAML assertion.
*
* @param User $user add MediaWiki permissions to this user from the current SAML assertion
*
* @return void $user is modified on return
*/
protected static function setGroups(User $user)
{
global $wgSamlGroupMap;
$attr = self::$as->getAttributes();
foreach ($wgSamlGroupMap as $group => $rules) {
foreach ($rules as $attrName => $needles) {
if (!isset($attr[$attrName])) {
continue;
}
foreach ($needles as $needle) {
if (in_array($needle, $attr[$attrName])) {
$user->addGroup($group);
} else {
$user->removeGroup($group);
}
}
}
}
}
/**
* On every page load, the user's permissions are recalculated. They are based
* upon the groups to which the user belongs.
*/
function manageMediawikiGroupsForUser(User $mediawiki_user, PFUser $tuleap_user, Group $group)
{
$groups_mapper = new MediawikiUserGroupsMapper(new MediawikiDao(), new User_ForgeUserGroupPermissionsDao());
$mediawiki_groups = $groups_mapper->defineUserMediawikiGroups($tuleap_user, $group);
foreach ($mediawiki_groups['removed'] as $group_to_remove) {
$mediawiki_user->removeGroup($group_to_remove);
}
foreach ($mediawiki_groups['added'] as $group_to_add) {
$mediawiki_user->addGroup($group_to_add);
}
return $mediawiki_user;
}
/**
* Helper function for updateUser() and initUser(). Adds users into MediaWiki security groups
* based upon groups retreived from LDAP.
*
* @param User $user
* @access private
*/
function setGroups(&$user)
{
$this->printDebug("Pulling groups from LDAP.", 1);
# add groups permissions
$localAvailGrps = $user->getAllGroups();
$localUserGrps = $user->getEffectiveGroups();
$this->printDebug("Available groups are: " . implode(",", $localAvailGrps) . "", 1);
$this->printDebug("Effective groups are: " . implode(",", $localUserGrps) . "", 1);
# note: $localUserGrps does not need to be updated with $cGroup added,
# as $localAvailGrps contains $cGroup only once.
foreach ($localAvailGrps as $cGroup) {
# did we once add the user to the group?
if (in_array($cGroup, $localUserGrps)) {
$this->printDebug("Checking to see if we need to remove user from: {$cGroup}", 1);
if (!$this->hasLDAPGroup($cGroup) && $this->isLDAPGroup($cGroup)) {
$this->printDebug("Removing user from: {$cGroup}", 1);
# the ldap group overrides the local group
# so as the user is currently not a member of the ldap group, he shall be removed from the local group
$user->removeGroup($cGroup);
}
} else {
# no, but maybe the user has recently been added to the ldap group?
$this->printDebug("Checking to see if user is in: {$cGroup}", 1);
if ($this->hasLDAPGroup($cGroup)) {
$this->printDebug("Adding user to: {$cGroup}", 1);
# so use the addGroup function
$user->addGroup($cGroup);
# completedfor $cGroup.
}
}
}
}
/**
* When a user logs in, optionally fill in preferences and such.
* For instance, you might pull the email address or real name from the
* external user database.
*
* The User object is passed by reference so it can be modified; don't
* forget the & on your function declaration.
*
* @param User $user
* @public
*/
function updateUser(&$user)
{
if ($this->debug) {
echo 'updateUser';
}
$username = addslashes($user->getName());
$find_user_query = "SELECT\n\t\t\tuser_id,\n\t\t\tuser_accesslevel, user_email, \n\t\t\tuser_name_short, user_name\n\t\t\tFROM users WHERE lower(user_name_short)=lower('{$username}')";
$find_result = mysql_query($find_user_query, $this->database);
// make sure that there is only one person with the username
if (mysql_num_rows($find_result) == 1) {
$userinfo = mysql_fetch_assoc($find_result);
mysql_free_result($find_result);
$user->setEmail($userinfo['user_email']);
$user->confirmEmail();
$user->setRealName($userinfo['user_name']);
// Accessrights
if ($userinfo['user_accesslevel'] > 2) {
$user->addGroup('sysop');
}
$user->saveSettings();
return true;
}
return false;
}
/**
* Put the user in the effective group 'artist' if she is not already in.
* @param User $user
* @return boolean false if she is already in the group, true if just added
*/
private static function addSubscribersGroupToUser($user)
{
if (!in_array(WP_SUBSCRIBERS_USER_GROUP, $user->getGroups())) {
$user->addGroup(WP_SUBSCRIBERS_USER_GROUP);
return true;
}
return false;
}
/**
* Save user groups changes in the database.
*
* @param User|UserRightsProxy $user
* @param array $add Array of groups to add
* @param array $remove Array of groups to remove
* @param string $reason Reason for group change
* @return array Tuple of added, then removed groups
*/
function doSaveUserGroups($user, $add, $remove, $reason = '')
{
global $wgAuth;
// Validate input set...
$isself = $user->getName() == $this->getUser()->getName();
$groups = $user->getGroups();
$changeable = $this->changeableGroups();
$addable = array_merge($changeable['add'], $isself ? $changeable['add-self'] : array());
$removable = array_merge($changeable['remove'], $isself ? $changeable['remove-self'] : array());
$remove = array_unique(array_intersect((array) $remove, $removable, $groups));
$add = array_unique(array_diff(array_intersect((array) $add, $addable), $groups));
$oldGroups = $user->getGroups();
$newGroups = $oldGroups;
// Remove then add groups
if ($remove) {
foreach ($remove as $index => $group) {
if (!$user->removeGroup($group)) {
unset($remove[$index]);
}
}
$newGroups = array_diff($newGroups, $remove);
}
if ($add) {
foreach ($add as $index => $group) {
if (!$user->addGroup($group)) {
unset($add[$index]);
}
}
$newGroups = array_merge($newGroups, $add);
}
$newGroups = array_unique($newGroups);
// Ensure that caches are cleared
$user->invalidateCache();
// update groups in external authentication database
Hooks::run('UserGroupsChanged', array($user, $add, $remove, $this->getUser()));
$wgAuth->updateExternalDBGroups($user, $add, $remove);
wfDebug('oldGroups: ' . print_r($oldGroups, true) . "\n");
wfDebug('newGroups: ' . print_r($newGroups, true) . "\n");
// Deprecated in favor of UserGroupsChanged hook
Hooks::run('UserRights', array(&$user, $add, $remove), '1.26');
if ($newGroups != $oldGroups) {
$this->addLogEntry($user, $oldGroups, $newGroups, $reason);
}
return array($add, $remove);
}
/**
* @covers AppBundle\Entity\User::addGroup
* Implement testAddGroup().
*/
public function testAddGroup()
{
$this->assertEmpty($this->user->getGroup());
$this->user->addGroup($this->group);
$this->assertNotEmpty($this->user->getGroup());
}
/**
* Processes a request to create the master account.
*
* Processes the request from the master account creation form, checking that:
* 1. The honeypot has not been changed;
* 2. The master account does not already exist;
* 3. The correct configuration token was submitted;
* 3. The submitted data is valid.
* This route is "public access" (until the master account has been created, that is)
* Request type: POST
*/
public function setupMasterAccount()
{
$post = $this->_app->request->post();
// Get the alert message stream
$ms = $this->_app->alerts;
// Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
$ms->addMessage("danger", "Aww hellllls no!");
$this->_app->halt(500);
// Don't let on about why the request failed ;-)
}
// Do not allow registering a master account if one has already been created
if (User::find($this->_app->config('user_id_master'))) {
$ms->addMessageTranslated("danger", "MASTER_ACCOUNT_EXISTS");
$this->_app->halt(403);
}
// Check the configuration token
if ($post['root_account_config_token'] != $this->_app->site->root_account_config_token) {
$ms->addMessageTranslated("danger", "CONFIG_TOKEN_MISMATCH");
$this->_app->halt(403);
}
// Load the request schema
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
// Set up Fortress to process the request
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
// Sanitize data
$rf->sanitize();
// Validate, and halt on validation errors.
$error = !$rf->validate(true);
// Get the filtered data
$data = $rf->data();
// Remove configuration token, password confirmation from object data
$rf->removeFields(['root_account_config_token', 'passwordc']);
// Perform desired data transformations. Is this a feature we could add to Fortress?
$data['display_name'] = trim($data['display_name']);
$data['flag_verified'] = 1;
$data['locale'] = $this->_app->site->default_locale;
// Halt on any validation errors
if ($error) {
$this->_app->halt(400);
}
// Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
$primaryGroup = Group::where('is_default', GROUP_DEFAULT_PRIMARY)->first();
$data['primary_group_id'] = $primaryGroup->id;
// Set default title for new users
$data['title'] = $primaryGroup->new_user_title;
// Hash password
$data['password'] = Authentication::hashPassword($data['password']);
// Create the master user
$user = new User($data);
$user->id = $this->_app->config('user_id_master');
// Add user to default groups, including default primary group
$defaultGroups = Group::where('is_default', GROUP_DEFAULT)->get();
$user->addGroup($primaryGroup->id);
foreach ($defaultGroups as $group) {
$group_id = $group->id;
$user->addGroup($group_id);
}
// Add sign-up event
$user->newEventSignUp();
// Store new user to database
$user->save();
// No activation required
$ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
// Update install status
$this->_app->site->install_status = "new";
$this->_app->site->root_account_config_token = "";
$this->_app->site->store();
}
/**
* Processes the request to create a new user (from the admin controls).
*
* Processes the request from the user creation form, checking that:
* 1. The username and email are not already in use;
* 2. The logged-in user has the necessary permissions to update the posted field(s);
* 3. The submitted data is valid.
* This route requires authentication.
* Request type: POST
* @see formUserCreate
*/
public function createUser()
{
$post = $this->_app->request->post();
// Load the request schema
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/user-create.json");
// Get the alert message stream
$ms = $this->_app->alerts;
// Access-controlled resource
if (!$this->_app->user->checkAccess('create_account')) {
$ms->addMessageTranslated("danger", "ACCESS_DENIED");
$this->_app->halt(403);
}
// Set up Fortress to process the request
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
// Sanitize data
$rf->sanitize();
// Validate, and halt on validation errors.
$error = !$rf->validate(true);
// Get the filtered data
$data = $rf->data();
// Remove csrf_token, password confirmation from object data
$rf->removeFields(['csrf_token, passwordc']);
// Perform desired data transformations on required fields. Is this a feature we could add to Fortress?
$data['user_name'] = strtolower(trim($data['user_name']));
$data['display_name'] = trim($data['display_name']);
$data['email'] = strtolower(trim($data['email']));
$data['active'] = 1;
// Check if username or email already exists
if (UserLoader::exists($data['user_name'], 'user_name')) {
$ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
$error = true;
}
if (UserLoader::exists($data['email'], 'email')) {
$ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
$error = true;
}
// Halt on any validation errors
if ($error) {
$this->_app->halt(400);
}
// Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
$primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
// Set default values if not specified or not authorized
if (!isset($data['locale']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "locale"])) {
$data['locale'] = $this->_app->site->default_locale;
}
if (!isset($data['title']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "title"])) {
// Set default title for new users
$data['title'] = $primaryGroup->new_user_title;
}
if (!isset($data['primary_group_id']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "primary_group_id"])) {
$data['primary_group_id'] = $primaryGroup->id;
}
// Set groups to default groups if not specified or not authorized to set groups
if (!isset($data['groups']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "groups"])) {
$default_groups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
$data['groups'] = [];
foreach ($default_groups as $group_id => $group) {
$data['groups'][$group_id] = "1";
}
}
// Hash password
$data['password'] = Authentication::hashPassword($data['password']);
// Create the user
$user = new User($data);
// Add user to groups, including selected primary group
$user->addGroup($data['primary_group_id']);
foreach ($data['groups'] as $group_id => $is_member) {
if ($is_member == "1") {
$user->addGroup($group_id);
}
}
// Store new user to database
$user->store();
// Success message
$ms->addMessageTranslated("success", "ACCOUNT_CREATION_COMPLETE", $data);
}
/**
* Processes an new account registration request.
*
* Processes the request from the form on the registration page, checking that:
* 1. The honeypot was not modified;
* 2. The master account has already been created (during installation);
* 3. Account registration is enabled;
* 4. The user is not already logged in;
* 5. Valid information was entered;
* 6. The captcha, if enabled, is correct;
* 7. The username and email are not already taken.
* Automatically sends an activation link upon success, if account activation is enabled.
* This route is "public access".
* Request type: POST
* Returns the User Object for the user record that was created.
*/
public function register()
{
// POST: user_name, display_name, email, title, password, passwordc, captcha, spiderbro, csrf_token
$post = $this->_app->request->post();
// Get the alert message stream
$ms = $this->_app->alerts;
// Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
$ms->addMessage("danger", "Aww hellllls no!");
$this->_app->halt(500);
// Don't let on about why the request failed ;-)
}
// Load the request schema
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
// Set up Fortress to process the request
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
// Security measure: do not allow registering new users until the master account has been created.
if (!User::find($this->_app->config('user_id_master'))) {
$ms->addMessageTranslated("danger", "MASTER_ACCOUNT_NOT_EXISTS");
$this->_app->halt(403);
}
// Check if registration is currently enabled
if (!$this->_app->site->can_register) {
$ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_DISABLED");
$this->_app->halt(403);
}
// Prevent the user from registering if he/she is already logged in
if (!$this->_app->user->isGuest()) {
$ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_LOGOUT");
$this->_app->halt(200);
}
// Sanitize data
$rf->sanitize();
// Validate, and halt on validation errors.
$error = !$rf->validate(true);
// Get the filtered data
$data = $rf->data();
// Check captcha, if required
if ($this->_app->site->enable_captcha == "1") {
if (!$data['captcha'] || md5($data['captcha']) != $_SESSION['userfrosting']['captcha']) {
$ms->addMessageTranslated("danger", "CAPTCHA_FAIL");
$error = true;
}
}
// Remove captcha, password confirmation from object data
$rf->removeFields(['captcha', 'passwordc']);
// Perform desired data transformations. Is this a feature we could add to Fortress?
$data['display_name'] = trim($data['display_name']);
$data['locale'] = $this->_app->site->default_locale;
if ($this->_app->site->require_activation) {
$data['flag_verified'] = 0;
} else {
$data['flag_verified'] = 1;
}
// Check if username or email already exists
if (User::where('user_name', $data['user_name'])->first()) {
$ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
$error = true;
}
if (User::where('email', $data['email'])->first()) {
$ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
$error = true;
}
// Halt on any validation errors
if ($error) {
$this->_app->halt(400);
}
// Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
$primaryGroup = Group::where('is_default', GROUP_DEFAULT_PRIMARY)->first();
// Check that a default primary group is actually set
if (!$primaryGroup) {
$ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_BROKEN");
error_log("Account registration is not working because a default primary group has not been set.");
$this->_app->halt(500);
}
$data['primary_group_id'] = $primaryGroup->id;
// Set default title for new users
$data['title'] = $primaryGroup->new_user_title;
// Hash password
$data['password'] = Authentication::hashPassword($data['password']);
// Create the user
$user = new User($data);
// Add user to default groups, including default primary group
$defaultGroups = Group::where('is_default', GROUP_DEFAULT)->get();
$user->addGroup($primaryGroup->id);
foreach ($defaultGroups as $group) {
$user->addGroup($group->id);
}
// Create sign-up event
$user->newEventSignUp();
// Store new user to database
$user->save();
if ($this->_app->site->require_activation) {
// Create verification request event
$user->newEventVerificationRequest();
$user->save();
// Re-save with verification event
// Create and send verification email
$twig = $this->_app->view()->getEnvironment();
$template = $twig->loadTemplate("mail/activate-new.twig");
$notification = new Notification($template);
$notification->fromWebsite();
// Automatically sets sender and reply-to
$notification->addEmailRecipient($user->email, $user->display_name, ["user" => $user]);
try {
$notification->send();
} catch (\phpmailerException $e) {
$ms->addMessageTranslated("danger", "MAIL_ERROR");
error_log('Mailer Error: ' . $e->errorMessage());
$this->_app->halt(500);
}
$ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
// No activation required
$ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
// Return the user object to the calling program
return $user;
}
function actaddgroup()
{
$model = new User();
$model->addGroup();
$this->redirect('/user/group/');
}