Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / tests / phpunit / includes / user / UserTest.php
blobfe56d27c93083f120c634f6677bf093ad4960525
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->addGroup( 'unittesters' );
31 private function setUpPermissionGlobals() {
32 global $wgGroupPermissions, $wgRevokePermissions;
34 # Data for regular $wgGroupPermissions test
35 $wgGroupPermissions['unittesters'] = [
36 'test' => true,
37 'runtest' => true,
38 'writetest' => false,
39 'nukeworld' => false,
41 $wgGroupPermissions['testwriters'] = [
42 'test' => true,
43 'writetest' => true,
44 'modifytest' => true,
47 # Data for regular $wgRevokePermissions test
48 $wgRevokePermissions['formertesters'] = [
49 'runtest' => true,
52 # For the options test
53 $wgGroupPermissions['*'] = [
54 'editmyoptions' => true,
58 /**
59 * @covers User::getGroupPermissions
61 public function testGroupPermissions() {
62 $rights = User::getGroupPermissions( [ 'unittesters' ] );
63 $this->assertContains( 'runtest', $rights );
64 $this->assertNotContains( 'writetest', $rights );
65 $this->assertNotContains( 'modifytest', $rights );
66 $this->assertNotContains( 'nukeworld', $rights );
68 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
69 $this->assertContains( 'runtest', $rights );
70 $this->assertContains( 'writetest', $rights );
71 $this->assertContains( 'modifytest', $rights );
72 $this->assertNotContains( 'nukeworld', $rights );
75 /**
76 * @covers User::getGroupPermissions
78 public function testRevokePermissions() {
79 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
80 $this->assertNotContains( 'runtest', $rights );
81 $this->assertNotContains( 'writetest', $rights );
82 $this->assertNotContains( 'modifytest', $rights );
83 $this->assertNotContains( 'nukeworld', $rights );
86 /**
87 * @covers User::getRights
89 public function testUserPermissions() {
90 $rights = $this->user->getRights();
91 $this->assertContains( 'runtest', $rights );
92 $this->assertNotContains( 'writetest', $rights );
93 $this->assertNotContains( 'modifytest', $rights );
94 $this->assertNotContains( 'nukeworld', $rights );
97 /**
98 * @covers User::getRights
100 public function testUserGetRightsHooks() {
101 $user = new User;
102 $user->addGroup( 'unittesters' );
103 $user->addGroup( 'testwriters' );
104 $userWrapper = TestingAccessWrapper::newFromObject( $user );
106 $rights = $user->getRights();
107 $this->assertContains( 'test', $rights, 'sanity check' );
108 $this->assertContains( 'runtest', $rights, 'sanity check' );
109 $this->assertContains( 'writetest', $rights, 'sanity check' );
110 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
112 // Add a hook manipluating the rights
113 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
114 $rights[] = 'nukeworld';
115 $rights = array_diff( $rights, [ 'writetest' ] );
116 } ] ] );
118 $userWrapper->mRights = null;
119 $rights = $user->getRights();
120 $this->assertContains( 'test', $rights );
121 $this->assertContains( 'runtest', $rights );
122 $this->assertNotContains( 'writetest', $rights );
123 $this->assertContains( 'nukeworld', $rights );
125 // Add a Session that limits rights
126 $mock = $this->getMockBuilder( stdclass::class )
127 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
128 ->getMock();
129 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
130 $mock->method( 'getSessionId' )->willReturn(
131 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
133 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
134 $mockRequest = $this->getMockBuilder( FauxRequest::class )
135 ->setMethods( [ 'getSession' ] )
136 ->getMock();
137 $mockRequest->method( 'getSession' )->willReturn( $session );
138 $userWrapper->mRequest = $mockRequest;
140 $userWrapper->mRights = null;
141 $rights = $user->getRights();
142 $this->assertContains( 'test', $rights );
143 $this->assertNotContains( 'runtest', $rights );
144 $this->assertNotContains( 'writetest', $rights );
145 $this->assertNotContains( 'nukeworld', $rights );
149 * @dataProvider provideGetGroupsWithPermission
150 * @covers User::getGroupsWithPermission
152 public function testGetGroupsWithPermission( $expected, $right ) {
153 $result = User::getGroupsWithPermission( $right );
154 sort( $result );
155 sort( $expected );
157 $this->assertEquals( $expected, $result, "Groups with permission $right" );
160 public static function provideGetGroupsWithPermission() {
161 return [
163 [ 'unittesters', 'testwriters' ],
164 'test'
167 [ 'unittesters' ],
168 'runtest'
171 [ 'testwriters' ],
172 'writetest'
175 [ 'testwriters' ],
176 'modifytest'
182 * @dataProvider provideIPs
183 * @covers User::isIP
185 public function testIsIP( $value, $result, $message ) {
186 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
189 public static function provideIPs() {
190 return [
191 [ '', false, 'Empty string' ],
192 [ ' ', false, 'Blank space' ],
193 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
194 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
195 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
196 [ '203.0.113.0', true, 'IPv4 example' ],
197 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
198 // Not valid IPs but classified as such by MediaWiki for negated asserting
199 // of whether this might be the identifier of a logged-out user or whether
200 // to allow usernames like it.
201 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
202 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
207 * @dataProvider provideUserNames
208 * @covers User::isValidUserName
210 public function testIsValidUserName( $username, $result, $message ) {
211 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
214 public static function provideUserNames() {
215 return [
216 [ '', false, 'Empty string' ],
217 [ ' ', false, 'Blank space' ],
218 [ 'abcd', false, 'Starts with small letter' ],
219 [ 'Ab/cd', false, 'Contains slash' ],
220 [ 'Ab cd', true, 'Whitespace' ],
221 [ '192.168.1.1', false, 'IP' ],
222 [ 'User:Abcd', false, 'Reserved Namespace' ],
223 [ '12abcd232', true, 'Starts with Numbers' ],
224 [ '?abcd', true, 'Start with ? mark' ],
225 [ '#abcd', false, 'Start with #' ],
226 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
227 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
228 [ 'Ab cd', false, ' Ideographic space' ],
229 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
230 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
231 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
236 * Test, if for all rights a right- message exist,
237 * which is used on Special:ListGroupRights as help text
238 * Extensions and core
240 public function testAllRightsWithMessage() {
241 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
242 $allRights = User::getAllRights();
243 $allMessageKeys = Language::getMessageKeysFor( 'en' );
245 $rightsWithMessage = [];
246 foreach ( $allMessageKeys as $message ) {
247 // === 0: must be at beginning of string (position 0)
248 if ( strpos( $message, 'right-' ) === 0 ) {
249 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
253 sort( $allRights );
254 sort( $rightsWithMessage );
256 $this->assertEquals(
257 $allRights,
258 $rightsWithMessage,
259 'Each user rights (core/extensions) has a corresponding right- message.'
264 * Test User::editCount
265 * @group medium
266 * @covers User::getEditCount
268 public function testGetEditCount() {
269 $user = $this->getMutableTestUser()->getUser();
271 // let the user have a few (3) edits
272 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
273 for ( $i = 0; $i < 3; $i++ ) {
274 $page->doEditContent(
275 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
276 'test',
278 false,
279 $user
283 $this->assertEquals(
285 $user->getEditCount(),
286 'After three edits, the user edit count should be 3'
289 // increase the edit count
290 $user->incEditCount();
292 $this->assertEquals(
294 $user->getEditCount(),
295 'After increasing the edit count manually, the user edit count should be 4'
300 * Test User::editCount
301 * @group medium
302 * @covers User::getEditCount
304 public function testGetEditCountForAnons() {
305 $user = User::newFromName( 'Anonymous' );
307 $this->assertNull(
308 $user->getEditCount(),
309 'Edit count starts null for anonymous users.'
312 $user->incEditCount();
314 $this->assertNull(
315 $user->getEditCount(),
316 'Edit count remains null for anonymous users despite calls to increase it.'
321 * Test User::editCount
322 * @group medium
323 * @covers User::incEditCount
325 public function testIncEditCount() {
326 $user = $this->getMutableTestUser()->getUser();
327 $user->incEditCount();
329 $reloadedUser = User::newFromId( $user->getId() );
330 $reloadedUser->incEditCount();
332 $this->assertEquals(
334 $reloadedUser->getEditCount(),
335 'Increasing the edit count after a fresh load leaves the object up to date.'
340 * Test changing user options.
341 * @covers User::setOption
342 * @covers User::getOption
344 public function testOptions() {
345 $user = $this->getMutableTestUser()->getUser();
347 $user->setOption( 'userjs-someoption', 'test' );
348 $user->setOption( 'rclimit', 200 );
349 $user->saveSettings();
351 $user = User::newFromName( $user->getName() );
352 $user->load( User::READ_LATEST );
353 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
354 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
356 $user = User::newFromName( $user->getName() );
357 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
358 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
359 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
363 * Bug 37963
364 * Make sure defaults are loaded when setOption is called.
365 * @covers User::loadOptions
367 public function testAnonOptions() {
368 global $wgDefaultUserOptions;
369 $this->user->setOption( 'userjs-someoption', 'test' );
370 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
371 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
375 * Test password validity checks. There are 3 checks in core,
376 * - ensure the password meets the minimal length
377 * - ensure the password is not the same as the username
378 * - ensure the username/password combo isn't forbidden
379 * @covers User::checkPasswordValidity()
380 * @covers User::getPasswordValidity()
381 * @covers User::isValidPassword()
383 public function testCheckPasswordValidity() {
384 $this->setMwGlobals( [
385 'wgPasswordPolicy' => [
386 'policies' => [
387 'sysop' => [
388 'MinimalPasswordLength' => 8,
389 'MinimumPasswordLengthToLogin' => 1,
390 'PasswordCannotMatchUsername' => 1,
392 'default' => [
393 'MinimalPasswordLength' => 6,
394 'PasswordCannotMatchUsername' => true,
395 'PasswordCannotMatchBlacklist' => true,
396 'MaximalPasswordLength' => 40,
399 'checks' => [
400 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
401 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
402 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
403 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
404 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
407 ] );
409 $user = static::getTestUser()->getUser();
411 // Sanity
412 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
414 // Minimum length
415 $this->assertFalse( $user->isValidPassword( 'a' ) );
416 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
417 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
418 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
420 // Maximum length
421 $longPass = str_repeat( 'a', 41 );
422 $this->assertFalse( $user->isValidPassword( $longPass ) );
423 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
424 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
425 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
427 // Matches username
428 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
429 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
430 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
432 // On the forbidden list
433 $user = User::newFromName( 'Useruser' );
434 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
435 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
439 * @covers User::getCanonicalName()
440 * @dataProvider provideGetCanonicalName
442 public function testGetCanonicalName( $name, $expectedArray ) {
443 // fake interwiki map for the 'Interwiki prefix' testcase
444 $this->mergeMwGlobalArrayValue( 'wgHooks', [
445 'InterwikiLoadPrefix' => [
446 function ( $prefix, &$iwdata ) {
447 if ( $prefix === 'interwiki' ) {
448 $iwdata = [
449 'iw_url' => 'http://example.com/',
450 'iw_local' => 0,
451 'iw_trans' => 0,
453 return false;
457 ] );
459 foreach ( $expectedArray as $validate => $expected ) {
460 $this->assertEquals(
461 $expected,
462 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
466 public static function provideGetCanonicalName() {
467 return [
468 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
469 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
470 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
471 'valid' => false, 'false' => 'Talk:Username' ] ],
472 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
473 'valid' => false, 'false' => 'Interwiki:Username' ] ],
474 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
475 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
476 'usable' => 'Multi spaces' ] ],
477 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
478 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
479 'valid' => false, 'false' => 'In[]valid' ] ],
480 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
481 'false' => 'With / slash' ] ],
486 * @covers User::equals
488 public function testEquals() {
489 $first = $this->getMutableTestUser()->getUser();
490 $second = User::newFromName( $first->getName() );
492 $this->assertTrue( $first->equals( $first ) );
493 $this->assertTrue( $first->equals( $second ) );
494 $this->assertTrue( $second->equals( $first ) );
496 $third = $this->getMutableTestUser()->getUser();
497 $fourth = $this->getMutableTestUser()->getUser();
499 $this->assertFalse( $third->equals( $fourth ) );
500 $this->assertFalse( $fourth->equals( $third ) );
502 // Test users loaded from db with id
503 $user = $this->getMutableTestUser()->getUser();
504 $fifth = User::newFromId( $user->getId() );
505 $sixth = User::newFromName( $user->getName() );
506 $this->assertTrue( $fifth->equals( $sixth ) );
510 * @covers User::getId
512 public function testGetId() {
513 $user = static::getTestUser()->getUser();
514 $this->assertTrue( $user->getId() > 0 );
518 * @covers User::isLoggedIn
519 * @covers User::isAnon
521 public function testLoggedIn() {
522 $user = $this->getMutableTestUser()->getUser();
523 $this->assertTrue( $user->isLoggedIn() );
524 $this->assertFalse( $user->isAnon() );
526 // Non-existent users are perceived as anonymous
527 $user = User::newFromName( 'UTNonexistent' );
528 $this->assertFalse( $user->isLoggedIn() );
529 $this->assertTrue( $user->isAnon() );
531 $user = new User;
532 $this->assertFalse( $user->isLoggedIn() );
533 $this->assertTrue( $user->isAnon() );
537 * @covers User::checkAndSetTouched
539 public function testCheckAndSetTouched() {
540 $user = $this->getMutableTestUser()->getUser();
541 $user = TestingAccessWrapper::newFromObject( $user );
542 $this->assertTrue( $user->isLoggedIn() );
544 $touched = $user->getDBTouched();
545 $this->assertTrue(
546 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
547 $this->assertGreaterThan(
548 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
550 $touched = $user->getDBTouched();
551 $this->assertTrue(
552 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
553 $this->assertGreaterThan(
554 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
558 * @covers User::findUsersByGroup
560 public function testFindUsersByGroup() {
561 $users = User::findUsersByGroup( [] );
562 $this->assertEquals( 0, iterator_count( $users ) );
564 $users = User::findUsersByGroup( 'foo' );
565 $this->assertEquals( 0, iterator_count( $users ) );
567 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
568 $users = User::findUsersByGroup( 'foo' );
569 $this->assertEquals( 1, iterator_count( $users ) );
570 $users->rewind();
571 $this->assertTrue( $user->equals( $users->current() ) );
573 // arguments have OR relationship
574 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
575 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
576 $this->assertEquals( 2, iterator_count( $users ) );
577 $users->rewind();
578 $this->assertTrue( $user->equals( $users->current() ) );
579 $users->next();
580 $this->assertTrue( $user2->equals( $users->current() ) );
582 // users are not duplicated
583 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
584 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
585 $this->assertEquals( 1, iterator_count( $users ) );
586 $users->rewind();
587 $this->assertTrue( $user->equals( $users->current() ) );
591 * When a user is autoblocked a cookie is set with which to track them
592 * in case they log out and change IP addresses.
593 * @link https://phabricator.wikimedia.org/T5233
595 public function testAutoblockCookies() {
596 // Set up the bits of global configuration that we use.
597 $this->setMwGlobals( [
598 'wgCookieSetOnAutoblock' => true,
599 'wgCookiePrefix' => 'wmsitetitle',
600 ] );
602 // 1. Log in a test user, and block them.
603 $user1tmp = $this->getTestUser()->getUser();
604 $request1 = new FauxRequest();
605 $request1->getSession()->setUser( $user1tmp );
606 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
607 $block = new Block( [
608 'enableAutoblock' => true,
609 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
610 ] );
611 $block->setTarget( $user1tmp );
612 $block->insert();
613 $user1 = User::newFromSession( $request1 );
614 $user1->mBlock = $block;
615 $user1->load();
617 // Confirm that the block has been applied as required.
618 $this->assertTrue( $user1->isLoggedIn() );
619 $this->assertTrue( $user1->isBlocked() );
620 $this->assertEquals( Block::TYPE_USER, $block->getType() );
621 $this->assertTrue( $block->isAutoblocking() );
622 $this->assertGreaterThanOrEqual( 1, $block->getId() );
624 // Test for the desired cookie name, value, and expiry.
625 $cookies = $request1->response()->getCookies();
626 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
627 $this->assertEquals( $block->getId(), $cookies['wmsitetitleBlockID']['value'] );
628 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
630 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
631 $request2 = new FauxRequest();
632 $request2->setCookie( 'BlockID', $block->getId() );
633 $user2 = User::newFromSession( $request2 );
634 $user2->load();
635 $this->assertNotEquals( $user1->getId(), $user2->getId() );
636 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
637 $this->assertTrue( $user2->isAnon() );
638 $this->assertFalse( $user2->isLoggedIn() );
639 $this->assertTrue( $user2->isBlocked() );
640 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
641 // Can't directly compare the objects becuase of member type differences.
642 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
643 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
644 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
646 // 3. Finally, set up a request as a new user, and the block should still be applied.
647 $user3tmp = $this->getTestUser()->getUser();
648 $request3 = new FauxRequest();
649 $request3->getSession()->setUser( $user3tmp );
650 $request3->setCookie( 'BlockID', $block->getId() );
651 $user3 = User::newFromSession( $request3 );
652 $user3->load();
653 $this->assertTrue( $user3->isLoggedIn() );
654 $this->assertTrue( $user3->isBlocked() );
655 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
657 // Clean up.
658 $block->delete();
662 * Make sure that no cookie is set to track autoblocked users
663 * when $wgCookieSetOnAutoblock is false.
665 public function testAutoblockCookiesDisabled() {
666 // Set up the bits of global configuration that we use.
667 $this->setMwGlobals( [
668 'wgCookieSetOnAutoblock' => false,
669 'wgCookiePrefix' => 'wm_no_cookies',
670 ] );
672 // 1. Log in a test user, and block them.
673 $testUser = $this->getTestUser()->getUser();
674 $request1 = new FauxRequest();
675 $request1->getSession()->setUser( $testUser );
676 $block = new Block( [ 'enableAutoblock' => true ] );
677 $block->setTarget( $testUser );
678 $block->insert();
679 $user = User::newFromSession( $request1 );
680 $user->mBlock = $block;
681 $user->load();
683 // 2. Test that the cookie IS NOT present.
684 $this->assertTrue( $user->isLoggedIn() );
685 $this->assertTrue( $user->isBlocked() );
686 $this->assertEquals( Block::TYPE_USER, $block->getType() );
687 $this->assertTrue( $block->isAutoblocking() );
688 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
689 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
690 $cookies = $request1->response()->getCookies();
691 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
693 // Clean up.
694 $block->delete();
698 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
699 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
700 * the cookie's should change with it.
702 public function testAutoblockCookieInfiniteExpiry() {
703 $this->setMwGlobals( [
704 'wgCookieSetOnAutoblock' => true,
705 'wgCookiePrefix' => 'wm_infinite_block',
706 ] );
707 // 1. Log in a test user, and block them indefinitely.
708 $user1Tmp = $this->getTestUser()->getUser();
709 $request1 = new FauxRequest();
710 $request1->getSession()->setUser( $user1Tmp );
711 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
712 $block->setTarget( $user1Tmp );
713 $block->insert();
714 $user1 = User::newFromSession( $request1 );
715 $user1->mBlock = $block;
716 $user1->load();
718 // 2. Test the cookie's expiry timestamp.
719 $this->assertTrue( $user1->isLoggedIn() );
720 $this->assertTrue( $user1->isBlocked() );
721 $this->assertEquals( Block::TYPE_USER, $block->getType() );
722 $this->assertTrue( $block->isAutoblocking() );
723 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
724 $cookies = $request1->response()->getCookies();
725 // Test the cookie's expiry to the nearest minute.
726 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
727 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
728 // Check for expiry dates in a 10-second window, to account for slow testing.
729 $this->assertEquals(
730 $expOneDay,
731 $cookies['wm_infinite_blockBlockID']['expire'],
732 'Expiry date',
736 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
737 $newExpiry = wfTimestamp() + 2 * 60 * 60;
738 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
739 $block->update();
740 $user2tmp = $this->getTestUser()->getUser();
741 $request2 = new FauxRequest();
742 $request2->getSession()->setUser( $user2tmp );
743 $user2 = User::newFromSession( $request2 );
744 $user2->mBlock = $block;
745 $user2->load();
746 $cookies = $request2->response()->getCookies();
747 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
748 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
750 // Clean up.
751 $block->delete();
754 public function testSoftBlockRanges() {
755 global $wgUser;
757 $this->setMwGlobals( [
758 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
759 'wgUser' => null,
760 ] );
762 // IP isn't in $wgSoftBlockRanges
763 $request = new FauxRequest();
764 $request->setIP( '192.168.0.1' );
765 $wgUser = User::newFromSession( $request );
766 $this->assertNull( $wgUser->getBlock() );
768 // IP is in $wgSoftBlockRanges
769 $request = new FauxRequest();
770 $request->setIP( '10.20.30.40' );
771 $wgUser = User::newFromSession( $request );
772 $block = $wgUser->getBlock();
773 $this->assertInstanceOf( Block::class, $block );
774 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
776 // Make sure the block is really soft
777 $request->getSession()->setUser( $this->getTestUser()->getUser() );
778 $wgUser = User::newFromSession( $request );
779 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
780 $this->assertNull( $wgUser->getBlock() );