本文整理汇总了PHP中User::addGroup方法的典型用法代码示例。如果您正苦于以下问题:PHP User::addGroup方法的具体用法?PHP User::addGroup怎么用?PHP User::addGroup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类User
的用法示例。
在下文中一共展示了User::addGroup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
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();
}
}
示例2: setUp
protected function setUp()
{
parent::setUp();
$this->setMwGlobals(array('wgGroupPermissions' => array(), 'wgRevokePermissions' => array()));
$this->setUpPermissionGlobals();
$this->user = new User();
$this->user->addGroup('unittesters');
}
示例3: testGroup
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());
}
示例4: provideAssert
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));
}
示例5: __construct
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();
}
}
示例6: testUserGetRightsHooks
/**
* @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);
}
示例7: testSerialize
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());
}
示例8: setUpUser
private function setUpUser()
{
$this->user = new User();
$this->user->addGroup('unittesters');
}
示例9: addUser
/**
* Add given user to group
*
* @param User $user
*/
public function addUser(User $user)
{
$user->addGroup($this);
$this->users[] = $user;
}
示例10: testDoRollbackFailureSameContent
/**
* @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());
}
示例11: setGroups
/**
* 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);
}
}
}
}
示例12: register
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()) {
//.........这里部分代码省略.........
示例13: updateUser
/**
* 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;
}
示例14: createUser
/**
* 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);
//.........这里部分代码省略.........
示例15: setGroups
/**
* 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);
}
}
}
}
}