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
,
37 $this->setUpPermissionGlobals();
39 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
42 private function setUpPermissionGlobals() {
43 global $wgGroupPermissions, $wgRevokePermissions;
45 # Data for regular $wgGroupPermissions test
46 $wgGroupPermissions['unittesters'] = [
52 $wgGroupPermissions['testwriters'] = [
58 # Data for regular $wgRevokePermissions test
59 $wgRevokePermissions['formertesters'] = [
63 # For the options test
64 $wgGroupPermissions['*'] = [
65 'editmyoptions' => true,
69 private function setSessionUser( User
$user, WebRequest
$request ) {
70 $this->setMwGlobals( 'wgUser', $user );
71 RequestContext
::getMain()->setUser( $user );
72 RequestContext
::getMain()->setRequest( $request );
73 TestingAccessWrapper
::newFromObject( $user )->mRequest
= $request;
74 $request->getSession()->setUser( $user );
78 * @covers User::getGroupPermissions
80 public function testGroupPermissions() {
81 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
82 $this->assertContains( 'runtest', $rights );
83 $this->assertNotContains( 'writetest', $rights );
84 $this->assertNotContains( 'modifytest', $rights );
85 $this->assertNotContains( 'nukeworld', $rights );
87 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
88 $this->assertContains( 'runtest', $rights );
89 $this->assertContains( 'writetest', $rights );
90 $this->assertContains( 'modifytest', $rights );
91 $this->assertNotContains( 'nukeworld', $rights );
95 * @covers User::getGroupPermissions
97 public function testRevokePermissions() {
98 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
99 $this->assertNotContains( 'runtest', $rights );
100 $this->assertNotContains( 'writetest', $rights );
101 $this->assertNotContains( 'modifytest', $rights );
102 $this->assertNotContains( 'nukeworld', $rights );
106 * TODO: Remove. This is the same as PermissionManagerTest::testGetUserPermissions
107 * @covers User::getRights
109 public function testUserPermissions() {
110 $rights = $this->user
->getRights();
111 $this->assertContains( 'runtest', $rights );
112 $this->assertNotContains( 'writetest', $rights );
113 $this->assertNotContains( 'modifytest', $rights );
114 $this->assertNotContains( 'nukeworld', $rights );
118 * TODO: Remove. This is the same as PermissionManagerTest::testGetUserPermissionsHooks
119 * @covers User::getRights
121 public function testUserGetRightsHooks() {
122 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
123 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
125 $rights = $user->getRights();
126 $this->assertContains( 'test', $rights, 'sanity check' );
127 $this->assertContains( 'runtest', $rights, 'sanity check' );
128 $this->assertContains( 'writetest', $rights, 'sanity check' );
129 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
131 // Add a hook manipluating the rights
132 $this->setTemporaryHook( 'UserGetRights', function ( $user, &$rights ) {
133 $rights[] = 'nukeworld';
134 $rights = array_diff( $rights, [ 'writetest' ] );
137 $rights = $user->getRights();
138 $this->assertContains( 'test', $rights );
139 $this->assertContains( 'runtest', $rights );
140 $this->assertNotContains( 'writetest', $rights );
141 $this->assertContains( 'nukeworld', $rights );
143 // Add a Session that limits rights
144 $mock = $this->getMockBuilder( stdClass
::class )
145 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
147 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
148 $mock->method( 'getSessionId' )->willReturn(
149 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
151 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
152 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
153 ->setMethods( [ 'getSession' ] )
155 $mockRequest->method( 'getSession' )->willReturn( $session );
156 $userWrapper->mRequest
= $mockRequest;
158 $this->resetServices();
159 $rights = $user->getRights();
160 $this->assertContains( 'test', $rights );
161 $this->assertNotContains( 'runtest', $rights );
162 $this->assertNotContains( 'writetest', $rights );
163 $this->assertNotContains( 'nukeworld', $rights );
167 * @dataProvider provideGetGroupsWithPermission
168 * @covers User::getGroupsWithPermission
170 public function testGetGroupsWithPermission( $expected, $right ) {
171 $result = User
::getGroupsWithPermission( $right );
175 $this->assertEquals( $expected, $result, "Groups with permission $right" );
178 public static function provideGetGroupsWithPermission() {
181 [ 'unittesters', 'testwriters' ],
200 * @dataProvider provideIPs
203 public function testIsIP( $value, $result, $message ) {
204 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
207 public static function provideIPs() {
209 [ '', false, 'Empty string' ],
210 [ ' ', false, 'Blank space' ],
211 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
212 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
213 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
214 [ '203.0.113.0', true, 'IPv4 example' ],
215 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
216 // Not valid IPs but classified as such by MediaWiki for negated asserting
217 // of whether this might be the identifier of a logged-out user or whether
218 // to allow usernames like it.
219 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
220 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
225 * @dataProvider provideUserNames
226 * @covers User::isValidUserName
228 public function testIsValidUserName( $username, $result, $message ) {
229 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
232 public static function provideUserNames() {
234 [ '', false, 'Empty string' ],
235 [ ' ', false, 'Blank space' ],
236 [ 'abcd', false, 'Starts with small letter' ],
237 [ 'Ab/cd', false, 'Contains slash' ],
238 [ 'Ab cd', true, 'Whitespace' ],
239 [ '192.168.1.1', false, 'IP' ],
240 [ '116.17.184.5/32', false, 'IP range' ],
241 [ '::e:f:2001/96', false, 'IPv6 range' ],
242 [ 'User:Abcd', false, 'Reserved Namespace' ],
243 [ '12abcd232', true, 'Starts with Numbers' ],
244 [ '?abcd', true, 'Start with ? mark' ],
245 [ '#abcd', false, 'Start with #' ],
246 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
247 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
248 [ 'Ab cd', false, ' Ideographic space' ],
249 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
250 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
251 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
256 * Test User::editCount
258 * @covers User::getEditCount
260 public function testGetEditCount() {
261 $user = $this->getMutableTestUser()->getUser();
263 // let the user have a few (3) edits
264 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
265 for ( $i = 0; $i < 3; $i++
) {
266 $page->doEditContent(
267 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
277 $user->getEditCount(),
278 'After three edits, the user edit count should be 3'
281 // increase the edit count
282 $user->incEditCount();
283 $user->clearInstanceCache();
287 $user->getEditCount(),
288 'After increasing the edit count manually, the user edit count should be 4'
293 * Test User::editCount
295 * @covers User::getEditCount
297 public function testGetEditCountForAnons() {
298 $user = User
::newFromName( 'Anonymous' );
301 $user->getEditCount(),
302 'Edit count starts null for anonymous users.'
305 $user->incEditCount();
308 $user->getEditCount(),
309 'Edit count remains null for anonymous users despite calls to increase it.'
314 * Test User::editCount
316 * @covers User::incEditCount
318 public function testIncEditCount() {
319 $user = $this->getMutableTestUser()->getUser();
320 $user->incEditCount();
322 $reloadedUser = User
::newFromId( $user->getId() );
323 $reloadedUser->incEditCount();
327 $reloadedUser->getEditCount(),
328 'Increasing the edit count after a fresh load leaves the object up to date.'
333 * Test changing user options.
334 * @covers User::setOption
335 * @covers User::getOption
337 public function testOptions() {
338 $user = $this->getMutableTestUser()->getUser();
340 $user->setOption( 'userjs-someoption', 'test' );
341 $user->setOption( 'rclimit', 200 );
342 $user->setOption( 'wpwatchlistdays', '0' );
343 $user->saveSettings();
345 $user = User
::newFromName( $user->getName() );
346 $user->load( User
::READ_LATEST
);
347 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
348 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
350 $user = User
::newFromName( $user->getName() );
351 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
352 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
353 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
355 // Check that an option saved as a string '0' is returned as an integer.
356 $user = User
::newFromName( $user->getName() );
357 $user->load( User
::READ_LATEST
);
358 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
363 * Make sure defaults are loaded when setOption is called.
364 * @covers User::loadOptions
366 public function testAnonOptions() {
367 global $wgDefaultUserOptions;
368 $this->user
->setOption( 'userjs-someoption', 'test' );
369 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
370 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
374 * Test password validity checks. There are 3 checks in core,
375 * - ensure the password meets the minimal length
376 * - ensure the password is not the same as the username
377 * - ensure the username/password combo isn't forbidden
378 * @covers User::checkPasswordValidity()
379 * @covers User::isValidPassword()
381 public function testCheckPasswordValidity() {
382 $this->setMwGlobals( [
383 'wgPasswordPolicy' => [
386 'MinimalPasswordLength' => 8,
387 'MinimumPasswordLengthToLogin' => 1,
388 'PasswordCannotMatchUsername' => 1,
391 'MinimalPasswordLength' => 6,
392 'PasswordCannotMatchUsername' => true,
393 'PasswordCannotMatchBlacklist' => true,
394 'MaximalPasswordLength' => 40,
398 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
399 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
400 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
401 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
402 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
407 $user = static::getTestUser()->getUser();
410 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
413 $this->assertFalse( $user->isValidPassword( 'a' ) );
414 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
415 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
418 $longPass = str_repeat( 'a', 41 );
419 $this->assertFalse( $user->isValidPassword( $longPass ) );
420 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
421 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
424 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
425 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
427 // On the forbidden list
428 $user = User
::newFromName( 'Useruser' );
429 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
433 * @covers User::getCanonicalName()
434 * @dataProvider provideGetCanonicalName
436 public function testGetCanonicalName( $name, $expectedArray ) {
437 // fake interwiki map for the 'Interwiki prefix' testcase
438 $this->mergeMwGlobalArrayValue( 'wgHooks', [
439 'InterwikiLoadPrefix' => [
440 function ( $prefix, &$iwdata ) {
441 if ( $prefix === 'interwiki' ) {
443 'iw_url' => 'http://example.com/',
453 foreach ( $expectedArray as $validate => $expected ) {
456 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
460 public static function provideGetCanonicalName() {
462 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
463 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
464 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
465 'valid' => false, 'false' => 'Talk:Username' ] ],
466 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
467 'valid' => false, 'false' => 'Interwiki:Username' ] ],
468 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
469 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
470 'usable' => 'Multi spaces' ] ],
471 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
472 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
473 'valid' => false, 'false' => 'In[]valid' ] ],
474 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
475 'false' => 'With / slash' ] ],
480 * @covers User::equals
482 public function testEquals() {
483 $first = $this->getMutableTestUser()->getUser();
484 $second = User
::newFromName( $first->getName() );
486 $this->assertTrue( $first->equals( $first ) );
487 $this->assertTrue( $first->equals( $second ) );
488 $this->assertTrue( $second->equals( $first ) );
490 $third = $this->getMutableTestUser()->getUser();
491 $fourth = $this->getMutableTestUser()->getUser();
493 $this->assertFalse( $third->equals( $fourth ) );
494 $this->assertFalse( $fourth->equals( $third ) );
496 // Test users loaded from db with id
497 $user = $this->getMutableTestUser()->getUser();
498 $fifth = User
::newFromId( $user->getId() );
499 $sixth = User
::newFromName( $user->getName() );
500 $this->assertTrue( $fifth->equals( $sixth ) );
504 * @covers User::getId
506 public function testGetId() {
507 $user = static::getTestUser()->getUser();
508 $this->assertTrue( $user->getId() > 0 );
512 * @covers User::isRegistered
513 * @covers User::isLoggedIn
514 * @covers User::isAnon
516 public function testLoggedIn() {
517 $user = $this->getMutableTestUser()->getUser();
518 $this->assertTrue( $user->isRegistered() );
519 $this->assertTrue( $user->isLoggedIn() );
520 $this->assertFalse( $user->isAnon() );
522 // Non-existent users are perceived as anonymous
523 $user = User
::newFromName( 'UTNonexistent' );
524 $this->assertFalse( $user->isRegistered() );
525 $this->assertFalse( $user->isLoggedIn() );
526 $this->assertTrue( $user->isAnon() );
529 $this->assertFalse( $user->isRegistered() );
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
535 * @covers User::checkAndSetTouched
537 public function testCheckAndSetTouched() {
538 $user = $this->getMutableTestUser()->getUser();
539 $user = TestingAccessWrapper
::newFromObject( $user );
540 $this->assertTrue( $user->isLoggedIn() );
542 $touched = $user->getDBTouched();
544 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
545 $this->assertGreaterThan(
546 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
548 $touched = $user->getDBTouched();
550 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
551 $this->assertGreaterThan(
552 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
556 * @covers User::findUsersByGroup
558 public function testFindUsersByGroup() {
559 // FIXME: fails under postgres
560 $this->markTestSkippedIfDbType( 'postgres' );
562 $users = User
::findUsersByGroup( [] );
563 $this->assertEquals( 0, iterator_count( $users ) );
565 $users = User
::findUsersByGroup( 'foo' );
566 $this->assertEquals( 0, iterator_count( $users ) );
568 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
569 $users = User
::findUsersByGroup( 'foo' );
570 $this->assertEquals( 1, iterator_count( $users ) );
572 $this->assertTrue( $user->equals( $users->current() ) );
574 // arguments have OR relationship
575 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
576 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
577 $this->assertEquals( 2, iterator_count( $users ) );
579 $this->assertTrue( $user->equals( $users->current() ) );
581 $this->assertTrue( $user2->equals( $users->current() ) );
583 // users are not duplicated
584 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
585 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
586 $this->assertEquals( 1, iterator_count( $users ) );
588 $this->assertTrue( $user->equals( $users->current() ) );
592 * When a user is autoblocked a cookie is set with which to track them
593 * in case they log out and change IP addresses.
594 * @link https://phabricator.wikimedia.org/T5233
595 * @covers User::trackBlockWithCookie
597 public function testAutoblockCookies() {
598 // Set up the bits of global configuration that we use.
599 $this->setMwGlobals( [
600 'wgCookieSetOnAutoblock' => true,
601 'wgCookiePrefix' => 'wmsitetitle',
602 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
605 // Unregister the hooks for proper unit testing
606 $this->mergeMwGlobalArrayValue( 'wgHooks', [
607 'PerformRetroactiveAutoblock' => []
610 // 1. Log in a test user, and block them.
611 $user1tmp = $this->getTestUser()->getUser();
612 $request1 = new FauxRequest();
613 $request1->getSession()->setUser( $user1tmp );
614 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
615 $block = new DatabaseBlock( [
616 'enableAutoblock' => true,
617 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
619 $block->setBlocker( $this->getTestSysop()->getUser() );
620 $block->setTarget( $user1tmp );
621 $res = $block->insert();
622 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
623 $user1 = User
::newFromSession( $request1 );
624 $user1->mBlock
= $block;
627 // Confirm that the block has been applied as required.
628 $this->assertTrue( $user1->isLoggedIn() );
629 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
630 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
631 $this->assertTrue( $block->isAutoblocking() );
632 $this->assertGreaterThanOrEqual( 1, $block->getId() );
634 // Test for the desired cookie name, value, and expiry.
635 $cookies = $request1->response()->getCookies();
636 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
637 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
638 $cookieId = MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue(
639 $cookies['wmsitetitleBlockID']['value']
641 $this->assertEquals( $block->getId(), $cookieId );
643 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
644 $request2 = new FauxRequest();
645 $request2->setCookie( 'BlockID', $block->getCookieValue() );
646 $user2 = User
::newFromSession( $request2 );
648 $this->assertNotEquals( $user1->getId(), $user2->getId() );
649 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
650 $this->assertTrue( $user2->isAnon() );
651 $this->assertFalse( $user2->isLoggedIn() );
652 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
653 // Non-strict type-check.
654 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
655 // Can't directly compare the objects because of member type differences.
656 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
657 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
658 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
660 // 3. Finally, set up a request as a new user, and the block should still be applied.
661 $user3tmp = $this->getTestUser()->getUser();
662 $request3 = new FauxRequest();
663 $request3->getSession()->setUser( $user3tmp );
664 $request3->setCookie( 'BlockID', $block->getId() );
665 $user3 = User
::newFromSession( $request3 );
667 $this->assertTrue( $user3->isLoggedIn() );
668 $this->assertInstanceOf( DatabaseBlock
::class, $user3->getBlock() );
669 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
676 * Make sure that no cookie is set to track autoblocked users
677 * when $wgCookieSetOnAutoblock is false.
678 * @covers User::trackBlockWithCookie
680 public function testAutoblockCookiesDisabled() {
681 // Set up the bits of global configuration that we use.
682 $this->setMwGlobals( [
683 'wgCookieSetOnAutoblock' => false,
684 'wgCookiePrefix' => 'wm_no_cookies',
685 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
688 // Unregister the hooks for proper unit testing
689 $this->mergeMwGlobalArrayValue( 'wgHooks', [
690 'PerformRetroactiveAutoblock' => []
693 // 1. Log in a test user, and block them.
694 $testUser = $this->getTestUser()->getUser();
695 $request1 = new FauxRequest();
696 $request1->getSession()->setUser( $testUser );
697 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
698 $block->setBlocker( $this->getTestSysop()->getUser() );
699 $block->setTarget( $testUser );
700 $res = $block->insert();
701 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
702 $user = User
::newFromSession( $request1 );
703 $user->mBlock
= $block;
706 // 2. Test that the cookie IS NOT present.
707 $this->assertTrue( $user->isLoggedIn() );
708 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock() );
709 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
710 $this->assertTrue( $block->isAutoblocking() );
711 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
712 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
713 $cookies = $request1->response()->getCookies();
714 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
721 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
722 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
723 * the cookie's should change with it.
724 * @covers User::trackBlockWithCookie
726 public function testAutoblockCookieInfiniteExpiry() {
727 $this->setMwGlobals( [
728 'wgCookieSetOnAutoblock' => true,
729 'wgCookiePrefix' => 'wm_infinite_block',
730 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
733 // Unregister the hooks for proper unit testing
734 $this->mergeMwGlobalArrayValue( 'wgHooks', [
735 'PerformRetroactiveAutoblock' => []
738 // 1. Log in a test user, and block them indefinitely.
739 $user1Tmp = $this->getTestUser()->getUser();
740 $request1 = new FauxRequest();
741 $request1->getSession()->setUser( $user1Tmp );
742 $block = new DatabaseBlock( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
743 $block->setBlocker( $this->getTestSysop()->getUser() );
744 $block->setTarget( $user1Tmp );
745 $res = $block->insert();
746 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
747 $user1 = User
::newFromSession( $request1 );
748 $user1->mBlock
= $block;
751 // 2. Test the cookie's expiry timestamp.
752 $this->assertTrue( $user1->isLoggedIn() );
753 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
754 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
755 $this->assertTrue( $block->isAutoblocking() );
756 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
757 $cookies = $request1->response()->getCookies();
758 // Test the cookie's expiry to the nearest minute.
759 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
760 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
761 // Check for expiry dates in a 10-second window, to account for slow testing.
764 $cookies['wm_infinite_blockBlockID']['expire'],
769 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
770 $newExpiry = wfTimestamp() +
2 * 60 * 60;
771 $block->setExpiry( wfTimestamp( TS_MW
, $newExpiry ) );
773 $user2tmp = $this->getTestUser()->getUser();
774 $request2 = new FauxRequest();
775 $request2->getSession()->setUser( $user2tmp );
776 $user2 = User
::newFromSession( $request2 );
777 $user2->mBlock
= $block;
779 $cookies = $request2->response()->getCookies();
780 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
781 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
788 * @covers User::getBlockedStatus
790 public function testSoftBlockRanges() {
791 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
793 // IP isn't in $wgSoftBlockRanges
794 $wgUser = new User();
795 $request = new FauxRequest();
796 $request->setIP( '192.168.0.1' );
797 $this->setSessionUser( $wgUser, $request );
798 $this->assertNull( $wgUser->getBlock() );
800 // IP is in $wgSoftBlockRanges
801 $wgUser = new User();
802 $request = new FauxRequest();
803 $request->setIP( '10.20.30.40' );
804 $this->setSessionUser( $wgUser, $request );
805 $block = $wgUser->getBlock();
806 $this->assertInstanceOf( SystemBlock
::class, $block );
807 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
809 // Make sure the block is really soft
810 $wgUser = $this->getTestUser()->getUser();
811 $request = new FauxRequest();
812 $request->setIP( '10.20.30.40' );
813 $this->setSessionUser( $wgUser, $request );
814 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
815 $this->assertNull( $wgUser->getBlock() );
819 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
820 * @covers User::trackBlockWithCookie
822 public function testAutoblockCookieInauthentic() {
823 // Set up the bits of global configuration that we use.
824 $this->setMwGlobals( [
825 'wgCookieSetOnAutoblock' => true,
826 'wgCookiePrefix' => 'wmsitetitle',
827 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
830 // Unregister the hooks for proper unit testing
831 $this->mergeMwGlobalArrayValue( 'wgHooks', [
832 'PerformRetroactiveAutoblock' => []
835 // 1. Log in a blocked test user.
836 $user1tmp = $this->getTestUser()->getUser();
837 $request1 = new FauxRequest();
838 $request1->getSession()->setUser( $user1tmp );
839 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
840 $block->setBlocker( $this->getTestSysop()->getUser() );
841 $block->setTarget( $user1tmp );
842 $res = $block->insert();
843 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
844 $user1 = User
::newFromSession( $request1 );
845 $user1->mBlock
= $block;
848 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
850 $request2 = new FauxRequest();
851 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
852 $user2 = User
::newFromSession( $request2 );
854 $this->assertTrue( $user2->isAnon() );
855 $this->assertFalse( $user2->isLoggedIn() );
856 $this->assertNull( $user2->getBlock() );
863 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
864 * This checks that a non-authenticated cookie still works.
865 * @covers User::trackBlockWithCookie
867 public function testAutoblockCookieNoSecretKey() {
868 // Set up the bits of global configuration that we use.
869 $this->setMwGlobals( [
870 'wgCookieSetOnAutoblock' => true,
871 'wgCookiePrefix' => 'wmsitetitle',
872 'wgSecretKey' => null,
875 // Unregister the hooks for proper unit testing
876 $this->mergeMwGlobalArrayValue( 'wgHooks', [
877 'PerformRetroactiveAutoblock' => []
880 // 1. Log in a blocked test user.
881 $user1tmp = $this->getTestUser()->getUser();
882 $request1 = new FauxRequest();
883 $request1->getSession()->setUser( $user1tmp );
884 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
885 $block->setBlocker( $this->getTestSysop()->getUser() );
886 $block->setTarget( $user1tmp );
887 $res = $block->insert();
888 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
889 $user1 = User
::newFromSession( $request1 );
890 $user1->mBlock
= $block;
892 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
894 // 2. Create a new request, set the cookie to just the block ID, and the user should
895 // still get blocked when they log in again.
896 $request2 = new FauxRequest();
897 $request2->setCookie( 'BlockID', $block->getId() );
898 $user2 = User
::newFromSession( $request2 );
900 $this->assertNotEquals( $user1->getId(), $user2->getId() );
901 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
902 $this->assertTrue( $user2->isAnon() );
903 $this->assertFalse( $user2->isLoggedIn() );
904 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
905 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
912 * @covers User::isPingLimitable
914 public function testIsPingLimitable() {
915 $request = new FauxRequest();
916 $request->setIP( '1.2.3.4' );
917 $user = User
::newFromSession( $request );
919 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
920 $this->assertTrue( $user->isPingLimitable() );
922 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
923 $this->assertFalse( $user->isPingLimitable() );
925 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
926 $this->assertFalse( $user->isPingLimitable() );
928 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
929 $this->overrideUserPermissions( $user, 'noratelimit' );
930 $this->assertFalse( $user->isPingLimitable() );
933 public function provideExperienceLevel() {
935 [ 2, 2, 'newcomer' ],
936 [ 12, 3, 'newcomer' ],
937 [ 8, 5, 'newcomer' ],
938 [ 15, 10, 'learner' ],
939 [ 450, 20, 'learner' ],
940 [ 460, 33, 'learner' ],
941 [ 525, 28, 'learner' ],
942 [ 538, 33, 'experienced' ],
947 * @covers User::getExperienceLevel
948 * @dataProvider provideExperienceLevel
950 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
951 $this->setMwGlobals( [
952 'wgLearnerEdits' => 10,
953 'wgLearnerMemberSince' => 4,
954 'wgExperiencedUserEdits' => 500,
955 'wgExperiencedUserMemberSince' => 30,
958 $db = wfGetDB( DB_MASTER
);
959 $userQuery = User
::getQueryInfo();
960 $row = $db->selectRow(
961 $userQuery['tables'],
962 $userQuery['fields'],
963 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
968 $row->user_editcount
= $editCount;
969 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
970 $user = User
::newFromRow( $row );
972 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
976 * @covers User::getExperienceLevel
978 public function testExperienceLevelAnon() {
979 $user = User
::newFromName( '10.11.12.13', false );
981 $this->assertFalse( $user->getExperienceLevel() );
984 public static function provideIsLocallyBlockedProxy() {
986 [ '1.2.3.4', '1.2.3.4' ],
987 [ '1.2.3.4', '1.2.3.0/16' ],
992 * @dataProvider provideIsLocallyBlockedProxy
993 * @covers User::isLocallyBlockedProxy
995 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
996 $this->hideDeprecated( 'User::isLocallyBlockedProxy' );
1001 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1003 $this->setMwGlobals(
1009 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1011 $this->setMwGlobals(
1014 'test' => $blockListEntry
1017 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1021 * @covers User::newFromActorId
1023 public function testActorId() {
1024 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1025 $this->hideDeprecated( 'User::selectFields' );
1027 // Newly-created user has an actor ID
1028 $user = User
::createNew( 'UserTestActorId1' );
1029 $id = $user->getId();
1030 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1032 $user = User
::newFromName( 'UserTestActorId2' );
1033 $user->addToDatabase();
1034 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1036 $user = User
::newFromName( 'UserTestActorId1' );
1037 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1039 $user = User
::newFromId( $id );
1040 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1042 $user2 = User
::newFromActorId( $user->getActorId() );
1043 $this->assertEquals( $user->getId(), $user2->getId(),
1044 'User::newFromActorId works for an existing user' );
1046 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1047 $user = User
::newFromRow( $row );
1048 $this->assertTrue( $user->getActorId() > 0,
1049 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1051 $user = User
::newFromId( $id );
1052 $user->setName( 'UserTestActorId4-renamed' );
1053 $user->saveSettings();
1054 $this->assertEquals(
1056 $this->db
->selectField(
1057 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1059 'User::saveSettings updates actor table for name change'
1063 $ip = '192.168.12.34';
1064 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1066 $user = User
::newFromName( $ip, false );
1067 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1068 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1069 'Actor ID can be created for an anonymous user' );
1071 $user = User
::newFromName( $ip, false );
1072 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1073 $user2 = User
::newFromActorId( $user->getActorId() );
1074 $this->assertEquals( $user->getName(), $user2->getName(),
1075 'User::newFromActorId works for an anonymous user' );
1079 * Actor tests with SCHEMA_COMPAT_READ_OLD
1081 * The only thing different from testActorId() is the behavior if the actor
1082 * row doesn't exist in the DB, since with SCHEMA_COMPAT_READ_NEW that
1083 * situation can't happen. But we copy all the other tests too just for good measure.
1085 * @covers User::newFromActorId
1087 public function testActorId_old() {
1088 $this->setMwGlobals( [
1089 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
1092 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1093 $this->hideDeprecated( 'User::selectFields' );
1095 // Newly-created user has an actor ID
1096 $user = User
::createNew( 'UserTestActorIdOld1' );
1097 $id = $user->getId();
1098 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1100 $user = User
::newFromName( 'UserTestActorIdOld2' );
1101 $user->addToDatabase();
1102 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1104 $user = User
::newFromName( 'UserTestActorIdOld1' );
1105 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1107 $user = User
::newFromId( $id );
1108 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1110 $user2 = User
::newFromActorId( $user->getActorId() );
1111 $this->assertEquals( $user->getId(), $user2->getId(),
1112 'User::newFromActorId works for an existing user' );
1114 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1115 $user = User
::newFromRow( $row );
1116 $this->assertTrue( $user->getActorId() > 0,
1117 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1119 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1120 User
::purge( $domain, $id );
1121 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1123 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
1125 $user = User
::newFromId( $id );
1126 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1127 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1129 $user->setName( 'UserTestActorIdOld4-renamed' );
1130 $user->saveSettings();
1131 $this->assertEquals(
1133 $this->db
->selectField(
1134 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1136 'User::saveSettings updates actor table for name change'
1140 $ip = '192.168.12.34';
1141 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1143 $user = User
::newFromName( $ip, false );
1144 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1145 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1146 'Actor ID can be created for an anonymous user' );
1148 $user = User
::newFromName( $ip, false );
1149 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1150 $user2 = User
::newFromActorId( $user->getActorId() );
1151 $this->assertEquals( $user->getName(), $user2->getName(),
1152 'User::newFromActorId works for an anonymous user' );
1156 * @covers User::newFromAnyId
1158 public function testNewFromAnyId() {
1160 $user = $this->getTestUser()->getUser();
1161 for ( $i = 1; $i <= 7; $i++
) {
1162 $test = User
::newFromAnyId(
1163 ( $i & 1 ) ?
$user->getId() : null,
1164 ( $i & 2 ) ?
$user->getName() : null,
1165 ( $i & 4 ) ?
$user->getActorId() : null
1167 $this->assertSame( $user->getId(), $test->getId() );
1168 $this->assertSame( $user->getName(), $test->getName() );
1169 $this->assertSame( $user->getActorId(), $test->getActorId() );
1172 // Anon user. Can't load by only user ID when that's 0.
1173 $user = User
::newFromName( '192.168.12.34', false );
1174 $user->getActorId( $this->db
); // Make sure an actor ID exists
1176 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1177 $this->assertSame( $user->getId(), $test->getId() );
1178 $this->assertSame( $user->getName(), $test->getName() );
1179 $this->assertSame( $user->getActorId(), $test->getActorId() );
1180 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1181 $this->assertSame( $user->getId(), $test->getId() );
1182 $this->assertSame( $user->getName(), $test->getName() );
1183 $this->assertSame( $user->getActorId(), $test->getActorId() );
1185 // Bogus data should still "work" as long as nothing triggers a ->load(),
1186 // and accessing the specified data shouldn't do that.
1187 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1188 $this->assertSame( 123456, $test->getId() );
1189 $this->assertSame( 'Bogus', $test->getName() );
1190 $this->assertSame( 654321, $test->getActorId() );
1192 // Loading remote user by name from remote wiki should succeed
1193 $test = User
::newFromAnyId( null, 'Bogus', null, 'foo' );
1194 $this->assertSame( 0, $test->getId() );
1195 $this->assertSame( 'Bogus', $test->getName() );
1196 $this->assertSame( 0, $test->getActorId() );
1197 $test = User
::newFromAnyId( 123456, 'Bogus', 654321, 'foo' );
1198 $this->assertSame( 0, $test->getId() );
1199 $this->assertSame( 0, $test->getActorId() );
1201 // Exceptional cases
1203 User
::newFromAnyId( null, null, null );
1204 $this->fail( 'Expected exception not thrown' );
1205 } catch ( InvalidArgumentException
$ex ) {
1208 User
::newFromAnyId( 0, null, 0 );
1209 $this->fail( 'Expected exception not thrown' );
1210 } catch ( InvalidArgumentException
$ex ) {
1213 // Loading remote user by id from remote wiki should fail
1215 User
::newFromAnyId( 123456, null, 654321, 'foo' );
1216 $this->fail( 'Expected exception not thrown' );
1217 } catch ( InvalidArgumentException
$ex ) {
1222 * @covers User::newFromIdentity
1224 public function testNewFromIdentity() {
1226 $user = $this->getTestUser()->getUser();
1228 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1231 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1232 $result = User
::newFromIdentity( $identity );
1233 $this->assertInstanceOf( User
::class, $result );
1234 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1235 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1236 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1239 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1240 $result = User
::newFromIdentity( $identity );
1241 $this->assertInstanceOf( User
::class, $result );
1242 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1243 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1244 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1247 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1248 $result = User
::newFromIdentity( $identity );
1249 $this->assertInstanceOf( User
::class, $result );
1250 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1251 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1252 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1256 * @covers User::getBlockedStatus
1257 * @covers User::getBlock
1258 * @covers User::blockedBy
1259 * @covers User::blockedFor
1260 * @covers User::isHidden
1261 * @covers User::isBlockedFrom
1263 public function testBlockInstanceCache() {
1264 // First, check the user isn't blocked
1265 $user = $this->getMutableTestUser()->getUser();
1266 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1267 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1268 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1269 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1270 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1271 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1274 $blocker = $this->getTestSysop()->getUser();
1275 $block = new DatabaseBlock( [
1277 'allowUsertalk' => false,
1278 'reason' => 'Because',
1280 $block->setTarget( $user );
1281 $block->setBlocker( $blocker );
1282 $res = $block->insert();
1283 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1285 // Clear cache and confirm it loaded the block properly
1286 $user->clearInstanceCache();
1287 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock( false ) );
1288 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1289 $this->assertSame( 'Because', $user->blockedFor() );
1290 $this->assertTrue( (bool)$user->isHidden() );
1291 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1296 // Clear cache and confirm it loaded the not-blocked properly
1297 $user->clearInstanceCache();
1298 $this->assertNull( $user->getBlock( false ) );
1299 $this->assertSame( '', $user->blockedBy() );
1300 $this->assertSame( '', $user->blockedFor() );
1301 $this->assertFalse( (bool)$user->isHidden() );
1302 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1306 * @covers User::getBlockedStatus
1308 public function testCompositeBlocks() {
1309 $user = $this->getMutableTestUser()->getUser();
1310 $request = $user->getRequest();
1311 $this->setSessionUser( $user, $request );
1313 $ipBlock = new Block( [
1314 'address' => $user->getRequest()->getIP(),
1315 'by' => $this->getTestSysop()->getUser()->getId(),
1316 'createAccount' => true,
1320 $userBlock = new Block( [
1322 'by' => $this->getTestSysop()->getUser()->getId(),
1323 'createAccount' => false,
1325 $userBlock->insert();
1327 $block = $user->getBlock();
1328 $this->assertInstanceOf( CompositeBlock
::class, $block );
1329 $this->assertTrue( $block->isCreateAccountBlocked() );
1330 $this->assertTrue( $block->appliesToPasswordReset() );
1331 $this->assertTrue( $block->appliesToNamespace( NS_MAIN
) );
1335 * @covers User::isBlockedFrom
1336 * @dataProvider provideIsBlockedFrom
1337 * @param string|null $title Title to test.
1338 * @param bool $expect Expected result from User::isBlockedFrom()
1339 * @param array $options Additional test options:
1340 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1341 * - 'allowUsertalk': (bool, default false) Passed to DatabaseBlock::__construct()
1342 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1344 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1345 $this->setMwGlobals( [
1346 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1349 $user = $this->getTestUser()->getUser();
1351 if ( $title === self
::USER_TALK_PAGE
) {
1352 $title = $user->getTalkPage();
1354 $title = Title
::newFromText( $title );
1358 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1359 $page = $this->getExistingTestPage(
1360 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1362 $restrictions[] = new PageRestriction( 0, $page->getId() );
1364 foreach ( $options['namespaceRestrictions'] ??
[] as $ns ) {
1365 $restrictions[] = new NamespaceRestriction( 0, $ns );
1368 $block = new DatabaseBlock( [
1369 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1370 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1371 'sitewide' => !$restrictions,
1373 $block->setTarget( $user );
1374 $block->setBlocker( $this->getTestSysop()->getUser() );
1375 if ( $restrictions ) {
1376 $block->setRestrictions( $restrictions );
1381 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1387 public static function provideIsBlockedFrom() {
1389 'Sitewide block, basic operation' => [ 'Test page', true ],
1390 'Sitewide block, not allowing user talk' => [
1391 self
::USER_TALK_PAGE
, true, [
1392 'allowUsertalk' => false,
1395 'Sitewide block, allowing user talk' => [
1396 self
::USER_TALK_PAGE
, false, [
1397 'allowUsertalk' => true,
1400 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1401 self
::USER_TALK_PAGE
, true, [
1402 'allowUsertalk' => true,
1403 'blockAllowsUTEdit' => false,
1406 'Partial block, blocking the page' => [
1407 'Test page', true, [
1408 'pageRestrictions' => [ 'Test page' ],
1411 'Partial block, not blocking the page' => [
1412 'Test page 2', false, [
1413 'pageRestrictions' => [ 'Test page' ],
1416 'Partial block, not allowing user talk but user talk page is not blocked' => [
1417 self
::USER_TALK_PAGE
, false, [
1418 'allowUsertalk' => false,
1419 'pageRestrictions' => [ 'Test page' ],
1422 'Partial block, allowing user talk but user talk page is blocked' => [
1423 self
::USER_TALK_PAGE
, true, [
1424 'allowUsertalk' => true,
1425 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1428 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1429 self
::USER_TALK_PAGE
, false, [
1430 'allowUsertalk' => false,
1431 'pageRestrictions' => [ 'Test page' ],
1432 'blockAllowsUTEdit' => false,
1435 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1436 self
::USER_TALK_PAGE
, true, [
1437 'allowUsertalk' => true,
1438 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1439 'blockAllowsUTEdit' => false,
1442 'Partial user talk namespace block, not allowing user talk' => [
1443 self
::USER_TALK_PAGE
, true, [
1444 'allowUsertalk' => false,
1445 'namespaceRestrictions' => [ NS_USER_TALK
],
1448 'Partial user talk namespace block, allowing user talk' => [
1449 self
::USER_TALK_PAGE
, false, [
1450 'allowUsertalk' => true,
1451 'namespaceRestrictions' => [ NS_USER_TALK
],
1454 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1455 self
::USER_TALK_PAGE
, true, [
1456 'allowUsertalk' => true,
1457 'namespaceRestrictions' => [ NS_USER_TALK
],
1458 'blockAllowsUTEdit' => false,
1465 * Block cookie should be set for IP Blocks if
1466 * wgCookieSetOnIpBlock is set to true
1467 * @covers User::trackBlockWithCookie
1469 public function testIpBlockCookieSet() {
1470 $this->setMwGlobals( [
1471 'wgCookieSetOnIpBlock' => true,
1472 'wgCookiePrefix' => 'wiki',
1473 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1477 $block = new DatabaseBlock( [
1478 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1480 $block->setTarget( '1.2.3.4' );
1481 $block->setBlocker( $this->getTestSysop()->getUser() );
1485 $request = new FauxRequest();
1486 $request->setIP( '1.2.3.4' );
1489 $user = User
::newFromSession( $request );
1490 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1492 // test cookie was set
1493 $cookies = $request->response()->getCookies();
1494 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1501 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1503 * @covers User::trackBlockWithCookie
1505 public function testIpBlockCookieNotSet() {
1506 $this->setMwGlobals( [
1507 'wgCookieSetOnIpBlock' => false,
1508 'wgCookiePrefix' => 'wiki',
1509 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1513 $block = new DatabaseBlock( [
1514 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1516 $block->setTarget( '1.2.3.4' );
1517 $block->setBlocker( $this->getTestSysop()->getUser() );
1521 $request = new FauxRequest();
1522 $request->setIP( '1.2.3.4' );
1525 $user = User
::newFromSession( $request );
1526 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1528 // test cookie was not set
1529 $cookies = $request->response()->getCookies();
1530 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1537 * When an ip user is blocked and then they log in, cookie block
1538 * should be invalid and the cookie removed.
1539 * @covers User::trackBlockWithCookie
1541 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1542 $this->setMwGlobals( [
1543 'wgAutoblockExpiry' => 8000,
1544 'wgCookieSetOnIpBlock' => true,
1545 'wgCookiePrefix' => 'wiki',
1546 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1550 $block = new DatabaseBlock( [
1551 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1553 $block->setTarget( '1.2.3.4' );
1554 $block->setBlocker( $this->getTestSysop()->getUser() );
1558 $request = new FauxRequest();
1559 $request->setIP( '1.2.3.4' );
1560 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1561 $request->setCookie( 'BlockID', $block->getCookieValue() );
1564 $user = User
::newFromSession( $request );
1566 // logged in users should be inmune to cookie block of type ip/range
1567 $this->assertNull( $user->getBlock() );
1569 // cookie is being cleared
1570 $cookies = $request->response()->getCookies();
1571 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1578 * @covers User::getFirstEditTimestamp
1579 * @covers User::getLatestEditTimestamp
1581 public function testGetFirstLatestEditTimestamp() {
1582 $clock = MWTimestamp
::convert( TS_UNIX
, '20100101000000' );
1583 MWTimestamp
::setFakeTime( function () use ( &$clock ) {
1584 return $clock +
= 1000;
1587 $user = $this->getTestUser()->getUser();
1588 $firstRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'one', 'test' );
1589 $secondRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'two', 'test' );
1590 // Sanity check: revisions timestamp are different
1591 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1593 $this->assertEquals( $firstRevision->getTimestamp(), $user->getFirstEditTimestamp() );
1594 $this->assertEquals( $secondRevision->getTimestamp(), $user->getLatestEditTimestamp() );
1596 MWTimestamp
::setFakeTime( false );
1602 * @param string $title
1603 * @param string $content
1604 * @param string $comment
1605 * @return \MediaWiki\Revision\RevisionRecord|null
1607 private static function makeEdit( User
$user, $title, $content, $comment ) {
1608 $page = WikiPage
::factory( Title
::newFromText( $title ) );
1609 $content = ContentHandler
::makeContent( $content, $page->getTitle() );
1610 $updater = $page->newPageUpdater( $user );
1611 $updater->setContent( 'main', $content );
1612 return $updater->saveRevision( CommentStoreComment
::newUnsavedComment( $comment ) );
1616 * @covers User::idFromName
1618 public function testExistingIdFromName() {
1620 array_key_exists( $this->user
->getName(), User
::$idCacheByName ),
1621 'Test user should already be in the id cache.'
1624 $this->user
->getId(), User
::idFromName( $this->user
->getName() ),
1625 'Id is correctly retreived from the cache.'
1628 $this->user
->getId(), User
::idFromName( $this->user
->getName(), User
::READ_LATEST
),
1629 'Id is correctly retreived from the database.'
1634 * @covers User::idFromName
1636 public function testNonExistingIdFromName() {
1638 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1639 'Non exisitng user should not be in the id cache.'
1641 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );
1643 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1644 'Username will be cached when requested once.'
1646 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );