3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\Block\Restriction\PageRestriction
;
7 use MediaWiki\MediaWikiServices
;
8 use MediaWiki\User\UserIdentityValue
;
9 use Wikimedia\TestingAccessWrapper
;
14 class UserTest
extends MediaWikiTestCase
{
16 /** Constant for self::testIsBlockedFrom */
17 const USER_TALK_PAGE
= '<user talk page>';
24 protected function setUp() {
27 $this->setMwGlobals( [
28 'wgGroupPermissions' => [],
29 'wgRevokePermissions' => [],
30 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
32 $this->overrideMwServices();
34 $this->setUpPermissionGlobals();
36 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
39 private function setUpPermissionGlobals() {
40 global $wgGroupPermissions, $wgRevokePermissions;
42 # Data for regular $wgGroupPermissions test
43 $wgGroupPermissions['unittesters'] = [
49 $wgGroupPermissions['testwriters'] = [
55 # Data for regular $wgRevokePermissions test
56 $wgRevokePermissions['formertesters'] = [
60 # For the options test
61 $wgGroupPermissions['*'] = [
62 'editmyoptions' => true,
67 * @covers User::getGroupPermissions
69 public function testGroupPermissions() {
70 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
71 $this->assertContains( 'runtest', $rights );
72 $this->assertNotContains( 'writetest', $rights );
73 $this->assertNotContains( 'modifytest', $rights );
74 $this->assertNotContains( 'nukeworld', $rights );
76 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
77 $this->assertContains( 'runtest', $rights );
78 $this->assertContains( 'writetest', $rights );
79 $this->assertContains( 'modifytest', $rights );
80 $this->assertNotContains( 'nukeworld', $rights );
84 * @covers User::getGroupPermissions
86 public function testRevokePermissions() {
87 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
88 $this->assertNotContains( 'runtest', $rights );
89 $this->assertNotContains( 'writetest', $rights );
90 $this->assertNotContains( 'modifytest', $rights );
91 $this->assertNotContains( 'nukeworld', $rights );
95 * @covers User::getRights
97 public function testUserPermissions() {
98 $rights = $this->user
->getRights();
99 $this->assertContains( 'runtest', $rights );
100 $this->assertNotContains( 'writetest', $rights );
101 $this->assertNotContains( 'modifytest', $rights );
102 $this->assertNotContains( 'nukeworld', $rights );
106 * @covers User::getRights
108 public function testUserGetRightsHooks() {
109 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
110 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
112 $rights = $user->getRights();
113 $this->assertContains( 'test', $rights, 'sanity check' );
114 $this->assertContains( 'runtest', $rights, 'sanity check' );
115 $this->assertContains( 'writetest', $rights, 'sanity check' );
116 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
118 // Add a hook manipluating the rights
119 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
120 $rights[] = 'nukeworld';
121 $rights = array_diff( $rights, [ 'writetest' ] );
124 $userWrapper->mRights
= null;
125 $rights = $user->getRights();
126 $this->assertContains( 'test', $rights );
127 $this->assertContains( 'runtest', $rights );
128 $this->assertNotContains( 'writetest', $rights );
129 $this->assertContains( 'nukeworld', $rights );
131 // Add a Session that limits rights
132 $mock = $this->getMockBuilder( stdClass
::class )
133 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
135 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
136 $mock->method( 'getSessionId' )->willReturn(
137 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
139 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
140 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
141 ->setMethods( [ 'getSession' ] )
143 $mockRequest->method( 'getSession' )->willReturn( $session );
144 $userWrapper->mRequest
= $mockRequest;
146 $userWrapper->mRights
= null;
147 $rights = $user->getRights();
148 $this->assertContains( 'test', $rights );
149 $this->assertNotContains( 'runtest', $rights );
150 $this->assertNotContains( 'writetest', $rights );
151 $this->assertNotContains( 'nukeworld', $rights );
155 * @dataProvider provideGetGroupsWithPermission
156 * @covers User::getGroupsWithPermission
158 public function testGetGroupsWithPermission( $expected, $right ) {
159 $result = User
::getGroupsWithPermission( $right );
163 $this->assertEquals( $expected, $result, "Groups with permission $right" );
166 public static function provideGetGroupsWithPermission() {
169 [ 'unittesters', 'testwriters' ],
188 * @dataProvider provideIPs
191 public function testIsIP( $value, $result, $message ) {
192 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
195 public static function provideIPs() {
197 [ '', false, 'Empty string' ],
198 [ ' ', false, 'Blank space' ],
199 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
200 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
201 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
202 [ '203.0.113.0', true, 'IPv4 example' ],
203 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
204 // Not valid IPs but classified as such by MediaWiki for negated asserting
205 // of whether this might be the identifier of a logged-out user or whether
206 // to allow usernames like it.
207 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
208 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
213 * @dataProvider provideUserNames
214 * @covers User::isValidUserName
216 public function testIsValidUserName( $username, $result, $message ) {
217 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
220 public static function provideUserNames() {
222 [ '', false, 'Empty string' ],
223 [ ' ', false, 'Blank space' ],
224 [ 'abcd', false, 'Starts with small letter' ],
225 [ 'Ab/cd', false, 'Contains slash' ],
226 [ 'Ab cd', true, 'Whitespace' ],
227 [ '192.168.1.1', false, 'IP' ],
228 [ '116.17.184.5/32', false, 'IP range' ],
229 [ '::e:f:2001/96', false, 'IPv6 range' ],
230 [ 'User:Abcd', false, 'Reserved Namespace' ],
231 [ '12abcd232', true, 'Starts with Numbers' ],
232 [ '?abcd', true, 'Start with ? mark' ],
233 [ '#abcd', false, 'Start with #' ],
234 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
235 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
236 [ 'Ab cd', false, ' Ideographic space' ],
237 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
238 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
239 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
244 * Test User::editCount
246 * @covers User::getEditCount
248 public function testGetEditCount() {
249 $user = $this->getMutableTestUser()->getUser();
251 // let the user have a few (3) edits
252 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
253 for ( $i = 0; $i < 3; $i++
) {
254 $page->doEditContent(
255 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
265 $user->getEditCount(),
266 'After three edits, the user edit count should be 3'
269 // increase the edit count
270 $user->incEditCount();
271 $user->clearInstanceCache();
275 $user->getEditCount(),
276 'After increasing the edit count manually, the user edit count should be 4'
281 * Test User::editCount
283 * @covers User::getEditCount
285 public function testGetEditCountForAnons() {
286 $user = User
::newFromName( 'Anonymous' );
289 $user->getEditCount(),
290 'Edit count starts null for anonymous users.'
293 $user->incEditCount();
296 $user->getEditCount(),
297 'Edit count remains null for anonymous users despite calls to increase it.'
302 * Test User::editCount
304 * @covers User::incEditCount
306 public function testIncEditCount() {
307 $user = $this->getMutableTestUser()->getUser();
308 $user->incEditCount();
310 $reloadedUser = User
::newFromId( $user->getId() );
311 $reloadedUser->incEditCount();
315 $reloadedUser->getEditCount(),
316 'Increasing the edit count after a fresh load leaves the object up to date.'
321 * Test changing user options.
322 * @covers User::setOption
323 * @covers User::getOption
325 public function testOptions() {
326 $user = $this->getMutableTestUser()->getUser();
328 $user->setOption( 'userjs-someoption', 'test' );
329 $user->setOption( 'rclimit', 200 );
330 $user->setOption( 'wpwatchlistdays', '0' );
331 $user->saveSettings();
333 $user = User
::newFromName( $user->getName() );
334 $user->load( User
::READ_LATEST
);
335 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
336 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
338 $user = User
::newFromName( $user->getName() );
339 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
340 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
341 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
343 // Check that an option saved as a string '0' is returned as an integer.
344 $user = User
::newFromName( $user->getName() );
345 $user->load( User
::READ_LATEST
);
346 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
351 * Make sure defaults are loaded when setOption is called.
352 * @covers User::loadOptions
354 public function testAnonOptions() {
355 global $wgDefaultUserOptions;
356 $this->user
->setOption( 'userjs-someoption', 'test' );
357 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
358 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
362 * Test password validity checks. There are 3 checks in core,
363 * - ensure the password meets the minimal length
364 * - ensure the password is not the same as the username
365 * - ensure the username/password combo isn't forbidden
366 * @covers User::checkPasswordValidity()
367 * @covers User::getPasswordValidity()
368 * @covers User::isValidPassword()
370 public function testCheckPasswordValidity() {
371 $this->setMwGlobals( [
372 'wgPasswordPolicy' => [
375 'MinimalPasswordLength' => 8,
376 'MinimumPasswordLengthToLogin' => 1,
377 'PasswordCannotMatchUsername' => 1,
380 'MinimalPasswordLength' => 6,
381 'PasswordCannotMatchUsername' => true,
382 'PasswordCannotMatchBlacklist' => true,
383 'MaximalPasswordLength' => 40,
387 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
388 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
389 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
390 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
391 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
395 $this->hideDeprecated( 'User::getPasswordValidity' );
397 $user = static::getTestUser()->getUser();
400 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
403 $this->assertFalse( $user->isValidPassword( 'a' ) );
404 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
405 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
406 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
409 $longPass = str_repeat( 'a', 41 );
410 $this->assertFalse( $user->isValidPassword( $longPass ) );
411 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
412 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
413 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
416 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
417 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
418 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
420 // On the forbidden list
421 $user = User
::newFromName( 'Useruser' );
422 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
423 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
427 * @covers User::getCanonicalName()
428 * @dataProvider provideGetCanonicalName
430 public function testGetCanonicalName( $name, $expectedArray ) {
431 // fake interwiki map for the 'Interwiki prefix' testcase
432 $this->mergeMwGlobalArrayValue( 'wgHooks', [
433 'InterwikiLoadPrefix' => [
434 function ( $prefix, &$iwdata ) {
435 if ( $prefix === 'interwiki' ) {
437 'iw_url' => 'http://example.com/',
447 foreach ( $expectedArray as $validate => $expected ) {
450 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
454 public static function provideGetCanonicalName() {
456 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
457 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
458 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
459 'valid' => false, 'false' => 'Talk:Username' ] ],
460 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
461 'valid' => false, 'false' => 'Interwiki:Username' ] ],
462 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
463 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
464 'usable' => 'Multi spaces' ] ],
465 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
466 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
467 'valid' => false, 'false' => 'In[]valid' ] ],
468 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
469 'false' => 'With / slash' ] ],
474 * @covers User::equals
476 public function testEquals() {
477 $first = $this->getMutableTestUser()->getUser();
478 $second = User
::newFromName( $first->getName() );
480 $this->assertTrue( $first->equals( $first ) );
481 $this->assertTrue( $first->equals( $second ) );
482 $this->assertTrue( $second->equals( $first ) );
484 $third = $this->getMutableTestUser()->getUser();
485 $fourth = $this->getMutableTestUser()->getUser();
487 $this->assertFalse( $third->equals( $fourth ) );
488 $this->assertFalse( $fourth->equals( $third ) );
490 // Test users loaded from db with id
491 $user = $this->getMutableTestUser()->getUser();
492 $fifth = User
::newFromId( $user->getId() );
493 $sixth = User
::newFromName( $user->getName() );
494 $this->assertTrue( $fifth->equals( $sixth ) );
498 * @covers User::getId
500 public function testGetId() {
501 $user = static::getTestUser()->getUser();
502 $this->assertTrue( $user->getId() > 0 );
506 * @covers User::isLoggedIn
507 * @covers User::isAnon
509 public function testLoggedIn() {
510 $user = $this->getMutableTestUser()->getUser();
511 $this->assertTrue( $user->isLoggedIn() );
512 $this->assertFalse( $user->isAnon() );
514 // Non-existent users are perceived as anonymous
515 $user = User
::newFromName( 'UTNonexistent' );
516 $this->assertFalse( $user->isLoggedIn() );
517 $this->assertTrue( $user->isAnon() );
520 $this->assertFalse( $user->isLoggedIn() );
521 $this->assertTrue( $user->isAnon() );
525 * @covers User::checkAndSetTouched
527 public function testCheckAndSetTouched() {
528 $user = $this->getMutableTestUser()->getUser();
529 $user = TestingAccessWrapper
::newFromObject( $user );
530 $this->assertTrue( $user->isLoggedIn() );
532 $touched = $user->getDBTouched();
534 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
535 $this->assertGreaterThan(
536 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
538 $touched = $user->getDBTouched();
540 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
541 $this->assertGreaterThan(
542 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
546 * @covers User::findUsersByGroup
548 public function testFindUsersByGroup() {
549 // FIXME: fails under postgres
550 $this->markTestSkippedIfDbType( 'postgres' );
552 $users = User
::findUsersByGroup( [] );
553 $this->assertEquals( 0, iterator_count( $users ) );
555 $users = User
::findUsersByGroup( 'foo' );
556 $this->assertEquals( 0, iterator_count( $users ) );
558 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
559 $users = User
::findUsersByGroup( 'foo' );
560 $this->assertEquals( 1, iterator_count( $users ) );
562 $this->assertTrue( $user->equals( $users->current() ) );
564 // arguments have OR relationship
565 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
566 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
567 $this->assertEquals( 2, iterator_count( $users ) );
569 $this->assertTrue( $user->equals( $users->current() ) );
571 $this->assertTrue( $user2->equals( $users->current() ) );
573 // users are not duplicated
574 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
575 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
576 $this->assertEquals( 1, iterator_count( $users ) );
578 $this->assertTrue( $user->equals( $users->current() ) );
582 * When a user is autoblocked a cookie is set with which to track them
583 * in case they log out and change IP addresses.
584 * @link https://phabricator.wikimedia.org/T5233
586 public function testAutoblockCookies() {
587 // Set up the bits of global configuration that we use.
588 $this->setMwGlobals( [
589 'wgCookieSetOnAutoblock' => true,
590 'wgCookiePrefix' => 'wmsitetitle',
591 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
594 // Unregister the hooks for proper unit testing
595 $this->mergeMwGlobalArrayValue( 'wgHooks', [
596 'PerformRetroactiveAutoblock' => []
599 // 1. Log in a test user, and block them.
600 $userBlocker = $this->getTestSysop()->getUser();
601 $user1tmp = $this->getTestUser()->getUser();
602 $request1 = new FauxRequest();
603 $request1->getSession()->setUser( $user1tmp );
604 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
605 $block = new Block( [
606 'enableAutoblock' => true,
607 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
609 $block->setBlocker( $this->getTestSysop()->getUser() );
610 $block->setTarget( $user1tmp );
611 $block->setBlocker( $userBlocker );
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.
668 public function testAutoblockCookiesDisabled() {
669 // Set up the bits of global configuration that we use.
670 $this->setMwGlobals( [
671 'wgCookieSetOnAutoblock' => false,
672 'wgCookiePrefix' => 'wm_no_cookies',
673 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
676 // Unregister the hooks for proper unit testing
677 $this->mergeMwGlobalArrayValue( 'wgHooks', [
678 'PerformRetroactiveAutoblock' => []
681 // 1. Log in a test user, and block them.
682 $userBlocker = $this->getTestSysop()->getUser();
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 $block->setBlocker( $userBlocker );
690 $res = $block->insert();
691 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
692 $user = User
::newFromSession( $request1 );
693 $user->mBlock
= $block;
696 // 2. Test that the cookie IS NOT present.
697 $this->assertTrue( $user->isLoggedIn() );
698 $this->assertTrue( $user->isBlocked() );
699 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
700 $this->assertTrue( $block->isAutoblocking() );
701 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
702 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
703 $cookies = $request1->response()->getCookies();
704 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
711 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
712 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
713 * the cookie's should change with it.
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 $userBlocker = $this->getTestSysop()->getUser();
729 $user1Tmp = $this->getTestUser()->getUser();
730 $request1 = new FauxRequest();
731 $request1->getSession()->setUser( $user1Tmp );
732 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
733 $block->setBlocker( $this->getTestSysop()->getUser() );
734 $block->setTarget( $user1Tmp );
735 $block->setBlocker( $userBlocker );
736 $res = $block->insert();
737 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
738 $user1 = User
::newFromSession( $request1 );
739 $user1->mBlock
= $block;
742 // 2. Test the cookie's expiry timestamp.
743 $this->assertTrue( $user1->isLoggedIn() );
744 $this->assertTrue( $user1->isBlocked() );
745 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
746 $this->assertTrue( $block->isAutoblocking() );
747 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
748 $cookies = $request1->response()->getCookies();
749 // Test the cookie's expiry to the nearest minute.
750 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
751 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
752 // Check for expiry dates in a 10-second window, to account for slow testing.
755 $cookies['wm_infinite_blockBlockID']['expire'],
760 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
761 $newExpiry = wfTimestamp() +
2 * 60 * 60;
762 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
764 $user2tmp = $this->getTestUser()->getUser();
765 $request2 = new FauxRequest();
766 $request2->getSession()->setUser( $user2tmp );
767 $user2 = User
::newFromSession( $request2 );
768 $user2->mBlock
= $block;
770 $cookies = $request2->response()->getCookies();
771 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
772 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
778 public function testSoftBlockRanges() {
781 $this->setMwGlobals( [
782 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
786 // IP isn't in $wgSoftBlockRanges
787 $request = new FauxRequest();
788 $request->setIP( '192.168.0.1' );
789 $wgUser = User
::newFromSession( $request );
790 $this->assertNull( $wgUser->getBlock() );
792 // IP is in $wgSoftBlockRanges
793 $request = new FauxRequest();
794 $request->setIP( '10.20.30.40' );
795 $wgUser = User
::newFromSession( $request );
796 $block = $wgUser->getBlock();
797 $this->assertInstanceOf( Block
::class, $block );
798 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
800 // Make sure the block is really soft
801 $request->getSession()->setUser( $this->getTestUser()->getUser() );
802 $wgUser = User
::newFromSession( $request );
803 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
804 $this->assertNull( $wgUser->getBlock() );
808 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
810 public function testAutoblockCookieInauthentic() {
811 // Set up the bits of global configuration that we use.
812 $this->setMwGlobals( [
813 'wgCookieSetOnAutoblock' => true,
814 'wgCookiePrefix' => 'wmsitetitle',
815 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
818 // Unregister the hooks for proper unit testing
819 $this->mergeMwGlobalArrayValue( 'wgHooks', [
820 'PerformRetroactiveAutoblock' => []
823 // 1. Log in a blocked test user.
824 $userBlocker = $this->getTestSysop()->getUser();
825 $user1tmp = $this->getTestUser()->getUser();
826 $request1 = new FauxRequest();
827 $request1->getSession()->setUser( $user1tmp );
828 $block = new Block( [ 'enableAutoblock' => true ] );
829 $block->setBlocker( $this->getTestSysop()->getUser() );
830 $block->setTarget( $user1tmp );
831 $block->setBlocker( $userBlocker );
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.
856 public function testAutoblockCookieNoSecretKey() {
857 // Set up the bits of global configuration that we use.
858 $this->setMwGlobals( [
859 'wgCookieSetOnAutoblock' => true,
860 'wgCookiePrefix' => 'wmsitetitle',
861 'wgSecretKey' => null,
864 // Unregister the hooks for proper unit testing
865 $this->mergeMwGlobalArrayValue( 'wgHooks', [
866 'PerformRetroactiveAutoblock' => []
869 // 1. Log in a blocked test user.
870 $userBlocker = $this->getTestSysop()->getUser();
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 $block->setBlocker( $userBlocker );
878 $res = $block->insert();
879 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
880 $user1 = User
::newFromSession( $request1 );
881 $user1->mBlock
= $block;
883 $this->assertTrue( $user1->isBlocked() );
885 // 2. Create a new request, set the cookie to just the block ID, and the user should
886 // still get blocked when they log in again.
887 $request2 = new FauxRequest();
888 $request2->setCookie( 'BlockID', $block->getId() );
889 $user2 = User
::newFromSession( $request2 );
891 $this->assertNotEquals( $user1->getId(), $user2->getId() );
892 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
893 $this->assertTrue( $user2->isAnon() );
894 $this->assertFalse( $user2->isLoggedIn() );
895 $this->assertTrue( $user2->isBlocked() );
896 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
903 * @covers User::isPingLimitable
905 public function testIsPingLimitable() {
906 $request = new FauxRequest();
907 $request->setIP( '1.2.3.4' );
908 $user = User
::newFromSession( $request );
910 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
911 $this->assertTrue( $user->isPingLimitable() );
913 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
914 $this->assertFalse( $user->isPingLimitable() );
916 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
917 $this->assertFalse( $user->isPingLimitable() );
919 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
920 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
921 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
922 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
923 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
924 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
927 public function provideExperienceLevel() {
929 [ 2, 2, 'newcomer' ],
930 [ 12, 3, 'newcomer' ],
931 [ 8, 5, 'newcomer' ],
932 [ 15, 10, 'learner' ],
933 [ 450, 20, 'learner' ],
934 [ 460, 33, 'learner' ],
935 [ 525, 28, 'learner' ],
936 [ 538, 33, 'experienced' ],
941 * @covers User::getExperienceLevel
942 * @dataProvider provideExperienceLevel
944 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
945 $this->setMwGlobals( [
946 'wgLearnerEdits' => 10,
947 'wgLearnerMemberSince' => 4,
948 'wgExperiencedUserEdits' => 500,
949 'wgExperiencedUserMemberSince' => 30,
952 $db = wfGetDB( DB_MASTER
);
953 $userQuery = User
::getQueryInfo();
954 $row = $db->selectRow(
955 $userQuery['tables'],
956 $userQuery['fields'],
957 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
962 $row->user_editcount
= $editCount;
963 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
964 $user = User
::newFromRow( $row );
966 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
970 * @covers User::getExperienceLevel
972 public function testExperienceLevelAnon() {
973 $user = User
::newFromName( '10.11.12.13', false );
975 $this->assertFalse( $user->getExperienceLevel() );
978 public static function provideIsLocallBlockedProxy() {
980 [ '1.2.3.4', '1.2.3.4' ],
981 [ '1.2.3.4', '1.2.3.0/16' ],
986 * @dataProvider provideIsLocallBlockedProxy
987 * @covers User::isLocallyBlockedProxy
989 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
993 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1001 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1003 $this->setMwGlobals(
1006 'test' => $blockListEntry
1009 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1011 $this->hideDeprecated(
1012 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1013 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1015 $this->setMwGlobals(
1018 $blockListEntry => 'test'
1021 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1024 public function testActorId() {
1025 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1026 $this->hideDeprecated( 'User::selectFields' );
1028 // Newly-created user has an actor ID
1029 $user = User
::createNew( 'UserTestActorId1' );
1030 $id = $user->getId();
1031 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1033 $user = User
::newFromName( 'UserTestActorId2' );
1034 $user->addToDatabase();
1035 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1037 $user = User
::newFromName( 'UserTestActorId1' );
1038 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1040 $user = User
::newFromId( $id );
1041 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1043 $user2 = User
::newFromActorId( $user->getActorId() );
1044 $this->assertEquals( $user->getId(), $user2->getId(),
1045 'User::newFromActorId works for an existing user' );
1047 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1048 $user = User
::newFromRow( $row );
1049 $this->assertTrue( $user->getActorId() > 0,
1050 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1052 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1053 User
::purge( $domain, $id );
1054 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1055 ObjectCache
::getMainWANInstance()->clearProcessCache();
1057 $user = User
::newFromId( $id );
1058 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1059 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1061 $user->setName( 'UserTestActorId4-renamed' );
1062 $user->saveSettings();
1063 $this->assertEquals(
1065 $this->db
->selectField(
1066 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1068 'User::saveSettings updates actor table for name change'
1072 $ip = '192.168.12.34';
1073 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1075 $user = User
::newFromName( $ip, false );
1076 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1077 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1078 'Actor ID can be created for an anonymous user' );
1080 $user = User
::newFromName( $ip, false );
1081 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1082 $user2 = User
::newFromActorId( $user->getActorId() );
1083 $this->assertEquals( $user->getName(), $user2->getName(),
1084 'User::newFromActorId works for an anonymous user' );
1087 public function testNewFromAnyId() {
1089 $user = $this->getTestUser()->getUser();
1090 for ( $i = 1; $i <= 7; $i++
) {
1091 $test = User
::newFromAnyId(
1092 ( $i & 1 ) ?
$user->getId() : null,
1093 ( $i & 2 ) ?
$user->getName() : null,
1094 ( $i & 4 ) ?
$user->getActorId() : null
1096 $this->assertSame( $user->getId(), $test->getId() );
1097 $this->assertSame( $user->getName(), $test->getName() );
1098 $this->assertSame( $user->getActorId(), $test->getActorId() );
1101 // Anon user. Can't load by only user ID when that's 0.
1102 $user = User
::newFromName( '192.168.12.34', false );
1103 $user->getActorId( $this->db
); // Make sure an actor ID exists
1105 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1106 $this->assertSame( $user->getId(), $test->getId() );
1107 $this->assertSame( $user->getName(), $test->getName() );
1108 $this->assertSame( $user->getActorId(), $test->getActorId() );
1109 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1110 $this->assertSame( $user->getId(), $test->getId() );
1111 $this->assertSame( $user->getName(), $test->getName() );
1112 $this->assertSame( $user->getActorId(), $test->getActorId() );
1114 // Bogus data should still "work" as long as nothing triggers a ->load(),
1115 // and accessing the specified data shouldn't do that.
1116 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1117 $this->assertSame( 123456, $test->getId() );
1118 $this->assertSame( 'Bogus', $test->getName() );
1119 $this->assertSame( 654321, $test->getActorId() );
1121 // Exceptional cases
1123 User
::newFromAnyId( null, null, null );
1124 $this->fail( 'Expected exception not thrown' );
1125 } catch ( InvalidArgumentException
$ex ) {
1128 User
::newFromAnyId( 0, null, 0 );
1129 $this->fail( 'Expected exception not thrown' );
1130 } catch ( InvalidArgumentException
$ex ) {
1135 * @covers User::newFromIdentity
1137 public function testNewFromIdentity() {
1139 $user = $this->getTestUser()->getUser();
1141 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1144 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1145 $result = User
::newFromIdentity( $identity );
1146 $this->assertInstanceOf( User
::class, $result );
1147 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1148 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1149 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1152 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1153 $result = User
::newFromIdentity( $identity );
1154 $this->assertInstanceOf( User
::class, $result );
1155 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1156 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1157 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1160 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1161 $result = User
::newFromIdentity( $identity );
1162 $this->assertInstanceOf( User
::class, $result );
1163 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1164 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1165 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1169 * @covers User::getBlockedStatus
1170 * @covers User::getBlock
1171 * @covers User::blockedBy
1172 * @covers User::blockedFor
1173 * @covers User::isHidden
1174 * @covers User::isBlockedFrom
1176 public function testBlockInstanceCache() {
1177 // First, check the user isn't blocked
1178 $user = $this->getMutableTestUser()->getUser();
1179 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1180 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1181 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1182 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1183 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1184 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1187 $blocker = $this->getTestSysop()->getUser();
1188 $block = new Block( [
1190 'allowUsertalk' => false,
1191 'reason' => 'Because',
1193 $block->setTarget( $user );
1194 $block->setBlocker( $blocker );
1195 $res = $block->insert();
1196 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1198 // Clear cache and confirm it loaded the block properly
1199 $user->clearInstanceCache();
1200 $this->assertInstanceOf( Block
::class, $user->getBlock( false ) );
1201 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1202 $this->assertSame( 'Because', $user->blockedFor() );
1203 $this->assertTrue( (bool)$user->isHidden() );
1204 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1209 // Clear cache and confirm it loaded the not-blocked properly
1210 $user->clearInstanceCache();
1211 $this->assertNull( $user->getBlock( false ) );
1212 $this->assertSame( '', $user->blockedBy() );
1213 $this->assertSame( '', $user->blockedFor() );
1214 $this->assertFalse( (bool)$user->isHidden() );
1215 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1219 * @covers User::isBlockedFrom
1220 * @dataProvider provideIsBlockedFrom
1221 * @param string|null $title Title to test.
1222 * @param bool $expect Expected result from User::isBlockedFrom()
1223 * @param array $options Additional test options:
1224 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1225 * - 'allowUsertalk': (bool, default false) Passed to Block::__construct()
1226 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1228 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1229 $this->setMwGlobals( [
1230 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1233 $user = $this->getTestUser()->getUser();
1235 if ( $title === self
::USER_TALK_PAGE
) {
1236 $title = $user->getTalkPage();
1238 $title = Title
::newFromText( $title );
1242 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1243 $page = $this->getExistingTestPage(
1244 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1246 $restrictions[] = new PageRestriction( 0, $page->getId() );
1249 $block = new Block( [
1250 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1251 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1252 'sitewide' => !$restrictions,
1254 $block->setTarget( $user );
1255 $block->setBlocker( $this->getTestSysop()->getUser() );
1256 if ( $restrictions ) {
1257 $block->setRestrictions( $restrictions );
1262 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1268 public static function provideIsBlockedFrom() {
1270 'Basic operation' => [ 'Test page', true ],
1271 'User talk page, not allowed' => [ self
::USER_TALK_PAGE
, true, [
1272 'allowUsertalk' => false,
1275 'User talk page, allowed' => [
1276 self
::USER_TALK_PAGE
, false, [
1277 'allowUsertalk' => true,
1280 'User talk page, allowed but $wgBlockAllowsUTEdit is false' => [
1281 self
::USER_TALK_PAGE
, true, [
1282 'allowUsertalk' => true,
1283 'blockAllowsUTEdit' => false,
1286 'Partial block, blocking the page' => [
1287 'Test page', true, [
1288 'pageRestrictions' => [ 'Test page' ],
1291 'Partial block, not blocking the page' => [
1292 'Test page 2', false, [
1293 'pageRestrictions' => [ 'Test page' ],
1296 'Partial block, allowing user talk' => [
1297 self
::USER_TALK_PAGE
, false, [
1298 'allowUsertalk' => false,
1299 'pageRestrictions' => [ 'Test page' ],
1302 'Partial block, not allowing user talk' => [
1303 self
::USER_TALK_PAGE
, true, [
1304 'allowUsertalk' => true,
1305 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1308 'Partial block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1309 self
::USER_TALK_PAGE
, false, [
1310 'allowUsertalk' => false,
1311 'pageRestrictions' => [ 'Test page' ],
1312 'blockAllowsUTEdit' => false,
1315 'Partial block, not allowing user talk with $wgBlockAllowsUTEdit set to false' => [
1316 self
::USER_TALK_PAGE
, true, [
1317 'allowUsertalk' => true,
1318 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1319 'blockAllowsUTEdit' => false,
1326 * Block cookie should be set for IP Blocks if
1327 * wgCookieSetOnIpBlock is set to true
1329 public function testIpBlockCookieSet() {
1330 $this->setMwGlobals( [
1331 'wgCookieSetOnIpBlock' => true,
1332 'wgCookiePrefix' => 'wiki',
1333 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1337 $block = new Block( [
1338 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1340 $block->setTarget( '1.2.3.4' );
1341 $block->setBlocker( $this->getTestSysop()->getUser() );
1345 $request = new FauxRequest();
1346 $request->setIP( '1.2.3.4' );
1349 $user = User
::newFromSession( $request );
1350 $user->trackBlockWithCookie();
1352 // test cookie was set
1353 $cookies = $request->response()->getCookies();
1354 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1361 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1364 public function testIpBlockCookieNotSet() {
1365 $this->setMwGlobals( [
1366 'wgCookieSetOnIpBlock' => false,
1367 'wgCookiePrefix' => 'wiki',
1368 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1372 $block = new Block( [
1373 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1375 $block->setTarget( '1.2.3.4' );
1376 $block->setBlocker( $this->getTestSysop()->getUser() );
1380 $request = new FauxRequest();
1381 $request->setIP( '1.2.3.4' );
1384 $user = User
::newFromSession( $request );
1385 $user->trackBlockWithCookie();
1387 // test cookie was not set
1388 $cookies = $request->response()->getCookies();
1389 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1396 * When an ip user is blocked and then they log in, cookie block
1397 * should be invalid and the cookie removed.
1399 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1400 $this->setMwGlobals( [
1401 'wgAutoblockExpiry' => 8000,
1402 'wgCookieSetOnIpBlock' => true,
1403 'wgCookiePrefix' => 'wiki',
1404 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1408 $block = new Block( [
1409 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1411 $block->setTarget( '1.2.3.4' );
1412 $block->setBlocker( $this->getTestSysop()->getUser() );
1416 $request = new FauxRequest();
1417 $request->setIP( '1.2.3.4' );
1418 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1419 $request->setCookie( 'BlockID', $block->getCookieValue() );
1422 $user = User
::newFromSession( $request );
1424 // logged in users should be inmune to cookie block of type ip/range
1425 $this->assertFalse( $user->isBlocked() );
1427 // cookie is being cleared
1428 $cookies = $request->response()->getCookies();
1429 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );