3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\MediaWikiServices
;
7 use MediaWiki\User\UserIdentityValue
;
8 use Wikimedia\TestingAccessWrapper
;
13 class UserTest
extends MediaWikiTestCase
{
19 protected function setUp() {
22 $this->setMwGlobals( [
23 'wgGroupPermissions' => [],
24 'wgRevokePermissions' => [],
25 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
27 $this->overrideMwServices();
29 $this->setUpPermissionGlobals();
31 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
34 private function setUpPermissionGlobals() {
35 global $wgGroupPermissions, $wgRevokePermissions;
37 # Data for regular $wgGroupPermissions test
38 $wgGroupPermissions['unittesters'] = [
44 $wgGroupPermissions['testwriters'] = [
50 # Data for regular $wgRevokePermissions test
51 $wgRevokePermissions['formertesters'] = [
55 # For the options test
56 $wgGroupPermissions['*'] = [
57 'editmyoptions' => true,
62 * @covers User::getGroupPermissions
64 public function testGroupPermissions() {
65 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
66 $this->assertContains( 'runtest', $rights );
67 $this->assertNotContains( 'writetest', $rights );
68 $this->assertNotContains( 'modifytest', $rights );
69 $this->assertNotContains( 'nukeworld', $rights );
71 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
72 $this->assertContains( 'runtest', $rights );
73 $this->assertContains( 'writetest', $rights );
74 $this->assertContains( 'modifytest', $rights );
75 $this->assertNotContains( 'nukeworld', $rights );
79 * @covers User::getGroupPermissions
81 public function testRevokePermissions() {
82 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
83 $this->assertNotContains( 'runtest', $rights );
84 $this->assertNotContains( 'writetest', $rights );
85 $this->assertNotContains( 'modifytest', $rights );
86 $this->assertNotContains( 'nukeworld', $rights );
90 * @covers User::getRights
92 public function testUserPermissions() {
93 $rights = $this->user
->getRights();
94 $this->assertContains( 'runtest', $rights );
95 $this->assertNotContains( 'writetest', $rights );
96 $this->assertNotContains( 'modifytest', $rights );
97 $this->assertNotContains( 'nukeworld', $rights );
101 * @covers User::getRights
103 public function testUserGetRightsHooks() {
104 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
105 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
107 $rights = $user->getRights();
108 $this->assertContains( 'test', $rights, 'sanity check' );
109 $this->assertContains( 'runtest', $rights, 'sanity check' );
110 $this->assertContains( 'writetest', $rights, 'sanity check' );
111 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
113 // Add a hook manipluating the rights
114 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
115 $rights[] = 'nukeworld';
116 $rights = array_diff( $rights, [ 'writetest' ] );
119 $userWrapper->mRights
= null;
120 $rights = $user->getRights();
121 $this->assertContains( 'test', $rights );
122 $this->assertContains( 'runtest', $rights );
123 $this->assertNotContains( 'writetest', $rights );
124 $this->assertContains( 'nukeworld', $rights );
126 // Add a Session that limits rights
127 $mock = $this->getMockBuilder( stdClass
::class )
128 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
130 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
131 $mock->method( 'getSessionId' )->willReturn(
132 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
134 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
135 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
136 ->setMethods( [ 'getSession' ] )
138 $mockRequest->method( 'getSession' )->willReturn( $session );
139 $userWrapper->mRequest
= $mockRequest;
141 $userWrapper->mRights
= null;
142 $rights = $user->getRights();
143 $this->assertContains( 'test', $rights );
144 $this->assertNotContains( 'runtest', $rights );
145 $this->assertNotContains( 'writetest', $rights );
146 $this->assertNotContains( 'nukeworld', $rights );
150 * @dataProvider provideGetGroupsWithPermission
151 * @covers User::getGroupsWithPermission
153 public function testGetGroupsWithPermission( $expected, $right ) {
154 $result = User
::getGroupsWithPermission( $right );
158 $this->assertEquals( $expected, $result, "Groups with permission $right" );
161 public static function provideGetGroupsWithPermission() {
164 [ 'unittesters', 'testwriters' ],
183 * @dataProvider provideIPs
186 public function testIsIP( $value, $result, $message ) {
187 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
190 public static function provideIPs() {
192 [ '', false, 'Empty string' ],
193 [ ' ', false, 'Blank space' ],
194 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
195 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
196 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
197 [ '203.0.113.0', true, 'IPv4 example' ],
198 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
199 // Not valid IPs but classified as such by MediaWiki for negated asserting
200 // of whether this might be the identifier of a logged-out user or whether
201 // to allow usernames like it.
202 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
203 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
208 * @dataProvider provideUserNames
209 * @covers User::isValidUserName
211 public function testIsValidUserName( $username, $result, $message ) {
212 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
215 public static function provideUserNames() {
217 [ '', false, 'Empty string' ],
218 [ ' ', false, 'Blank space' ],
219 [ 'abcd', false, 'Starts with small letter' ],
220 [ 'Ab/cd', false, 'Contains slash' ],
221 [ 'Ab cd', true, 'Whitespace' ],
222 [ '192.168.1.1', false, 'IP' ],
223 [ '116.17.184.5/32', false, 'IP range' ],
224 [ '::e:f:2001/96', false, 'IPv6 range' ],
225 [ 'User:Abcd', false, 'Reserved Namespace' ],
226 [ '12abcd232', true, 'Starts with Numbers' ],
227 [ '?abcd', true, 'Start with ? mark' ],
228 [ '#abcd', false, 'Start with #' ],
229 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
230 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
231 [ 'Ab cd', false, ' Ideographic space' ],
232 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
233 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
234 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
239 * Test User::editCount
241 * @covers User::getEditCount
243 public function testGetEditCount() {
244 $user = $this->getMutableTestUser()->getUser();
246 // let the user have a few (3) edits
247 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
248 for ( $i = 0; $i < 3; $i++
) {
249 $page->doEditContent(
250 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
260 $user->getEditCount(),
261 'After three edits, the user edit count should be 3'
264 // increase the edit count
265 $user->incEditCount();
266 $user->clearInstanceCache();
270 $user->getEditCount(),
271 'After increasing the edit count manually, the user edit count should be 4'
276 * Test User::editCount
278 * @covers User::getEditCount
280 public function testGetEditCountForAnons() {
281 $user = User
::newFromName( 'Anonymous' );
284 $user->getEditCount(),
285 'Edit count starts null for anonymous users.'
288 $user->incEditCount();
291 $user->getEditCount(),
292 'Edit count remains null for anonymous users despite calls to increase it.'
297 * Test User::editCount
299 * @covers User::incEditCount
301 public function testIncEditCount() {
302 $user = $this->getMutableTestUser()->getUser();
303 $user->incEditCount();
305 $reloadedUser = User
::newFromId( $user->getId() );
306 $reloadedUser->incEditCount();
310 $reloadedUser->getEditCount(),
311 'Increasing the edit count after a fresh load leaves the object up to date.'
316 * Test changing user options.
317 * @covers User::setOption
318 * @covers User::getOption
320 public function testOptions() {
321 $user = $this->getMutableTestUser()->getUser();
323 $user->setOption( 'userjs-someoption', 'test' );
324 $user->setOption( 'rclimit', 200 );
325 $user->setOption( 'wpwatchlistdays', '0' );
326 $user->saveSettings();
328 $user = User
::newFromName( $user->getName() );
329 $user->load( User
::READ_LATEST
);
330 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
331 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
333 $user = User
::newFromName( $user->getName() );
334 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
335 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
336 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
338 // Check that an option saved as a string '0' is returned as an integer.
339 $user = User
::newFromName( $user->getName() );
340 $user->load( User
::READ_LATEST
);
341 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
346 * Make sure defaults are loaded when setOption is called.
347 * @covers User::loadOptions
349 public function testAnonOptions() {
350 global $wgDefaultUserOptions;
351 $this->user
->setOption( 'userjs-someoption', 'test' );
352 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
353 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
357 * Test password validity checks. There are 3 checks in core,
358 * - ensure the password meets the minimal length
359 * - ensure the password is not the same as the username
360 * - ensure the username/password combo isn't forbidden
361 * @covers User::checkPasswordValidity()
362 * @covers User::getPasswordValidity()
363 * @covers User::isValidPassword()
365 public function testCheckPasswordValidity() {
366 $this->setMwGlobals( [
367 'wgPasswordPolicy' => [
370 'MinimalPasswordLength' => 8,
371 'MinimumPasswordLengthToLogin' => 1,
372 'PasswordCannotMatchUsername' => 1,
375 'MinimalPasswordLength' => 6,
376 'PasswordCannotMatchUsername' => true,
377 'PasswordCannotMatchBlacklist' => true,
378 'MaximalPasswordLength' => 40,
382 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
383 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
384 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
385 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
386 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
391 $user = static::getTestUser()->getUser();
394 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
397 $this->assertFalse( $user->isValidPassword( 'a' ) );
398 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
399 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
400 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
403 $longPass = str_repeat( 'a', 41 );
404 $this->assertFalse( $user->isValidPassword( $longPass ) );
405 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
406 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
407 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
410 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
411 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
412 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
414 // On the forbidden list
415 $user = User
::newFromName( 'Useruser' );
416 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
417 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
421 * @covers User::getCanonicalName()
422 * @dataProvider provideGetCanonicalName
424 public function testGetCanonicalName( $name, $expectedArray ) {
425 // fake interwiki map for the 'Interwiki prefix' testcase
426 $this->mergeMwGlobalArrayValue( 'wgHooks', [
427 'InterwikiLoadPrefix' => [
428 function ( $prefix, &$iwdata ) {
429 if ( $prefix === 'interwiki' ) {
431 'iw_url' => 'http://example.com/',
441 foreach ( $expectedArray as $validate => $expected ) {
444 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
448 public static function provideGetCanonicalName() {
450 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
451 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
452 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
453 'valid' => false, 'false' => 'Talk:Username' ] ],
454 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
455 'valid' => false, 'false' => 'Interwiki:Username' ] ],
456 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
457 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
458 'usable' => 'Multi spaces' ] ],
459 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
460 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
461 'valid' => false, 'false' => 'In[]valid' ] ],
462 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
463 'false' => 'With / slash' ] ],
468 * @covers User::equals
470 public function testEquals() {
471 $first = $this->getMutableTestUser()->getUser();
472 $second = User
::newFromName( $first->getName() );
474 $this->assertTrue( $first->equals( $first ) );
475 $this->assertTrue( $first->equals( $second ) );
476 $this->assertTrue( $second->equals( $first ) );
478 $third = $this->getMutableTestUser()->getUser();
479 $fourth = $this->getMutableTestUser()->getUser();
481 $this->assertFalse( $third->equals( $fourth ) );
482 $this->assertFalse( $fourth->equals( $third ) );
484 // Test users loaded from db with id
485 $user = $this->getMutableTestUser()->getUser();
486 $fifth = User
::newFromId( $user->getId() );
487 $sixth = User
::newFromName( $user->getName() );
488 $this->assertTrue( $fifth->equals( $sixth ) );
492 * @covers User::getId
494 public function testGetId() {
495 $user = static::getTestUser()->getUser();
496 $this->assertTrue( $user->getId() > 0 );
500 * @covers User::isLoggedIn
501 * @covers User::isAnon
503 public function testLoggedIn() {
504 $user = $this->getMutableTestUser()->getUser();
505 $this->assertTrue( $user->isLoggedIn() );
506 $this->assertFalse( $user->isAnon() );
508 // Non-existent users are perceived as anonymous
509 $user = User
::newFromName( 'UTNonexistent' );
510 $this->assertFalse( $user->isLoggedIn() );
511 $this->assertTrue( $user->isAnon() );
514 $this->assertFalse( $user->isLoggedIn() );
515 $this->assertTrue( $user->isAnon() );
519 * @covers User::checkAndSetTouched
521 public function testCheckAndSetTouched() {
522 $user = $this->getMutableTestUser()->getUser();
523 $user = TestingAccessWrapper
::newFromObject( $user );
524 $this->assertTrue( $user->isLoggedIn() );
526 $touched = $user->getDBTouched();
528 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
529 $this->assertGreaterThan(
530 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
532 $touched = $user->getDBTouched();
534 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
535 $this->assertGreaterThan(
536 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
540 * @covers User::findUsersByGroup
542 public function testFindUsersByGroup() {
543 // FIXME: fails under postgres
544 $this->markTestSkippedIfDbType( 'postgres' );
546 $users = User
::findUsersByGroup( [] );
547 $this->assertEquals( 0, iterator_count( $users ) );
549 $users = User
::findUsersByGroup( 'foo' );
550 $this->assertEquals( 0, iterator_count( $users ) );
552 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
553 $users = User
::findUsersByGroup( 'foo' );
554 $this->assertEquals( 1, iterator_count( $users ) );
556 $this->assertTrue( $user->equals( $users->current() ) );
558 // arguments have OR relationship
559 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
560 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
561 $this->assertEquals( 2, iterator_count( $users ) );
563 $this->assertTrue( $user->equals( $users->current() ) );
565 $this->assertTrue( $user2->equals( $users->current() ) );
567 // users are not duplicated
568 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
569 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
570 $this->assertEquals( 1, iterator_count( $users ) );
572 $this->assertTrue( $user->equals( $users->current() ) );
576 * When a user is autoblocked a cookie is set with which to track them
577 * in case they log out and change IP addresses.
578 * @link https://phabricator.wikimedia.org/T5233
580 public function testAutoblockCookies() {
581 // Set up the bits of global configuration that we use.
582 $this->setMwGlobals( [
583 'wgCookieSetOnAutoblock' => true,
584 'wgCookiePrefix' => 'wmsitetitle',
585 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
588 // Unregister the hooks for proper unit testing
589 $this->mergeMwGlobalArrayValue( 'wgHooks', [
590 'PerformRetroactiveAutoblock' => []
593 // 1. Log in a test user, and block them.
594 $userBlocker = $this->getTestSysop()->getUser();
595 $user1tmp = $this->getTestUser()->getUser();
596 $request1 = new FauxRequest();
597 $request1->getSession()->setUser( $user1tmp );
598 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
599 $block = new Block( [
600 'enableAutoblock' => true,
601 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
603 $block->setBlocker( $this->getTestSysop()->getUser() );
604 $block->setTarget( $user1tmp );
605 $block->setBlocker( $userBlocker );
606 $res = $block->insert();
607 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
608 $user1 = User
::newFromSession( $request1 );
609 $user1->mBlock
= $block;
612 // Confirm that the block has been applied as required.
613 $this->assertTrue( $user1->isLoggedIn() );
614 $this->assertTrue( $user1->isBlocked() );
615 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
616 $this->assertTrue( $block->isAutoblocking() );
617 $this->assertGreaterThanOrEqual( 1, $block->getId() );
619 // Test for the desired cookie name, value, and expiry.
620 $cookies = $request1->response()->getCookies();
621 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
622 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
623 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
624 $this->assertEquals( $block->getId(), $cookieValue );
626 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
627 $request2 = new FauxRequest();
628 $request2->setCookie( 'BlockID', $block->getCookieValue() );
629 $user2 = User
::newFromSession( $request2 );
631 $this->assertNotEquals( $user1->getId(), $user2->getId() );
632 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
633 $this->assertTrue( $user2->isAnon() );
634 $this->assertFalse( $user2->isLoggedIn() );
635 $this->assertTrue( $user2->isBlocked() );
636 // Non-strict type-check.
637 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
638 // Can't directly compare the objects because of member type differences.
639 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
640 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
641 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
643 // 3. Finally, set up a request as a new user, and the block should still be applied.
644 $user3tmp = $this->getTestUser()->getUser();
645 $request3 = new FauxRequest();
646 $request3->getSession()->setUser( $user3tmp );
647 $request3->setCookie( 'BlockID', $block->getId() );
648 $user3 = User
::newFromSession( $request3 );
650 $this->assertTrue( $user3->isLoggedIn() );
651 $this->assertTrue( $user3->isBlocked() );
652 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
659 * Make sure that no cookie is set to track autoblocked users
660 * when $wgCookieSetOnAutoblock is false.
662 public function testAutoblockCookiesDisabled() {
663 // Set up the bits of global configuration that we use.
664 $this->setMwGlobals( [
665 'wgCookieSetOnAutoblock' => false,
666 'wgCookiePrefix' => 'wm_no_cookies',
667 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
670 // Unregister the hooks for proper unit testing
671 $this->mergeMwGlobalArrayValue( 'wgHooks', [
672 'PerformRetroactiveAutoblock' => []
675 // 1. Log in a test user, and block them.
676 $userBlocker = $this->getTestSysop()->getUser();
677 $testUser = $this->getTestUser()->getUser();
678 $request1 = new FauxRequest();
679 $request1->getSession()->setUser( $testUser );
680 $block = new Block( [ 'enableAutoblock' => true ] );
681 $block->setBlocker( $this->getTestSysop()->getUser() );
682 $block->setTarget( $testUser );
683 $block->setBlocker( $userBlocker );
684 $res = $block->insert();
685 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
686 $user = User
::newFromSession( $request1 );
687 $user->mBlock
= $block;
690 // 2. Test that the cookie IS NOT present.
691 $this->assertTrue( $user->isLoggedIn() );
692 $this->assertTrue( $user->isBlocked() );
693 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
694 $this->assertTrue( $block->isAutoblocking() );
695 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
696 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
697 $cookies = $request1->response()->getCookies();
698 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
705 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
706 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
707 * the cookie's should change with it.
709 public function testAutoblockCookieInfiniteExpiry() {
710 $this->setMwGlobals( [
711 'wgCookieSetOnAutoblock' => true,
712 'wgCookiePrefix' => 'wm_infinite_block',
713 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
716 // Unregister the hooks for proper unit testing
717 $this->mergeMwGlobalArrayValue( 'wgHooks', [
718 'PerformRetroactiveAutoblock' => []
721 // 1. Log in a test user, and block them indefinitely.
722 $userBlocker = $this->getTestSysop()->getUser();
723 $user1Tmp = $this->getTestUser()->getUser();
724 $request1 = new FauxRequest();
725 $request1->getSession()->setUser( $user1Tmp );
726 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
727 $block->setBlocker( $this->getTestSysop()->getUser() );
728 $block->setTarget( $user1Tmp );
729 $block->setBlocker( $userBlocker );
730 $res = $block->insert();
731 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
732 $user1 = User
::newFromSession( $request1 );
733 $user1->mBlock
= $block;
736 // 2. Test the cookie's expiry timestamp.
737 $this->assertTrue( $user1->isLoggedIn() );
738 $this->assertTrue( $user1->isBlocked() );
739 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
740 $this->assertTrue( $block->isAutoblocking() );
741 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
742 $cookies = $request1->response()->getCookies();
743 // Test the cookie's expiry to the nearest minute.
744 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
745 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
746 // Check for expiry dates in a 10-second window, to account for slow testing.
749 $cookies['wm_infinite_blockBlockID']['expire'],
754 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
755 $newExpiry = wfTimestamp() +
2 * 60 * 60;
756 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
758 $user2tmp = $this->getTestUser()->getUser();
759 $request2 = new FauxRequest();
760 $request2->getSession()->setUser( $user2tmp );
761 $user2 = User
::newFromSession( $request2 );
762 $user2->mBlock
= $block;
764 $cookies = $request2->response()->getCookies();
765 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
766 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
772 public function testSoftBlockRanges() {
775 $this->setMwGlobals( [
776 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
780 // IP isn't in $wgSoftBlockRanges
781 $request = new FauxRequest();
782 $request->setIP( '192.168.0.1' );
783 $wgUser = User
::newFromSession( $request );
784 $this->assertNull( $wgUser->getBlock() );
786 // IP is in $wgSoftBlockRanges
787 $request = new FauxRequest();
788 $request->setIP( '10.20.30.40' );
789 $wgUser = User
::newFromSession( $request );
790 $block = $wgUser->getBlock();
791 $this->assertInstanceOf( Block
::class, $block );
792 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
794 // Make sure the block is really soft
795 $request->getSession()->setUser( $this->getTestUser()->getUser() );
796 $wgUser = User
::newFromSession( $request );
797 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
798 $this->assertNull( $wgUser->getBlock() );
802 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
804 public function testAutoblockCookieInauthentic() {
805 // Set up the bits of global configuration that we use.
806 $this->setMwGlobals( [
807 'wgCookieSetOnAutoblock' => true,
808 'wgCookiePrefix' => 'wmsitetitle',
809 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
812 // Unregister the hooks for proper unit testing
813 $this->mergeMwGlobalArrayValue( 'wgHooks', [
814 'PerformRetroactiveAutoblock' => []
817 // 1. Log in a blocked test user.
818 $userBlocker = $this->getTestSysop()->getUser();
819 $user1tmp = $this->getTestUser()->getUser();
820 $request1 = new FauxRequest();
821 $request1->getSession()->setUser( $user1tmp );
822 $block = new Block( [ 'enableAutoblock' => true ] );
823 $block->setBlocker( $this->getTestSysop()->getUser() );
824 $block->setTarget( $user1tmp );
825 $block->setBlocker( $userBlocker );
826 $res = $block->insert();
827 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
828 $user1 = User
::newFromSession( $request1 );
829 $user1->mBlock
= $block;
832 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
834 $request2 = new FauxRequest();
835 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
836 $user2 = User
::newFromSession( $request2 );
838 $this->assertTrue( $user2->isAnon() );
839 $this->assertFalse( $user2->isLoggedIn() );
840 $this->assertFalse( $user2->isBlocked() );
847 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
848 * This checks that a non-authenticated cookie still works.
850 public function testAutoblockCookieNoSecretKey() {
851 // Set up the bits of global configuration that we use.
852 $this->setMwGlobals( [
853 'wgCookieSetOnAutoblock' => true,
854 'wgCookiePrefix' => 'wmsitetitle',
855 'wgSecretKey' => null,
858 // Unregister the hooks for proper unit testing
859 $this->mergeMwGlobalArrayValue( 'wgHooks', [
860 'PerformRetroactiveAutoblock' => []
863 // 1. Log in a blocked test user.
864 $userBlocker = $this->getTestSysop()->getUser();
865 $user1tmp = $this->getTestUser()->getUser();
866 $request1 = new FauxRequest();
867 $request1->getSession()->setUser( $user1tmp );
868 $block = new Block( [ 'enableAutoblock' => true ] );
869 $block->setBlocker( $this->getTestSysop()->getUser() );
870 $block->setTarget( $user1tmp );
871 $block->setBlocker( $userBlocker );
872 $res = $block->insert();
873 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
874 $user1 = User
::newFromSession( $request1 );
875 $user1->mBlock
= $block;
877 $this->assertTrue( $user1->isBlocked() );
879 // 2. Create a new request, set the cookie to just the block ID, and the user should
880 // still get blocked when they log in again.
881 $request2 = new FauxRequest();
882 $request2->setCookie( 'BlockID', $block->getId() );
883 $user2 = User
::newFromSession( $request2 );
885 $this->assertNotEquals( $user1->getId(), $user2->getId() );
886 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
887 $this->assertTrue( $user2->isAnon() );
888 $this->assertFalse( $user2->isLoggedIn() );
889 $this->assertTrue( $user2->isBlocked() );
890 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
897 * @covers User::isPingLimitable
899 public function testIsPingLimitable() {
900 $request = new FauxRequest();
901 $request->setIP( '1.2.3.4' );
902 $user = User
::newFromSession( $request );
904 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
905 $this->assertTrue( $user->isPingLimitable() );
907 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
908 $this->assertFalse( $user->isPingLimitable() );
910 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
911 $this->assertFalse( $user->isPingLimitable() );
913 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
914 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
915 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
916 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
917 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
918 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
921 public function provideExperienceLevel() {
923 [ 2, 2, 'newcomer' ],
924 [ 12, 3, 'newcomer' ],
925 [ 8, 5, 'newcomer' ],
926 [ 15, 10, 'learner' ],
927 [ 450, 20, 'learner' ],
928 [ 460, 33, 'learner' ],
929 [ 525, 28, 'learner' ],
930 [ 538, 33, 'experienced' ],
935 * @covers User::getExperienceLevel
936 * @dataProvider provideExperienceLevel
938 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
939 $this->setMwGlobals( [
940 'wgLearnerEdits' => 10,
941 'wgLearnerMemberSince' => 4,
942 'wgExperiencedUserEdits' => 500,
943 'wgExperiencedUserMemberSince' => 30,
946 $db = wfGetDB( DB_MASTER
);
947 $userQuery = User
::getQueryInfo();
948 $row = $db->selectRow(
949 $userQuery['tables'],
950 $userQuery['fields'],
951 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
956 $row->user_editcount
= $editCount;
957 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
958 $user = User
::newFromRow( $row );
960 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
964 * @covers User::getExperienceLevel
966 public function testExperienceLevelAnon() {
967 $user = User
::newFromName( '10.11.12.13', false );
969 $this->assertFalse( $user->getExperienceLevel() );
972 public static function provideIsLocallBlockedProxy() {
974 [ '1.2.3.4', '1.2.3.4' ],
975 [ '1.2.3.4', '1.2.3.0/16' ],
980 * @dataProvider provideIsLocallBlockedProxy
981 * @covers User::isLocallyBlockedProxy
983 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
987 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
995 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1000 'test' => $blockListEntry
1003 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1005 $this->hideDeprecated(
1006 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1007 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1009 $this->setMwGlobals(
1012 $blockListEntry => 'test'
1015 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1018 public function testActorId() {
1019 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1020 $this->hideDeprecated( 'User::selectFields' );
1022 // Newly-created user has an actor ID
1023 $user = User
::createNew( 'UserTestActorId1' );
1024 $id = $user->getId();
1025 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1027 $user = User
::newFromName( 'UserTestActorId2' );
1028 $user->addToDatabase();
1029 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1031 $user = User
::newFromName( 'UserTestActorId1' );
1032 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1034 $user = User
::newFromId( $id );
1035 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1037 $user2 = User
::newFromActorId( $user->getActorId() );
1038 $this->assertEquals( $user->getId(), $user2->getId(),
1039 'User::newFromActorId works for an existing user' );
1041 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1042 $user = User
::newFromRow( $row );
1043 $this->assertTrue( $user->getActorId() > 0,
1044 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1046 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1047 User
::purge( $domain, $id );
1048 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1049 ObjectCache
::getMainWANInstance()->clearProcessCache();
1051 $user = User
::newFromId( $id );
1052 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1053 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1055 $user->setName( 'UserTestActorId4-renamed' );
1056 $user->saveSettings();
1057 $this->assertEquals(
1059 $this->db
->selectField(
1060 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1062 'User::saveSettings updates actor table for name change'
1066 $ip = '192.168.12.34';
1067 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1069 $user = User
::newFromName( $ip, false );
1070 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1071 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1072 'Actor ID can be created for an anonymous user' );
1074 $user = User
::newFromName( $ip, false );
1075 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1076 $user2 = User
::newFromActorId( $user->getActorId() );
1077 $this->assertEquals( $user->getName(), $user2->getName(),
1078 'User::newFromActorId works for an anonymous user' );
1081 public function testNewFromAnyId() {
1083 $user = $this->getTestUser()->getUser();
1084 for ( $i = 1; $i <= 7; $i++
) {
1085 $test = User
::newFromAnyId(
1086 ( $i & 1 ) ?
$user->getId() : null,
1087 ( $i & 2 ) ?
$user->getName() : null,
1088 ( $i & 4 ) ?
$user->getActorId() : null
1090 $this->assertSame( $user->getId(), $test->getId() );
1091 $this->assertSame( $user->getName(), $test->getName() );
1092 $this->assertSame( $user->getActorId(), $test->getActorId() );
1095 // Anon user. Can't load by only user ID when that's 0.
1096 $user = User
::newFromName( '192.168.12.34', false );
1097 $user->getActorId( $this->db
); // Make sure an actor ID exists
1099 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1100 $this->assertSame( $user->getId(), $test->getId() );
1101 $this->assertSame( $user->getName(), $test->getName() );
1102 $this->assertSame( $user->getActorId(), $test->getActorId() );
1103 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1104 $this->assertSame( $user->getId(), $test->getId() );
1105 $this->assertSame( $user->getName(), $test->getName() );
1106 $this->assertSame( $user->getActorId(), $test->getActorId() );
1108 // Bogus data should still "work" as long as nothing triggers a ->load(),
1109 // and accessing the specified data shouldn't do that.
1110 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1111 $this->assertSame( 123456, $test->getId() );
1112 $this->assertSame( 'Bogus', $test->getName() );
1113 $this->assertSame( 654321, $test->getActorId() );
1115 // Exceptional cases
1117 User
::newFromAnyId( null, null, null );
1118 $this->fail( 'Expected exception not thrown' );
1119 } catch ( InvalidArgumentException
$ex ) {
1122 User
::newFromAnyId( 0, null, 0 );
1123 $this->fail( 'Expected exception not thrown' );
1124 } catch ( InvalidArgumentException
$ex ) {
1129 * @covers User::newFromIdentity
1131 public function testNewFromIdentity() {
1133 $user = $this->getTestUser()->getUser();
1135 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1138 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1139 $result = User
::newFromIdentity( $identity );
1140 $this->assertInstanceOf( User
::class, $result );
1141 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1142 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1143 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1146 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1147 $result = User
::newFromIdentity( $identity );
1148 $this->assertInstanceOf( User
::class, $result );
1149 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1150 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1151 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1154 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1155 $result = User
::newFromIdentity( $identity );
1156 $this->assertInstanceOf( User
::class, $result );
1157 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1158 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1159 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1163 * @covers User::getBlockedStatus
1164 * @covers User::getBlock
1165 * @covers User::blockedBy
1166 * @covers User::blockedFor
1167 * @covers User::isHidden
1168 * @covers User::isBlockedFrom
1170 public function testBlockInstanceCache() {
1171 // First, check the user isn't blocked
1172 $user = $this->getMutableTestUser()->getUser();
1173 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1174 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1175 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1176 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1177 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1178 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1181 $blocker = $this->getTestSysop()->getUser();
1182 $block = new Block( [
1184 'allowUsertalk' => false,
1185 'reason' => 'Because',
1187 $block->setTarget( $user );
1188 $block->setBlocker( $blocker );
1189 $res = $block->insert();
1190 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1192 // Clear cache and confirm it loaded the block properly
1193 $user->clearInstanceCache();
1194 $this->assertInstanceOf( Block
::class, $user->getBlock( false ) );
1195 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1196 $this->assertSame( 'Because', $user->blockedFor() );
1197 $this->assertTrue( (bool)$user->isHidden() );
1198 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1203 // Clear cache and confirm it loaded the not-blocked properly
1204 $user->clearInstanceCache();
1205 $this->assertNull( $user->getBlock( false ) );
1206 $this->assertSame( '', $user->blockedBy() );
1207 $this->assertSame( '', $user->blockedFor() );
1208 $this->assertFalse( (bool)$user->isHidden() );
1209 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1213 * Block cookie should be set for IP Blocks if
1214 * wgCookieSetOnIpBlock is set to true
1216 public function testIpBlockCookieSet() {
1217 $this->setMwGlobals( [
1218 'wgCookieSetOnIpBlock' => true,
1219 'wgCookiePrefix' => 'wiki',
1220 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1224 $block = new Block( [
1225 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1227 $block->setTarget( '1.2.3.4' );
1228 $block->setBlocker( $this->getTestSysop()->getUser() );
1232 $request = new FauxRequest();
1233 $request->setIP( '1.2.3.4' );
1236 $user = User
::newFromSession( $request );
1237 $user->trackBlockWithCookie();
1239 // test cookie was set
1240 $cookies = $request->response()->getCookies();
1241 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1248 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1251 public function testIpBlockCookieNotSet() {
1252 $this->setMwGlobals( [
1253 'wgCookieSetOnIpBlock' => false,
1254 'wgCookiePrefix' => 'wiki',
1255 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1259 $block = new Block( [
1260 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1262 $block->setTarget( '1.2.3.4' );
1263 $block->setBlocker( $this->getTestSysop()->getUser() );
1267 $request = new FauxRequest();
1268 $request->setIP( '1.2.3.4' );
1271 $user = User
::newFromSession( $request );
1272 $user->trackBlockWithCookie();
1274 // test cookie was not set
1275 $cookies = $request->response()->getCookies();
1276 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1283 * When an ip user is blocked and then they log in, cookie block
1284 * should be invalid and the cookie removed.
1286 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1287 $this->setMwGlobals( [
1288 'wgAutoblockExpiry' => 8000,
1289 'wgCookieSetOnIpBlock' => true,
1290 'wgCookiePrefix' => 'wiki',
1291 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1295 $block = new Block( [
1296 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1298 $block->setTarget( '1.2.3.4' );
1299 $block->setBlocker( $this->getTestSysop()->getUser() );
1303 $request = new FauxRequest();
1304 $request->setIP( '1.2.3.4' );
1305 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1306 $request->setCookie( 'BlockID', $block->getCookieValue() );
1309 $user = User
::newFromSession( $request );
1311 // logged in users should be inmune to cookie block of type ip/range
1312 $this->assertFalse( $user->isBlocked() );
1314 // cookie is being cleared
1315 $cookies = $request->response()->getCookies();
1316 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );