3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\Block\DatabaseBlock
;
7 use MediaWiki\Block\CompositeBlock
;
8 use MediaWiki\Block\Restriction\PageRestriction
;
9 use MediaWiki\Block\Restriction\NamespaceRestriction
;
10 use MediaWiki\Block\SystemBlock
;
11 use MediaWiki\MediaWikiServices
;
12 use MediaWiki\User\UserIdentityValue
;
13 use Wikimedia\TestingAccessWrapper
;
18 class UserTest
extends MediaWikiTestCase
{
20 /** Constant for self::testIsBlockedFrom */
21 const USER_TALK_PAGE
= '<user talk page>';
28 protected function setUp() {
31 $this->setMwGlobals( [
32 'wgGroupPermissions' => [],
33 'wgRevokePermissions' => [],
34 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_NEW
,
36 $this->overrideMwServices();
38 $this->setUpPermissionGlobals();
40 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
43 private function setUpPermissionGlobals() {
44 global $wgGroupPermissions, $wgRevokePermissions;
46 # Data for regular $wgGroupPermissions test
47 $wgGroupPermissions['unittesters'] = [
53 $wgGroupPermissions['testwriters'] = [
59 # Data for regular $wgRevokePermissions test
60 $wgRevokePermissions['formertesters'] = [
64 # For the options test
65 $wgGroupPermissions['*'] = [
66 'editmyoptions' => true,
70 private function setSessionUser( User
$user, WebRequest
$request ) {
71 $this->setMwGlobals( 'wgUser', $user );
72 RequestContext
::getMain()->setUser( $user );
73 RequestContext
::getMain()->setRequest( $request );
74 TestingAccessWrapper
::newFromObject( $user )->mRequest
= $request;
75 $request->getSession()->setUser( $user );
76 $this->overrideMwServices();
80 * @covers User::getGroupPermissions
82 public function testGroupPermissions() {
83 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
84 $this->assertContains( 'runtest', $rights );
85 $this->assertNotContains( 'writetest', $rights );
86 $this->assertNotContains( 'modifytest', $rights );
87 $this->assertNotContains( 'nukeworld', $rights );
89 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
90 $this->assertContains( 'runtest', $rights );
91 $this->assertContains( 'writetest', $rights );
92 $this->assertContains( 'modifytest', $rights );
93 $this->assertNotContains( 'nukeworld', $rights );
97 * @covers User::getGroupPermissions
99 public function testRevokePermissions() {
100 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
101 $this->assertNotContains( 'runtest', $rights );
102 $this->assertNotContains( 'writetest', $rights );
103 $this->assertNotContains( 'modifytest', $rights );
104 $this->assertNotContains( 'nukeworld', $rights );
108 * TODO: Remove. This is the same as PermissionManagerTest::testGetUserPermissions
109 * @covers User::getRights
111 public function testUserPermissions() {
112 $rights = $this->user
->getRights();
113 $this->assertContains( 'runtest', $rights );
114 $this->assertNotContains( 'writetest', $rights );
115 $this->assertNotContains( 'modifytest', $rights );
116 $this->assertNotContains( 'nukeworld', $rights );
120 * TODO: Remove. This is the same as PermissionManagerTest::testGetUserPermissionsHooks
121 * @covers User::getRights
123 public function testUserGetRightsHooks() {
124 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
125 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
127 $rights = $user->getRights();
128 $this->assertContains( 'test', $rights, 'sanity check' );
129 $this->assertContains( 'runtest', $rights, 'sanity check' );
130 $this->assertContains( 'writetest', $rights, 'sanity check' );
131 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
133 // Add a hook manipluating the rights
134 $this->setTemporaryHook( 'UserGetRights', function ( $user, &$rights ) {
135 $rights[] = 'nukeworld';
136 $rights = array_diff( $rights, [ 'writetest' ] );
139 $this->resetServices();
140 $rights = $user->getRights();
141 $this->assertContains( 'test', $rights );
142 $this->assertContains( 'runtest', $rights );
143 $this->assertNotContains( 'writetest', $rights );
144 $this->assertContains( 'nukeworld', $rights );
146 // Add a Session that limits rights
147 $mock = $this->getMockBuilder( stdClass
::class )
148 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
150 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
151 $mock->method( 'getSessionId' )->willReturn(
152 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
154 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
155 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
156 ->setMethods( [ 'getSession' ] )
158 $mockRequest->method( 'getSession' )->willReturn( $session );
159 $userWrapper->mRequest
= $mockRequest;
161 $this->resetServices();
162 $rights = $user->getRights();
163 $this->assertContains( 'test', $rights );
164 $this->assertNotContains( 'runtest', $rights );
165 $this->assertNotContains( 'writetest', $rights );
166 $this->assertNotContains( 'nukeworld', $rights );
170 * @dataProvider provideGetGroupsWithPermission
171 * @covers User::getGroupsWithPermission
173 public function testGetGroupsWithPermission( $expected, $right ) {
174 $result = User
::getGroupsWithPermission( $right );
178 $this->assertEquals( $expected, $result, "Groups with permission $right" );
181 public static function provideGetGroupsWithPermission() {
184 [ 'unittesters', 'testwriters' ],
203 * @dataProvider provideIPs
206 public function testIsIP( $value, $result, $message ) {
207 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
210 public static function provideIPs() {
212 [ '', false, 'Empty string' ],
213 [ ' ', false, 'Blank space' ],
214 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
215 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
216 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
217 [ '203.0.113.0', true, 'IPv4 example' ],
218 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
219 // Not valid IPs but classified as such by MediaWiki for negated asserting
220 // of whether this might be the identifier of a logged-out user or whether
221 // to allow usernames like it.
222 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
223 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
228 * @dataProvider provideUserNames
229 * @covers User::isValidUserName
231 public function testIsValidUserName( $username, $result, $message ) {
232 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
235 public static function provideUserNames() {
237 [ '', false, 'Empty string' ],
238 [ ' ', false, 'Blank space' ],
239 [ 'abcd', false, 'Starts with small letter' ],
240 [ 'Ab/cd', false, 'Contains slash' ],
241 [ 'Ab cd', true, 'Whitespace' ],
242 [ '192.168.1.1', false, 'IP' ],
243 [ '116.17.184.5/32', false, 'IP range' ],
244 [ '::e:f:2001/96', false, 'IPv6 range' ],
245 [ 'User:Abcd', false, 'Reserved Namespace' ],
246 [ '12abcd232', true, 'Starts with Numbers' ],
247 [ '?abcd', true, 'Start with ? mark' ],
248 [ '#abcd', false, 'Start with #' ],
249 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
250 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
251 [ 'Ab cd', false, ' Ideographic space' ],
252 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
253 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
254 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
259 * Test User::editCount
261 * @covers User::getEditCount
263 public function testGetEditCount() {
264 $user = $this->getMutableTestUser()->getUser();
266 // let the user have a few (3) edits
267 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
268 for ( $i = 0; $i < 3; $i++
) {
269 $page->doEditContent(
270 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
280 $user->getEditCount(),
281 'After three edits, the user edit count should be 3'
284 // increase the edit count
285 $user->incEditCount();
286 $user->clearInstanceCache();
290 $user->getEditCount(),
291 'After increasing the edit count manually, the user edit count should be 4'
296 * Test User::editCount
298 * @covers User::getEditCount
300 public function testGetEditCountForAnons() {
301 $user = User
::newFromName( 'Anonymous' );
304 $user->getEditCount(),
305 'Edit count starts null for anonymous users.'
308 $user->incEditCount();
311 $user->getEditCount(),
312 'Edit count remains null for anonymous users despite calls to increase it.'
317 * Test User::editCount
319 * @covers User::incEditCount
321 public function testIncEditCount() {
322 $user = $this->getMutableTestUser()->getUser();
323 $user->incEditCount();
325 $reloadedUser = User
::newFromId( $user->getId() );
326 $reloadedUser->incEditCount();
330 $reloadedUser->getEditCount(),
331 'Increasing the edit count after a fresh load leaves the object up to date.'
336 * Test changing user options.
337 * @covers User::setOption
338 * @covers User::getOption
340 public function testOptions() {
341 $user = $this->getMutableTestUser()->getUser();
343 $user->setOption( 'userjs-someoption', 'test' );
344 $user->setOption( 'rclimit', 200 );
345 $user->setOption( 'wpwatchlistdays', '0' );
346 $user->saveSettings();
348 $user = User
::newFromName( $user->getName() );
349 $user->load( User
::READ_LATEST
);
350 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
351 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
353 $user = User
::newFromName( $user->getName() );
354 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
355 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
356 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
358 // Check that an option saved as a string '0' is returned as an integer.
359 $user = User
::newFromName( $user->getName() );
360 $user->load( User
::READ_LATEST
);
361 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
366 * Make sure defaults are loaded when setOption is called.
367 * @covers User::loadOptions
369 public function testAnonOptions() {
370 global $wgDefaultUserOptions;
371 $this->user
->setOption( 'userjs-someoption', 'test' );
372 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
373 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
377 * Test password validity checks. There are 3 checks in core,
378 * - ensure the password meets the minimal length
379 * - ensure the password is not the same as the username
380 * - ensure the username/password combo isn't forbidden
381 * @covers User::checkPasswordValidity()
382 * @covers User::isValidPassword()
384 public function testCheckPasswordValidity() {
385 $this->setMwGlobals( [
386 'wgPasswordPolicy' => [
389 'MinimalPasswordLength' => 8,
390 'MinimumPasswordLengthToLogin' => 1,
391 'PasswordCannotMatchUsername' => 1,
394 'MinimalPasswordLength' => 6,
395 'PasswordCannotMatchUsername' => true,
396 'PasswordCannotMatchBlacklist' => true,
397 'MaximalPasswordLength' => 40,
401 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
402 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
403 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
404 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
405 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
410 $user = static::getTestUser()->getUser();
413 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
416 $this->assertFalse( $user->isValidPassword( 'a' ) );
417 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
418 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
421 $longPass = str_repeat( 'a', 41 );
422 $this->assertFalse( $user->isValidPassword( $longPass ) );
423 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
424 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
427 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
428 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
430 // On the forbidden list
431 $user = User
::newFromName( 'Useruser' );
432 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
436 * @covers User::getCanonicalName()
437 * @dataProvider provideGetCanonicalName
439 public function testGetCanonicalName( $name, $expectedArray ) {
440 // fake interwiki map for the 'Interwiki prefix' testcase
441 $this->mergeMwGlobalArrayValue( 'wgHooks', [
442 'InterwikiLoadPrefix' => [
443 function ( $prefix, &$iwdata ) {
444 if ( $prefix === 'interwiki' ) {
446 'iw_url' => 'http://example.com/',
456 foreach ( $expectedArray as $validate => $expected ) {
459 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
463 public static function provideGetCanonicalName() {
465 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
466 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
467 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
468 'valid' => false, 'false' => 'Talk:Username' ] ],
469 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
470 'valid' => false, 'false' => 'Interwiki:Username' ] ],
471 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
472 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
473 'usable' => 'Multi spaces' ] ],
474 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
475 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
476 'valid' => false, 'false' => 'In[]valid' ] ],
477 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
478 'false' => 'With / slash' ] ],
483 * @covers User::equals
485 public function testEquals() {
486 $first = $this->getMutableTestUser()->getUser();
487 $second = User
::newFromName( $first->getName() );
489 $this->assertTrue( $first->equals( $first ) );
490 $this->assertTrue( $first->equals( $second ) );
491 $this->assertTrue( $second->equals( $first ) );
493 $third = $this->getMutableTestUser()->getUser();
494 $fourth = $this->getMutableTestUser()->getUser();
496 $this->assertFalse( $third->equals( $fourth ) );
497 $this->assertFalse( $fourth->equals( $third ) );
499 // Test users loaded from db with id
500 $user = $this->getMutableTestUser()->getUser();
501 $fifth = User
::newFromId( $user->getId() );
502 $sixth = User
::newFromName( $user->getName() );
503 $this->assertTrue( $fifth->equals( $sixth ) );
507 * @covers User::getId
509 public function testGetId() {
510 $user = static::getTestUser()->getUser();
511 $this->assertTrue( $user->getId() > 0 );
515 * @covers User::isRegistered
516 * @covers User::isLoggedIn
517 * @covers User::isAnon
519 public function testLoggedIn() {
520 $user = $this->getMutableTestUser()->getUser();
521 $this->assertTrue( $user->isRegistered() );
522 $this->assertTrue( $user->isLoggedIn() );
523 $this->assertFalse( $user->isAnon() );
525 // Non-existent users are perceived as anonymous
526 $user = User
::newFromName( 'UTNonexistent' );
527 $this->assertFalse( $user->isRegistered() );
528 $this->assertFalse( $user->isLoggedIn() );
529 $this->assertTrue( $user->isAnon() );
532 $this->assertFalse( $user->isRegistered() );
533 $this->assertFalse( $user->isLoggedIn() );
534 $this->assertTrue( $user->isAnon() );
538 * @covers User::checkAndSetTouched
540 public function testCheckAndSetTouched() {
541 $user = $this->getMutableTestUser()->getUser();
542 $user = TestingAccessWrapper
::newFromObject( $user );
543 $this->assertTrue( $user->isLoggedIn() );
545 $touched = $user->getDBTouched();
547 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
548 $this->assertGreaterThan(
549 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
551 $touched = $user->getDBTouched();
553 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
554 $this->assertGreaterThan(
555 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
559 * @covers User::findUsersByGroup
561 public function testFindUsersByGroup() {
562 // FIXME: fails under postgres
563 $this->markTestSkippedIfDbType( 'postgres' );
565 $users = User
::findUsersByGroup( [] );
566 $this->assertEquals( 0, iterator_count( $users ) );
568 $users = User
::findUsersByGroup( 'foo' );
569 $this->assertEquals( 0, iterator_count( $users ) );
571 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
572 $users = User
::findUsersByGroup( 'foo' );
573 $this->assertEquals( 1, iterator_count( $users ) );
575 $this->assertTrue( $user->equals( $users->current() ) );
577 // arguments have OR relationship
578 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
579 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
580 $this->assertEquals( 2, iterator_count( $users ) );
582 $this->assertTrue( $user->equals( $users->current() ) );
584 $this->assertTrue( $user2->equals( $users->current() ) );
586 // users are not duplicated
587 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
588 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
589 $this->assertEquals( 1, iterator_count( $users ) );
591 $this->assertTrue( $user->equals( $users->current() ) );
595 * When a user is autoblocked a cookie is set with which to track them
596 * in case they log out and change IP addresses.
597 * @link https://phabricator.wikimedia.org/T5233
598 * @covers User::trackBlockWithCookie
600 public function testAutoblockCookies() {
601 // Set up the bits of global configuration that we use.
602 $this->setMwGlobals( [
603 'wgCookieSetOnAutoblock' => true,
604 'wgCookiePrefix' => 'wmsitetitle',
605 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
608 // Unregister the hooks for proper unit testing
609 $this->mergeMwGlobalArrayValue( 'wgHooks', [
610 'PerformRetroactiveAutoblock' => []
613 // 1. Log in a test user, and block them.
614 $user1tmp = $this->getTestUser()->getUser();
615 $request1 = new FauxRequest();
616 $request1->getSession()->setUser( $user1tmp );
617 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
618 $block = new DatabaseBlock( [
619 'enableAutoblock' => true,
620 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
622 $block->setBlocker( $this->getTestSysop()->getUser() );
623 $block->setTarget( $user1tmp );
624 $res = $block->insert();
625 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
626 $user1 = User
::newFromSession( $request1 );
627 $user1->mBlock
= $block;
630 // Confirm that the block has been applied as required.
631 $this->assertTrue( $user1->isLoggedIn() );
632 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
633 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
634 $this->assertTrue( $block->isAutoblocking() );
635 $this->assertGreaterThanOrEqual( 1, $block->getId() );
637 // Test for the desired cookie name, value, and expiry.
638 $cookies = $request1->response()->getCookies();
639 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
640 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
641 $cookieId = MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue(
642 $cookies['wmsitetitleBlockID']['value']
644 $this->assertEquals( $block->getId(), $cookieId );
646 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
647 $request2 = new FauxRequest();
648 $request2->setCookie( 'BlockID', $block->getCookieValue() );
649 $user2 = User
::newFromSession( $request2 );
651 $this->assertNotEquals( $user1->getId(), $user2->getId() );
652 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
653 $this->assertTrue( $user2->isAnon() );
654 $this->assertFalse( $user2->isLoggedIn() );
655 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
656 // Non-strict type-check.
657 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
658 // Can't directly compare the objects because of member type differences.
659 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
660 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
661 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
663 // 3. Finally, set up a request as a new user, and the block should still be applied.
664 $user3tmp = $this->getTestUser()->getUser();
665 $request3 = new FauxRequest();
666 $request3->getSession()->setUser( $user3tmp );
667 $request3->setCookie( 'BlockID', $block->getId() );
668 $user3 = User
::newFromSession( $request3 );
670 $this->assertTrue( $user3->isLoggedIn() );
671 $this->assertInstanceOf( DatabaseBlock
::class, $user3->getBlock() );
672 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
679 * Make sure that no cookie is set to track autoblocked users
680 * when $wgCookieSetOnAutoblock is false.
681 * @covers User::trackBlockWithCookie
683 public function testAutoblockCookiesDisabled() {
684 // Set up the bits of global configuration that we use.
685 $this->setMwGlobals( [
686 'wgCookieSetOnAutoblock' => false,
687 'wgCookiePrefix' => 'wm_no_cookies',
688 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
691 // Unregister the hooks for proper unit testing
692 $this->mergeMwGlobalArrayValue( 'wgHooks', [
693 'PerformRetroactiveAutoblock' => []
696 // 1. Log in a test user, and block them.
697 $testUser = $this->getTestUser()->getUser();
698 $request1 = new FauxRequest();
699 $request1->getSession()->setUser( $testUser );
700 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
701 $block->setBlocker( $this->getTestSysop()->getUser() );
702 $block->setTarget( $testUser );
703 $res = $block->insert();
704 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
705 $user = User
::newFromSession( $request1 );
706 $user->mBlock
= $block;
709 // 2. Test that the cookie IS NOT present.
710 $this->assertTrue( $user->isLoggedIn() );
711 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock() );
712 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
713 $this->assertTrue( $block->isAutoblocking() );
714 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
715 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
716 $cookies = $request1->response()->getCookies();
717 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
724 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
725 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
726 * the cookie's should change with it.
727 * @covers User::trackBlockWithCookie
729 public function testAutoblockCookieInfiniteExpiry() {
730 $this->setMwGlobals( [
731 'wgCookieSetOnAutoblock' => true,
732 'wgCookiePrefix' => 'wm_infinite_block',
733 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
736 // Unregister the hooks for proper unit testing
737 $this->mergeMwGlobalArrayValue( 'wgHooks', [
738 'PerformRetroactiveAutoblock' => []
741 // 1. Log in a test user, and block them indefinitely.
742 $user1Tmp = $this->getTestUser()->getUser();
743 $request1 = new FauxRequest();
744 $request1->getSession()->setUser( $user1Tmp );
745 $block = new DatabaseBlock( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
746 $block->setBlocker( $this->getTestSysop()->getUser() );
747 $block->setTarget( $user1Tmp );
748 $res = $block->insert();
749 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
750 $user1 = User
::newFromSession( $request1 );
751 $user1->mBlock
= $block;
754 // 2. Test the cookie's expiry timestamp.
755 $this->assertTrue( $user1->isLoggedIn() );
756 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
757 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
758 $this->assertTrue( $block->isAutoblocking() );
759 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
760 $cookies = $request1->response()->getCookies();
761 // Test the cookie's expiry to the nearest minute.
762 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
763 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
764 // Check for expiry dates in a 10-second window, to account for slow testing.
767 $cookies['wm_infinite_blockBlockID']['expire'],
772 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
773 $newExpiry = wfTimestamp() +
2 * 60 * 60;
774 $block->setExpiry( wfTimestamp( TS_MW
, $newExpiry ) );
776 $user2tmp = $this->getTestUser()->getUser();
777 $request2 = new FauxRequest();
778 $request2->getSession()->setUser( $user2tmp );
779 $user2 = User
::newFromSession( $request2 );
780 $user2->mBlock
= $block;
782 $cookies = $request2->response()->getCookies();
783 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
784 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
791 * @covers User::getBlockedStatus
793 public function testSoftBlockRanges() {
794 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
796 // IP isn't in $wgSoftBlockRanges
797 $wgUser = new User();
798 $request = new FauxRequest();
799 $request->setIP( '192.168.0.1' );
800 $this->setSessionUser( $wgUser, $request );
801 $this->assertNull( $wgUser->getBlock() );
803 // IP is in $wgSoftBlockRanges
804 $wgUser = new User();
805 $request = new FauxRequest();
806 $request->setIP( '10.20.30.40' );
807 $this->setSessionUser( $wgUser, $request );
808 $block = $wgUser->getBlock();
809 $this->assertInstanceOf( SystemBlock
::class, $block );
810 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
812 // Make sure the block is really soft
813 $wgUser = $this->getTestUser()->getUser();
814 $request = new FauxRequest();
815 $request->setIP( '10.20.30.40' );
816 $this->setSessionUser( $wgUser, $request );
817 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
818 $this->assertNull( $wgUser->getBlock() );
822 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
823 * @covers User::trackBlockWithCookie
825 public function testAutoblockCookieInauthentic() {
826 // Set up the bits of global configuration that we use.
827 $this->setMwGlobals( [
828 'wgCookieSetOnAutoblock' => true,
829 'wgCookiePrefix' => 'wmsitetitle',
830 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
833 // Unregister the hooks for proper unit testing
834 $this->mergeMwGlobalArrayValue( 'wgHooks', [
835 'PerformRetroactiveAutoblock' => []
838 // 1. Log in a blocked test user.
839 $user1tmp = $this->getTestUser()->getUser();
840 $request1 = new FauxRequest();
841 $request1->getSession()->setUser( $user1tmp );
842 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
843 $block->setBlocker( $this->getTestSysop()->getUser() );
844 $block->setTarget( $user1tmp );
845 $res = $block->insert();
846 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
847 $user1 = User
::newFromSession( $request1 );
848 $user1->mBlock
= $block;
851 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
853 $request2 = new FauxRequest();
854 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
855 $user2 = User
::newFromSession( $request2 );
857 $this->assertTrue( $user2->isAnon() );
858 $this->assertFalse( $user2->isLoggedIn() );
859 $this->assertNull( $user2->getBlock() );
866 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
867 * This checks that a non-authenticated cookie still works.
868 * @covers User::trackBlockWithCookie
870 public function testAutoblockCookieNoSecretKey() {
871 // Set up the bits of global configuration that we use.
872 $this->setMwGlobals( [
873 'wgCookieSetOnAutoblock' => true,
874 'wgCookiePrefix' => 'wmsitetitle',
875 'wgSecretKey' => null,
878 // Unregister the hooks for proper unit testing
879 $this->mergeMwGlobalArrayValue( 'wgHooks', [
880 'PerformRetroactiveAutoblock' => []
883 // 1. Log in a blocked test user.
884 $user1tmp = $this->getTestUser()->getUser();
885 $request1 = new FauxRequest();
886 $request1->getSession()->setUser( $user1tmp );
887 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
888 $block->setBlocker( $this->getTestSysop()->getUser() );
889 $block->setTarget( $user1tmp );
890 $res = $block->insert();
891 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
892 $user1 = User
::newFromSession( $request1 );
893 $user1->mBlock
= $block;
895 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
897 // 2. Create a new request, set the cookie to just the block ID, and the user should
898 // still get blocked when they log in again.
899 $request2 = new FauxRequest();
900 $request2->setCookie( 'BlockID', $block->getId() );
901 $user2 = User
::newFromSession( $request2 );
903 $this->assertNotEquals( $user1->getId(), $user2->getId() );
904 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
905 $this->assertTrue( $user2->isAnon() );
906 $this->assertFalse( $user2->isLoggedIn() );
907 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
908 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
915 * @covers User::isPingLimitable
917 public function testIsPingLimitable() {
918 $request = new FauxRequest();
919 $request->setIP( '1.2.3.4' );
920 $user = User
::newFromSession( $request );
922 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
923 $this->assertTrue( $user->isPingLimitable() );
925 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
926 $this->assertFalse( $user->isPingLimitable() );
928 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
929 $this->assertFalse( $user->isPingLimitable() );
931 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
932 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
933 ->setMethods( [ 'getIP', 'getId', 'getGroups' ] )->getMock();
934 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
935 $noRateLimitUser->expects( $this->any() )->method( 'getId' )->willReturn( 0 );
936 $noRateLimitUser->expects( $this->any() )->method( 'getGroups' )->willReturn( [] );
937 $this->overrideUserPermissions( $noRateLimitUser, 'noratelimit' );
938 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
941 public function provideExperienceLevel() {
943 [ 2, 2, 'newcomer' ],
944 [ 12, 3, 'newcomer' ],
945 [ 8, 5, 'newcomer' ],
946 [ 15, 10, 'learner' ],
947 [ 450, 20, 'learner' ],
948 [ 460, 33, 'learner' ],
949 [ 525, 28, 'learner' ],
950 [ 538, 33, 'experienced' ],
955 * @covers User::getExperienceLevel
956 * @dataProvider provideExperienceLevel
958 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
959 $this->setMwGlobals( [
960 'wgLearnerEdits' => 10,
961 'wgLearnerMemberSince' => 4,
962 'wgExperiencedUserEdits' => 500,
963 'wgExperiencedUserMemberSince' => 30,
966 $db = wfGetDB( DB_MASTER
);
967 $userQuery = User
::getQueryInfo();
968 $row = $db->selectRow(
969 $userQuery['tables'],
970 $userQuery['fields'],
971 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
976 $row->user_editcount
= $editCount;
977 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
978 $user = User
::newFromRow( $row );
980 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
984 * @covers User::getExperienceLevel
986 public function testExperienceLevelAnon() {
987 $user = User
::newFromName( '10.11.12.13', false );
989 $this->assertFalse( $user->getExperienceLevel() );
992 public static function provideIsLocallyBlockedProxy() {
994 [ '1.2.3.4', '1.2.3.4' ],
995 [ '1.2.3.4', '1.2.3.0/16' ],
1000 * @dataProvider provideIsLocallyBlockedProxy
1001 * @covers User::isLocallyBlockedProxy
1003 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1004 $this->hideDeprecated( 'User::isLocallyBlockedProxy' );
1006 $this->setMwGlobals(
1009 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1011 $this->setMwGlobals(
1017 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1019 $this->setMwGlobals(
1022 'test' => $blockListEntry
1025 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1029 * @covers User::newFromActorId
1031 public function testActorId() {
1032 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1033 $this->hideDeprecated( 'User::selectFields' );
1035 // Newly-created user has an actor ID
1036 $user = User
::createNew( 'UserTestActorId1' );
1037 $id = $user->getId();
1038 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1040 $user = User
::newFromName( 'UserTestActorId2' );
1041 $user->addToDatabase();
1042 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1044 $user = User
::newFromName( 'UserTestActorId1' );
1045 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1047 $user = User
::newFromId( $id );
1048 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1050 $user2 = User
::newFromActorId( $user->getActorId() );
1051 $this->assertEquals( $user->getId(), $user2->getId(),
1052 'User::newFromActorId works for an existing user' );
1054 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1055 $user = User
::newFromRow( $row );
1056 $this->assertTrue( $user->getActorId() > 0,
1057 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1059 $user = User
::newFromId( $id );
1060 $user->setName( 'UserTestActorId4-renamed' );
1061 $user->saveSettings();
1062 $this->assertEquals(
1064 $this->db
->selectField(
1065 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1067 'User::saveSettings updates actor table for name change'
1071 $ip = '192.168.12.34';
1072 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1074 $user = User
::newFromName( $ip, false );
1075 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1076 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1077 'Actor ID can be created for an anonymous user' );
1079 $user = User
::newFromName( $ip, false );
1080 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1081 $user2 = User
::newFromActorId( $user->getActorId() );
1082 $this->assertEquals( $user->getName(), $user2->getName(),
1083 'User::newFromActorId works for an anonymous user' );
1087 * Actor tests with SCHEMA_COMPAT_READ_OLD
1089 * The only thing different from testActorId() is the behavior if the actor
1090 * row doesn't exist in the DB, since with SCHEMA_COMPAT_READ_NEW that
1091 * situation can't happen. But we copy all the other tests too just for good measure.
1093 * @covers User::newFromActorId
1095 public function testActorId_old() {
1096 $this->setMwGlobals( [
1097 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
1099 $this->overrideMwServices();
1101 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1102 $this->hideDeprecated( 'User::selectFields' );
1104 // Newly-created user has an actor ID
1105 $user = User
::createNew( 'UserTestActorIdOld1' );
1106 $id = $user->getId();
1107 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1109 $user = User
::newFromName( 'UserTestActorIdOld2' );
1110 $user->addToDatabase();
1111 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1113 $user = User
::newFromName( 'UserTestActorIdOld1' );
1114 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1116 $user = User
::newFromId( $id );
1117 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1119 $user2 = User
::newFromActorId( $user->getActorId() );
1120 $this->assertEquals( $user->getId(), $user2->getId(),
1121 'User::newFromActorId works for an existing user' );
1123 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1124 $user = User
::newFromRow( $row );
1125 $this->assertTrue( $user->getActorId() > 0,
1126 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1128 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1129 User
::purge( $domain, $id );
1130 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1132 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
1134 $user = User
::newFromId( $id );
1135 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1136 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1138 $user->setName( 'UserTestActorIdOld4-renamed' );
1139 $user->saveSettings();
1140 $this->assertEquals(
1142 $this->db
->selectField(
1143 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1145 'User::saveSettings updates actor table for name change'
1149 $ip = '192.168.12.34';
1150 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1152 $user = User
::newFromName( $ip, false );
1153 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1154 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1155 'Actor ID can be created for an anonymous user' );
1157 $user = User
::newFromName( $ip, false );
1158 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1159 $user2 = User
::newFromActorId( $user->getActorId() );
1160 $this->assertEquals( $user->getName(), $user2->getName(),
1161 'User::newFromActorId works for an anonymous user' );
1165 * @covers User::newFromAnyId
1167 public function testNewFromAnyId() {
1169 $user = $this->getTestUser()->getUser();
1170 for ( $i = 1; $i <= 7; $i++
) {
1171 $test = User
::newFromAnyId(
1172 ( $i & 1 ) ?
$user->getId() : null,
1173 ( $i & 2 ) ?
$user->getName() : null,
1174 ( $i & 4 ) ?
$user->getActorId() : null
1176 $this->assertSame( $user->getId(), $test->getId() );
1177 $this->assertSame( $user->getName(), $test->getName() );
1178 $this->assertSame( $user->getActorId(), $test->getActorId() );
1181 // Anon user. Can't load by only user ID when that's 0.
1182 $user = User
::newFromName( '192.168.12.34', false );
1183 $user->getActorId( $this->db
); // Make sure an actor ID exists
1185 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1186 $this->assertSame( $user->getId(), $test->getId() );
1187 $this->assertSame( $user->getName(), $test->getName() );
1188 $this->assertSame( $user->getActorId(), $test->getActorId() );
1189 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1190 $this->assertSame( $user->getId(), $test->getId() );
1191 $this->assertSame( $user->getName(), $test->getName() );
1192 $this->assertSame( $user->getActorId(), $test->getActorId() );
1194 // Bogus data should still "work" as long as nothing triggers a ->load(),
1195 // and accessing the specified data shouldn't do that.
1196 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1197 $this->assertSame( 123456, $test->getId() );
1198 $this->assertSame( 'Bogus', $test->getName() );
1199 $this->assertSame( 654321, $test->getActorId() );
1201 // Loading remote user by name from remote wiki should succeed
1202 $test = User
::newFromAnyId( null, 'Bogus', null, 'foo' );
1203 $this->assertSame( 0, $test->getId() );
1204 $this->assertSame( 'Bogus', $test->getName() );
1205 $this->assertSame( 0, $test->getActorId() );
1206 $test = User
::newFromAnyId( 123456, 'Bogus', 654321, 'foo' );
1207 $this->assertSame( 0, $test->getId() );
1208 $this->assertSame( 0, $test->getActorId() );
1210 // Exceptional cases
1212 User
::newFromAnyId( null, null, null );
1213 $this->fail( 'Expected exception not thrown' );
1214 } catch ( InvalidArgumentException
$ex ) {
1217 User
::newFromAnyId( 0, null, 0 );
1218 $this->fail( 'Expected exception not thrown' );
1219 } catch ( InvalidArgumentException
$ex ) {
1222 // Loading remote user by id from remote wiki should fail
1224 User
::newFromAnyId( 123456, null, 654321, 'foo' );
1225 $this->fail( 'Expected exception not thrown' );
1226 } catch ( InvalidArgumentException
$ex ) {
1231 * @covers User::newFromIdentity
1233 public function testNewFromIdentity() {
1235 $user = $this->getTestUser()->getUser();
1237 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1240 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1241 $result = User
::newFromIdentity( $identity );
1242 $this->assertInstanceOf( User
::class, $result );
1243 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1244 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1245 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1248 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1249 $result = User
::newFromIdentity( $identity );
1250 $this->assertInstanceOf( User
::class, $result );
1251 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1252 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1253 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1256 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1257 $result = User
::newFromIdentity( $identity );
1258 $this->assertInstanceOf( User
::class, $result );
1259 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1260 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1261 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1265 * @covers User::getBlockedStatus
1266 * @covers User::getBlock
1267 * @covers User::blockedBy
1268 * @covers User::blockedFor
1269 * @covers User::isHidden
1270 * @covers User::isBlockedFrom
1272 public function testBlockInstanceCache() {
1273 // First, check the user isn't blocked
1274 $user = $this->getMutableTestUser()->getUser();
1275 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1276 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1277 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1278 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1279 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1280 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1283 $blocker = $this->getTestSysop()->getUser();
1284 $block = new DatabaseBlock( [
1286 'allowUsertalk' => false,
1287 'reason' => 'Because',
1289 $block->setTarget( $user );
1290 $block->setBlocker( $blocker );
1291 $res = $block->insert();
1292 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1294 // Clear cache and confirm it loaded the block properly
1295 $user->clearInstanceCache();
1296 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock( false ) );
1297 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1298 $this->assertSame( 'Because', $user->blockedFor() );
1299 $this->assertTrue( (bool)$user->isHidden() );
1300 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1305 // Clear cache and confirm it loaded the not-blocked properly
1306 $user->clearInstanceCache();
1307 $this->assertNull( $user->getBlock( false ) );
1308 $this->assertSame( '', $user->blockedBy() );
1309 $this->assertSame( '', $user->blockedFor() );
1310 $this->assertFalse( (bool)$user->isHidden() );
1311 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1315 * @covers User::getBlockedStatus
1317 public function testCompositeBlocks() {
1318 $user = $this->getMutableTestUser()->getUser();
1319 $request = $user->getRequest();
1320 $this->setSessionUser( $user, $request );
1322 $ipBlock = new Block( [
1323 'address' => $user->getRequest()->getIP(),
1324 'by' => $this->getTestSysop()->getUser()->getId(),
1325 'createAccount' => true,
1329 $userBlock = new Block( [
1331 'by' => $this->getTestSysop()->getUser()->getId(),
1332 'createAccount' => false,
1334 $userBlock->insert();
1336 $block = $user->getBlock();
1337 $this->assertInstanceOf( CompositeBlock
::class, $block );
1338 $this->assertTrue( $block->isCreateAccountBlocked() );
1339 $this->assertTrue( $block->appliesToPasswordReset() );
1340 $this->assertTrue( $block->appliesToNamespace( NS_MAIN
) );
1344 * @covers User::isBlockedFrom
1345 * @dataProvider provideIsBlockedFrom
1346 * @param string|null $title Title to test.
1347 * @param bool $expect Expected result from User::isBlockedFrom()
1348 * @param array $options Additional test options:
1349 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1350 * - 'allowUsertalk': (bool, default false) Passed to DatabaseBlock::__construct()
1351 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1353 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1354 $this->setMwGlobals( [
1355 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1358 $user = $this->getTestUser()->getUser();
1360 if ( $title === self
::USER_TALK_PAGE
) {
1361 $title = $user->getTalkPage();
1363 $title = Title
::newFromText( $title );
1367 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1368 $page = $this->getExistingTestPage(
1369 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1371 $restrictions[] = new PageRestriction( 0, $page->getId() );
1373 foreach ( $options['namespaceRestrictions'] ??
[] as $ns ) {
1374 $restrictions[] = new NamespaceRestriction( 0, $ns );
1377 $block = new DatabaseBlock( [
1378 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1379 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1380 'sitewide' => !$restrictions,
1382 $block->setTarget( $user );
1383 $block->setBlocker( $this->getTestSysop()->getUser() );
1384 if ( $restrictions ) {
1385 $block->setRestrictions( $restrictions );
1390 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1396 public static function provideIsBlockedFrom() {
1398 'Sitewide block, basic operation' => [ 'Test page', true ],
1399 'Sitewide block, not allowing user talk' => [
1400 self
::USER_TALK_PAGE
, true, [
1401 'allowUsertalk' => false,
1404 'Sitewide block, allowing user talk' => [
1405 self
::USER_TALK_PAGE
, false, [
1406 'allowUsertalk' => true,
1409 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1410 self
::USER_TALK_PAGE
, true, [
1411 'allowUsertalk' => true,
1412 'blockAllowsUTEdit' => false,
1415 'Partial block, blocking the page' => [
1416 'Test page', true, [
1417 'pageRestrictions' => [ 'Test page' ],
1420 'Partial block, not blocking the page' => [
1421 'Test page 2', false, [
1422 'pageRestrictions' => [ 'Test page' ],
1425 'Partial block, not allowing user talk but user talk page is not blocked' => [
1426 self
::USER_TALK_PAGE
, false, [
1427 'allowUsertalk' => false,
1428 'pageRestrictions' => [ 'Test page' ],
1431 'Partial block, allowing user talk but user talk page is blocked' => [
1432 self
::USER_TALK_PAGE
, true, [
1433 'allowUsertalk' => true,
1434 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1437 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1438 self
::USER_TALK_PAGE
, false, [
1439 'allowUsertalk' => false,
1440 'pageRestrictions' => [ 'Test page' ],
1441 'blockAllowsUTEdit' => false,
1444 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1445 self
::USER_TALK_PAGE
, true, [
1446 'allowUsertalk' => true,
1447 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1448 'blockAllowsUTEdit' => false,
1451 'Partial user talk namespace block, not allowing user talk' => [
1452 self
::USER_TALK_PAGE
, true, [
1453 'allowUsertalk' => false,
1454 'namespaceRestrictions' => [ NS_USER_TALK
],
1457 'Partial user talk namespace block, allowing user talk' => [
1458 self
::USER_TALK_PAGE
, false, [
1459 'allowUsertalk' => true,
1460 'namespaceRestrictions' => [ NS_USER_TALK
],
1463 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1464 self
::USER_TALK_PAGE
, true, [
1465 'allowUsertalk' => true,
1466 'namespaceRestrictions' => [ NS_USER_TALK
],
1467 'blockAllowsUTEdit' => false,
1474 * Block cookie should be set for IP Blocks if
1475 * wgCookieSetOnIpBlock is set to true
1476 * @covers User::trackBlockWithCookie
1478 public function testIpBlockCookieSet() {
1479 $this->setMwGlobals( [
1480 'wgCookieSetOnIpBlock' => true,
1481 'wgCookiePrefix' => 'wiki',
1482 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1486 $block = new DatabaseBlock( [
1487 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1489 $block->setTarget( '1.2.3.4' );
1490 $block->setBlocker( $this->getTestSysop()->getUser() );
1494 $request = new FauxRequest();
1495 $request->setIP( '1.2.3.4' );
1498 $user = User
::newFromSession( $request );
1499 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1501 // test cookie was set
1502 $cookies = $request->response()->getCookies();
1503 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1510 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1512 * @covers User::trackBlockWithCookie
1514 public function testIpBlockCookieNotSet() {
1515 $this->setMwGlobals( [
1516 'wgCookieSetOnIpBlock' => false,
1517 'wgCookiePrefix' => 'wiki',
1518 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1522 $block = new DatabaseBlock( [
1523 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1525 $block->setTarget( '1.2.3.4' );
1526 $block->setBlocker( $this->getTestSysop()->getUser() );
1530 $request = new FauxRequest();
1531 $request->setIP( '1.2.3.4' );
1534 $user = User
::newFromSession( $request );
1535 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1537 // test cookie was not set
1538 $cookies = $request->response()->getCookies();
1539 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1546 * When an ip user is blocked and then they log in, cookie block
1547 * should be invalid and the cookie removed.
1548 * @covers User::trackBlockWithCookie
1550 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1551 $this->setMwGlobals( [
1552 'wgAutoblockExpiry' => 8000,
1553 'wgCookieSetOnIpBlock' => true,
1554 'wgCookiePrefix' => 'wiki',
1555 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1559 $block = new DatabaseBlock( [
1560 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1562 $block->setTarget( '1.2.3.4' );
1563 $block->setBlocker( $this->getTestSysop()->getUser() );
1567 $request = new FauxRequest();
1568 $request->setIP( '1.2.3.4' );
1569 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1570 $request->setCookie( 'BlockID', $block->getCookieValue() );
1573 $user = User
::newFromSession( $request );
1575 // logged in users should be inmune to cookie block of type ip/range
1576 $this->assertNull( $user->getBlock() );
1578 // cookie is being cleared
1579 $cookies = $request->response()->getCookies();
1580 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1587 * @covers User::getFirstEditTimestamp
1588 * @covers User::getLatestEditTimestamp
1590 public function testGetFirstLatestEditTimestamp() {
1591 $clock = MWTimestamp
::convert( TS_UNIX
, '20100101000000' );
1592 MWTimestamp
::setFakeTime( function () use ( &$clock ) {
1593 return $clock +
= 1000;
1596 $user = $this->getTestUser()->getUser();
1597 $firstRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'one', 'test' );
1598 $secondRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'two', 'test' );
1599 // Sanity check: revisions timestamp are different
1600 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1602 $this->assertEquals( $firstRevision->getTimestamp(), $user->getFirstEditTimestamp() );
1603 $this->assertEquals( $secondRevision->getTimestamp(), $user->getLatestEditTimestamp() );
1605 MWTimestamp
::setFakeTime( false );
1611 * @param string $title
1612 * @param string $content
1613 * @param string $comment
1614 * @return \MediaWiki\Revision\RevisionRecord|null
1616 private static function makeEdit( User
$user, $title, $content, $comment ) {
1617 $page = WikiPage
::factory( Title
::newFromText( $title ) );
1618 $content = ContentHandler
::makeContent( $content, $page->getTitle() );
1619 $updater = $page->newPageUpdater( $user );
1620 $updater->setContent( 'main', $content );
1621 return $updater->saveRevision( CommentStoreComment
::newUnsavedComment( $comment ) );
1625 * @covers User::idFromName
1627 public function testExistingIdFromName() {
1629 array_key_exists( $this->user
->getName(), User
::$idCacheByName ),
1630 'Test user should already be in the id cache.'
1633 $this->user
->getId(), User
::idFromName( $this->user
->getName() ),
1634 'Id is correctly retreived from the cache.'
1637 $this->user
->getId(), User
::idFromName( $this->user
->getName(), User
::READ_LATEST
),
1638 'Id is correctly retreived from the database.'
1643 * @covers User::idFromName
1645 public function testNonExistingIdFromName() {
1647 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1648 'Non exisitng user should not be in the id cache.'
1650 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );
1652 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1653 'Username will be cached when requested once.'
1655 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );