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' => MIGRATION_WRITE_BOTH
,
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();
269 $user->getEditCount(),
270 'After increasing the edit count manually, the user edit count should be 4'
275 * Test User::editCount
277 * @covers User::getEditCount
279 public function testGetEditCountForAnons() {
280 $user = User
::newFromName( 'Anonymous' );
283 $user->getEditCount(),
284 'Edit count starts null for anonymous users.'
287 $user->incEditCount();
290 $user->getEditCount(),
291 'Edit count remains null for anonymous users despite calls to increase it.'
296 * Test User::editCount
298 * @covers User::incEditCount
300 public function testIncEditCount() {
301 $user = $this->getMutableTestUser()->getUser();
302 $user->incEditCount();
304 $reloadedUser = User
::newFromId( $user->getId() );
305 $reloadedUser->incEditCount();
309 $reloadedUser->getEditCount(),
310 'Increasing the edit count after a fresh load leaves the object up to date.'
315 * Test changing user options.
316 * @covers User::setOption
317 * @covers User::getOption
319 public function testOptions() {
320 $user = $this->getMutableTestUser()->getUser();
322 $user->setOption( 'userjs-someoption', 'test' );
323 $user->setOption( 'rclimit', 200 );
324 $user->setOption( 'wpwatchlistdays', '0' );
325 $user->saveSettings();
327 $user = User
::newFromName( $user->getName() );
328 $user->load( User
::READ_LATEST
);
329 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
330 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
332 $user = User
::newFromName( $user->getName() );
333 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
334 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
335 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
337 // Check that an option saved as a string '0' is returned as an integer.
338 $user = User
::newFromName( $user->getName() );
339 $user->load( User
::READ_LATEST
);
340 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
345 * Make sure defaults are loaded when setOption is called.
346 * @covers User::loadOptions
348 public function testAnonOptions() {
349 global $wgDefaultUserOptions;
350 $this->user
->setOption( 'userjs-someoption', 'test' );
351 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
352 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
356 * Test password validity checks. There are 3 checks in core,
357 * - ensure the password meets the minimal length
358 * - ensure the password is not the same as the username
359 * - ensure the username/password combo isn't forbidden
360 * @covers User::checkPasswordValidity()
361 * @covers User::getPasswordValidity()
362 * @covers User::isValidPassword()
364 public function testCheckPasswordValidity() {
365 $this->setMwGlobals( [
366 'wgPasswordPolicy' => [
369 'MinimalPasswordLength' => 8,
370 'MinimumPasswordLengthToLogin' => 1,
371 'PasswordCannotMatchUsername' => 1,
374 'MinimalPasswordLength' => 6,
375 'PasswordCannotMatchUsername' => true,
376 'PasswordCannotMatchBlacklist' => true,
377 'MaximalPasswordLength' => 40,
381 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
382 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
383 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
384 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
385 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
390 $user = static::getTestUser()->getUser();
393 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
396 $this->assertFalse( $user->isValidPassword( 'a' ) );
397 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
398 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
399 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
402 $longPass = str_repeat( 'a', 41 );
403 $this->assertFalse( $user->isValidPassword( $longPass ) );
404 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
405 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
406 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
409 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
410 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
411 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
413 // On the forbidden list
414 $user = User
::newFromName( 'Useruser' );
415 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
416 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
420 * @covers User::getCanonicalName()
421 * @dataProvider provideGetCanonicalName
423 public function testGetCanonicalName( $name, $expectedArray ) {
424 // fake interwiki map for the 'Interwiki prefix' testcase
425 $this->mergeMwGlobalArrayValue( 'wgHooks', [
426 'InterwikiLoadPrefix' => [
427 function ( $prefix, &$iwdata ) {
428 if ( $prefix === 'interwiki' ) {
430 'iw_url' => 'http://example.com/',
440 foreach ( $expectedArray as $validate => $expected ) {
443 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
447 public static function provideGetCanonicalName() {
449 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
450 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
451 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
452 'valid' => false, 'false' => 'Talk:Username' ] ],
453 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
454 'valid' => false, 'false' => 'Interwiki:Username' ] ],
455 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
456 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
457 'usable' => 'Multi spaces' ] ],
458 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
459 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
460 'valid' => false, 'false' => 'In[]valid' ] ],
461 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
462 'false' => 'With / slash' ] ],
467 * @covers User::equals
469 public function testEquals() {
470 $first = $this->getMutableTestUser()->getUser();
471 $second = User
::newFromName( $first->getName() );
473 $this->assertTrue( $first->equals( $first ) );
474 $this->assertTrue( $first->equals( $second ) );
475 $this->assertTrue( $second->equals( $first ) );
477 $third = $this->getMutableTestUser()->getUser();
478 $fourth = $this->getMutableTestUser()->getUser();
480 $this->assertFalse( $third->equals( $fourth ) );
481 $this->assertFalse( $fourth->equals( $third ) );
483 // Test users loaded from db with id
484 $user = $this->getMutableTestUser()->getUser();
485 $fifth = User
::newFromId( $user->getId() );
486 $sixth = User
::newFromName( $user->getName() );
487 $this->assertTrue( $fifth->equals( $sixth ) );
491 * @covers User::getId
493 public function testGetId() {
494 $user = static::getTestUser()->getUser();
495 $this->assertTrue( $user->getId() > 0 );
499 * @covers User::isLoggedIn
500 * @covers User::isAnon
502 public function testLoggedIn() {
503 $user = $this->getMutableTestUser()->getUser();
504 $this->assertTrue( $user->isLoggedIn() );
505 $this->assertFalse( $user->isAnon() );
507 // Non-existent users are perceived as anonymous
508 $user = User
::newFromName( 'UTNonexistent' );
509 $this->assertFalse( $user->isLoggedIn() );
510 $this->assertTrue( $user->isAnon() );
513 $this->assertFalse( $user->isLoggedIn() );
514 $this->assertTrue( $user->isAnon() );
518 * @covers User::checkAndSetTouched
520 public function testCheckAndSetTouched() {
521 $user = $this->getMutableTestUser()->getUser();
522 $user = TestingAccessWrapper
::newFromObject( $user );
523 $this->assertTrue( $user->isLoggedIn() );
525 $touched = $user->getDBTouched();
527 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
528 $this->assertGreaterThan(
529 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
531 $touched = $user->getDBTouched();
533 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
534 $this->assertGreaterThan(
535 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
539 * @covers User::findUsersByGroup
541 public function testFindUsersByGroup() {
542 $users = User
::findUsersByGroup( [] );
543 $this->assertEquals( 0, iterator_count( $users ) );
545 $users = User
::findUsersByGroup( 'foo' );
546 $this->assertEquals( 0, iterator_count( $users ) );
548 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
549 $users = User
::findUsersByGroup( 'foo' );
550 $this->assertEquals( 1, iterator_count( $users ) );
552 $this->assertTrue( $user->equals( $users->current() ) );
554 // arguments have OR relationship
555 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
556 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
557 $this->assertEquals( 2, iterator_count( $users ) );
559 $this->assertTrue( $user->equals( $users->current() ) );
561 $this->assertTrue( $user2->equals( $users->current() ) );
563 // users are not duplicated
564 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
565 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
566 $this->assertEquals( 1, iterator_count( $users ) );
568 $this->assertTrue( $user->equals( $users->current() ) );
572 * When a user is autoblocked a cookie is set with which to track them
573 * in case they log out and change IP addresses.
574 * @link https://phabricator.wikimedia.org/T5233
576 public function testAutoblockCookies() {
577 // Set up the bits of global configuration that we use.
578 $this->setMwGlobals( [
579 'wgCookieSetOnAutoblock' => true,
580 'wgCookiePrefix' => 'wmsitetitle',
581 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
584 // Unregister the hooks for proper unit testing
585 $this->mergeMwGlobalArrayValue( 'wgHooks', [
586 'PerformRetroactiveAutoblock' => []
589 // 1. Log in a test user, and block them.
590 $userBlocker = $this->getTestSysop()->getUser();
591 $user1tmp = $this->getTestUser()->getUser();
592 $request1 = new FauxRequest();
593 $request1->getSession()->setUser( $user1tmp );
594 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
595 $block = new Block( [
596 'enableAutoblock' => true,
597 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
599 $block->setBlocker( $this->getTestSysop()->getUser() );
600 $block->setTarget( $user1tmp );
601 $block->setBlocker( $userBlocker );
602 $res = $block->insert();
603 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
604 $user1 = User
::newFromSession( $request1 );
605 $user1->mBlock
= $block;
608 // Confirm that the block has been applied as required.
609 $this->assertTrue( $user1->isLoggedIn() );
610 $this->assertTrue( $user1->isBlocked() );
611 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
612 $this->assertTrue( $block->isAutoblocking() );
613 $this->assertGreaterThanOrEqual( 1, $block->getId() );
615 // Test for the desired cookie name, value, and expiry.
616 $cookies = $request1->response()->getCookies();
617 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
618 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
619 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
620 $this->assertEquals( $block->getId(), $cookieValue );
622 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
623 $request2 = new FauxRequest();
624 $request2->setCookie( 'BlockID', $block->getCookieValue() );
625 $user2 = User
::newFromSession( $request2 );
627 $this->assertNotEquals( $user1->getId(), $user2->getId() );
628 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
629 $this->assertTrue( $user2->isAnon() );
630 $this->assertFalse( $user2->isLoggedIn() );
631 $this->assertTrue( $user2->isBlocked() );
632 // Non-strict type-check.
633 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
634 // Can't directly compare the objects becuase of member type differences.
635 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
636 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
637 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
639 // 3. Finally, set up a request as a new user, and the block should still be applied.
640 $user3tmp = $this->getTestUser()->getUser();
641 $request3 = new FauxRequest();
642 $request3->getSession()->setUser( $user3tmp );
643 $request3->setCookie( 'BlockID', $block->getId() );
644 $user3 = User
::newFromSession( $request3 );
646 $this->assertTrue( $user3->isLoggedIn() );
647 $this->assertTrue( $user3->isBlocked() );
648 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
655 * Make sure that no cookie is set to track autoblocked users
656 * when $wgCookieSetOnAutoblock is false.
658 public function testAutoblockCookiesDisabled() {
659 // Set up the bits of global configuration that we use.
660 $this->setMwGlobals( [
661 'wgCookieSetOnAutoblock' => false,
662 'wgCookiePrefix' => 'wm_no_cookies',
663 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
666 // Unregister the hooks for proper unit testing
667 $this->mergeMwGlobalArrayValue( 'wgHooks', [
668 'PerformRetroactiveAutoblock' => []
671 // 1. Log in a test user, and block them.
672 $userBlocker = $this->getTestSysop()->getUser();
673 $testUser = $this->getTestUser()->getUser();
674 $request1 = new FauxRequest();
675 $request1->getSession()->setUser( $testUser );
676 $block = new Block( [ 'enableAutoblock' => true ] );
677 $block->setBlocker( $this->getTestSysop()->getUser() );
678 $block->setTarget( $testUser );
679 $block->setBlocker( $userBlocker );
680 $res = $block->insert();
681 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
682 $user = User
::newFromSession( $request1 );
683 $user->mBlock
= $block;
686 // 2. Test that the cookie IS NOT present.
687 $this->assertTrue( $user->isLoggedIn() );
688 $this->assertTrue( $user->isBlocked() );
689 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
690 $this->assertTrue( $block->isAutoblocking() );
691 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
692 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
693 $cookies = $request1->response()->getCookies();
694 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
701 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
702 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
703 * the cookie's should change with it.
705 public function testAutoblockCookieInfiniteExpiry() {
706 $this->setMwGlobals( [
707 'wgCookieSetOnAutoblock' => true,
708 'wgCookiePrefix' => 'wm_infinite_block',
709 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
712 // Unregister the hooks for proper unit testing
713 $this->mergeMwGlobalArrayValue( 'wgHooks', [
714 'PerformRetroactiveAutoblock' => []
717 // 1. Log in a test user, and block them indefinitely.
718 $userBlocker = $this->getTestSysop()->getUser();
719 $user1Tmp = $this->getTestUser()->getUser();
720 $request1 = new FauxRequest();
721 $request1->getSession()->setUser( $user1Tmp );
722 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
723 $block->setBlocker( $this->getTestSysop()->getUser() );
724 $block->setTarget( $user1Tmp );
725 $block->setBlocker( $userBlocker );
726 $res = $block->insert();
727 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
728 $user1 = User
::newFromSession( $request1 );
729 $user1->mBlock
= $block;
732 // 2. Test the cookie's expiry timestamp.
733 $this->assertTrue( $user1->isLoggedIn() );
734 $this->assertTrue( $user1->isBlocked() );
735 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
736 $this->assertTrue( $block->isAutoblocking() );
737 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
738 $cookies = $request1->response()->getCookies();
739 // Test the cookie's expiry to the nearest minute.
740 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
741 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
742 // Check for expiry dates in a 10-second window, to account for slow testing.
745 $cookies['wm_infinite_blockBlockID']['expire'],
750 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
751 $newExpiry = wfTimestamp() +
2 * 60 * 60;
752 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
754 $user2tmp = $this->getTestUser()->getUser();
755 $request2 = new FauxRequest();
756 $request2->getSession()->setUser( $user2tmp );
757 $user2 = User
::newFromSession( $request2 );
758 $user2->mBlock
= $block;
760 $cookies = $request2->response()->getCookies();
761 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
762 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
768 public function testSoftBlockRanges() {
771 $this->setMwGlobals( [
772 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
776 // IP isn't in $wgSoftBlockRanges
777 $request = new FauxRequest();
778 $request->setIP( '192.168.0.1' );
779 $wgUser = User
::newFromSession( $request );
780 $this->assertNull( $wgUser->getBlock() );
782 // IP is in $wgSoftBlockRanges
783 $request = new FauxRequest();
784 $request->setIP( '10.20.30.40' );
785 $wgUser = User
::newFromSession( $request );
786 $block = $wgUser->getBlock();
787 $this->assertInstanceOf( Block
::class, $block );
788 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
790 // Make sure the block is really soft
791 $request->getSession()->setUser( $this->getTestUser()->getUser() );
792 $wgUser = User
::newFromSession( $request );
793 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
794 $this->assertNull( $wgUser->getBlock() );
798 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
800 public function testAutoblockCookieInauthentic() {
801 // Set up the bits of global configuration that we use.
802 $this->setMwGlobals( [
803 'wgCookieSetOnAutoblock' => true,
804 'wgCookiePrefix' => 'wmsitetitle',
805 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
808 // Unregister the hooks for proper unit testing
809 $this->mergeMwGlobalArrayValue( 'wgHooks', [
810 'PerformRetroactiveAutoblock' => []
813 // 1. Log in a blocked test user.
814 $userBlocker = $this->getTestSysop()->getUser();
815 $user1tmp = $this->getTestUser()->getUser();
816 $request1 = new FauxRequest();
817 $request1->getSession()->setUser( $user1tmp );
818 $block = new Block( [ 'enableAutoblock' => true ] );
819 $block->setBlocker( $this->getTestSysop()->getUser() );
820 $block->setTarget( $user1tmp );
821 $block->setBlocker( $userBlocker );
822 $res = $block->insert();
823 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
824 $user1 = User
::newFromSession( $request1 );
825 $user1->mBlock
= $block;
828 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
830 $request2 = new FauxRequest();
831 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
832 $user2 = User
::newFromSession( $request2 );
834 $this->assertTrue( $user2->isAnon() );
835 $this->assertFalse( $user2->isLoggedIn() );
836 $this->assertFalse( $user2->isBlocked() );
843 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
844 * This checks that a non-authenticated cookie still works.
846 public function testAutoblockCookieNoSecretKey() {
847 // Set up the bits of global configuration that we use.
848 $this->setMwGlobals( [
849 'wgCookieSetOnAutoblock' => true,
850 'wgCookiePrefix' => 'wmsitetitle',
851 'wgSecretKey' => null,
854 // Unregister the hooks for proper unit testing
855 $this->mergeMwGlobalArrayValue( 'wgHooks', [
856 'PerformRetroactiveAutoblock' => []
859 // 1. Log in a blocked test user.
860 $userBlocker = $this->getTestSysop()->getUser();
861 $user1tmp = $this->getTestUser()->getUser();
862 $request1 = new FauxRequest();
863 $request1->getSession()->setUser( $user1tmp );
864 $block = new Block( [ 'enableAutoblock' => true ] );
865 $block->setBlocker( $this->getTestSysop()->getUser() );
866 $block->setTarget( $user1tmp );
867 $block->setBlocker( $userBlocker );
868 $res = $block->insert();
869 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
870 $user1 = User
::newFromSession( $request1 );
871 $user1->mBlock
= $block;
873 $this->assertTrue( $user1->isBlocked() );
875 // 2. Create a new request, set the cookie to just the block ID, and the user should
876 // still get blocked when they log in again.
877 $request2 = new FauxRequest();
878 $request2->setCookie( 'BlockID', $block->getId() );
879 $user2 = User
::newFromSession( $request2 );
881 $this->assertNotEquals( $user1->getId(), $user2->getId() );
882 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
883 $this->assertTrue( $user2->isAnon() );
884 $this->assertFalse( $user2->isLoggedIn() );
885 $this->assertTrue( $user2->isBlocked() );
886 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
893 * @covers User::isPingLimitable
895 public function testIsPingLimitable() {
896 $request = new FauxRequest();
897 $request->setIP( '1.2.3.4' );
898 $user = User
::newFromSession( $request );
900 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
901 $this->assertTrue( $user->isPingLimitable() );
903 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
904 $this->assertFalse( $user->isPingLimitable() );
906 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
907 $this->assertFalse( $user->isPingLimitable() );
909 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
910 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
911 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
912 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
913 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
914 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
917 public function provideExperienceLevel() {
919 [ 2, 2, 'newcomer' ],
920 [ 12, 3, 'newcomer' ],
921 [ 8, 5, 'newcomer' ],
922 [ 15, 10, 'learner' ],
923 [ 450, 20, 'learner' ],
924 [ 460, 33, 'learner' ],
925 [ 525, 28, 'learner' ],
926 [ 538, 33, 'experienced' ],
931 * @covers User::getExperienceLevel
932 * @dataProvider provideExperienceLevel
934 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
935 $this->setMwGlobals( [
936 'wgLearnerEdits' => 10,
937 'wgLearnerMemberSince' => 4,
938 'wgExperiencedUserEdits' => 500,
939 'wgExperiencedUserMemberSince' => 30,
942 $db = wfGetDB( DB_MASTER
);
943 $userQuery = User
::getQueryInfo();
944 $row = $db->selectRow(
945 $userQuery['tables'],
946 $userQuery['fields'],
947 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
952 $row->user_editcount
= $editCount;
953 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
954 $user = User
::newFromRow( $row );
956 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
960 * @covers User::getExperienceLevel
962 public function testExperienceLevelAnon() {
963 $user = User
::newFromName( '10.11.12.13', false );
965 $this->assertFalse( $user->getExperienceLevel() );
968 public static function provideIsLocallBlockedProxy() {
970 [ '1.2.3.4', '1.2.3.4' ],
971 [ '1.2.3.4', '1.2.3.0/16' ],
976 * @dataProvider provideIsLocallBlockedProxy
977 * @covers User::isLocallyBlockedProxy
979 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
983 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
991 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
996 'test' => $blockListEntry
999 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1001 $this->hideDeprecated(
1002 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1003 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1005 $this->setMwGlobals(
1008 $blockListEntry => 'test'
1011 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1014 public function testActorId() {
1015 $this->hideDeprecated( 'User::selectFields' );
1017 // Newly-created user has an actor ID
1018 $user = User
::createNew( 'UserTestActorId1' );
1019 $id = $user->getId();
1020 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1022 $user = User
::newFromName( 'UserTestActorId2' );
1023 $user->addToDatabase();
1024 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1026 $user = User
::newFromName( 'UserTestActorId1' );
1027 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1029 $user = User
::newFromId( $id );
1030 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1032 $user2 = User
::newFromActorId( $user->getActorId() );
1033 $this->assertEquals( $user->getId(), $user2->getId(),
1034 'User::newFromActorId works for an existing user' );
1036 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1037 $user = User
::newFromRow( $row );
1038 $this->assertTrue( $user->getActorId() > 0,
1039 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1041 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1042 User
::purge( wfWikiId(), $id );
1043 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1044 ObjectCache
::getMainWANInstance()->clearProcessCache();
1046 $user = User
::newFromId( $id );
1047 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1048 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1050 $user->setName( 'UserTestActorId4-renamed' );
1051 $user->saveSettings();
1052 $this->assertEquals(
1054 $this->db
->selectField(
1055 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1057 'User::saveSettings updates actor table for name change'
1061 $ip = '192.168.12.34';
1062 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1064 $user = User
::newFromName( $ip, false );
1065 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1066 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1067 'Actor ID can be created for an anonymous user' );
1069 $user = User
::newFromName( $ip, false );
1070 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1071 $user2 = User
::newFromActorId( $user->getActorId() );
1072 $this->assertEquals( $user->getName(), $user2->getName(),
1073 'User::newFromActorId works for an anonymous user' );
1076 public function testNewFromAnyId() {
1078 $user = $this->getTestUser()->getUser();
1079 for ( $i = 1; $i <= 7; $i++
) {
1080 $test = User
::newFromAnyId(
1081 ( $i & 1 ) ?
$user->getId() : null,
1082 ( $i & 2 ) ?
$user->getName() : null,
1083 ( $i & 4 ) ?
$user->getActorId() : null
1085 $this->assertSame( $user->getId(), $test->getId() );
1086 $this->assertSame( $user->getName(), $test->getName() );
1087 $this->assertSame( $user->getActorId(), $test->getActorId() );
1090 // Anon user. Can't load by only user ID when that's 0.
1091 $user = User
::newFromName( '192.168.12.34', false );
1092 $user->getActorId( $this->db
); // Make sure an actor ID exists
1094 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1095 $this->assertSame( $user->getId(), $test->getId() );
1096 $this->assertSame( $user->getName(), $test->getName() );
1097 $this->assertSame( $user->getActorId(), $test->getActorId() );
1098 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1099 $this->assertSame( $user->getId(), $test->getId() );
1100 $this->assertSame( $user->getName(), $test->getName() );
1101 $this->assertSame( $user->getActorId(), $test->getActorId() );
1103 // Bogus data should still "work" as long as nothing triggers a ->load(),
1104 // and accessing the specified data shouldn't do that.
1105 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1106 $this->assertSame( 123456, $test->getId() );
1107 $this->assertSame( 'Bogus', $test->getName() );
1108 $this->assertSame( 654321, $test->getActorId() );
1110 // Exceptional cases
1112 User
::newFromAnyId( null, null, null );
1113 $this->fail( 'Expected exception not thrown' );
1114 } catch ( InvalidArgumentException
$ex ) {
1117 User
::newFromAnyId( 0, null, 0 );
1118 $this->fail( 'Expected exception not thrown' );
1119 } catch ( InvalidArgumentException
$ex ) {
1124 * @covers User::newFromIdentity
1126 public function testNewFromIdentity() {
1128 $user = $this->getTestUser()->getUser();
1130 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1133 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1134 $result = User
::newFromIdentity( $identity );
1135 $this->assertInstanceOf( User
::class, $result );
1136 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1137 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1138 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1141 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1142 $result = User
::newFromIdentity( $identity );
1143 $this->assertInstanceOf( User
::class, $result );
1144 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1145 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1146 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1149 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1150 $result = User
::newFromIdentity( $identity );
1151 $this->assertInstanceOf( User
::class, $result );
1152 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1153 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1154 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1158 * @covers User::getBlockedStatus
1159 * @covers User::getBlock
1160 * @covers User::blockedBy
1161 * @covers User::blockedFor
1162 * @covers User::isHidden
1163 * @covers User::isBlockedFrom
1165 public function testBlockInstanceCache() {
1166 // First, check the user isn't blocked
1167 $user = $this->getMutableTestUser()->getUser();
1168 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1169 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1170 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1171 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1172 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1173 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1176 $blocker = $this->getTestSysop()->getUser();
1177 $block = new Block( [
1179 'allowUsertalk' => false,
1180 'reason' => 'Because',
1182 $block->setTarget( $user );
1183 $block->setBlocker( $blocker );
1184 $res = $block->insert();
1185 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1187 // Clear cache and confirm it loaded the block properly
1188 $user->clearInstanceCache();
1189 $this->assertInstanceOf( Block
::class, $user->getBlock( false ) );
1190 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1191 $this->assertSame( 'Because', $user->blockedFor() );
1192 $this->assertTrue( (bool)$user->isHidden() );
1193 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1198 // Clear cache and confirm it loaded the not-blocked properly
1199 $user->clearInstanceCache();
1200 $this->assertNull( $user->getBlock( false ) );
1201 $this->assertSame( '', $user->blockedBy() );
1202 $this->assertSame( '', $user->blockedFor() );
1203 $this->assertFalse( (bool)$user->isHidden() );
1204 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1208 * Block cookie should be set for IP Blocks if
1209 * wgCookieSetOnIpBlock is set to true
1211 public function testIpBlockCookieSet() {
1212 $this->setMwGlobals( [
1213 'wgCookieSetOnIpBlock' => true,
1214 'wgCookiePrefix' => 'wiki',
1215 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1219 $block = new Block( [
1220 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1222 $block->setTarget( '1.2.3.4' );
1223 $block->setBlocker( $this->getTestSysop()->getUser() );
1227 $request = new FauxRequest();
1228 $request->setIP( '1.2.3.4' );
1231 $user = User
::newFromSession( $request );
1232 $user->trackBlockWithCookie();
1234 // test cookie was set
1235 $cookies = $request->response()->getCookies();
1236 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1243 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1246 public function testIpBlockCookieNotSet() {
1247 $this->setMwGlobals( [
1248 'wgCookieSetOnIpBlock' => false,
1249 'wgCookiePrefix' => 'wiki',
1250 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1254 $block = new Block( [
1255 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1257 $block->setTarget( '1.2.3.4' );
1258 $block->setBlocker( $this->getTestSysop()->getUser() );
1262 $request = new FauxRequest();
1263 $request->setIP( '1.2.3.4' );
1266 $user = User
::newFromSession( $request );
1267 $user->trackBlockWithCookie();
1269 // test cookie was not set
1270 $cookies = $request->response()->getCookies();
1271 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1278 * When an ip user is blocked and then they log in, cookie block
1279 * should be invalid and the cookie removed.
1281 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1282 $this->setMwGlobals( [
1283 'wgAutoblockExpiry' => 8000,
1284 'wgCookieSetOnIpBlock' => true,
1285 'wgCookiePrefix' => 'wiki',
1286 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1290 $block = new Block( [
1291 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1293 $block->setTarget( '1.2.3.4' );
1294 $block->setBlocker( $this->getTestSysop()->getUser() );
1298 $request = new FauxRequest();
1299 $request->setIP( '1.2.3.4' );
1300 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1301 $request->setCookie( 'BlockID', $block->getCookieValue() );
1304 $user = User
::newFromSession( $request );
1306 // logged in users should be inmune to cookie block of type ip/range
1307 $this->assertFalse( $user->isBlocked() );
1309 // cookie is being cleared
1310 $cookies = $request->response()->getCookies();
1311 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );