3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\Block\Restriction\PageRestriction
;
7 use MediaWiki\Block\Restriction\NamespaceRestriction
;
8 use MediaWiki\MediaWikiServices
;
9 use MediaWiki\User\UserIdentityValue
;
10 use Wikimedia\TestingAccessWrapper
;
15 class UserTest
extends MediaWikiTestCase
{
17 /** Constant for self::testIsBlockedFrom */
18 const USER_TALK_PAGE
= '<user talk page>';
25 protected function setUp() {
28 $this->setMwGlobals( [
29 'wgGroupPermissions' => [],
30 'wgRevokePermissions' => [],
31 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
33 $this->overrideMwServices();
35 $this->setUpPermissionGlobals();
37 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
40 private function setUpPermissionGlobals() {
41 global $wgGroupPermissions, $wgRevokePermissions;
43 # Data for regular $wgGroupPermissions test
44 $wgGroupPermissions['unittesters'] = [
50 $wgGroupPermissions['testwriters'] = [
56 # Data for regular $wgRevokePermissions test
57 $wgRevokePermissions['formertesters'] = [
61 # For the options test
62 $wgGroupPermissions['*'] = [
63 'editmyoptions' => true,
68 * @covers User::getGroupPermissions
70 public function testGroupPermissions() {
71 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
72 $this->assertContains( 'runtest', $rights );
73 $this->assertNotContains( 'writetest', $rights );
74 $this->assertNotContains( 'modifytest', $rights );
75 $this->assertNotContains( 'nukeworld', $rights );
77 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
78 $this->assertContains( 'runtest', $rights );
79 $this->assertContains( 'writetest', $rights );
80 $this->assertContains( 'modifytest', $rights );
81 $this->assertNotContains( 'nukeworld', $rights );
85 * @covers User::getGroupPermissions
87 public function testRevokePermissions() {
88 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
89 $this->assertNotContains( 'runtest', $rights );
90 $this->assertNotContains( 'writetest', $rights );
91 $this->assertNotContains( 'modifytest', $rights );
92 $this->assertNotContains( 'nukeworld', $rights );
96 * @covers User::getRights
98 public function testUserPermissions() {
99 $rights = $this->user
->getRights();
100 $this->assertContains( 'runtest', $rights );
101 $this->assertNotContains( 'writetest', $rights );
102 $this->assertNotContains( 'modifytest', $rights );
103 $this->assertNotContains( 'nukeworld', $rights );
107 * @covers User::getRights
109 public function testUserGetRightsHooks() {
110 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
111 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
113 $rights = $user->getRights();
114 $this->assertContains( 'test', $rights, 'sanity check' );
115 $this->assertContains( 'runtest', $rights, 'sanity check' );
116 $this->assertContains( 'writetest', $rights, 'sanity check' );
117 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
119 // Add a hook manipluating the rights
120 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
121 $rights[] = 'nukeworld';
122 $rights = array_diff( $rights, [ 'writetest' ] );
125 $userWrapper->mRights
= null;
126 $rights = $user->getRights();
127 $this->assertContains( 'test', $rights );
128 $this->assertContains( 'runtest', $rights );
129 $this->assertNotContains( 'writetest', $rights );
130 $this->assertContains( 'nukeworld', $rights );
132 // Add a Session that limits rights
133 $mock = $this->getMockBuilder( stdClass
::class )
134 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
136 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
137 $mock->method( 'getSessionId' )->willReturn(
138 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
140 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
141 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
142 ->setMethods( [ 'getSession' ] )
144 $mockRequest->method( 'getSession' )->willReturn( $session );
145 $userWrapper->mRequest
= $mockRequest;
147 $userWrapper->mRights
= null;
148 $rights = $user->getRights();
149 $this->assertContains( 'test', $rights );
150 $this->assertNotContains( 'runtest', $rights );
151 $this->assertNotContains( 'writetest', $rights );
152 $this->assertNotContains( 'nukeworld', $rights );
156 * @dataProvider provideGetGroupsWithPermission
157 * @covers User::getGroupsWithPermission
159 public function testGetGroupsWithPermission( $expected, $right ) {
160 $result = User
::getGroupsWithPermission( $right );
164 $this->assertEquals( $expected, $result, "Groups with permission $right" );
167 public static function provideGetGroupsWithPermission() {
170 [ 'unittesters', 'testwriters' ],
189 * @dataProvider provideIPs
192 public function testIsIP( $value, $result, $message ) {
193 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
196 public static function provideIPs() {
198 [ '', false, 'Empty string' ],
199 [ ' ', false, 'Blank space' ],
200 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
201 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
202 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
203 [ '203.0.113.0', true, 'IPv4 example' ],
204 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
205 // Not valid IPs but classified as such by MediaWiki for negated asserting
206 // of whether this might be the identifier of a logged-out user or whether
207 // to allow usernames like it.
208 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
209 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
214 * @dataProvider provideUserNames
215 * @covers User::isValidUserName
217 public function testIsValidUserName( $username, $result, $message ) {
218 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
221 public static function provideUserNames() {
223 [ '', false, 'Empty string' ],
224 [ ' ', false, 'Blank space' ],
225 [ 'abcd', false, 'Starts with small letter' ],
226 [ 'Ab/cd', false, 'Contains slash' ],
227 [ 'Ab cd', true, 'Whitespace' ],
228 [ '192.168.1.1', false, 'IP' ],
229 [ '116.17.184.5/32', false, 'IP range' ],
230 [ '::e:f:2001/96', false, 'IPv6 range' ],
231 [ 'User:Abcd', false, 'Reserved Namespace' ],
232 [ '12abcd232', true, 'Starts with Numbers' ],
233 [ '?abcd', true, 'Start with ? mark' ],
234 [ '#abcd', false, 'Start with #' ],
235 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
236 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
237 [ 'Ab cd', false, ' Ideographic space' ],
238 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
239 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
240 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
245 * Test User::editCount
247 * @covers User::getEditCount
249 public function testGetEditCount() {
250 $user = $this->getMutableTestUser()->getUser();
252 // let the user have a few (3) edits
253 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
254 for ( $i = 0; $i < 3; $i++
) {
255 $page->doEditContent(
256 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
266 $user->getEditCount(),
267 'After three edits, the user edit count should be 3'
270 // increase the edit count
271 $user->incEditCount();
272 $user->clearInstanceCache();
276 $user->getEditCount(),
277 'After increasing the edit count manually, the user edit count should be 4'
282 * Test User::editCount
284 * @covers User::getEditCount
286 public function testGetEditCountForAnons() {
287 $user = User
::newFromName( 'Anonymous' );
290 $user->getEditCount(),
291 'Edit count starts null for anonymous users.'
294 $user->incEditCount();
297 $user->getEditCount(),
298 'Edit count remains null for anonymous users despite calls to increase it.'
303 * Test User::editCount
305 * @covers User::incEditCount
307 public function testIncEditCount() {
308 $user = $this->getMutableTestUser()->getUser();
309 $user->incEditCount();
311 $reloadedUser = User
::newFromId( $user->getId() );
312 $reloadedUser->incEditCount();
316 $reloadedUser->getEditCount(),
317 'Increasing the edit count after a fresh load leaves the object up to date.'
322 * Test changing user options.
323 * @covers User::setOption
324 * @covers User::getOption
326 public function testOptions() {
327 $user = $this->getMutableTestUser()->getUser();
329 $user->setOption( 'userjs-someoption', 'test' );
330 $user->setOption( 'rclimit', 200 );
331 $user->setOption( 'wpwatchlistdays', '0' );
332 $user->saveSettings();
334 $user = User
::newFromName( $user->getName() );
335 $user->load( User
::READ_LATEST
);
336 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
337 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
339 $user = User
::newFromName( $user->getName() );
340 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
341 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
342 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
344 // Check that an option saved as a string '0' is returned as an integer.
345 $user = User
::newFromName( $user->getName() );
346 $user->load( User
::READ_LATEST
);
347 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
352 * Make sure defaults are loaded when setOption is called.
353 * @covers User::loadOptions
355 public function testAnonOptions() {
356 global $wgDefaultUserOptions;
357 $this->user
->setOption( 'userjs-someoption', 'test' );
358 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
359 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
363 * Test password validity checks. There are 3 checks in core,
364 * - ensure the password meets the minimal length
365 * - ensure the password is not the same as the username
366 * - ensure the username/password combo isn't forbidden
367 * @covers User::checkPasswordValidity()
368 * @covers User::getPasswordValidity()
369 * @covers User::isValidPassword()
371 public function testCheckPasswordValidity() {
372 $this->setMwGlobals( [
373 'wgPasswordPolicy' => [
376 'MinimalPasswordLength' => 8,
377 'MinimumPasswordLengthToLogin' => 1,
378 'PasswordCannotMatchUsername' => 1,
381 'MinimalPasswordLength' => 6,
382 'PasswordCannotMatchUsername' => true,
383 'PasswordCannotMatchBlacklist' => true,
384 'MaximalPasswordLength' => 40,
388 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
389 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
390 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
391 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
392 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
396 $this->hideDeprecated( 'User::getPasswordValidity' );
398 $user = static::getTestUser()->getUser();
401 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
404 $this->assertFalse( $user->isValidPassword( 'a' ) );
405 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
406 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
407 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
410 $longPass = str_repeat( 'a', 41 );
411 $this->assertFalse( $user->isValidPassword( $longPass ) );
412 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
413 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
414 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
417 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
418 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
419 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
421 // On the forbidden list
422 $user = User
::newFromName( 'Useruser' );
423 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
424 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
428 * @covers User::getCanonicalName()
429 * @dataProvider provideGetCanonicalName
431 public function testGetCanonicalName( $name, $expectedArray ) {
432 // fake interwiki map for the 'Interwiki prefix' testcase
433 $this->mergeMwGlobalArrayValue( 'wgHooks', [
434 'InterwikiLoadPrefix' => [
435 function ( $prefix, &$iwdata ) {
436 if ( $prefix === 'interwiki' ) {
438 'iw_url' => 'http://example.com/',
448 foreach ( $expectedArray as $validate => $expected ) {
451 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
455 public static function provideGetCanonicalName() {
457 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
458 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
459 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
460 'valid' => false, 'false' => 'Talk:Username' ] ],
461 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
462 'valid' => false, 'false' => 'Interwiki:Username' ] ],
463 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
464 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
465 'usable' => 'Multi spaces' ] ],
466 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
467 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
468 'valid' => false, 'false' => 'In[]valid' ] ],
469 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
470 'false' => 'With / slash' ] ],
475 * @covers User::equals
477 public function testEquals() {
478 $first = $this->getMutableTestUser()->getUser();
479 $second = User
::newFromName( $first->getName() );
481 $this->assertTrue( $first->equals( $first ) );
482 $this->assertTrue( $first->equals( $second ) );
483 $this->assertTrue( $second->equals( $first ) );
485 $third = $this->getMutableTestUser()->getUser();
486 $fourth = $this->getMutableTestUser()->getUser();
488 $this->assertFalse( $third->equals( $fourth ) );
489 $this->assertFalse( $fourth->equals( $third ) );
491 // Test users loaded from db with id
492 $user = $this->getMutableTestUser()->getUser();
493 $fifth = User
::newFromId( $user->getId() );
494 $sixth = User
::newFromName( $user->getName() );
495 $this->assertTrue( $fifth->equals( $sixth ) );
499 * @covers User::getId
501 public function testGetId() {
502 $user = static::getTestUser()->getUser();
503 $this->assertTrue( $user->getId() > 0 );
507 * @covers User::isLoggedIn
508 * @covers User::isAnon
510 public function testLoggedIn() {
511 $user = $this->getMutableTestUser()->getUser();
512 $this->assertTrue( $user->isLoggedIn() );
513 $this->assertFalse( $user->isAnon() );
515 // Non-existent users are perceived as anonymous
516 $user = User
::newFromName( 'UTNonexistent' );
517 $this->assertFalse( $user->isLoggedIn() );
518 $this->assertTrue( $user->isAnon() );
521 $this->assertFalse( $user->isLoggedIn() );
522 $this->assertTrue( $user->isAnon() );
526 * @covers User::checkAndSetTouched
528 public function testCheckAndSetTouched() {
529 $user = $this->getMutableTestUser()->getUser();
530 $user = TestingAccessWrapper
::newFromObject( $user );
531 $this->assertTrue( $user->isLoggedIn() );
533 $touched = $user->getDBTouched();
535 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
536 $this->assertGreaterThan(
537 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
539 $touched = $user->getDBTouched();
541 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
542 $this->assertGreaterThan(
543 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
547 * @covers User::findUsersByGroup
549 public function testFindUsersByGroup() {
550 // FIXME: fails under postgres
551 $this->markTestSkippedIfDbType( 'postgres' );
553 $users = User
::findUsersByGroup( [] );
554 $this->assertEquals( 0, iterator_count( $users ) );
556 $users = User
::findUsersByGroup( 'foo' );
557 $this->assertEquals( 0, iterator_count( $users ) );
559 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
560 $users = User
::findUsersByGroup( 'foo' );
561 $this->assertEquals( 1, iterator_count( $users ) );
563 $this->assertTrue( $user->equals( $users->current() ) );
565 // arguments have OR relationship
566 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
567 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
568 $this->assertEquals( 2, iterator_count( $users ) );
570 $this->assertTrue( $user->equals( $users->current() ) );
572 $this->assertTrue( $user2->equals( $users->current() ) );
574 // users are not duplicated
575 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
576 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
577 $this->assertEquals( 1, iterator_count( $users ) );
579 $this->assertTrue( $user->equals( $users->current() ) );
583 * When a user is autoblocked a cookie is set with which to track them
584 * in case they log out and change IP addresses.
585 * @link https://phabricator.wikimedia.org/T5233
586 * @covers User::trackBlockWithCookie
588 public function testAutoblockCookies() {
589 // Set up the bits of global configuration that we use.
590 $this->setMwGlobals( [
591 'wgCookieSetOnAutoblock' => true,
592 'wgCookiePrefix' => 'wmsitetitle',
593 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
596 // Unregister the hooks for proper unit testing
597 $this->mergeMwGlobalArrayValue( 'wgHooks', [
598 'PerformRetroactiveAutoblock' => []
601 // 1. Log in a test user, and block them.
602 $user1tmp = $this->getTestUser()->getUser();
603 $request1 = new FauxRequest();
604 $request1->getSession()->setUser( $user1tmp );
605 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
606 $block = new Block( [
607 'enableAutoblock' => true,
608 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
610 $block->setBlocker( $this->getTestSysop()->getUser() );
611 $block->setTarget( $user1tmp );
612 $res = $block->insert();
613 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
614 $user1 = User
::newFromSession( $request1 );
615 $user1->mBlock
= $block;
618 // Confirm that the block has been applied as required.
619 $this->assertTrue( $user1->isLoggedIn() );
620 $this->assertTrue( $user1->isBlocked() );
621 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
622 $this->assertTrue( $block->isAutoblocking() );
623 $this->assertGreaterThanOrEqual( 1, $block->getId() );
625 // Test for the desired cookie name, value, and expiry.
626 $cookies = $request1->response()->getCookies();
627 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
628 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
629 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
630 $this->assertEquals( $block->getId(), $cookieValue );
632 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
633 $request2 = new FauxRequest();
634 $request2->setCookie( 'BlockID', $block->getCookieValue() );
635 $user2 = User
::newFromSession( $request2 );
637 $this->assertNotEquals( $user1->getId(), $user2->getId() );
638 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
639 $this->assertTrue( $user2->isAnon() );
640 $this->assertFalse( $user2->isLoggedIn() );
641 $this->assertTrue( $user2->isBlocked() );
642 // Non-strict type-check.
643 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
644 // Can't directly compare the objects because of member type differences.
645 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
646 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
647 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
649 // 3. Finally, set up a request as a new user, and the block should still be applied.
650 $user3tmp = $this->getTestUser()->getUser();
651 $request3 = new FauxRequest();
652 $request3->getSession()->setUser( $user3tmp );
653 $request3->setCookie( 'BlockID', $block->getId() );
654 $user3 = User
::newFromSession( $request3 );
656 $this->assertTrue( $user3->isLoggedIn() );
657 $this->assertTrue( $user3->isBlocked() );
658 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
665 * Make sure that no cookie is set to track autoblocked users
666 * when $wgCookieSetOnAutoblock is false.
667 * @covers User::trackBlockWithCookie
669 public function testAutoblockCookiesDisabled() {
670 // Set up the bits of global configuration that we use.
671 $this->setMwGlobals( [
672 'wgCookieSetOnAutoblock' => false,
673 'wgCookiePrefix' => 'wm_no_cookies',
674 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
677 // Unregister the hooks for proper unit testing
678 $this->mergeMwGlobalArrayValue( 'wgHooks', [
679 'PerformRetroactiveAutoblock' => []
682 // 1. Log in a test user, and block them.
683 $testUser = $this->getTestUser()->getUser();
684 $request1 = new FauxRequest();
685 $request1->getSession()->setUser( $testUser );
686 $block = new Block( [ 'enableAutoblock' => true ] );
687 $block->setBlocker( $this->getTestSysop()->getUser() );
688 $block->setTarget( $testUser );
689 $res = $block->insert();
690 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
691 $user = User
::newFromSession( $request1 );
692 $user->mBlock
= $block;
695 // 2. Test that the cookie IS NOT present.
696 $this->assertTrue( $user->isLoggedIn() );
697 $this->assertTrue( $user->isBlocked() );
698 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
699 $this->assertTrue( $block->isAutoblocking() );
700 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
701 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
702 $cookies = $request1->response()->getCookies();
703 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
710 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
711 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
712 * the cookie's should change with it.
713 * @covers User::trackBlockWithCookie
715 public function testAutoblockCookieInfiniteExpiry() {
716 $this->setMwGlobals( [
717 'wgCookieSetOnAutoblock' => true,
718 'wgCookiePrefix' => 'wm_infinite_block',
719 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
722 // Unregister the hooks for proper unit testing
723 $this->mergeMwGlobalArrayValue( 'wgHooks', [
724 'PerformRetroactiveAutoblock' => []
727 // 1. Log in a test user, and block them indefinitely.
728 $user1Tmp = $this->getTestUser()->getUser();
729 $request1 = new FauxRequest();
730 $request1->getSession()->setUser( $user1Tmp );
731 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
732 $block->setBlocker( $this->getTestSysop()->getUser() );
733 $block->setTarget( $user1Tmp );
734 $res = $block->insert();
735 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
736 $user1 = User
::newFromSession( $request1 );
737 $user1->mBlock
= $block;
740 // 2. Test the cookie's expiry timestamp.
741 $this->assertTrue( $user1->isLoggedIn() );
742 $this->assertTrue( $user1->isBlocked() );
743 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
744 $this->assertTrue( $block->isAutoblocking() );
745 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
746 $cookies = $request1->response()->getCookies();
747 // Test the cookie's expiry to the nearest minute.
748 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
749 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
750 // Check for expiry dates in a 10-second window, to account for slow testing.
753 $cookies['wm_infinite_blockBlockID']['expire'],
758 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
759 $newExpiry = wfTimestamp() +
2 * 60 * 60;
760 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
762 $user2tmp = $this->getTestUser()->getUser();
763 $request2 = new FauxRequest();
764 $request2->getSession()->setUser( $user2tmp );
765 $user2 = User
::newFromSession( $request2 );
766 $user2->mBlock
= $block;
768 $cookies = $request2->response()->getCookies();
769 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
770 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
777 * @covers User::getBlockedStatus
779 public function testSoftBlockRanges() {
782 $this->setMwGlobals( [
783 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
787 // IP isn't in $wgSoftBlockRanges
788 $request = new FauxRequest();
789 $request->setIP( '192.168.0.1' );
790 $wgUser = User
::newFromSession( $request );
791 $this->assertNull( $wgUser->getBlock() );
793 // IP is in $wgSoftBlockRanges
794 $request = new FauxRequest();
795 $request->setIP( '10.20.30.40' );
796 $wgUser = User
::newFromSession( $request );
797 $block = $wgUser->getBlock();
798 $this->assertInstanceOf( Block
::class, $block );
799 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
801 // Make sure the block is really soft
802 $request->getSession()->setUser( $this->getTestUser()->getUser() );
803 $wgUser = User
::newFromSession( $request );
804 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
805 $this->assertNull( $wgUser->getBlock() );
809 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
810 * @covers User::trackBlockWithCookie
812 public function testAutoblockCookieInauthentic() {
813 // Set up the bits of global configuration that we use.
814 $this->setMwGlobals( [
815 'wgCookieSetOnAutoblock' => true,
816 'wgCookiePrefix' => 'wmsitetitle',
817 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
820 // Unregister the hooks for proper unit testing
821 $this->mergeMwGlobalArrayValue( 'wgHooks', [
822 'PerformRetroactiveAutoblock' => []
825 // 1. Log in a blocked test user.
826 $user1tmp = $this->getTestUser()->getUser();
827 $request1 = new FauxRequest();
828 $request1->getSession()->setUser( $user1tmp );
829 $block = new Block( [ 'enableAutoblock' => true ] );
830 $block->setBlocker( $this->getTestSysop()->getUser() );
831 $block->setTarget( $user1tmp );
832 $res = $block->insert();
833 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
834 $user1 = User
::newFromSession( $request1 );
835 $user1->mBlock
= $block;
838 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
840 $request2 = new FauxRequest();
841 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
842 $user2 = User
::newFromSession( $request2 );
844 $this->assertTrue( $user2->isAnon() );
845 $this->assertFalse( $user2->isLoggedIn() );
846 $this->assertFalse( $user2->isBlocked() );
853 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
854 * This checks that a non-authenticated cookie still works.
855 * @covers User::trackBlockWithCookie
857 public function testAutoblockCookieNoSecretKey() {
858 // Set up the bits of global configuration that we use.
859 $this->setMwGlobals( [
860 'wgCookieSetOnAutoblock' => true,
861 'wgCookiePrefix' => 'wmsitetitle',
862 'wgSecretKey' => null,
865 // Unregister the hooks for proper unit testing
866 $this->mergeMwGlobalArrayValue( 'wgHooks', [
867 'PerformRetroactiveAutoblock' => []
870 // 1. Log in a blocked test user.
871 $user1tmp = $this->getTestUser()->getUser();
872 $request1 = new FauxRequest();
873 $request1->getSession()->setUser( $user1tmp );
874 $block = new Block( [ 'enableAutoblock' => true ] );
875 $block->setBlocker( $this->getTestSysop()->getUser() );
876 $block->setTarget( $user1tmp );
877 $res = $block->insert();
878 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
879 $user1 = User
::newFromSession( $request1 );
880 $user1->mBlock
= $block;
882 $this->assertTrue( $user1->isBlocked() );
884 // 2. Create a new request, set the cookie to just the block ID, and the user should
885 // still get blocked when they log in again.
886 $request2 = new FauxRequest();
887 $request2->setCookie( 'BlockID', $block->getId() );
888 $user2 = User
::newFromSession( $request2 );
890 $this->assertNotEquals( $user1->getId(), $user2->getId() );
891 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
892 $this->assertTrue( $user2->isAnon() );
893 $this->assertFalse( $user2->isLoggedIn() );
894 $this->assertTrue( $user2->isBlocked() );
895 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
902 * @covers User::isPingLimitable
904 public function testIsPingLimitable() {
905 $request = new FauxRequest();
906 $request->setIP( '1.2.3.4' );
907 $user = User
::newFromSession( $request );
909 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
910 $this->assertTrue( $user->isPingLimitable() );
912 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
913 $this->assertFalse( $user->isPingLimitable() );
915 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
916 $this->assertFalse( $user->isPingLimitable() );
918 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
919 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
920 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
921 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
922 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
923 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
926 public function provideExperienceLevel() {
928 [ 2, 2, 'newcomer' ],
929 [ 12, 3, 'newcomer' ],
930 [ 8, 5, 'newcomer' ],
931 [ 15, 10, 'learner' ],
932 [ 450, 20, 'learner' ],
933 [ 460, 33, 'learner' ],
934 [ 525, 28, 'learner' ],
935 [ 538, 33, 'experienced' ],
940 * @covers User::getExperienceLevel
941 * @dataProvider provideExperienceLevel
943 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
944 $this->setMwGlobals( [
945 'wgLearnerEdits' => 10,
946 'wgLearnerMemberSince' => 4,
947 'wgExperiencedUserEdits' => 500,
948 'wgExperiencedUserMemberSince' => 30,
951 $db = wfGetDB( DB_MASTER
);
952 $userQuery = User
::getQueryInfo();
953 $row = $db->selectRow(
954 $userQuery['tables'],
955 $userQuery['fields'],
956 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
961 $row->user_editcount
= $editCount;
962 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
963 $user = User
::newFromRow( $row );
965 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
969 * @covers User::getExperienceLevel
971 public function testExperienceLevelAnon() {
972 $user = User
::newFromName( '10.11.12.13', false );
974 $this->assertFalse( $user->getExperienceLevel() );
977 public static function provideIsLocallBlockedProxy() {
979 [ '1.2.3.4', '1.2.3.4' ],
980 [ '1.2.3.4', '1.2.3.0/16' ],
985 * @dataProvider provideIsLocallBlockedProxy
986 * @covers User::isLocallyBlockedProxy
988 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
992 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1000 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1002 $this->setMwGlobals(
1005 'test' => $blockListEntry
1008 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1010 $this->hideDeprecated(
1011 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1012 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1014 $this->setMwGlobals(
1017 $blockListEntry => 'test'
1020 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1024 * @covers User::newFromActorId
1026 public function testActorId() {
1027 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1028 $this->hideDeprecated( 'User::selectFields' );
1030 // Newly-created user has an actor ID
1031 $user = User
::createNew( 'UserTestActorId1' );
1032 $id = $user->getId();
1033 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1035 $user = User
::newFromName( 'UserTestActorId2' );
1036 $user->addToDatabase();
1037 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1039 $user = User
::newFromName( 'UserTestActorId1' );
1040 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1042 $user = User
::newFromId( $id );
1043 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1045 $user2 = User
::newFromActorId( $user->getActorId() );
1046 $this->assertEquals( $user->getId(), $user2->getId(),
1047 'User::newFromActorId works for an existing user' );
1049 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1050 $user = User
::newFromRow( $row );
1051 $this->assertTrue( $user->getActorId() > 0,
1052 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1054 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1055 User
::purge( $domain, $id );
1056 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1057 ObjectCache
::getMainWANInstance()->clearProcessCache();
1059 $user = User
::newFromId( $id );
1060 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1061 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1063 $user->setName( 'UserTestActorId4-renamed' );
1064 $user->saveSettings();
1065 $this->assertEquals(
1067 $this->db
->selectField(
1068 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1070 'User::saveSettings updates actor table for name change'
1074 $ip = '192.168.12.34';
1075 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1077 $user = User
::newFromName( $ip, false );
1078 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1079 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1080 'Actor ID can be created for an anonymous user' );
1082 $user = User
::newFromName( $ip, false );
1083 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1084 $user2 = User
::newFromActorId( $user->getActorId() );
1085 $this->assertEquals( $user->getName(), $user2->getName(),
1086 'User::newFromActorId works for an anonymous user' );
1090 * @covers User::newFromAnyId
1092 public function testNewFromAnyId() {
1094 $user = $this->getTestUser()->getUser();
1095 for ( $i = 1; $i <= 7; $i++
) {
1096 $test = User
::newFromAnyId(
1097 ( $i & 1 ) ?
$user->getId() : null,
1098 ( $i & 2 ) ?
$user->getName() : null,
1099 ( $i & 4 ) ?
$user->getActorId() : null
1101 $this->assertSame( $user->getId(), $test->getId() );
1102 $this->assertSame( $user->getName(), $test->getName() );
1103 $this->assertSame( $user->getActorId(), $test->getActorId() );
1106 // Anon user. Can't load by only user ID when that's 0.
1107 $user = User
::newFromName( '192.168.12.34', false );
1108 $user->getActorId( $this->db
); // Make sure an actor ID exists
1110 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1111 $this->assertSame( $user->getId(), $test->getId() );
1112 $this->assertSame( $user->getName(), $test->getName() );
1113 $this->assertSame( $user->getActorId(), $test->getActorId() );
1114 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1115 $this->assertSame( $user->getId(), $test->getId() );
1116 $this->assertSame( $user->getName(), $test->getName() );
1117 $this->assertSame( $user->getActorId(), $test->getActorId() );
1119 // Bogus data should still "work" as long as nothing triggers a ->load(),
1120 // and accessing the specified data shouldn't do that.
1121 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1122 $this->assertSame( 123456, $test->getId() );
1123 $this->assertSame( 'Bogus', $test->getName() );
1124 $this->assertSame( 654321, $test->getActorId() );
1126 // Exceptional cases
1128 User
::newFromAnyId( null, null, null );
1129 $this->fail( 'Expected exception not thrown' );
1130 } catch ( InvalidArgumentException
$ex ) {
1133 User
::newFromAnyId( 0, null, 0 );
1134 $this->fail( 'Expected exception not thrown' );
1135 } catch ( InvalidArgumentException
$ex ) {
1140 * @covers User::newFromIdentity
1142 public function testNewFromIdentity() {
1144 $user = $this->getTestUser()->getUser();
1146 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1149 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1150 $result = User
::newFromIdentity( $identity );
1151 $this->assertInstanceOf( User
::class, $result );
1152 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1153 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1154 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1157 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1158 $result = User
::newFromIdentity( $identity );
1159 $this->assertInstanceOf( User
::class, $result );
1160 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1161 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1162 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1165 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1166 $result = User
::newFromIdentity( $identity );
1167 $this->assertInstanceOf( User
::class, $result );
1168 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1169 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1170 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1174 * @covers User::getBlockedStatus
1175 * @covers User::getBlock
1176 * @covers User::blockedBy
1177 * @covers User::blockedFor
1178 * @covers User::isHidden
1179 * @covers User::isBlockedFrom
1181 public function testBlockInstanceCache() {
1182 // First, check the user isn't blocked
1183 $user = $this->getMutableTestUser()->getUser();
1184 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1185 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1186 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1187 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1188 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1189 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1192 $blocker = $this->getTestSysop()->getUser();
1193 $block = new Block( [
1195 'allowUsertalk' => false,
1196 'reason' => 'Because',
1198 $block->setTarget( $user );
1199 $block->setBlocker( $blocker );
1200 $res = $block->insert();
1201 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1203 // Clear cache and confirm it loaded the block properly
1204 $user->clearInstanceCache();
1205 $this->assertInstanceOf( Block
::class, $user->getBlock( false ) );
1206 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1207 $this->assertSame( 'Because', $user->blockedFor() );
1208 $this->assertTrue( (bool)$user->isHidden() );
1209 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1214 // Clear cache and confirm it loaded the not-blocked properly
1215 $user->clearInstanceCache();
1216 $this->assertNull( $user->getBlock( false ) );
1217 $this->assertSame( '', $user->blockedBy() );
1218 $this->assertSame( '', $user->blockedFor() );
1219 $this->assertFalse( (bool)$user->isHidden() );
1220 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1224 * @covers User::isBlockedFrom
1225 * @dataProvider provideIsBlockedFrom
1226 * @param string|null $title Title to test.
1227 * @param bool $expect Expected result from User::isBlockedFrom()
1228 * @param array $options Additional test options:
1229 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1230 * - 'allowUsertalk': (bool, default false) Passed to Block::__construct()
1231 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1233 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1234 $this->setMwGlobals( [
1235 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1238 $user = $this->getTestUser()->getUser();
1240 if ( $title === self
::USER_TALK_PAGE
) {
1241 $title = $user->getTalkPage();
1243 $title = Title
::newFromText( $title );
1247 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1248 $page = $this->getExistingTestPage(
1249 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1251 $restrictions[] = new PageRestriction( 0, $page->getId() );
1253 foreach ( $options['namespaceRestrictions'] ??
[] as $ns ) {
1254 $restrictions[] = new NamespaceRestriction( 0, $ns );
1257 $block = new Block( [
1258 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1259 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1260 'sitewide' => !$restrictions,
1262 $block->setTarget( $user );
1263 $block->setBlocker( $this->getTestSysop()->getUser() );
1264 if ( $restrictions ) {
1265 $block->setRestrictions( $restrictions );
1270 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1276 public static function provideIsBlockedFrom() {
1278 'Sitewide block, basic operation' => [ 'Test page', true ],
1279 'Sitewide block, not allowing user talk' => [
1280 self
::USER_TALK_PAGE
, true, [
1281 'allowUsertalk' => false,
1284 'Sitewide block, allowing user talk' => [
1285 self
::USER_TALK_PAGE
, false, [
1286 'allowUsertalk' => true,
1289 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1290 self
::USER_TALK_PAGE
, true, [
1291 'allowUsertalk' => true,
1292 'blockAllowsUTEdit' => false,
1295 'Partial block, blocking the page' => [
1296 'Test page', true, [
1297 'pageRestrictions' => [ 'Test page' ],
1300 'Partial block, not blocking the page' => [
1301 'Test page 2', false, [
1302 'pageRestrictions' => [ 'Test page' ],
1305 'Partial block, not allowing user talk but user talk page is not blocked' => [
1306 self
::USER_TALK_PAGE
, false, [
1307 'allowUsertalk' => false,
1308 'pageRestrictions' => [ 'Test page' ],
1311 'Partial block, allowing user talk but user talk page is blocked' => [
1312 self
::USER_TALK_PAGE
, true, [
1313 'allowUsertalk' => true,
1314 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1317 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1318 self
::USER_TALK_PAGE
, false, [
1319 'allowUsertalk' => false,
1320 'pageRestrictions' => [ 'Test page' ],
1321 'blockAllowsUTEdit' => false,
1324 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1325 self
::USER_TALK_PAGE
, true, [
1326 'allowUsertalk' => true,
1327 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1328 'blockAllowsUTEdit' => false,
1331 'Partial user talk namespace block, not allowing user talk' => [
1332 self
::USER_TALK_PAGE
, true, [
1333 'allowUsertalk' => false,
1334 'namespaceRestrictions' => [ NS_USER_TALK
],
1337 'Partial user talk namespace block, allowing user talk' => [
1338 self
::USER_TALK_PAGE
, false, [
1339 'allowUsertalk' => true,
1340 'namespaceRestrictions' => [ NS_USER_TALK
],
1343 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1344 self
::USER_TALK_PAGE
, true, [
1345 'allowUsertalk' => true,
1346 'namespaceRestrictions' => [ NS_USER_TALK
],
1347 'blockAllowsUTEdit' => false,
1354 * Block cookie should be set for IP Blocks if
1355 * wgCookieSetOnIpBlock is set to true
1356 * @covers User::trackBlockWithCookie
1358 public function testIpBlockCookieSet() {
1359 $this->setMwGlobals( [
1360 'wgCookieSetOnIpBlock' => true,
1361 'wgCookiePrefix' => 'wiki',
1362 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1366 $block = new Block( [
1367 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1369 $block->setTarget( '1.2.3.4' );
1370 $block->setBlocker( $this->getTestSysop()->getUser() );
1374 $request = new FauxRequest();
1375 $request->setIP( '1.2.3.4' );
1378 $user = User
::newFromSession( $request );
1379 $user->trackBlockWithCookie();
1381 // test cookie was set
1382 $cookies = $request->response()->getCookies();
1383 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1390 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1392 * @covers User::trackBlockWithCookie
1394 public function testIpBlockCookieNotSet() {
1395 $this->setMwGlobals( [
1396 'wgCookieSetOnIpBlock' => false,
1397 'wgCookiePrefix' => 'wiki',
1398 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1402 $block = new Block( [
1403 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1405 $block->setTarget( '1.2.3.4' );
1406 $block->setBlocker( $this->getTestSysop()->getUser() );
1410 $request = new FauxRequest();
1411 $request->setIP( '1.2.3.4' );
1414 $user = User
::newFromSession( $request );
1415 $user->trackBlockWithCookie();
1417 // test cookie was not set
1418 $cookies = $request->response()->getCookies();
1419 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1426 * When an ip user is blocked and then they log in, cookie block
1427 * should be invalid and the cookie removed.
1428 * @covers User::trackBlockWithCookie
1430 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1431 $this->setMwGlobals( [
1432 'wgAutoblockExpiry' => 8000,
1433 'wgCookieSetOnIpBlock' => true,
1434 'wgCookiePrefix' => 'wiki',
1435 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1439 $block = new Block( [
1440 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1442 $block->setTarget( '1.2.3.4' );
1443 $block->setBlocker( $this->getTestSysop()->getUser() );
1447 $request = new FauxRequest();
1448 $request->setIP( '1.2.3.4' );
1449 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1450 $request->setCookie( 'BlockID', $block->getCookieValue() );
1453 $user = User
::newFromSession( $request );
1455 // logged in users should be inmune to cookie block of type ip/range
1456 $this->assertFalse( $user->isBlocked() );
1458 // cookie is being cleared
1459 $cookies = $request->response()->getCookies();
1460 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );