Move ResultWrapper subclasses to Rdbms
[mediawiki.git] / tests / phpunit / includes / user / UserTest.php
blobfea4a4480ad0a02da4d31006a6a1d060f021c084
1 <?php
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\MediaWikiServices;
8 /**
9 * @group Database
11 class UserTest extends MediaWikiTestCase {
12 /**
13 * @var User
15 protected $user;
17 protected function setUp() {
18 parent::setUp();
20 $this->setMwGlobals( [
21 'wgGroupPermissions' => [],
22 'wgRevokePermissions' => [],
23 ] );
25 $this->setUpPermissionGlobals();
27 $this->user = new User;
28 $this->user->addToDatabase();
29 $this->user->addGroup( 'unittesters' );
32 private function setUpPermissionGlobals() {
33 global $wgGroupPermissions, $wgRevokePermissions;
35 # Data for regular $wgGroupPermissions test
36 $wgGroupPermissions['unittesters'] = [
37 'test' => true,
38 'runtest' => true,
39 'writetest' => false,
40 'nukeworld' => false,
42 $wgGroupPermissions['testwriters'] = [
43 'test' => true,
44 'writetest' => true,
45 'modifytest' => true,
48 # Data for regular $wgRevokePermissions test
49 $wgRevokePermissions['formertesters'] = [
50 'runtest' => true,
53 # For the options test
54 $wgGroupPermissions['*'] = [
55 'editmyoptions' => true,
59 /**
60 * @covers User::getGroupPermissions
62 public function testGroupPermissions() {
63 $rights = User::getGroupPermissions( [ 'unittesters' ] );
64 $this->assertContains( 'runtest', $rights );
65 $this->assertNotContains( 'writetest', $rights );
66 $this->assertNotContains( 'modifytest', $rights );
67 $this->assertNotContains( 'nukeworld', $rights );
69 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
70 $this->assertContains( 'runtest', $rights );
71 $this->assertContains( 'writetest', $rights );
72 $this->assertContains( 'modifytest', $rights );
73 $this->assertNotContains( 'nukeworld', $rights );
76 /**
77 * @covers User::getGroupPermissions
79 public function testRevokePermissions() {
80 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
81 $this->assertNotContains( 'runtest', $rights );
82 $this->assertNotContains( 'writetest', $rights );
83 $this->assertNotContains( 'modifytest', $rights );
84 $this->assertNotContains( 'nukeworld', $rights );
87 /**
88 * @covers User::getRights
90 public function testUserPermissions() {
91 $rights = $this->user->getRights();
92 $this->assertContains( 'runtest', $rights );
93 $this->assertNotContains( 'writetest', $rights );
94 $this->assertNotContains( 'modifytest', $rights );
95 $this->assertNotContains( 'nukeworld', $rights );
98 /**
99 * @covers User::getRights
101 public function testUserGetRightsHooks() {
102 $user = new User;
103 $user->addToDatabase();
104 $user->addGroup( 'unittesters' );
105 $user->addGroup( 'testwriters' );
106 $userWrapper = TestingAccessWrapper::newFromObject( $user );
108 $rights = $user->getRights();
109 $this->assertContains( 'test', $rights, 'sanity check' );
110 $this->assertContains( 'runtest', $rights, 'sanity check' );
111 $this->assertContains( 'writetest', $rights, 'sanity check' );
112 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
114 // Add a hook manipluating the rights
115 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
116 $rights[] = 'nukeworld';
117 $rights = array_diff( $rights, [ 'writetest' ] );
118 } ] ] );
120 $userWrapper->mRights = null;
121 $rights = $user->getRights();
122 $this->assertContains( 'test', $rights );
123 $this->assertContains( 'runtest', $rights );
124 $this->assertNotContains( 'writetest', $rights );
125 $this->assertContains( 'nukeworld', $rights );
127 // Add a Session that limits rights
128 $mock = $this->getMockBuilder( stdclass::class )
129 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
130 ->getMock();
131 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
132 $mock->method( 'getSessionId' )->willReturn(
133 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
135 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
136 $mockRequest = $this->getMockBuilder( FauxRequest::class )
137 ->setMethods( [ 'getSession' ] )
138 ->getMock();
139 $mockRequest->method( 'getSession' )->willReturn( $session );
140 $userWrapper->mRequest = $mockRequest;
142 $userWrapper->mRights = null;
143 $rights = $user->getRights();
144 $this->assertContains( 'test', $rights );
145 $this->assertNotContains( 'runtest', $rights );
146 $this->assertNotContains( 'writetest', $rights );
147 $this->assertNotContains( 'nukeworld', $rights );
151 * @dataProvider provideGetGroupsWithPermission
152 * @covers User::getGroupsWithPermission
154 public function testGetGroupsWithPermission( $expected, $right ) {
155 $result = User::getGroupsWithPermission( $right );
156 sort( $result );
157 sort( $expected );
159 $this->assertEquals( $expected, $result, "Groups with permission $right" );
162 public static function provideGetGroupsWithPermission() {
163 return [
165 [ 'unittesters', 'testwriters' ],
166 'test'
169 [ 'unittesters' ],
170 'runtest'
173 [ 'testwriters' ],
174 'writetest'
177 [ 'testwriters' ],
178 'modifytest'
184 * @dataProvider provideIPs
185 * @covers User::isIP
187 public function testIsIP( $value, $result, $message ) {
188 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
191 public static function provideIPs() {
192 return [
193 [ '', false, 'Empty string' ],
194 [ ' ', false, 'Blank space' ],
195 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
196 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
197 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
198 [ '203.0.113.0', true, 'IPv4 example' ],
199 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
200 // Not valid IPs but classified as such by MediaWiki for negated asserting
201 // of whether this might be the identifier of a logged-out user or whether
202 // to allow usernames like it.
203 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
204 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
209 * @dataProvider provideUserNames
210 * @covers User::isValidUserName
212 public function testIsValidUserName( $username, $result, $message ) {
213 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
216 public static function provideUserNames() {
217 return [
218 [ '', false, 'Empty string' ],
219 [ ' ', false, 'Blank space' ],
220 [ 'abcd', false, 'Starts with small letter' ],
221 [ 'Ab/cd', false, 'Contains slash' ],
222 [ 'Ab cd', true, 'Whitespace' ],
223 [ '192.168.1.1', false, 'IP' ],
224 [ 'User:Abcd', false, 'Reserved Namespace' ],
225 [ '12abcd232', true, 'Starts with Numbers' ],
226 [ '?abcd', true, 'Start with ? mark' ],
227 [ '#abcd', false, 'Start with #' ],
228 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
229 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
230 [ 'Ab cd', false, ' Ideographic space' ],
231 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
232 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
233 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
238 * Test, if for all rights a right- message exist,
239 * which is used on Special:ListGroupRights as help text
240 * Extensions and core
242 public function testAllRightsWithMessage() {
243 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
244 $allRights = User::getAllRights();
245 $allMessageKeys = Language::getMessageKeysFor( 'en' );
247 $rightsWithMessage = [];
248 foreach ( $allMessageKeys as $message ) {
249 // === 0: must be at beginning of string (position 0)
250 if ( strpos( $message, 'right-' ) === 0 ) {
251 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
255 sort( $allRights );
256 sort( $rightsWithMessage );
258 $this->assertEquals(
259 $allRights,
260 $rightsWithMessage,
261 'Each user rights (core/extensions) has a corresponding right- message.'
266 * Test User::editCount
267 * @group medium
268 * @covers User::getEditCount
270 public function testGetEditCount() {
271 $user = $this->getMutableTestUser()->getUser();
273 // let the user have a few (3) edits
274 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
275 for ( $i = 0; $i < 3; $i++ ) {
276 $page->doEditContent(
277 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
278 'test',
280 false,
281 $user
285 $this->assertEquals(
287 $user->getEditCount(),
288 'After three edits, the user edit count should be 3'
291 // increase the edit count
292 $user->incEditCount();
294 $this->assertEquals(
296 $user->getEditCount(),
297 'After increasing the edit count manually, the user edit count should be 4'
302 * Test User::editCount
303 * @group medium
304 * @covers User::getEditCount
306 public function testGetEditCountForAnons() {
307 $user = User::newFromName( 'Anonymous' );
309 $this->assertNull(
310 $user->getEditCount(),
311 'Edit count starts null for anonymous users.'
314 $user->incEditCount();
316 $this->assertNull(
317 $user->getEditCount(),
318 'Edit count remains null for anonymous users despite calls to increase it.'
323 * Test User::editCount
324 * @group medium
325 * @covers User::incEditCount
327 public function testIncEditCount() {
328 $user = $this->getMutableTestUser()->getUser();
329 $user->incEditCount();
331 $reloadedUser = User::newFromId( $user->getId() );
332 $reloadedUser->incEditCount();
334 $this->assertEquals(
336 $reloadedUser->getEditCount(),
337 'Increasing the edit count after a fresh load leaves the object up to date.'
342 * Test changing user options.
343 * @covers User::setOption
344 * @covers User::getOption
346 public function testOptions() {
347 $user = $this->getMutableTestUser()->getUser();
349 $user->setOption( 'userjs-someoption', 'test' );
350 $user->setOption( 'rclimit', 200 );
351 $user->saveSettings();
353 $user = User::newFromName( $user->getName() );
354 $user->load( User::READ_LATEST );
355 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
356 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
358 $user = User::newFromName( $user->getName() );
359 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
360 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
361 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
365 * T39963
366 * Make sure defaults are loaded when setOption is called.
367 * @covers User::loadOptions
369 public function testAnonOptions() {
370 global $wgDefaultUserOptions;
371 $this->user->setOption( 'userjs-someoption', 'test' );
372 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
373 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
377 * Test password validity checks. There are 3 checks in core,
378 * - ensure the password meets the minimal length
379 * - ensure the password is not the same as the username
380 * - ensure the username/password combo isn't forbidden
381 * @covers User::checkPasswordValidity()
382 * @covers User::getPasswordValidity()
383 * @covers User::isValidPassword()
385 public function testCheckPasswordValidity() {
386 $this->setMwGlobals( [
387 'wgPasswordPolicy' => [
388 'policies' => [
389 'sysop' => [
390 'MinimalPasswordLength' => 8,
391 'MinimumPasswordLengthToLogin' => 1,
392 'PasswordCannotMatchUsername' => 1,
394 'default' => [
395 'MinimalPasswordLength' => 6,
396 'PasswordCannotMatchUsername' => true,
397 'PasswordCannotMatchBlacklist' => true,
398 'MaximalPasswordLength' => 40,
401 'checks' => [
402 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
403 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
404 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
405 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
406 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
409 ] );
411 $user = static::getTestUser()->getUser();
413 // Sanity
414 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
416 // Minimum length
417 $this->assertFalse( $user->isValidPassword( 'a' ) );
418 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
419 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
420 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
422 // Maximum length
423 $longPass = str_repeat( 'a', 41 );
424 $this->assertFalse( $user->isValidPassword( $longPass ) );
425 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
426 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
427 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
429 // Matches username
430 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
431 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
432 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
434 // On the forbidden list
435 $user = User::newFromName( 'Useruser' );
436 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
437 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
441 * @covers User::getCanonicalName()
442 * @dataProvider provideGetCanonicalName
444 public function testGetCanonicalName( $name, $expectedArray ) {
445 // fake interwiki map for the 'Interwiki prefix' testcase
446 $this->mergeMwGlobalArrayValue( 'wgHooks', [
447 'InterwikiLoadPrefix' => [
448 function ( $prefix, &$iwdata ) {
449 if ( $prefix === 'interwiki' ) {
450 $iwdata = [
451 'iw_url' => 'http://example.com/',
452 'iw_local' => 0,
453 'iw_trans' => 0,
455 return false;
459 ] );
461 foreach ( $expectedArray as $validate => $expected ) {
462 $this->assertEquals(
463 $expected,
464 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
468 public static function provideGetCanonicalName() {
469 return [
470 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
471 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
472 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
473 'valid' => false, 'false' => 'Talk:Username' ] ],
474 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
475 'valid' => false, 'false' => 'Interwiki:Username' ] ],
476 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
477 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
478 'usable' => 'Multi spaces' ] ],
479 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
480 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
481 'valid' => false, 'false' => 'In[]valid' ] ],
482 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
483 'false' => 'With / slash' ] ],
488 * @covers User::equals
490 public function testEquals() {
491 $first = $this->getMutableTestUser()->getUser();
492 $second = User::newFromName( $first->getName() );
494 $this->assertTrue( $first->equals( $first ) );
495 $this->assertTrue( $first->equals( $second ) );
496 $this->assertTrue( $second->equals( $first ) );
498 $third = $this->getMutableTestUser()->getUser();
499 $fourth = $this->getMutableTestUser()->getUser();
501 $this->assertFalse( $third->equals( $fourth ) );
502 $this->assertFalse( $fourth->equals( $third ) );
504 // Test users loaded from db with id
505 $user = $this->getMutableTestUser()->getUser();
506 $fifth = User::newFromId( $user->getId() );
507 $sixth = User::newFromName( $user->getName() );
508 $this->assertTrue( $fifth->equals( $sixth ) );
512 * @covers User::getId
514 public function testGetId() {
515 $user = static::getTestUser()->getUser();
516 $this->assertTrue( $user->getId() > 0 );
520 * @covers User::isLoggedIn
521 * @covers User::isAnon
523 public function testLoggedIn() {
524 $user = $this->getMutableTestUser()->getUser();
525 $this->assertTrue( $user->isLoggedIn() );
526 $this->assertFalse( $user->isAnon() );
528 // Non-existent users are perceived as anonymous
529 $user = User::newFromName( 'UTNonexistent' );
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
533 $user = new User;
534 $this->assertFalse( $user->isLoggedIn() );
535 $this->assertTrue( $user->isAnon() );
539 * @covers User::checkAndSetTouched
541 public function testCheckAndSetTouched() {
542 $user = $this->getMutableTestUser()->getUser();
543 $user = TestingAccessWrapper::newFromObject( $user );
544 $this->assertTrue( $user->isLoggedIn() );
546 $touched = $user->getDBTouched();
547 $this->assertTrue(
548 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
549 $this->assertGreaterThan(
550 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
552 $touched = $user->getDBTouched();
553 $this->assertTrue(
554 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
555 $this->assertGreaterThan(
556 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
560 * @covers User::findUsersByGroup
562 public function testFindUsersByGroup() {
563 $users = User::findUsersByGroup( [] );
564 $this->assertEquals( 0, iterator_count( $users ) );
566 $users = User::findUsersByGroup( 'foo' );
567 $this->assertEquals( 0, iterator_count( $users ) );
569 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
570 $users = User::findUsersByGroup( 'foo' );
571 $this->assertEquals( 1, iterator_count( $users ) );
572 $users->rewind();
573 $this->assertTrue( $user->equals( $users->current() ) );
575 // arguments have OR relationship
576 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
577 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
578 $this->assertEquals( 2, iterator_count( $users ) );
579 $users->rewind();
580 $this->assertTrue( $user->equals( $users->current() ) );
581 $users->next();
582 $this->assertTrue( $user2->equals( $users->current() ) );
584 // users are not duplicated
585 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
586 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
587 $this->assertEquals( 1, iterator_count( $users ) );
588 $users->rewind();
589 $this->assertTrue( $user->equals( $users->current() ) );
593 * When a user is autoblocked a cookie is set with which to track them
594 * in case they log out and change IP addresses.
595 * @link https://phabricator.wikimedia.org/T5233
597 public function testAutoblockCookies() {
598 // Set up the bits of global configuration that we use.
599 $this->setMwGlobals( [
600 'wgCookieSetOnAutoblock' => true,
601 'wgCookiePrefix' => 'wmsitetitle',
602 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
603 ] );
605 // 1. Log in a test user, and block them.
606 $user1tmp = $this->getTestUser()->getUser();
607 $request1 = new FauxRequest();
608 $request1->getSession()->setUser( $user1tmp );
609 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
610 $block = new Block( [
611 'enableAutoblock' => true,
612 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
613 ] );
614 $block->setTarget( $user1tmp );
615 $block->insert();
616 $user1 = User::newFromSession( $request1 );
617 $user1->mBlock = $block;
618 $user1->load();
620 // Confirm that the block has been applied as required.
621 $this->assertTrue( $user1->isLoggedIn() );
622 $this->assertTrue( $user1->isBlocked() );
623 $this->assertEquals( Block::TYPE_USER, $block->getType() );
624 $this->assertTrue( $block->isAutoblocking() );
625 $this->assertGreaterThanOrEqual( 1, $block->getId() );
627 // Test for the desired cookie name, value, and expiry.
628 $cookies = $request1->response()->getCookies();
629 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
630 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
631 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
632 $this->assertEquals( $block->getId(), $cookieValue );
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 );
638 $user2->load();
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->assertTrue( $user2->isBlocked() );
644 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
645 // Can't directly compare the objects becuase of member type differences.
646 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
647 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
648 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
650 // 3. Finally, set up a request as a new user, and the block should still be applied.
651 $user3tmp = $this->getTestUser()->getUser();
652 $request3 = new FauxRequest();
653 $request3->getSession()->setUser( $user3tmp );
654 $request3->setCookie( 'BlockID', $block->getId() );
655 $user3 = User::newFromSession( $request3 );
656 $user3->load();
657 $this->assertTrue( $user3->isLoggedIn() );
658 $this->assertTrue( $user3->isBlocked() );
659 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
661 // Clean up.
662 $block->delete();
666 * Make sure that no cookie is set to track autoblocked users
667 * when $wgCookieSetOnAutoblock is false.
669 public function testAutoblockCookiesDisabled() {
670 // Set up the bits of global configuration that we use.
671 $this->setMwGlobals( [
672 'wgCookieSetOnAutoblock' => false,
673 'wgCookiePrefix' => 'wm_no_cookies',
674 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
675 ] );
677 // 1. Log in a test user, and block them.
678 $testUser = $this->getTestUser()->getUser();
679 $request1 = new FauxRequest();
680 $request1->getSession()->setUser( $testUser );
681 $block = new Block( [ 'enableAutoblock' => true ] );
682 $block->setTarget( $testUser );
683 $block->insert();
684 $user = User::newFromSession( $request1 );
685 $user->mBlock = $block;
686 $user->load();
688 // 2. Test that the cookie IS NOT present.
689 $this->assertTrue( $user->isLoggedIn() );
690 $this->assertTrue( $user->isBlocked() );
691 $this->assertEquals( Block::TYPE_USER, $block->getType() );
692 $this->assertTrue( $block->isAutoblocking() );
693 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
694 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
695 $cookies = $request1->response()->getCookies();
696 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
698 // Clean up.
699 $block->delete();
703 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
704 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
705 * the cookie's should change with it.
707 public function testAutoblockCookieInfiniteExpiry() {
708 $this->setMwGlobals( [
709 'wgCookieSetOnAutoblock' => true,
710 'wgCookiePrefix' => 'wm_infinite_block',
711 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
712 ] );
713 // 1. Log in a test user, and block them indefinitely.
714 $user1Tmp = $this->getTestUser()->getUser();
715 $request1 = new FauxRequest();
716 $request1->getSession()->setUser( $user1Tmp );
717 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
718 $block->setTarget( $user1Tmp );
719 $block->insert();
720 $user1 = User::newFromSession( $request1 );
721 $user1->mBlock = $block;
722 $user1->load();
724 // 2. Test the cookie's expiry timestamp.
725 $this->assertTrue( $user1->isLoggedIn() );
726 $this->assertTrue( $user1->isBlocked() );
727 $this->assertEquals( Block::TYPE_USER, $block->getType() );
728 $this->assertTrue( $block->isAutoblocking() );
729 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
730 $cookies = $request1->response()->getCookies();
731 // Test the cookie's expiry to the nearest minute.
732 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
733 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
734 // Check for expiry dates in a 10-second window, to account for slow testing.
735 $this->assertEquals(
736 $expOneDay,
737 $cookies['wm_infinite_blockBlockID']['expire'],
738 'Expiry date',
742 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
743 $newExpiry = wfTimestamp() + 2 * 60 * 60;
744 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
745 $block->update();
746 $user2tmp = $this->getTestUser()->getUser();
747 $request2 = new FauxRequest();
748 $request2->getSession()->setUser( $user2tmp );
749 $user2 = User::newFromSession( $request2 );
750 $user2->mBlock = $block;
751 $user2->load();
752 $cookies = $request2->response()->getCookies();
753 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
754 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
756 // Clean up.
757 $block->delete();
760 public function testSoftBlockRanges() {
761 global $wgUser;
763 $this->setMwGlobals( [
764 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
765 'wgUser' => null,
766 ] );
768 // IP isn't in $wgSoftBlockRanges
769 $request = new FauxRequest();
770 $request->setIP( '192.168.0.1' );
771 $wgUser = User::newFromSession( $request );
772 $this->assertNull( $wgUser->getBlock() );
774 // IP is in $wgSoftBlockRanges
775 $request = new FauxRequest();
776 $request->setIP( '10.20.30.40' );
777 $wgUser = User::newFromSession( $request );
778 $block = $wgUser->getBlock();
779 $this->assertInstanceOf( Block::class, $block );
780 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
782 // Make sure the block is really soft
783 $request->getSession()->setUser( $this->getTestUser()->getUser() );
784 $wgUser = User::newFromSession( $request );
785 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
786 $this->assertNull( $wgUser->getBlock() );
790 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
792 public function testAutoblockCookieInauthentic() {
793 // Set up the bits of global configuration that we use.
794 $this->setMwGlobals( [
795 'wgCookieSetOnAutoblock' => true,
796 'wgCookiePrefix' => 'wmsitetitle',
797 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
798 ] );
800 // 1. Log in a blocked test user.
801 $user1tmp = $this->getTestUser()->getUser();
802 $request1 = new FauxRequest();
803 $request1->getSession()->setUser( $user1tmp );
804 $block = new Block( [ 'enableAutoblock' => true ] );
805 $block->setTarget( $user1tmp );
806 $block->insert();
807 $user1 = User::newFromSession( $request1 );
808 $user1->mBlock = $block;
809 $user1->load();
811 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
812 // user not blocked.
813 $request2 = new FauxRequest();
814 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
815 $user2 = User::newFromSession( $request2 );
816 $user2->load();
817 $this->assertTrue( $user2->isAnon() );
818 $this->assertFalse( $user2->isLoggedIn() );
819 $this->assertFalse( $user2->isBlocked() );
821 // Clean up.
822 $block->delete();
826 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
827 * This checks that a non-authenticated cookie still works.
829 public function testAutoblockCookieNoSecretKey() {
830 // Set up the bits of global configuration that we use.
831 $this->setMwGlobals( [
832 'wgCookieSetOnAutoblock' => true,
833 'wgCookiePrefix' => 'wmsitetitle',
834 'wgSecretKey' => null,
835 ] );
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->setTarget( $user1tmp );
843 $block->insert();
844 $user1 = User::newFromSession( $request1 );
845 $user1->mBlock = $block;
846 $user1->load();
847 $this->assertTrue( $user1->isBlocked() );
849 // 2. Create a new request, set the cookie to just the block ID, and the user should
850 // still get blocked when they log in again.
851 $request2 = new FauxRequest();
852 $request2->setCookie( 'BlockID', $block->getId() );
853 $user2 = User::newFromSession( $request2 );
854 $user2->load();
855 $this->assertNotEquals( $user1->getId(), $user2->getId() );
856 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
857 $this->assertTrue( $user2->isAnon() );
858 $this->assertFalse( $user2->isLoggedIn() );
859 $this->assertTrue( $user2->isBlocked() );
860 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
862 // Clean up.
863 $block->delete();
866 public function testIsPingLimitable() {
867 $request = new FauxRequest();
868 $request->setIP( '1.2.3.4' );
869 $user = User::newFromSession( $request );
871 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
872 $this->assertTrue( $user->isPingLimitable() );
874 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
875 $this->assertFalse( $user->isPingLimitable() );
877 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
878 $this->assertFalse( $user->isPingLimitable() );
880 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
881 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
882 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
883 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
884 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
885 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
888 public function provideExperienceLevel() {
889 return [
890 [ 2, 2, 'newcomer' ],
891 [ 12, 3, 'newcomer' ],
892 [ 8, 5, 'newcomer' ],
893 [ 15, 10, 'learner' ],
894 [ 450, 20, 'learner' ],
895 [ 460, 33, 'learner' ],
896 [ 525, 28, 'learner' ],
897 [ 538, 33, 'experienced' ],
902 * @dataProvider provideExperienceLevel
904 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
905 $this->setMwGlobals( [
906 'wgLearnerEdits' => 10,
907 'wgLearnerMemberSince' => 4,
908 'wgExperiencedUserEdits' => 500,
909 'wgExperiencedUserMemberSince' => 30,
910 ] );
912 $db = wfGetDB( DB_MASTER );
914 $data = new stdClass();
915 $data->user_id = 1;
916 $data->user_name = 'name';
917 $data->user_real_name = 'Real Name';
918 $data->user_touched = 1;
919 $data->user_token = 'token';
920 $data->user_email = 'a@a.a';
921 $data->user_email_authenticated = null;
922 $data->user_email_token = 'token';
923 $data->user_email_token_expires = null;
924 $data->user_editcount = $editCount;
925 $data->user_registration = $db->timestamp( time() - $memberSince * 86400 );
926 $user = User::newFromRow( $data );
928 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
931 public function testExperienceLevelAnon() {
932 $user = User::newFromName( '10.11.12.13', false );
934 $this->assertFalse( $user->getExperienceLevel() );