3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\Block\Restriction\PageRestriction
;
7 use MediaWiki\Block\Restriction\NamespaceRestriction
;
8 use MediaWiki\Block\SystemBlock
;
9 use MediaWiki\MediaWikiServices
;
10 use MediaWiki\User\UserIdentityValue
;
11 use Wikimedia\TestingAccessWrapper
;
16 class UserTest
extends MediaWikiTestCase
{
18 /** Constant for self::testIsBlockedFrom */
19 const USER_TALK_PAGE
= '<user talk page>';
26 protected function setUp() {
29 $this->setMwGlobals( [
30 'wgGroupPermissions' => [],
31 'wgRevokePermissions' => [],
32 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_NEW
,
34 $this->overrideMwServices();
36 $this->setUpPermissionGlobals();
38 $this->user
= $this->getTestUser( [ 'unittesters' ] )->getUser();
41 private function setUpPermissionGlobals() {
42 global $wgGroupPermissions, $wgRevokePermissions;
44 # Data for regular $wgGroupPermissions test
45 $wgGroupPermissions['unittesters'] = [
51 $wgGroupPermissions['testwriters'] = [
57 # Data for regular $wgRevokePermissions test
58 $wgRevokePermissions['formertesters'] = [
62 # For the options test
63 $wgGroupPermissions['*'] = [
64 'editmyoptions' => true,
69 * @covers User::getGroupPermissions
71 public function testGroupPermissions() {
72 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
73 $this->assertContains( 'runtest', $rights );
74 $this->assertNotContains( 'writetest', $rights );
75 $this->assertNotContains( 'modifytest', $rights );
76 $this->assertNotContains( 'nukeworld', $rights );
78 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
79 $this->assertContains( 'runtest', $rights );
80 $this->assertContains( 'writetest', $rights );
81 $this->assertContains( 'modifytest', $rights );
82 $this->assertNotContains( 'nukeworld', $rights );
86 * @covers User::getGroupPermissions
88 public function testRevokePermissions() {
89 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
90 $this->assertNotContains( 'runtest', $rights );
91 $this->assertNotContains( 'writetest', $rights );
92 $this->assertNotContains( 'modifytest', $rights );
93 $this->assertNotContains( 'nukeworld', $rights );
97 * @covers User::getRights
99 public function testUserPermissions() {
100 $rights = $this->user
->getRights();
101 $this->assertContains( 'runtest', $rights );
102 $this->assertNotContains( 'writetest', $rights );
103 $this->assertNotContains( 'modifytest', $rights );
104 $this->assertNotContains( 'nukeworld', $rights );
108 * @covers User::getRights
110 public function testUserGetRightsHooks() {
111 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
112 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
114 $rights = $user->getRights();
115 $this->assertContains( 'test', $rights, 'sanity check' );
116 $this->assertContains( 'runtest', $rights, 'sanity check' );
117 $this->assertContains( 'writetest', $rights, 'sanity check' );
118 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
120 // Add a hook manipluating the rights
121 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
122 $rights[] = 'nukeworld';
123 $rights = array_diff( $rights, [ 'writetest' ] );
126 $userWrapper->mRights
= null;
127 $rights = $user->getRights();
128 $this->assertContains( 'test', $rights );
129 $this->assertContains( 'runtest', $rights );
130 $this->assertNotContains( 'writetest', $rights );
131 $this->assertContains( 'nukeworld', $rights );
133 // Add a Session that limits rights
134 $mock = $this->getMockBuilder( stdClass
::class )
135 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
137 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
138 $mock->method( 'getSessionId' )->willReturn(
139 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
141 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
142 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
143 ->setMethods( [ 'getSession' ] )
145 $mockRequest->method( 'getSession' )->willReturn( $session );
146 $userWrapper->mRequest
= $mockRequest;
148 $userWrapper->mRights
= null;
149 $rights = $user->getRights();
150 $this->assertContains( 'test', $rights );
151 $this->assertNotContains( 'runtest', $rights );
152 $this->assertNotContains( 'writetest', $rights );
153 $this->assertNotContains( 'nukeworld', $rights );
157 * @dataProvider provideGetGroupsWithPermission
158 * @covers User::getGroupsWithPermission
160 public function testGetGroupsWithPermission( $expected, $right ) {
161 $result = User
::getGroupsWithPermission( $right );
165 $this->assertEquals( $expected, $result, "Groups with permission $right" );
168 public static function provideGetGroupsWithPermission() {
171 [ 'unittesters', 'testwriters' ],
190 * @dataProvider provideIPs
193 public function testIsIP( $value, $result, $message ) {
194 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
197 public static function provideIPs() {
199 [ '', false, 'Empty string' ],
200 [ ' ', false, 'Blank space' ],
201 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
202 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
203 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
204 [ '203.0.113.0', true, 'IPv4 example' ],
205 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
206 // Not valid IPs but classified as such by MediaWiki for negated asserting
207 // of whether this might be the identifier of a logged-out user or whether
208 // to allow usernames like it.
209 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
210 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
215 * @dataProvider provideUserNames
216 * @covers User::isValidUserName
218 public function testIsValidUserName( $username, $result, $message ) {
219 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
222 public static function provideUserNames() {
224 [ '', false, 'Empty string' ],
225 [ ' ', false, 'Blank space' ],
226 [ 'abcd', false, 'Starts with small letter' ],
227 [ 'Ab/cd', false, 'Contains slash' ],
228 [ 'Ab cd', true, 'Whitespace' ],
229 [ '192.168.1.1', false, 'IP' ],
230 [ '116.17.184.5/32', false, 'IP range' ],
231 [ '::e:f:2001/96', false, 'IPv6 range' ],
232 [ 'User:Abcd', false, 'Reserved Namespace' ],
233 [ '12abcd232', true, 'Starts with Numbers' ],
234 [ '?abcd', true, 'Start with ? mark' ],
235 [ '#abcd', false, 'Start with #' ],
236 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
237 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
238 [ 'Ab cd', false, ' Ideographic space' ],
239 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
240 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
241 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
246 * Test User::editCount
248 * @covers User::getEditCount
250 public function testGetEditCount() {
251 $user = $this->getMutableTestUser()->getUser();
253 // let the user have a few (3) edits
254 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
255 for ( $i = 0; $i < 3; $i++
) {
256 $page->doEditContent(
257 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
267 $user->getEditCount(),
268 'After three edits, the user edit count should be 3'
271 // increase the edit count
272 $user->incEditCount();
273 $user->clearInstanceCache();
277 $user->getEditCount(),
278 'After increasing the edit count manually, the user edit count should be 4'
283 * Test User::editCount
285 * @covers User::getEditCount
287 public function testGetEditCountForAnons() {
288 $user = User
::newFromName( 'Anonymous' );
291 $user->getEditCount(),
292 'Edit count starts null for anonymous users.'
295 $user->incEditCount();
298 $user->getEditCount(),
299 'Edit count remains null for anonymous users despite calls to increase it.'
304 * Test User::editCount
306 * @covers User::incEditCount
308 public function testIncEditCount() {
309 $user = $this->getMutableTestUser()->getUser();
310 $user->incEditCount();
312 $reloadedUser = User
::newFromId( $user->getId() );
313 $reloadedUser->incEditCount();
317 $reloadedUser->getEditCount(),
318 'Increasing the edit count after a fresh load leaves the object up to date.'
323 * Test changing user options.
324 * @covers User::setOption
325 * @covers User::getOption
327 public function testOptions() {
328 $user = $this->getMutableTestUser()->getUser();
330 $user->setOption( 'userjs-someoption', 'test' );
331 $user->setOption( 'rclimit', 200 );
332 $user->setOption( 'wpwatchlistdays', '0' );
333 $user->saveSettings();
335 $user = User
::newFromName( $user->getName() );
336 $user->load( User
::READ_LATEST
);
337 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
338 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
340 $user = User
::newFromName( $user->getName() );
341 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
342 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
343 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
345 // Check that an option saved as a string '0' is returned as an integer.
346 $user = User
::newFromName( $user->getName() );
347 $user->load( User
::READ_LATEST
);
348 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
353 * Make sure defaults are loaded when setOption is called.
354 * @covers User::loadOptions
356 public function testAnonOptions() {
357 global $wgDefaultUserOptions;
358 $this->user
->setOption( 'userjs-someoption', 'test' );
359 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
360 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
364 * Test password validity checks. There are 3 checks in core,
365 * - ensure the password meets the minimal length
366 * - ensure the password is not the same as the username
367 * - ensure the username/password combo isn't forbidden
368 * @covers User::checkPasswordValidity()
369 * @covers User::getPasswordValidity()
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',
397 $this->hideDeprecated( 'User::getPasswordValidity' );
399 $user = static::getTestUser()->getUser();
402 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
405 $this->assertFalse( $user->isValidPassword( 'a' ) );
406 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
407 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
408 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
411 $longPass = str_repeat( 'a', 41 );
412 $this->assertFalse( $user->isValidPassword( $longPass ) );
413 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
414 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
415 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
418 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
419 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
420 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
422 // On the forbidden list
423 $user = User
::newFromName( 'Useruser' );
424 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
425 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
429 * @covers User::getCanonicalName()
430 * @dataProvider provideGetCanonicalName
432 public function testGetCanonicalName( $name, $expectedArray ) {
433 // fake interwiki map for the 'Interwiki prefix' testcase
434 $this->mergeMwGlobalArrayValue( 'wgHooks', [
435 'InterwikiLoadPrefix' => [
436 function ( $prefix, &$iwdata ) {
437 if ( $prefix === 'interwiki' ) {
439 'iw_url' => 'http://example.com/',
449 foreach ( $expectedArray as $validate => $expected ) {
452 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
456 public static function provideGetCanonicalName() {
458 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
459 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
460 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
461 'valid' => false, 'false' => 'Talk:Username' ] ],
462 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
463 'valid' => false, 'false' => 'Interwiki:Username' ] ],
464 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
465 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
466 'usable' => 'Multi spaces' ] ],
467 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
468 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
469 'valid' => false, 'false' => 'In[]valid' ] ],
470 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
471 'false' => 'With / slash' ] ],
476 * @covers User::equals
478 public function testEquals() {
479 $first = $this->getMutableTestUser()->getUser();
480 $second = User
::newFromName( $first->getName() );
482 $this->assertTrue( $first->equals( $first ) );
483 $this->assertTrue( $first->equals( $second ) );
484 $this->assertTrue( $second->equals( $first ) );
486 $third = $this->getMutableTestUser()->getUser();
487 $fourth = $this->getMutableTestUser()->getUser();
489 $this->assertFalse( $third->equals( $fourth ) );
490 $this->assertFalse( $fourth->equals( $third ) );
492 // Test users loaded from db with id
493 $user = $this->getMutableTestUser()->getUser();
494 $fifth = User
::newFromId( $user->getId() );
495 $sixth = User
::newFromName( $user->getName() );
496 $this->assertTrue( $fifth->equals( $sixth ) );
500 * @covers User::getId
502 public function testGetId() {
503 $user = static::getTestUser()->getUser();
504 $this->assertTrue( $user->getId() > 0 );
508 * @covers User::isRegistered
509 * @covers User::isLoggedIn
510 * @covers User::isAnon
512 public function testLoggedIn() {
513 $user = $this->getMutableTestUser()->getUser();
514 $this->assertTrue( $user->isRegistered() );
515 $this->assertTrue( $user->isLoggedIn() );
516 $this->assertFalse( $user->isAnon() );
518 // Non-existent users are perceived as anonymous
519 $user = User
::newFromName( 'UTNonexistent' );
520 $this->assertFalse( $user->isRegistered() );
521 $this->assertFalse( $user->isLoggedIn() );
522 $this->assertTrue( $user->isAnon() );
525 $this->assertFalse( $user->isRegistered() );
526 $this->assertFalse( $user->isLoggedIn() );
527 $this->assertTrue( $user->isAnon() );
531 * @covers User::checkAndSetTouched
533 public function testCheckAndSetTouched() {
534 $user = $this->getMutableTestUser()->getUser();
535 $user = TestingAccessWrapper
::newFromObject( $user );
536 $this->assertTrue( $user->isLoggedIn() );
538 $touched = $user->getDBTouched();
540 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
541 $this->assertGreaterThan(
542 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
544 $touched = $user->getDBTouched();
546 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
547 $this->assertGreaterThan(
548 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
552 * @covers User::findUsersByGroup
554 public function testFindUsersByGroup() {
555 // FIXME: fails under postgres
556 $this->markTestSkippedIfDbType( 'postgres' );
558 $users = User
::findUsersByGroup( [] );
559 $this->assertEquals( 0, iterator_count( $users ) );
561 $users = User
::findUsersByGroup( 'foo' );
562 $this->assertEquals( 0, iterator_count( $users ) );
564 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
565 $users = User
::findUsersByGroup( 'foo' );
566 $this->assertEquals( 1, iterator_count( $users ) );
568 $this->assertTrue( $user->equals( $users->current() ) );
570 // arguments have OR relationship
571 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
572 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
573 $this->assertEquals( 2, iterator_count( $users ) );
575 $this->assertTrue( $user->equals( $users->current() ) );
577 $this->assertTrue( $user2->equals( $users->current() ) );
579 // users are not duplicated
580 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
581 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
582 $this->assertEquals( 1, iterator_count( $users ) );
584 $this->assertTrue( $user->equals( $users->current() ) );
588 * When a user is autoblocked a cookie is set with which to track them
589 * in case they log out and change IP addresses.
590 * @link https://phabricator.wikimedia.org/T5233
591 * @covers User::trackBlockWithCookie
593 public function testAutoblockCookies() {
594 // Set up the bits of global configuration that we use.
595 $this->setMwGlobals( [
596 'wgCookieSetOnAutoblock' => true,
597 'wgCookiePrefix' => 'wmsitetitle',
598 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
601 // Unregister the hooks for proper unit testing
602 $this->mergeMwGlobalArrayValue( 'wgHooks', [
603 'PerformRetroactiveAutoblock' => []
606 // 1. Log in a test user, and block them.
607 $user1tmp = $this->getTestUser()->getUser();
608 $request1 = new FauxRequest();
609 $request1->getSession()->setUser( $user1tmp );
610 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
611 $block = new Block( [
612 'enableAutoblock' => true,
613 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
615 $block->setBlocker( $this->getTestSysop()->getUser() );
616 $block->setTarget( $user1tmp );
617 $res = $block->insert();
618 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
619 $user1 = User
::newFromSession( $request1 );
620 $user1->mBlock
= $block;
623 // Confirm that the block has been applied as required.
624 $this->assertTrue( $user1->isLoggedIn() );
625 $this->assertInstanceOf( Block
::class, $user1->getBlock() );
626 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
627 $this->assertTrue( $block->isAutoblocking() );
628 $this->assertGreaterThanOrEqual( 1, $block->getId() );
630 // Test for the desired cookie name, value, and expiry.
631 $cookies = $request1->response()->getCookies();
632 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
633 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
634 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
635 $this->assertEquals( $block->getId(), $cookieValue );
637 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
638 $request2 = new FauxRequest();
639 $request2->setCookie( 'BlockID', $block->getCookieValue() );
640 $user2 = User
::newFromSession( $request2 );
642 $this->assertNotEquals( $user1->getId(), $user2->getId() );
643 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
644 $this->assertTrue( $user2->isAnon() );
645 $this->assertFalse( $user2->isLoggedIn() );
646 $this->assertInstanceOf( Block
::class, $user2->getBlock() );
647 // Non-strict type-check.
648 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
649 // Can't directly compare the objects because of member type differences.
650 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
651 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
652 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
654 // 3. Finally, set up a request as a new user, and the block should still be applied.
655 $user3tmp = $this->getTestUser()->getUser();
656 $request3 = new FauxRequest();
657 $request3->getSession()->setUser( $user3tmp );
658 $request3->setCookie( 'BlockID', $block->getId() );
659 $user3 = User
::newFromSession( $request3 );
661 $this->assertTrue( $user3->isLoggedIn() );
662 $this->assertInstanceOf( Block
::class, $user3->getBlock() );
663 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
670 * Make sure that no cookie is set to track autoblocked users
671 * when $wgCookieSetOnAutoblock is false.
672 * @covers User::trackBlockWithCookie
674 public function testAutoblockCookiesDisabled() {
675 // Set up the bits of global configuration that we use.
676 $this->setMwGlobals( [
677 'wgCookieSetOnAutoblock' => false,
678 'wgCookiePrefix' => 'wm_no_cookies',
679 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
682 // Unregister the hooks for proper unit testing
683 $this->mergeMwGlobalArrayValue( 'wgHooks', [
684 'PerformRetroactiveAutoblock' => []
687 // 1. Log in a test user, and block them.
688 $testUser = $this->getTestUser()->getUser();
689 $request1 = new FauxRequest();
690 $request1->getSession()->setUser( $testUser );
691 $block = new Block( [ 'enableAutoblock' => true ] );
692 $block->setBlocker( $this->getTestSysop()->getUser() );
693 $block->setTarget( $testUser );
694 $res = $block->insert();
695 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
696 $user = User
::newFromSession( $request1 );
697 $user->mBlock
= $block;
700 // 2. Test that the cookie IS NOT present.
701 $this->assertTrue( $user->isLoggedIn() );
702 $this->assertInstanceOf( Block
::class, $user->getBlock() );
703 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
704 $this->assertTrue( $block->isAutoblocking() );
705 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
706 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
707 $cookies = $request1->response()->getCookies();
708 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
715 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
716 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
717 * the cookie's should change with it.
718 * @covers User::trackBlockWithCookie
720 public function testAutoblockCookieInfiniteExpiry() {
721 $this->setMwGlobals( [
722 'wgCookieSetOnAutoblock' => true,
723 'wgCookiePrefix' => 'wm_infinite_block',
724 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
727 // Unregister the hooks for proper unit testing
728 $this->mergeMwGlobalArrayValue( 'wgHooks', [
729 'PerformRetroactiveAutoblock' => []
732 // 1. Log in a test user, and block them indefinitely.
733 $user1Tmp = $this->getTestUser()->getUser();
734 $request1 = new FauxRequest();
735 $request1->getSession()->setUser( $user1Tmp );
736 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
737 $block->setBlocker( $this->getTestSysop()->getUser() );
738 $block->setTarget( $user1Tmp );
739 $res = $block->insert();
740 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
741 $user1 = User
::newFromSession( $request1 );
742 $user1->mBlock
= $block;
745 // 2. Test the cookie's expiry timestamp.
746 $this->assertTrue( $user1->isLoggedIn() );
747 $this->assertInstanceOf( Block
::class, $user1->getBlock() );
748 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
749 $this->assertTrue( $block->isAutoblocking() );
750 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
751 $cookies = $request1->response()->getCookies();
752 // Test the cookie's expiry to the nearest minute.
753 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
754 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
755 // Check for expiry dates in a 10-second window, to account for slow testing.
758 $cookies['wm_infinite_blockBlockID']['expire'],
763 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
764 $newExpiry = wfTimestamp() +
2 * 60 * 60;
765 $block->setExpiry( wfTimestamp( TS_MW
, $newExpiry ) );
767 $user2tmp = $this->getTestUser()->getUser();
768 $request2 = new FauxRequest();
769 $request2->getSession()->setUser( $user2tmp );
770 $user2 = User
::newFromSession( $request2 );
771 $user2->mBlock
= $block;
773 $cookies = $request2->response()->getCookies();
774 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
775 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
782 * @covers User::getBlockedStatus
784 public function testSoftBlockRanges() {
785 $setSessionUser = function ( User
$user, WebRequest
$request ) {
786 $this->setMwGlobals( 'wgUser', $user );
787 RequestContext
::getMain()->setUser( $user );
788 RequestContext
::getMain()->setRequest( $request );
789 TestingAccessWrapper
::newFromObject( $user )->mRequest
= $request;
790 $request->getSession()->setUser( $user );
791 $this->overrideMwServices();
793 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
795 // IP isn't in $wgSoftBlockRanges
796 $wgUser = new User();
797 $request = new FauxRequest();
798 $request->setIP( '192.168.0.1' );
799 $setSessionUser( $wgUser, $request );
800 $this->assertNull( $wgUser->getBlock() );
802 // IP is in $wgSoftBlockRanges
803 $wgUser = new User();
804 $request = new FauxRequest();
805 $request->setIP( '10.20.30.40' );
806 $setSessionUser( $wgUser, $request );
807 $block = $wgUser->getBlock();
808 $this->assertInstanceOf( SystemBlock
::class, $block );
809 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
811 // Make sure the block is really soft
812 $wgUser = $this->getTestUser()->getUser();
813 $request = new FauxRequest();
814 $request->setIP( '10.20.30.40' );
815 $setSessionUser( $wgUser, $request );
816 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
817 $this->assertNull( $wgUser->getBlock() );
821 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
822 * @covers User::trackBlockWithCookie
824 public function testAutoblockCookieInauthentic() {
825 // Set up the bits of global configuration that we use.
826 $this->setMwGlobals( [
827 'wgCookieSetOnAutoblock' => true,
828 'wgCookiePrefix' => 'wmsitetitle',
829 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
832 // Unregister the hooks for proper unit testing
833 $this->mergeMwGlobalArrayValue( 'wgHooks', [
834 'PerformRetroactiveAutoblock' => []
837 // 1. Log in a blocked test user.
838 $user1tmp = $this->getTestUser()->getUser();
839 $request1 = new FauxRequest();
840 $request1->getSession()->setUser( $user1tmp );
841 $block = new Block( [ 'enableAutoblock' => true ] );
842 $block->setBlocker( $this->getTestSysop()->getUser() );
843 $block->setTarget( $user1tmp );
844 $res = $block->insert();
845 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
846 $user1 = User
::newFromSession( $request1 );
847 $user1->mBlock
= $block;
850 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
852 $request2 = new FauxRequest();
853 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
854 $user2 = User
::newFromSession( $request2 );
856 $this->assertTrue( $user2->isAnon() );
857 $this->assertFalse( $user2->isLoggedIn() );
858 $this->assertNull( $user2->getBlock() );
865 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
866 * This checks that a non-authenticated cookie still works.
867 * @covers User::trackBlockWithCookie
869 public function testAutoblockCookieNoSecretKey() {
870 // Set up the bits of global configuration that we use.
871 $this->setMwGlobals( [
872 'wgCookieSetOnAutoblock' => true,
873 'wgCookiePrefix' => 'wmsitetitle',
874 'wgSecretKey' => null,
877 // Unregister the hooks for proper unit testing
878 $this->mergeMwGlobalArrayValue( 'wgHooks', [
879 'PerformRetroactiveAutoblock' => []
882 // 1. Log in a blocked test user.
883 $user1tmp = $this->getTestUser()->getUser();
884 $request1 = new FauxRequest();
885 $request1->getSession()->setUser( $user1tmp );
886 $block = new Block( [ 'enableAutoblock' => true ] );
887 $block->setBlocker( $this->getTestSysop()->getUser() );
888 $block->setTarget( $user1tmp );
889 $res = $block->insert();
890 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
891 $user1 = User
::newFromSession( $request1 );
892 $user1->mBlock
= $block;
894 $this->assertInstanceOf( Block
::class, $user1->getBlock() );
896 // 2. Create a new request, set the cookie to just the block ID, and the user should
897 // still get blocked when they log in again.
898 $request2 = new FauxRequest();
899 $request2->setCookie( 'BlockID', $block->getId() );
900 $user2 = User
::newFromSession( $request2 );
902 $this->assertNotEquals( $user1->getId(), $user2->getId() );
903 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
904 $this->assertTrue( $user2->isAnon() );
905 $this->assertFalse( $user2->isLoggedIn() );
906 $this->assertInstanceOf( Block
::class, $user2->getBlock() );
907 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
914 * @covers User::isPingLimitable
916 public function testIsPingLimitable() {
917 $request = new FauxRequest();
918 $request->setIP( '1.2.3.4' );
919 $user = User
::newFromSession( $request );
921 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
922 $this->assertTrue( $user->isPingLimitable() );
924 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
925 $this->assertFalse( $user->isPingLimitable() );
927 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
928 $this->assertFalse( $user->isPingLimitable() );
930 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
931 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
932 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
933 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
934 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
935 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
938 public function provideExperienceLevel() {
940 [ 2, 2, 'newcomer' ],
941 [ 12, 3, 'newcomer' ],
942 [ 8, 5, 'newcomer' ],
943 [ 15, 10, 'learner' ],
944 [ 450, 20, 'learner' ],
945 [ 460, 33, 'learner' ],
946 [ 525, 28, 'learner' ],
947 [ 538, 33, 'experienced' ],
952 * @covers User::getExperienceLevel
953 * @dataProvider provideExperienceLevel
955 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
956 $this->setMwGlobals( [
957 'wgLearnerEdits' => 10,
958 'wgLearnerMemberSince' => 4,
959 'wgExperiencedUserEdits' => 500,
960 'wgExperiencedUserMemberSince' => 30,
963 $db = wfGetDB( DB_MASTER
);
964 $userQuery = User
::getQueryInfo();
965 $row = $db->selectRow(
966 $userQuery['tables'],
967 $userQuery['fields'],
968 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
973 $row->user_editcount
= $editCount;
974 $row->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
975 $user = User
::newFromRow( $row );
977 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
981 * @covers User::getExperienceLevel
983 public function testExperienceLevelAnon() {
984 $user = User
::newFromName( '10.11.12.13', false );
986 $this->assertFalse( $user->getExperienceLevel() );
989 public static function provideIsLocallyBlockedProxy() {
991 [ '1.2.3.4', '1.2.3.4' ],
992 [ '1.2.3.4', '1.2.3.0/16' ],
997 * @dataProvider provideIsLocallyBlockedProxy
998 * @covers User::isLocallyBlockedProxy
1000 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1001 $this->hideDeprecated( 'User::isLocallyBlockedProxy' );
1003 $this->setMwGlobals(
1006 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1008 $this->setMwGlobals(
1014 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1016 $this->setMwGlobals(
1019 'test' => $blockListEntry
1022 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1024 $this->hideDeprecated(
1025 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1026 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1028 $this->setMwGlobals(
1031 $blockListEntry => 'test'
1034 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1038 * @covers User::newFromActorId
1040 public function testActorId() {
1041 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1042 $this->hideDeprecated( 'User::selectFields' );
1044 // Newly-created user has an actor ID
1045 $user = User
::createNew( 'UserTestActorId1' );
1046 $id = $user->getId();
1047 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1049 $user = User
::newFromName( 'UserTestActorId2' );
1050 $user->addToDatabase();
1051 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1053 $user = User
::newFromName( 'UserTestActorId1' );
1054 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1056 $user = User
::newFromId( $id );
1057 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1059 $user2 = User
::newFromActorId( $user->getActorId() );
1060 $this->assertEquals( $user->getId(), $user2->getId(),
1061 'User::newFromActorId works for an existing user' );
1063 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1064 $user = User
::newFromRow( $row );
1065 $this->assertTrue( $user->getActorId() > 0,
1066 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1068 $user = User
::newFromId( $id );
1069 $user->setName( 'UserTestActorId4-renamed' );
1070 $user->saveSettings();
1071 $this->assertEquals(
1073 $this->db
->selectField(
1074 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1076 'User::saveSettings updates actor table for name change'
1080 $ip = '192.168.12.34';
1081 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1083 $user = User
::newFromName( $ip, false );
1084 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1085 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1086 'Actor ID can be created for an anonymous user' );
1088 $user = User
::newFromName( $ip, false );
1089 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1090 $user2 = User
::newFromActorId( $user->getActorId() );
1091 $this->assertEquals( $user->getName(), $user2->getName(),
1092 'User::newFromActorId works for an anonymous user' );
1096 * Actor tests with SCHEMA_COMPAT_READ_OLD
1098 * The only thing different from testActorId() is the behavior if the actor
1099 * row doesn't exist in the DB, since with SCHEMA_COMPAT_READ_NEW that
1100 * situation can't happen. But we copy all the other tests too just for good measure.
1102 * @covers User::newFromActorId
1104 public function testActorId_old() {
1105 $this->setMwGlobals( [
1106 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD
,
1108 $this->overrideMwServices();
1110 $domain = MediaWikiServices
::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1111 $this->hideDeprecated( 'User::selectFields' );
1113 // Newly-created user has an actor ID
1114 $user = User
::createNew( 'UserTestActorIdOld1' );
1115 $id = $user->getId();
1116 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1118 $user = User
::newFromName( 'UserTestActorIdOld2' );
1119 $user->addToDatabase();
1120 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1122 $user = User
::newFromName( 'UserTestActorIdOld1' );
1123 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1125 $user = User
::newFromId( $id );
1126 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1128 $user2 = User
::newFromActorId( $user->getActorId() );
1129 $this->assertEquals( $user->getId(), $user2->getId(),
1130 'User::newFromActorId works for an existing user' );
1132 $row = $this->db
->selectRow( 'user', User
::selectFields(), [ 'user_id' => $id ], __METHOD__
);
1133 $user = User
::newFromRow( $row );
1134 $this->assertTrue( $user->getActorId() > 0,
1135 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1137 $this->db
->delete( 'actor', [ 'actor_user' => $id ], __METHOD__
);
1138 User
::purge( $domain, $id );
1139 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1140 ObjectCache
::getMainWANInstance()->clearProcessCache();
1142 $user = User
::newFromId( $id );
1143 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1144 $this->assertTrue( $user->getActorId( $this->db
) > 0, 'Actor ID can be created if none in db' );
1146 $user->setName( 'UserTestActorIdOld4-renamed' );
1147 $user->saveSettings();
1148 $this->assertEquals(
1150 $this->db
->selectField(
1151 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1153 'User::saveSettings updates actor table for name change'
1157 $ip = '192.168.12.34';
1158 $this->db
->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__
);
1160 $user = User
::newFromName( $ip, false );
1161 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1162 $this->assertTrue( $user->getActorId( $this->db
) > 0,
1163 'Actor ID can be created for an anonymous user' );
1165 $user = User
::newFromName( $ip, false );
1166 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1167 $user2 = User
::newFromActorId( $user->getActorId() );
1168 $this->assertEquals( $user->getName(), $user2->getName(),
1169 'User::newFromActorId works for an anonymous user' );
1173 * @covers User::newFromAnyId
1175 public function testNewFromAnyId() {
1177 $user = $this->getTestUser()->getUser();
1178 for ( $i = 1; $i <= 7; $i++
) {
1179 $test = User
::newFromAnyId(
1180 ( $i & 1 ) ?
$user->getId() : null,
1181 ( $i & 2 ) ?
$user->getName() : null,
1182 ( $i & 4 ) ?
$user->getActorId() : null
1184 $this->assertSame( $user->getId(), $test->getId() );
1185 $this->assertSame( $user->getName(), $test->getName() );
1186 $this->assertSame( $user->getActorId(), $test->getActorId() );
1189 // Anon user. Can't load by only user ID when that's 0.
1190 $user = User
::newFromName( '192.168.12.34', false );
1191 $user->getActorId( $this->db
); // Make sure an actor ID exists
1193 $test = User
::newFromAnyId( null, '192.168.12.34', null );
1194 $this->assertSame( $user->getId(), $test->getId() );
1195 $this->assertSame( $user->getName(), $test->getName() );
1196 $this->assertSame( $user->getActorId(), $test->getActorId() );
1197 $test = User
::newFromAnyId( null, null, $user->getActorId() );
1198 $this->assertSame( $user->getId(), $test->getId() );
1199 $this->assertSame( $user->getName(), $test->getName() );
1200 $this->assertSame( $user->getActorId(), $test->getActorId() );
1202 // Bogus data should still "work" as long as nothing triggers a ->load(),
1203 // and accessing the specified data shouldn't do that.
1204 $test = User
::newFromAnyId( 123456, 'Bogus', 654321 );
1205 $this->assertSame( 123456, $test->getId() );
1206 $this->assertSame( 'Bogus', $test->getName() );
1207 $this->assertSame( 654321, $test->getActorId() );
1209 // Loading remote user by name from remote wiki should succeed
1210 $test = User
::newFromAnyId( null, 'Bogus', null, 'foo' );
1211 $this->assertSame( 0, $test->getId() );
1212 $this->assertSame( 'Bogus', $test->getName() );
1213 $this->assertSame( 0, $test->getActorId() );
1214 $test = User
::newFromAnyId( 123456, 'Bogus', 654321, 'foo' );
1215 $this->assertSame( 0, $test->getId() );
1216 $this->assertSame( 0, $test->getActorId() );
1218 // Exceptional cases
1220 User
::newFromAnyId( null, null, null );
1221 $this->fail( 'Expected exception not thrown' );
1222 } catch ( InvalidArgumentException
$ex ) {
1225 User
::newFromAnyId( 0, null, 0 );
1226 $this->fail( 'Expected exception not thrown' );
1227 } catch ( InvalidArgumentException
$ex ) {
1230 // Loading remote user by id from remote wiki should fail
1232 User
::newFromAnyId( 123456, null, 654321, 'foo' );
1233 $this->fail( 'Expected exception not thrown' );
1234 } catch ( InvalidArgumentException
$ex ) {
1239 * @covers User::newFromIdentity
1241 public function testNewFromIdentity() {
1243 $user = $this->getTestUser()->getUser();
1245 $this->assertSame( $user, User
::newFromIdentity( $user ) );
1248 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1249 $result = User
::newFromIdentity( $identity );
1250 $this->assertInstanceOf( User
::class, $result );
1251 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1252 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1253 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1256 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1257 $result = User
::newFromIdentity( $identity );
1258 $this->assertInstanceOf( User
::class, $result );
1259 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1260 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1261 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1264 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1265 $result = User
::newFromIdentity( $identity );
1266 $this->assertInstanceOf( User
::class, $result );
1267 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1268 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1269 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1273 * @covers User::getBlockedStatus
1274 * @covers User::getBlock
1275 * @covers User::blockedBy
1276 * @covers User::blockedFor
1277 * @covers User::isHidden
1278 * @covers User::isBlockedFrom
1280 public function testBlockInstanceCache() {
1281 // First, check the user isn't blocked
1282 $user = $this->getMutableTestUser()->getUser();
1283 $ut = Title
::makeTitle( NS_USER_TALK
, $user->getName() );
1284 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1285 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1286 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1287 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1288 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1291 $blocker = $this->getTestSysop()->getUser();
1292 $block = new Block( [
1294 'allowUsertalk' => false,
1295 'reason' => 'Because',
1297 $block->setTarget( $user );
1298 $block->setBlocker( $blocker );
1299 $res = $block->insert();
1300 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1302 // Clear cache and confirm it loaded the block properly
1303 $user->clearInstanceCache();
1304 $this->assertInstanceOf( Block
::class, $user->getBlock( false ) );
1305 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1306 $this->assertSame( 'Because', $user->blockedFor() );
1307 $this->assertTrue( (bool)$user->isHidden() );
1308 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1313 // Clear cache and confirm it loaded the not-blocked properly
1314 $user->clearInstanceCache();
1315 $this->assertNull( $user->getBlock( false ) );
1316 $this->assertSame( '', $user->blockedBy() );
1317 $this->assertSame( '', $user->blockedFor() );
1318 $this->assertFalse( (bool)$user->isHidden() );
1319 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1323 * @covers User::isBlockedFrom
1324 * @dataProvider provideIsBlockedFrom
1325 * @param string|null $title Title to test.
1326 * @param bool $expect Expected result from User::isBlockedFrom()
1327 * @param array $options Additional test options:
1328 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1329 * - 'allowUsertalk': (bool, default false) Passed to Block::__construct()
1330 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1332 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1333 $this->setMwGlobals( [
1334 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ??
true,
1337 $user = $this->getTestUser()->getUser();
1339 if ( $title === self
::USER_TALK_PAGE
) {
1340 $title = $user->getTalkPage();
1342 $title = Title
::newFromText( $title );
1346 foreach ( $options['pageRestrictions'] ??
[] as $pagestr ) {
1347 $page = $this->getExistingTestPage(
1348 $pagestr === self
::USER_TALK_PAGE ?
$user->getTalkPage() : $pagestr
1350 $restrictions[] = new PageRestriction( 0, $page->getId() );
1352 foreach ( $options['namespaceRestrictions'] ??
[] as $ns ) {
1353 $restrictions[] = new NamespaceRestriction( 0, $ns );
1356 $block = new Block( [
1357 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1358 'allowUsertalk' => $options['allowUsertalk'] ??
false,
1359 'sitewide' => !$restrictions,
1361 $block->setTarget( $user );
1362 $block->setBlocker( $this->getTestSysop()->getUser() );
1363 if ( $restrictions ) {
1364 $block->setRestrictions( $restrictions );
1369 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1375 public static function provideIsBlockedFrom() {
1377 'Sitewide block, basic operation' => [ 'Test page', true ],
1378 'Sitewide block, not allowing user talk' => [
1379 self
::USER_TALK_PAGE
, true, [
1380 'allowUsertalk' => false,
1383 'Sitewide block, allowing user talk' => [
1384 self
::USER_TALK_PAGE
, false, [
1385 'allowUsertalk' => true,
1388 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1389 self
::USER_TALK_PAGE
, true, [
1390 'allowUsertalk' => true,
1391 'blockAllowsUTEdit' => false,
1394 'Partial block, blocking the page' => [
1395 'Test page', true, [
1396 'pageRestrictions' => [ 'Test page' ],
1399 'Partial block, not blocking the page' => [
1400 'Test page 2', false, [
1401 'pageRestrictions' => [ 'Test page' ],
1404 'Partial block, not allowing user talk but user talk page is not blocked' => [
1405 self
::USER_TALK_PAGE
, false, [
1406 'allowUsertalk' => false,
1407 'pageRestrictions' => [ 'Test page' ],
1410 'Partial block, allowing user talk but user talk page is blocked' => [
1411 self
::USER_TALK_PAGE
, true, [
1412 'allowUsertalk' => true,
1413 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1416 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1417 self
::USER_TALK_PAGE
, false, [
1418 'allowUsertalk' => false,
1419 'pageRestrictions' => [ 'Test page' ],
1420 'blockAllowsUTEdit' => false,
1423 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1424 self
::USER_TALK_PAGE
, true, [
1425 'allowUsertalk' => true,
1426 'pageRestrictions' => [ self
::USER_TALK_PAGE
],
1427 'blockAllowsUTEdit' => false,
1430 'Partial user talk namespace block, not allowing user talk' => [
1431 self
::USER_TALK_PAGE
, true, [
1432 'allowUsertalk' => false,
1433 'namespaceRestrictions' => [ NS_USER_TALK
],
1436 'Partial user talk namespace block, allowing user talk' => [
1437 self
::USER_TALK_PAGE
, false, [
1438 'allowUsertalk' => true,
1439 'namespaceRestrictions' => [ NS_USER_TALK
],
1442 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1443 self
::USER_TALK_PAGE
, true, [
1444 'allowUsertalk' => true,
1445 'namespaceRestrictions' => [ NS_USER_TALK
],
1446 'blockAllowsUTEdit' => false,
1453 * Block cookie should be set for IP Blocks if
1454 * wgCookieSetOnIpBlock is set to true
1455 * @covers User::trackBlockWithCookie
1457 public function testIpBlockCookieSet() {
1458 $this->setMwGlobals( [
1459 'wgCookieSetOnIpBlock' => true,
1460 'wgCookiePrefix' => 'wiki',
1461 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1465 $block = new Block( [
1466 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1468 $block->setTarget( '1.2.3.4' );
1469 $block->setBlocker( $this->getTestSysop()->getUser() );
1473 $request = new FauxRequest();
1474 $request->setIP( '1.2.3.4' );
1477 $user = User
::newFromSession( $request );
1478 $user->trackBlockWithCookie();
1480 // test cookie was set
1481 $cookies = $request->response()->getCookies();
1482 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1489 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1491 * @covers User::trackBlockWithCookie
1493 public function testIpBlockCookieNotSet() {
1494 $this->setMwGlobals( [
1495 'wgCookieSetOnIpBlock' => false,
1496 'wgCookiePrefix' => 'wiki',
1497 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1501 $block = new Block( [
1502 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 5 * 60 * 60 ) ),
1504 $block->setTarget( '1.2.3.4' );
1505 $block->setBlocker( $this->getTestSysop()->getUser() );
1509 $request = new FauxRequest();
1510 $request->setIP( '1.2.3.4' );
1513 $user = User
::newFromSession( $request );
1514 $user->trackBlockWithCookie();
1516 // test cookie was not set
1517 $cookies = $request->response()->getCookies();
1518 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1525 * When an ip user is blocked and then they log in, cookie block
1526 * should be invalid and the cookie removed.
1527 * @covers User::trackBlockWithCookie
1529 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1530 $this->setMwGlobals( [
1531 'wgAutoblockExpiry' => 8000,
1532 'wgCookieSetOnIpBlock' => true,
1533 'wgCookiePrefix' => 'wiki',
1534 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
1538 $block = new Block( [
1539 'expiry' => wfTimestamp( TS_MW
, wfTimestamp() +
( 40 * 60 * 60 ) ),
1541 $block->setTarget( '1.2.3.4' );
1542 $block->setBlocker( $this->getTestSysop()->getUser() );
1546 $request = new FauxRequest();
1547 $request->setIP( '1.2.3.4' );
1548 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1549 $request->setCookie( 'BlockID', $block->getCookieValue() );
1552 $user = User
::newFromSession( $request );
1554 // logged in users should be inmune to cookie block of type ip/range
1555 $this->assertNull( $user->getBlock() );
1557 // cookie is being cleared
1558 $cookies = $request->response()->getCookies();
1559 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1566 * @covers User::getFirstEditTimestamp
1567 * @covers User::getLatestEditTimestamp
1569 public function testGetFirstLatestEditTimestamp() {
1570 $clock = MWTimestamp
::convert( TS_UNIX
, '20100101000000' );
1571 MWTimestamp
::setFakeTime( function () use ( &$clock ) {
1572 return $clock +
= 1000;
1575 $user = $this->getTestUser()->getUser();
1576 $firstRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'one', 'test' );
1577 $secondRevision = self
::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'two', 'test' );
1578 // Sanity check: revisions timestamp are different
1579 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1581 $this->assertEquals( $firstRevision->getTimestamp(), $user->getFirstEditTimestamp() );
1582 $this->assertEquals( $secondRevision->getTimestamp(), $user->getLatestEditTimestamp() );
1584 MWTimestamp
::setFakeTime( false );
1590 * @param string $title
1591 * @param string $content
1592 * @param string $comment
1593 * @return \MediaWiki\Revision\RevisionRecord|null
1595 private static function makeEdit( User
$user, $title, $content, $comment ) {
1596 $page = WikiPage
::factory( Title
::newFromText( $title ) );
1597 $content = ContentHandler
::makeContent( $content, $page->getTitle() );
1598 $updater = $page->newPageUpdater( $user );
1599 $updater->setContent( 'main', $content );
1600 return $updater->saveRevision( CommentStoreComment
::newUnsavedComment( $comment ) );
1604 * @covers User::idFromName
1606 public function testExistingIdFromName() {
1608 array_key_exists( $this->user
->getName(), User
::$idCacheByName ),
1609 'Test user should already be in the id cache.'
1612 $this->user
->getId(), User
::idFromName( $this->user
->getName() ),
1613 'Id is correctly retreived from the cache.'
1616 $this->user
->getId(), User
::idFromName( $this->user
->getName(), User
::READ_LATEST
),
1617 'Id is correctly retreived from the database.'
1622 * @covers User::idFromName
1624 public function testNonExistingIdFromName() {
1626 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1627 'Non exisitng user should not be in the id cache.'
1629 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );
1631 array_key_exists( 'NotExisitngUser', User
::$idCacheByName ),
1632 'Username will be cached when requested once.'
1634 $this->assertSame( null, User
::idFromName( 'NotExisitngUser' ) );