3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\Block\DatabaseBlock
;
7 use MediaWiki\Block\Restriction\PageRestriction
;
8 use MediaWiki\Block\Restriction\NamespaceRestriction
;
9 use MediaWiki\Block\SystemBlock
;
10 use MediaWiki\MediaWikiServices
;
11 use MediaWiki\User\UserIdentityValue
;
12 use Wikimedia\TestingAccessWrapper
;
17 class UserTest
extends MediaWikiTestCase
{
19 /** Constant for self::testIsBlockedFrom */
20 const USER_TALK_PAGE
= '<user talk page>';
27 protected function setUp() {
30 $this->setMwGlobals( [
31 'wgGroupPermissions' => [],
32 'wgRevokePermissions' => [],
33 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_NEW
,
35 $this->overrideMwServices();
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,
70 * @covers User::getGroupPermissions
72 public function testGroupPermissions() {
73 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
74 $this->assertContains( 'runtest', $rights );
75 $this->assertNotContains( 'writetest', $rights );
76 $this->assertNotContains( 'modifytest', $rights );
77 $this->assertNotContains( 'nukeworld', $rights );
79 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
80 $this->assertContains( 'runtest', $rights );
81 $this->assertContains( 'writetest', $rights );
82 $this->assertContains( 'modifytest', $rights );
83 $this->assertNotContains( 'nukeworld', $rights );
87 * @covers User::getGroupPermissions
89 public function testRevokePermissions() {
90 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
91 $this->assertNotContains( 'runtest', $rights );
92 $this->assertNotContains( 'writetest', $rights );
93 $this->assertNotContains( 'modifytest', $rights );
94 $this->assertNotContains( 'nukeworld', $rights );
98 * @covers User::getRights
100 public function testUserPermissions() {
101 $rights = $this->user
->getRights();
102 $this->assertContains( 'runtest', $rights );
103 $this->assertNotContains( 'writetest', $rights );
104 $this->assertNotContains( 'modifytest', $rights );
105 $this->assertNotContains( 'nukeworld', $rights );
109 * @covers User::getRights
111 public function testUserGetRightsHooks() {
112 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
113 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
115 $rights = $user->getRights();
116 $this->assertContains( 'test', $rights, 'sanity check' );
117 $this->assertContains( 'runtest', $rights, 'sanity check' );
118 $this->assertContains( 'writetest', $rights, 'sanity check' );
119 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
121 // Add a hook manipluating the rights
122 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
123 $rights[] = 'nukeworld';
124 $rights = array_diff( $rights, [ 'writetest' ] );
127 $userWrapper->mRights
= null;
128 $rights = $user->getRights();
129 $this->assertContains( 'test', $rights );
130 $this->assertContains( 'runtest', $rights );
131 $this->assertNotContains( 'writetest', $rights );
132 $this->assertContains( 'nukeworld', $rights );
134 // Add a Session that limits rights
135 $mock = $this->getMockBuilder( stdClass
::class )
136 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
138 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
139 $mock->method( 'getSessionId' )->willReturn(
140 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
142 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
143 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
144 ->setMethods( [ 'getSession' ] )
146 $mockRequest->method( 'getSession' )->willReturn( $session );
147 $userWrapper->mRequest
= $mockRequest;
149 $userWrapper->mRights
= null;
150 $rights = $user->getRights();
151 $this->assertContains( 'test', $rights );
152 $this->assertNotContains( 'runtest', $rights );
153 $this->assertNotContains( 'writetest', $rights );
154 $this->assertNotContains( 'nukeworld', $rights );
158 * @dataProvider provideGetGroupsWithPermission
159 * @covers User::getGroupsWithPermission
161 public function testGetGroupsWithPermission( $expected, $right ) {
162 $result = User
::getGroupsWithPermission( $right );
166 $this->assertEquals( $expected, $result, "Groups with permission $right" );
169 public static function provideGetGroupsWithPermission() {
172 [ 'unittesters', 'testwriters' ],
191 * @dataProvider provideIPs
194 public function testIsIP( $value, $result, $message ) {
195 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
198 public static function provideIPs() {
200 [ '', false, 'Empty string' ],
201 [ ' ', false, 'Blank space' ],
202 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
203 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
204 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
205 [ '203.0.113.0', true, 'IPv4 example' ],
206 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
207 // Not valid IPs but classified as such by MediaWiki for negated asserting
208 // of whether this might be the identifier of a logged-out user or whether
209 // to allow usernames like it.
210 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
211 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
216 * @dataProvider provideUserNames
217 * @covers User::isValidUserName
219 public function testIsValidUserName( $username, $result, $message ) {
220 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
223 public static function provideUserNames() {
225 [ '', false, 'Empty string' ],
226 [ ' ', false, 'Blank space' ],
227 [ 'abcd', false, 'Starts with small letter' ],
228 [ 'Ab/cd', false, 'Contains slash' ],
229 [ 'Ab cd', true, 'Whitespace' ],
230 [ '192.168.1.1', false, 'IP' ],
231 [ '116.17.184.5/32', false, 'IP range' ],
232 [ '::e:f:2001/96', false, 'IPv6 range' ],
233 [ 'User:Abcd', false, 'Reserved Namespace' ],
234 [ '12abcd232', true, 'Starts with Numbers' ],
235 [ '?abcd', true, 'Start with ? mark' ],
236 [ '#abcd', false, 'Start with #' ],
237 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
238 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
239 [ 'Ab cd', false, ' Ideographic space' ],
240 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
241 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
242 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
247 * Test User::editCount
249 * @covers User::getEditCount
251 public function testGetEditCount() {
252 $user = $this->getMutableTestUser()->getUser();
254 // let the user have a few (3) edits
255 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
256 for ( $i = 0; $i < 3; $i++
) {
257 $page->doEditContent(
258 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
268 $user->getEditCount(),
269 'After three edits, the user edit count should be 3'
272 // increase the edit count
273 $user->incEditCount();
274 $user->clearInstanceCache();
278 $user->getEditCount(),
279 'After increasing the edit count manually, the user edit count should be 4'
284 * Test User::editCount
286 * @covers User::getEditCount
288 public function testGetEditCountForAnons() {
289 $user = User
::newFromName( 'Anonymous' );
292 $user->getEditCount(),
293 'Edit count starts null for anonymous users.'
296 $user->incEditCount();
299 $user->getEditCount(),
300 'Edit count remains null for anonymous users despite calls to increase it.'
305 * Test User::editCount
307 * @covers User::incEditCount
309 public function testIncEditCount() {
310 $user = $this->getMutableTestUser()->getUser();
311 $user->incEditCount();
313 $reloadedUser = User
::newFromId( $user->getId() );
314 $reloadedUser->incEditCount();
318 $reloadedUser->getEditCount(),
319 'Increasing the edit count after a fresh load leaves the object up to date.'
324 * Test changing user options.
325 * @covers User::setOption
326 * @covers User::getOption
328 public function testOptions() {
329 $user = $this->getMutableTestUser()->getUser();
331 $user->setOption( 'userjs-someoption', 'test' );
332 $user->setOption( 'rclimit', 200 );
333 $user->setOption( 'wpwatchlistdays', '0' );
334 $user->saveSettings();
336 $user = User
::newFromName( $user->getName() );
337 $user->load( User
::READ_LATEST
);
338 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
339 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
341 $user = User
::newFromName( $user->getName() );
342 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
343 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
344 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
346 // Check that an option saved as a string '0' is returned as an integer.
347 $user = User
::newFromName( $user->getName() );
348 $user->load( User
::READ_LATEST
);
349 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
354 * Make sure defaults are loaded when setOption is called.
355 * @covers User::loadOptions
357 public function testAnonOptions() {
358 global $wgDefaultUserOptions;
359 $this->user
->setOption( 'userjs-someoption', 'test' );
360 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
361 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
365 * Test password validity checks. There are 3 checks in core,
366 * - ensure the password meets the minimal length
367 * - ensure the password is not the same as the username
368 * - ensure the username/password combo isn't forbidden
369 * @covers User::checkPasswordValidity()
370 * @covers User::isValidPassword()
372 public function testCheckPasswordValidity() {
373 $this->setMwGlobals( [
374 'wgPasswordPolicy' => [
377 'MinimalPasswordLength' => 8,
378 'MinimumPasswordLengthToLogin' => 1,
379 'PasswordCannotMatchUsername' => 1,
382 'MinimalPasswordLength' => 6,
383 'PasswordCannotMatchUsername' => true,
384 'PasswordCannotMatchBlacklist' => true,
385 'MaximalPasswordLength' => 40,
389 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
390 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
391 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
392 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
393 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
398 $user = static::getTestUser()->getUser();
401 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
404 $this->assertFalse( $user->isValidPassword( 'a' ) );
405 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
406 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
409 $longPass = str_repeat( 'a', 41 );
410 $this->assertFalse( $user->isValidPassword( $longPass ) );
411 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
412 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
415 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
416 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
418 // On the forbidden list
419 $user = User
::newFromName( 'Useruser' );
420 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
424 * @covers User::getCanonicalName()
425 * @dataProvider provideGetCanonicalName
427 public function testGetCanonicalName( $name, $expectedArray ) {
428 // fake interwiki map for the 'Interwiki prefix' testcase
429 $this->mergeMwGlobalArrayValue( 'wgHooks', [
430 'InterwikiLoadPrefix' => [
431 function ( $prefix, &$iwdata ) {
432 if ( $prefix === 'interwiki' ) {
434 'iw_url' => 'http://example.com/',
444 foreach ( $expectedArray as $validate => $expected ) {
447 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
451 public static function provideGetCanonicalName() {
453 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
454 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
455 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
456 'valid' => false, 'false' => 'Talk:Username' ] ],
457 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
458 'valid' => false, 'false' => 'Interwiki:Username' ] ],
459 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
460 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
461 'usable' => 'Multi spaces' ] ],
462 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
463 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
464 'valid' => false, 'false' => 'In[]valid' ] ],
465 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
466 'false' => 'With / slash' ] ],
471 * @covers User::equals
473 public function testEquals() {
474 $first = $this->getMutableTestUser()->getUser();
475 $second = User
::newFromName( $first->getName() );
477 $this->assertTrue( $first->equals( $first ) );
478 $this->assertTrue( $first->equals( $second ) );
479 $this->assertTrue( $second->equals( $first ) );
481 $third = $this->getMutableTestUser()->getUser();
482 $fourth = $this->getMutableTestUser()->getUser();
484 $this->assertFalse( $third->equals( $fourth ) );
485 $this->assertFalse( $fourth->equals( $third ) );
487 // Test users loaded from db with id
488 $user = $this->getMutableTestUser()->getUser();
489 $fifth = User
::newFromId( $user->getId() );
490 $sixth = User
::newFromName( $user->getName() );
491 $this->assertTrue( $fifth->equals( $sixth ) );
495 * @covers User::getId
497 public function testGetId() {
498 $user = static::getTestUser()->getUser();
499 $this->assertTrue( $user->getId() > 0 );
503 * @covers User::isRegistered
504 * @covers User::isLoggedIn
505 * @covers User::isAnon
507 public function testLoggedIn() {
508 $user = $this->getMutableTestUser()->getUser();
509 $this->assertTrue( $user->isRegistered() );
510 $this->assertTrue( $user->isLoggedIn() );
511 $this->assertFalse( $user->isAnon() );
513 // Non-existent users are perceived as anonymous
514 $user = User
::newFromName( 'UTNonexistent' );
515 $this->assertFalse( $user->isRegistered() );
516 $this->assertFalse( $user->isLoggedIn() );
517 $this->assertTrue( $user->isAnon() );
520 $this->assertFalse( $user->isRegistered() );
521 $this->assertFalse( $user->isLoggedIn() );
522 $this->assertTrue( $user->isAnon() );
526 * @covers User::checkAndSetTouched
528 public function testCheckAndSetTouched() {
529 $user = $this->getMutableTestUser()->getUser();
530 $user = TestingAccessWrapper
::newFromObject( $user );
531 $this->assertTrue( $user->isLoggedIn() );
533 $touched = $user->getDBTouched();
535 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
536 $this->assertGreaterThan(
537 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
539 $touched = $user->getDBTouched();
541 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
542 $this->assertGreaterThan(
543 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
547 * @covers User::findUsersByGroup
549 public function testFindUsersByGroup() {
550 // FIXME: fails under postgres
551 $this->markTestSkippedIfDbType( 'postgres' );
553 $users = User
::findUsersByGroup( [] );
554 $this->assertEquals( 0, iterator_count( $users ) );
556 $users = User
::findUsersByGroup( 'foo' );
557 $this->assertEquals( 0, iterator_count( $users ) );
559 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
560 $users = User
::findUsersByGroup( 'foo' );
561 $this->assertEquals( 1, iterator_count( $users ) );
563 $this->assertTrue( $user->equals( $users->current() ) );
565 // arguments have OR relationship
566 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
567 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
568 $this->assertEquals( 2, iterator_count( $users ) );
570 $this->assertTrue( $user->equals( $users->current() ) );
572 $this->assertTrue( $user2->equals( $users->current() ) );
574 // users are not duplicated
575 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
576 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
577 $this->assertEquals( 1, iterator_count( $users ) );
579 $this->assertTrue( $user->equals( $users->current() ) );
583 * When a user is autoblocked a cookie is set with which to track them
584 * in case they log out and change IP addresses.
585 * @link https://phabricator.wikimedia.org/T5233
586 * @covers User::trackBlockWithCookie
588 public function testAutoblockCookies() {
589 // Set up the bits of global configuration that we use.
590 $this->setMwGlobals( [
591 'wgCookieSetOnAutoblock' => true,
592 'wgCookiePrefix' => 'wmsitetitle',
593 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
596 // Unregister the hooks for proper unit testing
597 $this->mergeMwGlobalArrayValue( 'wgHooks', [
598 'PerformRetroactiveAutoblock' => []
601 // 1. Log in a test user, and block them.
602 $user1tmp = $this->getTestUser()->getUser();
603 $request1 = new FauxRequest();
604 $request1->getSession()->setUser( $user1tmp );
605 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
606 $block = new DatabaseBlock( [
607 'enableAutoblock' => true,
608 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
610 $block->setBlocker( $this->getTestSysop()->getUser() );
611 $block->setTarget( $user1tmp );
612 $res = $block->insert();
613 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
614 $user1 = User
::newFromSession( $request1 );
615 $user1->mBlock
= $block;
618 // Confirm that the block has been applied as required.
619 $this->assertTrue( $user1->isLoggedIn() );
620 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
621 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
622 $this->assertTrue( $block->isAutoblocking() );
623 $this->assertGreaterThanOrEqual( 1, $block->getId() );
625 // Test for the desired cookie name, value, and expiry.
626 $cookies = $request1->response()->getCookies();
627 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
628 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
629 $cookieId = MediaWikiServices
::getInstance()->getBlockManager()->getIdFromCookieValue(
630 $cookies['wmsitetitleBlockID']['value']
632 $this->assertEquals( $block->getId(), $cookieId );
634 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
635 $request2 = new FauxRequest();
636 $request2->setCookie( 'BlockID', $block->getCookieValue() );
637 $user2 = User
::newFromSession( $request2 );
639 $this->assertNotEquals( $user1->getId(), $user2->getId() );
640 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
641 $this->assertTrue( $user2->isAnon() );
642 $this->assertFalse( $user2->isLoggedIn() );
643 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
644 // Non-strict type-check.
645 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
646 // Can't directly compare the objects because of member type differences.
647 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
648 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
649 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
651 // 3. Finally, set up a request as a new user, and the block should still be applied.
652 $user3tmp = $this->getTestUser()->getUser();
653 $request3 = new FauxRequest();
654 $request3->getSession()->setUser( $user3tmp );
655 $request3->setCookie( 'BlockID', $block->getId() );
656 $user3 = User
::newFromSession( $request3 );
658 $this->assertTrue( $user3->isLoggedIn() );
659 $this->assertInstanceOf( DatabaseBlock
::class, $user3->getBlock() );
660 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
667 * Make sure that no cookie is set to track autoblocked users
668 * when $wgCookieSetOnAutoblock is false.
669 * @covers User::trackBlockWithCookie
671 public function testAutoblockCookiesDisabled() {
672 // Set up the bits of global configuration that we use.
673 $this->setMwGlobals( [
674 'wgCookieSetOnAutoblock' => false,
675 'wgCookiePrefix' => 'wm_no_cookies',
676 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
679 // Unregister the hooks for proper unit testing
680 $this->mergeMwGlobalArrayValue( 'wgHooks', [
681 'PerformRetroactiveAutoblock' => []
684 // 1. Log in a test user, and block them.
685 $testUser = $this->getTestUser()->getUser();
686 $request1 = new FauxRequest();
687 $request1->getSession()->setUser( $testUser );
688 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
689 $block->setBlocker( $this->getTestSysop()->getUser() );
690 $block->setTarget( $testUser );
691 $res = $block->insert();
692 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
693 $user = User
::newFromSession( $request1 );
694 $user->mBlock
= $block;
697 // 2. Test that the cookie IS NOT present.
698 $this->assertTrue( $user->isLoggedIn() );
699 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock() );
700 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
701 $this->assertTrue( $block->isAutoblocking() );
702 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
703 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
704 $cookies = $request1->response()->getCookies();
705 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
712 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
713 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
714 * the cookie's should change with it.
715 * @covers User::trackBlockWithCookie
717 public function testAutoblockCookieInfiniteExpiry() {
718 $this->setMwGlobals( [
719 'wgCookieSetOnAutoblock' => true,
720 'wgCookiePrefix' => 'wm_infinite_block',
721 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
724 // Unregister the hooks for proper unit testing
725 $this->mergeMwGlobalArrayValue( 'wgHooks', [
726 'PerformRetroactiveAutoblock' => []
729 // 1. Log in a test user, and block them indefinitely.
730 $user1Tmp = $this->getTestUser()->getUser();
731 $request1 = new FauxRequest();
732 $request1->getSession()->setUser( $user1Tmp );
733 $block = new DatabaseBlock( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
734 $block->setBlocker( $this->getTestSysop()->getUser() );
735 $block->setTarget( $user1Tmp );
736 $res = $block->insert();
737 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
738 $user1 = User
::newFromSession( $request1 );
739 $user1->mBlock
= $block;
742 // 2. Test the cookie's expiry timestamp.
743 $this->assertTrue( $user1->isLoggedIn() );
744 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
745 $this->assertEquals( DatabaseBlock
::TYPE_USER
, $block->getType() );
746 $this->assertTrue( $block->isAutoblocking() );
747 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
748 $cookies = $request1->response()->getCookies();
749 // Test the cookie's expiry to the nearest minute.
750 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
751 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
752 // Check for expiry dates in a 10-second window, to account for slow testing.
755 $cookies['wm_infinite_blockBlockID']['expire'],
760 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
761 $newExpiry = wfTimestamp() +
2 * 60 * 60;
762 $block->setExpiry( wfTimestamp( TS_MW
, $newExpiry ) );
764 $user2tmp = $this->getTestUser()->getUser();
765 $request2 = new FauxRequest();
766 $request2->getSession()->setUser( $user2tmp );
767 $user2 = User
::newFromSession( $request2 );
768 $user2->mBlock
= $block;
770 $cookies = $request2->response()->getCookies();
771 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
772 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
779 * @covers User::getBlockedStatus
781 public function testSoftBlockRanges() {
782 $setSessionUser = function ( User
$user, WebRequest
$request ) {
783 $this->setMwGlobals( 'wgUser', $user );
784 RequestContext
::getMain()->setUser( $user );
785 RequestContext
::getMain()->setRequest( $request );
786 TestingAccessWrapper
::newFromObject( $user )->mRequest
= $request;
787 $request->getSession()->setUser( $user );
788 $this->overrideMwServices();
790 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
792 // IP isn't in $wgSoftBlockRanges
793 $wgUser = new User();
794 $request = new FauxRequest();
795 $request->setIP( '192.168.0.1' );
796 $setSessionUser( $wgUser, $request );
797 $this->assertNull( $wgUser->getBlock() );
799 // IP is in $wgSoftBlockRanges
800 $wgUser = new User();
801 $request = new FauxRequest();
802 $request->setIP( '10.20.30.40' );
803 $setSessionUser( $wgUser, $request );
804 $block = $wgUser->getBlock();
805 $this->assertInstanceOf( SystemBlock
::class, $block );
806 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
808 // Make sure the block is really soft
809 $wgUser = $this->getTestUser()->getUser();
810 $request = new FauxRequest();
811 $request->setIP( '10.20.30.40' );
812 $setSessionUser( $wgUser, $request );
813 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
814 $this->assertNull( $wgUser->getBlock() );
818 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
819 * @covers User::trackBlockWithCookie
821 public function testAutoblockCookieInauthentic() {
822 // Set up the bits of global configuration that we use.
823 $this->setMwGlobals( [
824 'wgCookieSetOnAutoblock' => true,
825 'wgCookiePrefix' => 'wmsitetitle',
826 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
829 // Unregister the hooks for proper unit testing
830 $this->mergeMwGlobalArrayValue( 'wgHooks', [
831 'PerformRetroactiveAutoblock' => []
834 // 1. Log in a blocked test user.
835 $user1tmp = $this->getTestUser()->getUser();
836 $request1 = new FauxRequest();
837 $request1->getSession()->setUser( $user1tmp );
838 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
839 $block->setBlocker( $this->getTestSysop()->getUser() );
840 $block->setTarget( $user1tmp );
841 $res = $block->insert();
842 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
843 $user1 = User
::newFromSession( $request1 );
844 $user1->mBlock
= $block;
847 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
849 $request2 = new FauxRequest();
850 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
851 $user2 = User
::newFromSession( $request2 );
853 $this->assertTrue( $user2->isAnon() );
854 $this->assertFalse( $user2->isLoggedIn() );
855 $this->assertNull( $user2->getBlock() );
862 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
863 * This checks that a non-authenticated cookie still works.
864 * @covers User::trackBlockWithCookie
866 public function testAutoblockCookieNoSecretKey() {
867 // Set up the bits of global configuration that we use.
868 $this->setMwGlobals( [
869 'wgCookieSetOnAutoblock' => true,
870 'wgCookiePrefix' => 'wmsitetitle',
871 'wgSecretKey' => null,
874 // Unregister the hooks for proper unit testing
875 $this->mergeMwGlobalArrayValue( 'wgHooks', [
876 'PerformRetroactiveAutoblock' => []
879 // 1. Log in a blocked test user.
880 $user1tmp = $this->getTestUser()->getUser();
881 $request1 = new FauxRequest();
882 $request1->getSession()->setUser( $user1tmp );
883 $block = new DatabaseBlock( [ 'enableAutoblock' => true ] );
884 $block->setBlocker( $this->getTestSysop()->getUser() );
885 $block->setTarget( $user1tmp );
886 $res = $block->insert();
887 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
888 $user1 = User
::newFromSession( $request1 );
889 $user1->mBlock
= $block;
891 $this->assertInstanceOf( DatabaseBlock
::class, $user1->getBlock() );
893 // 2. Create a new request, set the cookie to just the block ID, and the user should
894 // still get blocked when they log in again.
895 $request2 = new FauxRequest();
896 $request2->setCookie( 'BlockID', $block->getId() );
897 $user2 = User
::newFromSession( $request2 );
899 $this->assertNotEquals( $user1->getId(), $user2->getId() );
900 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
901 $this->assertTrue( $user2->isAnon() );
902 $this->assertFalse( $user2->isLoggedIn() );
903 $this->assertInstanceOf( DatabaseBlock
::class, $user2->getBlock() );
904 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
911 * @covers User::isPingLimitable
913 public function testIsPingLimitable() {
914 $request = new FauxRequest();
915 $request->setIP( '1.2.3.4' );
916 $user = User
::newFromSession( $request );
918 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
919 $this->assertTrue( $user->isPingLimitable() );
921 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
922 $this->assertFalse( $user->isPingLimitable() );
924 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
925 $this->assertFalse( $user->isPingLimitable() );
927 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
928 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
929 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
930 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
931 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
932 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
935 public function provideExperienceLevel() {
937 [ 2, 2, 'newcomer' ],
938 [ 12, 3, 'newcomer' ],
939 [ 8, 5, 'newcomer' ],
940 [ 15, 10, 'learner' ],
941 [ 450, 20, 'learner' ],
942 [ 460, 33, 'learner' ],
943 [ 525, 28, 'learner' ],
944 [ 538, 33, 'experienced' ],
949 * @covers User::getExperienceLevel
950 * @dataProvider provideExperienceLevel
952 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
953 $this->setMwGlobals( [
954 'wgLearnerEdits' => 10,
955 'wgLearnerMemberSince' => 4,
956 'wgExperiencedUserEdits' => 500,
957 'wgExperiencedUserMemberSince' => 30,
960 $db = wfGetDB( DB_MASTER
);
961 $userQuery = User
::getQueryInfo();
962 $row = $db->selectRow(
963 $userQuery['tables'],
964 $userQuery['fields'],
965 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
970 $row->user_editcount
= $editCount;
971 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
972 $user = User
::newFromRow( $row );
974 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
978 * @covers User::getExperienceLevel
980 public function testExperienceLevelAnon() {
981 $user = User
::newFromName( '10.11.12.13', false );
983 $this->assertFalse( $user->getExperienceLevel() );
986 public static function provideIsLocallyBlockedProxy() {
988 [ '1.2.3.4', '1.2.3.4' ],
989 [ '1.2.3.4', '1.2.3.0/16' ],
994 * @dataProvider provideIsLocallyBlockedProxy
995 * @covers User::isLocallyBlockedProxy
997 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
998 $this->hideDeprecated( 'User::isLocallyBlockedProxy' );
1000 $this->setMwGlobals(
1003 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1005 $this->setMwGlobals(
1011 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1013 $this->setMwGlobals(
1016 'test' => $blockListEntry
1019 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1021 $this->hideDeprecated(
1022 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1023 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1025 $this->setMwGlobals(
1028 $blockListEntry => 'test'
1031 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1035 * @covers User::newFromActorId
1037 public function testActorId() {
1038 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1039 $this->hideDeprecated( 'User::selectFields' );
1041 // Newly-created user has an actor ID
1042 $user = User
::createNew( 'UserTestActorId1' );
1043 $id = $user->getId();
1044 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1046 $user = User
::newFromName( 'UserTestActorId2' );
1047 $user->addToDatabase();
1048 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1050 $user = User
::newFromName( 'UserTestActorId1' );
1051 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1053 $user = User
::newFromId( $id );
1054 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1056 $user2 = User
::newFromActorId( $user->getActorId() );
1057 $this->assertEquals( $user->getId(), $user2->getId(),
1058 'User::newFromActorId works for an existing user' );
1060 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1061 $user = User
::newFromRow( $row );
1062 $this->assertTrue( $user->getActorId() > 0,
1063 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1065 $user = User
::newFromId( $id );
1066 $user->setName( 'UserTestActorId4-renamed' );
1067 $user->saveSettings();
1068 $this->assertEquals(
1070 $this->db
->selectField(
1071 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1073 'User::saveSettings updates actor table for name change'
1077 $ip = '192.168.12.34';
1078 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1080 $user = User
::newFromName( $ip, false );
1081 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1082 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1083 'Actor ID can be created for an anonymous user' );
1085 $user = User
::newFromName( $ip, false );
1086 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1087 $user2 = User
::newFromActorId( $user->getActorId() );
1088 $this->assertEquals( $user->getName(), $user2->getName(),
1089 'User::newFromActorId works for an anonymous user' );
1093 * Actor tests with SCHEMA_COMPAT_READ_OLD
1095 * The only thing different from testActorId() is the behavior if the actor
1096 * row doesn't exist in the DB, since with SCHEMA_COMPAT_READ_NEW that
1097 * situation can't happen. But we copy all the other tests too just for good measure.
1099 * @covers User::newFromActorId
1101 public function testActorId_old() {
1102 $this->setMwGlobals( [
1103 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
1105 $this->overrideMwServices();
1107 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1108 $this->hideDeprecated( 'User::selectFields' );
1110 // Newly-created user has an actor ID
1111 $user = User
::createNew( 'UserTestActorIdOld1' );
1112 $id = $user->getId();
1113 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1115 $user = User
::newFromName( 'UserTestActorIdOld2' );
1116 $user->addToDatabase();
1117 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1119 $user = User
::newFromName( 'UserTestActorIdOld1' );
1120 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1122 $user = User
::newFromId( $id );
1123 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1125 $user2 = User
::newFromActorId( $user->getActorId() );
1126 $this->assertEquals( $user->getId(), $user2->getId(),
1127 'User::newFromActorId works for an existing user' );
1129 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1130 $user = User
::newFromRow( $row );
1131 $this->assertTrue( $user->getActorId() > 0,
1132 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1134 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1135 User
::purge( $domain, $id );
1136 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1137 ObjectCache
::getMainWANInstance()->clearProcessCache();
1139 $user = User
::newFromId( $id );
1140 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1141 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1143 $user->setName( 'UserTestActorIdOld4-renamed' );
1144 $user->saveSettings();
1145 $this->assertEquals(
1147 $this->db
->selectField(
1148 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1150 'User::saveSettings updates actor table for name change'
1154 $ip = '192.168.12.34';
1155 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1157 $user = User
::newFromName( $ip, false );
1158 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1159 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1160 'Actor ID can be created for an anonymous user' );
1162 $user = User
::newFromName( $ip, false );
1163 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1164 $user2 = User
::newFromActorId( $user->getActorId() );
1165 $this->assertEquals( $user->getName(), $user2->getName(),
1166 'User::newFromActorId works for an anonymous user' );
1170 * @covers User::newFromAnyId
1172 public function testNewFromAnyId() {
1174 $user = $this->getTestUser()->getUser();
1175 for ( $i = 1; $i <= 7; $i++
) {
1176 $test = User
::newFromAnyId(
1177 ( $i & 1 ) ?
$user->getId() : null,
1178 ( $i & 2 ) ?
$user->getName() : null,
1179 ( $i & 4 ) ?
$user->getActorId() : null
1181 $this->assertSame( $user->getId(), $test->getId() );
1182 $this->assertSame( $user->getName(), $test->getName() );
1183 $this->assertSame( $user->getActorId(), $test->getActorId() );
1186 // Anon user. Can't load by only user ID when that's 0.
1187 $user = User
::newFromName( '192.168.12.34', false );
1188 $user->getActorId( $this->db
); // Make sure an actor ID exists
1190 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1191 $this->assertSame( $user->getId(), $test->getId() );
1192 $this->assertSame( $user->getName(), $test->getName() );
1193 $this->assertSame( $user->getActorId(), $test->getActorId() );
1194 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1195 $this->assertSame( $user->getId(), $test->getId() );
1196 $this->assertSame( $user->getName(), $test->getName() );
1197 $this->assertSame( $user->getActorId(), $test->getActorId() );
1199 // Bogus data should still "work" as long as nothing triggers a ->load(),
1200 // and accessing the specified data shouldn't do that.
1201 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1202 $this->assertSame( 123456, $test->getId() );
1203 $this->assertSame( 'Bogus', $test->getName() );
1204 $this->assertSame( 654321, $test->getActorId() );
1206 // Loading remote user by name from remote wiki should succeed
1207 $test = User
::newFromAnyId( null, 'Bogus', null, 'foo' );
1208 $this->assertSame( 0, $test->getId() );
1209 $this->assertSame( 'Bogus', $test->getName() );
1210 $this->assertSame( 0, $test->getActorId() );
1211 $test = User
::newFromAnyId( 123456, 'Bogus', 654321, 'foo' );
1212 $this->assertSame( 0, $test->getId() );
1213 $this->assertSame( 0, $test->getActorId() );
1215 // Exceptional cases
1217 User
::newFromAnyId( null, null, null );
1218 $this->fail( 'Expected exception not thrown' );
1219 } catch ( InvalidArgumentException
$ex ) {
1222 User
::newFromAnyId( 0, null, 0 );
1223 $this->fail( 'Expected exception not thrown' );
1224 } catch ( InvalidArgumentException
$ex ) {
1227 // Loading remote user by id from remote wiki should fail
1229 User
::newFromAnyId( 123456, null, 654321, 'foo' );
1230 $this->fail( 'Expected exception not thrown' );
1231 } catch ( InvalidArgumentException
$ex ) {
1236 * @covers User::newFromIdentity
1238 public function testNewFromIdentity() {
1240 $user = $this->getTestUser()->getUser();
1242 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1245 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1246 $result = User
::newFromIdentity( $identity );
1247 $this->assertInstanceOf( User
::class, $result );
1248 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1249 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1250 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1253 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1254 $result = User
::newFromIdentity( $identity );
1255 $this->assertInstanceOf( User
::class, $result );
1256 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1257 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1258 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1261 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1262 $result = User
::newFromIdentity( $identity );
1263 $this->assertInstanceOf( User
::class, $result );
1264 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1265 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1266 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1270 * @covers User::getBlockedStatus
1271 * @covers User::getBlock
1272 * @covers User::blockedBy
1273 * @covers User::blockedFor
1274 * @covers User::isHidden
1275 * @covers User::isBlockedFrom
1277 public function testBlockInstanceCache() {
1278 // First, check the user isn't blocked
1279 $user = $this->getMutableTestUser()->getUser();
1280 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1281 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1282 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1283 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1284 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1285 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1288 $blocker = $this->getTestSysop()->getUser();
1289 $block = new DatabaseBlock( [
1291 'allowUsertalk' => false,
1292 'reason' => 'Because',
1294 $block->setTarget( $user );
1295 $block->setBlocker( $blocker );
1296 $res = $block->insert();
1297 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1299 // Clear cache and confirm it loaded the block properly
1300 $user->clearInstanceCache();
1301 $this->assertInstanceOf( DatabaseBlock
::class, $user->getBlock( false ) );
1302 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1303 $this->assertSame( 'Because', $user->blockedFor() );
1304 $this->assertTrue( (bool)$user->isHidden() );
1305 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1310 // Clear cache and confirm it loaded the not-blocked properly
1311 $user->clearInstanceCache();
1312 $this->assertNull( $user->getBlock( false ) );
1313 $this->assertSame( '', $user->blockedBy() );
1314 $this->assertSame( '', $user->blockedFor() );
1315 $this->assertFalse( (bool)$user->isHidden() );
1316 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1320 * @covers User::isBlockedFrom
1321 * @dataProvider provideIsBlockedFrom
1322 * @param string|null $title Title to test.
1323 * @param bool $expect Expected result from User::isBlockedFrom()
1324 * @param array $options Additional test options:
1325 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1326 * - 'allowUsertalk': (bool, default false) Passed to DatabaseBlock::__construct()
1327 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1329 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1330 $this->setMwGlobals( [
1331 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1334 $user = $this->getTestUser()->getUser();
1336 if ( $title === self
::USER_TALK_PAGE
) {
1337 $title = $user->getTalkPage();
1339 $title = Title
::newFromText( $title );
1343 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1344 $page = $this->getExistingTestPage(
1345 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1347 $restrictions[] = new PageRestriction( 0, $page->getId() );
1349 foreach ( $options['namespaceRestrictions'] ??
[] as $ns ) {
1350 $restrictions[] = new NamespaceRestriction( 0, $ns );
1353 $block = new DatabaseBlock( [
1354 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1355 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1356 'sitewide' => !$restrictions,
1358 $block->setTarget( $user );
1359 $block->setBlocker( $this->getTestSysop()->getUser() );
1360 if ( $restrictions ) {
1361 $block->setRestrictions( $restrictions );
1366 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1372 public static function provideIsBlockedFrom() {
1374 'Sitewide block, basic operation' => [ 'Test page', true ],
1375 'Sitewide block, not allowing user talk' => [
1376 self
::USER_TALK_PAGE
, true, [
1377 'allowUsertalk' => false,
1380 'Sitewide block, allowing user talk' => [
1381 self
::USER_TALK_PAGE
, false, [
1382 'allowUsertalk' => true,
1385 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1386 self
::USER_TALK_PAGE
, true, [
1387 'allowUsertalk' => true,
1388 'blockAllowsUTEdit' => false,
1391 'Partial block, blocking the page' => [
1392 'Test page', true, [
1393 'pageRestrictions' => [ 'Test page' ],
1396 'Partial block, not blocking the page' => [
1397 'Test page 2', false, [
1398 'pageRestrictions' => [ 'Test page' ],
1401 'Partial block, not allowing user talk but user talk page is not blocked' => [
1402 self
::USER_TALK_PAGE
, false, [
1403 'allowUsertalk' => false,
1404 'pageRestrictions' => [ 'Test page' ],
1407 'Partial block, allowing user talk but user talk page is blocked' => [
1408 self
::USER_TALK_PAGE
, true, [
1409 'allowUsertalk' => true,
1410 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1413 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1414 self
::USER_TALK_PAGE
, false, [
1415 'allowUsertalk' => false,
1416 'pageRestrictions' => [ 'Test page' ],
1417 'blockAllowsUTEdit' => false,
1420 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1421 self
::USER_TALK_PAGE
, true, [
1422 'allowUsertalk' => true,
1423 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1424 'blockAllowsUTEdit' => false,
1427 'Partial user talk namespace block, not allowing user talk' => [
1428 self
::USER_TALK_PAGE
, true, [
1429 'allowUsertalk' => false,
1430 'namespaceRestrictions' => [ NS_USER_TALK
],
1433 'Partial user talk namespace block, allowing user talk' => [
1434 self
::USER_TALK_PAGE
, false, [
1435 'allowUsertalk' => true,
1436 'namespaceRestrictions' => [ NS_USER_TALK
],
1439 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1440 self
::USER_TALK_PAGE
, true, [
1441 'allowUsertalk' => true,
1442 'namespaceRestrictions' => [ NS_USER_TALK
],
1443 'blockAllowsUTEdit' => false,
1450 * Block cookie should be set for IP Blocks if
1451 * wgCookieSetOnIpBlock is set to true
1452 * @covers User::trackBlockWithCookie
1454 public function testIpBlockCookieSet() {
1455 $this->setMwGlobals( [
1456 'wgCookieSetOnIpBlock' => true,
1457 'wgCookiePrefix' => 'wiki',
1458 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1462 $block = new DatabaseBlock( [
1463 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1465 $block->setTarget( '1.2.3.4' );
1466 $block->setBlocker( $this->getTestSysop()->getUser() );
1470 $request = new FauxRequest();
1471 $request->setIP( '1.2.3.4' );
1474 $user = User
::newFromSession( $request );
1475 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1477 // test cookie was set
1478 $cookies = $request->response()->getCookies();
1479 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1486 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1488 * @covers User::trackBlockWithCookie
1490 public function testIpBlockCookieNotSet() {
1491 $this->setMwGlobals( [
1492 'wgCookieSetOnIpBlock' => false,
1493 'wgCookiePrefix' => 'wiki',
1494 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1498 $block = new DatabaseBlock( [
1499 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1501 $block->setTarget( '1.2.3.4' );
1502 $block->setBlocker( $this->getTestSysop()->getUser() );
1506 $request = new FauxRequest();
1507 $request->setIP( '1.2.3.4' );
1510 $user = User
::newFromSession( $request );
1511 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $user );
1513 // test cookie was not set
1514 $cookies = $request->response()->getCookies();
1515 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1522 * When an ip user is blocked and then they log in, cookie block
1523 * should be invalid and the cookie removed.
1524 * @covers User::trackBlockWithCookie
1526 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1527 $this->setMwGlobals( [
1528 'wgAutoblockExpiry' => 8000,
1529 'wgCookieSetOnIpBlock' => true,
1530 'wgCookiePrefix' => 'wiki',
1531 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1535 $block = new DatabaseBlock( [
1536 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1538 $block->setTarget( '1.2.3.4' );
1539 $block->setBlocker( $this->getTestSysop()->getUser() );
1543 $request = new FauxRequest();
1544 $request->setIP( '1.2.3.4' );
1545 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1546 $request->setCookie( 'BlockID', $block->getCookieValue() );
1549 $user = User
::newFromSession( $request );
1551 // logged in users should be inmune to cookie block of type ip/range
1552 $this->assertNull( $user->getBlock() );
1554 // cookie is being cleared
1555 $cookies = $request->response()->getCookies();
1556 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1563 * @covers User::getFirstEditTimestamp
1564 * @covers User::getLatestEditTimestamp
1566 public function testGetFirstLatestEditTimestamp() {
1567 $clock = MWTimestamp
::convert( TS_UNIX
, '20100101000000' );
1568 MWTimestamp
::setFakeTime( function () use ( &$clock ) {
1569 return $clock +
= 1000;
1572 $user = $this->getTestUser()->getUser();
1573 $firstRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'one', 'test' );
1574 $secondRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'two', 'test' );
1575 // Sanity check: revisions timestamp are different
1576 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1578 $this->assertEquals( $firstRevision->getTimestamp(), $user->getFirstEditTimestamp() );
1579 $this->assertEquals( $secondRevision->getTimestamp(), $user->getLatestEditTimestamp() );
1581 MWTimestamp
::setFakeTime( false );
1587 * @param string $title
1588 * @param string $content
1589 * @param string $comment
1590 * @return \MediaWiki\Revision\RevisionRecord|null
1592 private static function makeEdit( User
$user, $title, $content, $comment ) {
1593 $page = WikiPage
::factory( Title
::newFromText( $title ) );
1594 $content = ContentHandler
::makeContent( $content, $page->getTitle() );
1595 $updater = $page->newPageUpdater( $user );
1596 $updater->setContent( 'main', $content );
1597 return $updater->saveRevision( CommentStoreComment
::newUnsavedComment( $comment ) );
1601 * @covers User::idFromName
1603 public function testExistingIdFromName() {
1605 array_key_exists( $this->user
->getName(), User
::$idCacheByName ),
1606 'Test user should already be in the id cache.'
1609 $this->user
->getId(), User
::idFromName( $this->user
->getName() ),
1610 'Id is correctly retreived from the cache.'
1613 $this->user
->getId(), User
::idFromName( $this->user
->getName(), User
::READ_LATEST
),
1614 'Id is correctly retreived from the database.'
1619 * @covers User::idFromName
1621 public function testNonExistingIdFromName() {
1623 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1624 'Non exisitng user should not be in the id cache.'
1626 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );
1628 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1629 'Username will be cached when requested once.'
1631 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );