Merge "Ensure whether user can rollback page in ChangesList"
[lhc/web/wiklou.git] / tests / phpunit / includes / user / UserTest.php
1 <?php
2
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
5
6 use MediaWiki\MediaWikiServices;
7 use MediaWiki\User\UserIdentityValue;
8 use Wikimedia\TestingAccessWrapper;
9
10 /**
11 * @group Database
12 */
13 class UserTest extends MediaWikiTestCase {
14 /**
15 * @var User
16 */
17 protected $user;
18
19 protected function setUp() {
20 parent::setUp();
21
22 $this->setMwGlobals( [
23 'wgGroupPermissions' => [],
24 'wgRevokePermissions' => [],
25 'wgActorTableSchemaMigrationStage' => MIGRATION_WRITE_BOTH,
26 ] );
27 $this->overrideMwServices();
28
29 $this->setUpPermissionGlobals();
30
31 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
32 }
33
34 private function setUpPermissionGlobals() {
35 global $wgGroupPermissions, $wgRevokePermissions;
36
37 # Data for regular $wgGroupPermissions test
38 $wgGroupPermissions['unittesters'] = [
39 'test' => true,
40 'runtest' => true,
41 'writetest' => false,
42 'nukeworld' => false,
43 ];
44 $wgGroupPermissions['testwriters'] = [
45 'test' => true,
46 'writetest' => true,
47 'modifytest' => true,
48 ];
49
50 # Data for regular $wgRevokePermissions test
51 $wgRevokePermissions['formertesters'] = [
52 'runtest' => true,
53 ];
54
55 # For the options test
56 $wgGroupPermissions['*'] = [
57 'editmyoptions' => true,
58 ];
59 }
60
61 /**
62 * @covers User::getGroupPermissions
63 */
64 public function testGroupPermissions() {
65 $rights = User::getGroupPermissions( [ 'unittesters' ] );
66 $this->assertContains( 'runtest', $rights );
67 $this->assertNotContains( 'writetest', $rights );
68 $this->assertNotContains( 'modifytest', $rights );
69 $this->assertNotContains( 'nukeworld', $rights );
70
71 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
72 $this->assertContains( 'runtest', $rights );
73 $this->assertContains( 'writetest', $rights );
74 $this->assertContains( 'modifytest', $rights );
75 $this->assertNotContains( 'nukeworld', $rights );
76 }
77
78 /**
79 * @covers User::getGroupPermissions
80 */
81 public function testRevokePermissions() {
82 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
83 $this->assertNotContains( 'runtest', $rights );
84 $this->assertNotContains( 'writetest', $rights );
85 $this->assertNotContains( 'modifytest', $rights );
86 $this->assertNotContains( 'nukeworld', $rights );
87 }
88
89 /**
90 * @covers User::getRights
91 */
92 public function testUserPermissions() {
93 $rights = $this->user->getRights();
94 $this->assertContains( 'runtest', $rights );
95 $this->assertNotContains( 'writetest', $rights );
96 $this->assertNotContains( 'modifytest', $rights );
97 $this->assertNotContains( 'nukeworld', $rights );
98 }
99
100 /**
101 * @covers User::getRights
102 */
103 public function testUserGetRightsHooks() {
104 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
105 $userWrapper = TestingAccessWrapper::newFromObject( $user );
106
107 $rights = $user->getRights();
108 $this->assertContains( 'test', $rights, 'sanity check' );
109 $this->assertContains( 'runtest', $rights, 'sanity check' );
110 $this->assertContains( 'writetest', $rights, 'sanity check' );
111 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
112
113 // Add a hook manipluating the rights
114 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
115 $rights[] = 'nukeworld';
116 $rights = array_diff( $rights, [ 'writetest' ] );
117 } ] ] );
118
119 $userWrapper->mRights = null;
120 $rights = $user->getRights();
121 $this->assertContains( 'test', $rights );
122 $this->assertContains( 'runtest', $rights );
123 $this->assertNotContains( 'writetest', $rights );
124 $this->assertContains( 'nukeworld', $rights );
125
126 // Add a Session that limits rights
127 $mock = $this->getMockBuilder( stdClass::class )
128 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
129 ->getMock();
130 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
131 $mock->method( 'getSessionId' )->willReturn(
132 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
133 );
134 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
135 $mockRequest = $this->getMockBuilder( FauxRequest::class )
136 ->setMethods( [ 'getSession' ] )
137 ->getMock();
138 $mockRequest->method( 'getSession' )->willReturn( $session );
139 $userWrapper->mRequest = $mockRequest;
140
141 $userWrapper->mRights = null;
142 $rights = $user->getRights();
143 $this->assertContains( 'test', $rights );
144 $this->assertNotContains( 'runtest', $rights );
145 $this->assertNotContains( 'writetest', $rights );
146 $this->assertNotContains( 'nukeworld', $rights );
147 }
148
149 /**
150 * @dataProvider provideGetGroupsWithPermission
151 * @covers User::getGroupsWithPermission
152 */
153 public function testGetGroupsWithPermission( $expected, $right ) {
154 $result = User::getGroupsWithPermission( $right );
155 sort( $result );
156 sort( $expected );
157
158 $this->assertEquals( $expected, $result, "Groups with permission $right" );
159 }
160
161 public static function provideGetGroupsWithPermission() {
162 return [
163 [
164 [ 'unittesters', 'testwriters' ],
165 'test'
166 ],
167 [
168 [ 'unittesters' ],
169 'runtest'
170 ],
171 [
172 [ 'testwriters' ],
173 'writetest'
174 ],
175 [
176 [ 'testwriters' ],
177 'modifytest'
178 ],
179 ];
180 }
181
182 /**
183 * @dataProvider provideIPs
184 * @covers User::isIP
185 */
186 public function testIsIP( $value, $result, $message ) {
187 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
188 }
189
190 public static function provideIPs() {
191 return [
192 [ '', false, 'Empty string' ],
193 [ ' ', false, 'Blank space' ],
194 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
195 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
196 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
197 [ '203.0.113.0', true, 'IPv4 example' ],
198 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
199 // Not valid IPs but classified as such by MediaWiki for negated asserting
200 // of whether this might be the identifier of a logged-out user or whether
201 // to allow usernames like it.
202 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
203 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
204 ];
205 }
206
207 /**
208 * @dataProvider provideUserNames
209 * @covers User::isValidUserName
210 */
211 public function testIsValidUserName( $username, $result, $message ) {
212 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
213 }
214
215 public static function provideUserNames() {
216 return [
217 [ '', false, 'Empty string' ],
218 [ ' ', false, 'Blank space' ],
219 [ 'abcd', false, 'Starts with small letter' ],
220 [ 'Ab/cd', false, 'Contains slash' ],
221 [ 'Ab cd', true, 'Whitespace' ],
222 [ '192.168.1.1', false, 'IP' ],
223 [ '116.17.184.5/32', false, 'IP range' ],
224 [ '::e:f:2001/96', false, 'IPv6 range' ],
225 [ 'User:Abcd', false, 'Reserved Namespace' ],
226 [ '12abcd232', true, 'Starts with Numbers' ],
227 [ '?abcd', true, 'Start with ? mark' ],
228 [ '#abcd', false, 'Start with #' ],
229 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
230 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
231 [ 'Ab cd', false, ' Ideographic space' ],
232 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
233 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
234 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
235 ];
236 }
237
238 /**
239 * Test, if for all rights a right- message exist,
240 * which is used on Special:ListGroupRights as help text
241 * Extensions and core
242 *
243 * @coversNothing
244 */
245 public function testAllRightsWithMessage() {
246 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
247 $allRights = User::getAllRights();
248 $allMessageKeys = Language::getMessageKeysFor( 'en' );
249
250 $rightsWithMessage = [];
251 foreach ( $allMessageKeys as $message ) {
252 // === 0: must be at beginning of string (position 0)
253 if ( strpos( $message, 'right-' ) === 0 ) {
254 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
255 }
256 }
257
258 sort( $allRights );
259 sort( $rightsWithMessage );
260
261 $this->assertEquals(
262 $allRights,
263 $rightsWithMessage,
264 'Each user rights (core/extensions) has a corresponding right- message.'
265 );
266 }
267
268 /**
269 * Test User::editCount
270 * @group medium
271 * @covers User::getEditCount
272 */
273 public function testGetEditCount() {
274 $user = $this->getMutableTestUser()->getUser();
275
276 // let the user have a few (3) edits
277 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
278 for ( $i = 0; $i < 3; $i++ ) {
279 $page->doEditContent(
280 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
281 'test',
282 0,
283 false,
284 $user
285 );
286 }
287
288 $this->assertEquals(
289 3,
290 $user->getEditCount(),
291 'After three edits, the user edit count should be 3'
292 );
293
294 // increase the edit count
295 $user->incEditCount();
296
297 $this->assertEquals(
298 4,
299 $user->getEditCount(),
300 'After increasing the edit count manually, the user edit count should be 4'
301 );
302 }
303
304 /**
305 * Test User::editCount
306 * @group medium
307 * @covers User::getEditCount
308 */
309 public function testGetEditCountForAnons() {
310 $user = User::newFromName( 'Anonymous' );
311
312 $this->assertNull(
313 $user->getEditCount(),
314 'Edit count starts null for anonymous users.'
315 );
316
317 $user->incEditCount();
318
319 $this->assertNull(
320 $user->getEditCount(),
321 'Edit count remains null for anonymous users despite calls to increase it.'
322 );
323 }
324
325 /**
326 * Test User::editCount
327 * @group medium
328 * @covers User::incEditCount
329 */
330 public function testIncEditCount() {
331 $user = $this->getMutableTestUser()->getUser();
332 $user->incEditCount();
333
334 $reloadedUser = User::newFromId( $user->getId() );
335 $reloadedUser->incEditCount();
336
337 $this->assertEquals(
338 2,
339 $reloadedUser->getEditCount(),
340 'Increasing the edit count after a fresh load leaves the object up to date.'
341 );
342 }
343
344 /**
345 * Test changing user options.
346 * @covers User::setOption
347 * @covers User::getOption
348 */
349 public function testOptions() {
350 $user = $this->getMutableTestUser()->getUser();
351
352 $user->setOption( 'userjs-someoption', 'test' );
353 $user->setOption( 'rclimit', 200 );
354 $user->setOption( 'wpwatchlistdays', '0' );
355 $user->saveSettings();
356
357 $user = User::newFromName( $user->getName() );
358 $user->load( User::READ_LATEST );
359 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
360 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
361
362 $user = User::newFromName( $user->getName() );
363 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
364 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
365 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
366
367 // Check that an option saved as a string '0' is returned as an integer.
368 $user = User::newFromName( $user->getName() );
369 $user->load( User::READ_LATEST );
370 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
371 }
372
373 /**
374 * T39963
375 * Make sure defaults are loaded when setOption is called.
376 * @covers User::loadOptions
377 */
378 public function testAnonOptions() {
379 global $wgDefaultUserOptions;
380 $this->user->setOption( 'userjs-someoption', 'test' );
381 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
382 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
383 }
384
385 /**
386 * Test password validity checks. There are 3 checks in core,
387 * - ensure the password meets the minimal length
388 * - ensure the password is not the same as the username
389 * - ensure the username/password combo isn't forbidden
390 * @covers User::checkPasswordValidity()
391 * @covers User::getPasswordValidity()
392 * @covers User::isValidPassword()
393 */
394 public function testCheckPasswordValidity() {
395 $this->setMwGlobals( [
396 'wgPasswordPolicy' => [
397 'policies' => [
398 'sysop' => [
399 'MinimalPasswordLength' => 8,
400 'MinimumPasswordLengthToLogin' => 1,
401 'PasswordCannotMatchUsername' => 1,
402 ],
403 'default' => [
404 'MinimalPasswordLength' => 6,
405 'PasswordCannotMatchUsername' => true,
406 'PasswordCannotMatchBlacklist' => true,
407 'MaximalPasswordLength' => 40,
408 ],
409 ],
410 'checks' => [
411 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
412 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
413 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
414 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
415 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
416 ],
417 ],
418 ] );
419
420 $user = static::getTestUser()->getUser();
421
422 // Sanity
423 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
424
425 // Minimum length
426 $this->assertFalse( $user->isValidPassword( 'a' ) );
427 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
428 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
429 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
430
431 // Maximum length
432 $longPass = str_repeat( 'a', 41 );
433 $this->assertFalse( $user->isValidPassword( $longPass ) );
434 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
435 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
436 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
437
438 // Matches username
439 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
440 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
441 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
442
443 // On the forbidden list
444 $user = User::newFromName( 'Useruser' );
445 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
446 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
447 }
448
449 /**
450 * @covers User::getCanonicalName()
451 * @dataProvider provideGetCanonicalName
452 */
453 public function testGetCanonicalName( $name, $expectedArray ) {
454 // fake interwiki map for the 'Interwiki prefix' testcase
455 $this->mergeMwGlobalArrayValue( 'wgHooks', [
456 'InterwikiLoadPrefix' => [
457 function ( $prefix, &$iwdata ) {
458 if ( $prefix === 'interwiki' ) {
459 $iwdata = [
460 'iw_url' => 'http://example.com/',
461 'iw_local' => 0,
462 'iw_trans' => 0,
463 ];
464 return false;
465 }
466 },
467 ],
468 ] );
469
470 foreach ( $expectedArray as $validate => $expected ) {
471 $this->assertEquals(
472 $expected,
473 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
474 }
475 }
476
477 public static function provideGetCanonicalName() {
478 return [
479 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
480 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
481 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
482 'valid' => false, 'false' => 'Talk:Username' ] ],
483 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
484 'valid' => false, 'false' => 'Interwiki:Username' ] ],
485 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
486 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
487 'usable' => 'Multi spaces' ] ],
488 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
489 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
490 'valid' => false, 'false' => 'In[]valid' ] ],
491 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
492 'false' => 'With / slash' ] ],
493 ];
494 }
495
496 /**
497 * @covers User::equals
498 */
499 public function testEquals() {
500 $first = $this->getMutableTestUser()->getUser();
501 $second = User::newFromName( $first->getName() );
502
503 $this->assertTrue( $first->equals( $first ) );
504 $this->assertTrue( $first->equals( $second ) );
505 $this->assertTrue( $second->equals( $first ) );
506
507 $third = $this->getMutableTestUser()->getUser();
508 $fourth = $this->getMutableTestUser()->getUser();
509
510 $this->assertFalse( $third->equals( $fourth ) );
511 $this->assertFalse( $fourth->equals( $third ) );
512
513 // Test users loaded from db with id
514 $user = $this->getMutableTestUser()->getUser();
515 $fifth = User::newFromId( $user->getId() );
516 $sixth = User::newFromName( $user->getName() );
517 $this->assertTrue( $fifth->equals( $sixth ) );
518 }
519
520 /**
521 * @covers User::getId
522 */
523 public function testGetId() {
524 $user = static::getTestUser()->getUser();
525 $this->assertTrue( $user->getId() > 0 );
526 }
527
528 /**
529 * @covers User::isLoggedIn
530 * @covers User::isAnon
531 */
532 public function testLoggedIn() {
533 $user = $this->getMutableTestUser()->getUser();
534 $this->assertTrue( $user->isLoggedIn() );
535 $this->assertFalse( $user->isAnon() );
536
537 // Non-existent users are perceived as anonymous
538 $user = User::newFromName( 'UTNonexistent' );
539 $this->assertFalse( $user->isLoggedIn() );
540 $this->assertTrue( $user->isAnon() );
541
542 $user = new User;
543 $this->assertFalse( $user->isLoggedIn() );
544 $this->assertTrue( $user->isAnon() );
545 }
546
547 /**
548 * @covers User::checkAndSetTouched
549 */
550 public function testCheckAndSetTouched() {
551 $user = $this->getMutableTestUser()->getUser();
552 $user = TestingAccessWrapper::newFromObject( $user );
553 $this->assertTrue( $user->isLoggedIn() );
554
555 $touched = $user->getDBTouched();
556 $this->assertTrue(
557 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
558 $this->assertGreaterThan(
559 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
560
561 $touched = $user->getDBTouched();
562 $this->assertTrue(
563 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
564 $this->assertGreaterThan(
565 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
566 }
567
568 /**
569 * @covers User::findUsersByGroup
570 */
571 public function testFindUsersByGroup() {
572 $users = User::findUsersByGroup( [] );
573 $this->assertEquals( 0, iterator_count( $users ) );
574
575 $users = User::findUsersByGroup( 'foo' );
576 $this->assertEquals( 0, iterator_count( $users ) );
577
578 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
579 $users = User::findUsersByGroup( 'foo' );
580 $this->assertEquals( 1, iterator_count( $users ) );
581 $users->rewind();
582 $this->assertTrue( $user->equals( $users->current() ) );
583
584 // arguments have OR relationship
585 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
586 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
587 $this->assertEquals( 2, iterator_count( $users ) );
588 $users->rewind();
589 $this->assertTrue( $user->equals( $users->current() ) );
590 $users->next();
591 $this->assertTrue( $user2->equals( $users->current() ) );
592
593 // users are not duplicated
594 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
595 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
596 $this->assertEquals( 1, iterator_count( $users ) );
597 $users->rewind();
598 $this->assertTrue( $user->equals( $users->current() ) );
599 }
600
601 /**
602 * When a user is autoblocked a cookie is set with which to track them
603 * in case they log out and change IP addresses.
604 * @link https://phabricator.wikimedia.org/T5233
605 */
606 public function testAutoblockCookies() {
607 // Set up the bits of global configuration that we use.
608 $this->setMwGlobals( [
609 'wgCookieSetOnAutoblock' => true,
610 'wgCookiePrefix' => 'wmsitetitle',
611 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
612 ] );
613
614 // Unregister the hooks for proper unit testing
615 $this->mergeMwGlobalArrayValue( 'wgHooks', [
616 'PerformRetroactiveAutoblock' => []
617 ] );
618
619 // 1. Log in a test user, and block them.
620 $userBlocker = $this->getTestSysop()->getUser();
621 $user1tmp = $this->getTestUser()->getUser();
622 $request1 = new FauxRequest();
623 $request1->getSession()->setUser( $user1tmp );
624 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
625 $block = new Block( [
626 'enableAutoblock' => true,
627 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
628 ] );
629 $block->setBlocker( $this->getTestSysop()->getUser() );
630 $block->setTarget( $user1tmp );
631 $block->setBlocker( $userBlocker );
632 $res = $block->insert();
633 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
634 $user1 = User::newFromSession( $request1 );
635 $user1->mBlock = $block;
636 $user1->load();
637
638 // Confirm that the block has been applied as required.
639 $this->assertTrue( $user1->isLoggedIn() );
640 $this->assertTrue( $user1->isBlocked() );
641 $this->assertEquals( Block::TYPE_USER, $block->getType() );
642 $this->assertTrue( $block->isAutoblocking() );
643 $this->assertGreaterThanOrEqual( 1, $block->getId() );
644
645 // Test for the desired cookie name, value, and expiry.
646 $cookies = $request1->response()->getCookies();
647 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
648 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
649 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
650 $this->assertEquals( $block->getId(), $cookieValue );
651
652 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
653 $request2 = new FauxRequest();
654 $request2->setCookie( 'BlockID', $block->getCookieValue() );
655 $user2 = User::newFromSession( $request2 );
656 $user2->load();
657 $this->assertNotEquals( $user1->getId(), $user2->getId() );
658 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
659 $this->assertTrue( $user2->isAnon() );
660 $this->assertFalse( $user2->isLoggedIn() );
661 $this->assertTrue( $user2->isBlocked() );
662 // Non-strict type-check.
663 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
664 // Can't directly compare the objects becuase of member type differences.
665 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
666 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
667 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
668
669 // 3. Finally, set up a request as a new user, and the block should still be applied.
670 $user3tmp = $this->getTestUser()->getUser();
671 $request3 = new FauxRequest();
672 $request3->getSession()->setUser( $user3tmp );
673 $request3->setCookie( 'BlockID', $block->getId() );
674 $user3 = User::newFromSession( $request3 );
675 $user3->load();
676 $this->assertTrue( $user3->isLoggedIn() );
677 $this->assertTrue( $user3->isBlocked() );
678 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
679
680 // Clean up.
681 $block->delete();
682 }
683
684 /**
685 * Make sure that no cookie is set to track autoblocked users
686 * when $wgCookieSetOnAutoblock is false.
687 */
688 public function testAutoblockCookiesDisabled() {
689 // Set up the bits of global configuration that we use.
690 $this->setMwGlobals( [
691 'wgCookieSetOnAutoblock' => false,
692 'wgCookiePrefix' => 'wm_no_cookies',
693 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
694 ] );
695
696 // Unregister the hooks for proper unit testing
697 $this->mergeMwGlobalArrayValue( 'wgHooks', [
698 'PerformRetroactiveAutoblock' => []
699 ] );
700
701 // 1. Log in a test user, and block them.
702 $userBlocker = $this->getTestSysop()->getUser();
703 $testUser = $this->getTestUser()->getUser();
704 $request1 = new FauxRequest();
705 $request1->getSession()->setUser( $testUser );
706 $block = new Block( [ 'enableAutoblock' => true ] );
707 $block->setBlocker( $this->getTestSysop()->getUser() );
708 $block->setTarget( $testUser );
709 $block->setBlocker( $userBlocker );
710 $res = $block->insert();
711 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
712 $user = User::newFromSession( $request1 );
713 $user->mBlock = $block;
714 $user->load();
715
716 // 2. Test that the cookie IS NOT present.
717 $this->assertTrue( $user->isLoggedIn() );
718 $this->assertTrue( $user->isBlocked() );
719 $this->assertEquals( Block::TYPE_USER, $block->getType() );
720 $this->assertTrue( $block->isAutoblocking() );
721 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
722 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
723 $cookies = $request1->response()->getCookies();
724 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
725
726 // Clean up.
727 $block->delete();
728 }
729
730 /**
731 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
732 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
733 * the cookie's should change with it.
734 */
735 public function testAutoblockCookieInfiniteExpiry() {
736 $this->setMwGlobals( [
737 'wgCookieSetOnAutoblock' => true,
738 'wgCookiePrefix' => 'wm_infinite_block',
739 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
740 ] );
741
742 // Unregister the hooks for proper unit testing
743 $this->mergeMwGlobalArrayValue( 'wgHooks', [
744 'PerformRetroactiveAutoblock' => []
745 ] );
746
747 // 1. Log in a test user, and block them indefinitely.
748 $userBlocker = $this->getTestSysop()->getUser();
749 $user1Tmp = $this->getTestUser()->getUser();
750 $request1 = new FauxRequest();
751 $request1->getSession()->setUser( $user1Tmp );
752 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
753 $block->setBlocker( $this->getTestSysop()->getUser() );
754 $block->setTarget( $user1Tmp );
755 $block->setBlocker( $userBlocker );
756 $res = $block->insert();
757 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
758 $user1 = User::newFromSession( $request1 );
759 $user1->mBlock = $block;
760 $user1->load();
761
762 // 2. Test the cookie's expiry timestamp.
763 $this->assertTrue( $user1->isLoggedIn() );
764 $this->assertTrue( $user1->isBlocked() );
765 $this->assertEquals( Block::TYPE_USER, $block->getType() );
766 $this->assertTrue( $block->isAutoblocking() );
767 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
768 $cookies = $request1->response()->getCookies();
769 // Test the cookie's expiry to the nearest minute.
770 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
771 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
772 // Check for expiry dates in a 10-second window, to account for slow testing.
773 $this->assertEquals(
774 $expOneDay,
775 $cookies['wm_infinite_blockBlockID']['expire'],
776 'Expiry date',
777 5.0
778 );
779
780 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
781 $newExpiry = wfTimestamp() + 2 * 60 * 60;
782 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
783 $block->update();
784 $user2tmp = $this->getTestUser()->getUser();
785 $request2 = new FauxRequest();
786 $request2->getSession()->setUser( $user2tmp );
787 $user2 = User::newFromSession( $request2 );
788 $user2->mBlock = $block;
789 $user2->load();
790 $cookies = $request2->response()->getCookies();
791 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
792 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
793
794 // Clean up.
795 $block->delete();
796 }
797
798 public function testSoftBlockRanges() {
799 global $wgUser;
800
801 $this->setMwGlobals( [
802 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
803 'wgUser' => null,
804 ] );
805
806 // IP isn't in $wgSoftBlockRanges
807 $request = new FauxRequest();
808 $request->setIP( '192.168.0.1' );
809 $wgUser = User::newFromSession( $request );
810 $this->assertNull( $wgUser->getBlock() );
811
812 // IP is in $wgSoftBlockRanges
813 $request = new FauxRequest();
814 $request->setIP( '10.20.30.40' );
815 $wgUser = User::newFromSession( $request );
816 $block = $wgUser->getBlock();
817 $this->assertInstanceOf( Block::class, $block );
818 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
819
820 // Make sure the block is really soft
821 $request->getSession()->setUser( $this->getTestUser()->getUser() );
822 $wgUser = User::newFromSession( $request );
823 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
824 $this->assertNull( $wgUser->getBlock() );
825 }
826
827 /**
828 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
829 */
830 public function testAutoblockCookieInauthentic() {
831 // Set up the bits of global configuration that we use.
832 $this->setMwGlobals( [
833 'wgCookieSetOnAutoblock' => true,
834 'wgCookiePrefix' => 'wmsitetitle',
835 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
836 ] );
837
838 // Unregister the hooks for proper unit testing
839 $this->mergeMwGlobalArrayValue( 'wgHooks', [
840 'PerformRetroactiveAutoblock' => []
841 ] );
842
843 // 1. Log in a blocked test user.
844 $userBlocker = $this->getTestSysop()->getUser();
845 $user1tmp = $this->getTestUser()->getUser();
846 $request1 = new FauxRequest();
847 $request1->getSession()->setUser( $user1tmp );
848 $block = new Block( [ 'enableAutoblock' => true ] );
849 $block->setBlocker( $this->getTestSysop()->getUser() );
850 $block->setTarget( $user1tmp );
851 $block->setBlocker( $userBlocker );
852 $res = $block->insert();
853 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
854 $user1 = User::newFromSession( $request1 );
855 $user1->mBlock = $block;
856 $user1->load();
857
858 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
859 // user not blocked.
860 $request2 = new FauxRequest();
861 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
862 $user2 = User::newFromSession( $request2 );
863 $user2->load();
864 $this->assertTrue( $user2->isAnon() );
865 $this->assertFalse( $user2->isLoggedIn() );
866 $this->assertFalse( $user2->isBlocked() );
867
868 // Clean up.
869 $block->delete();
870 }
871
872 /**
873 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
874 * This checks that a non-authenticated cookie still works.
875 */
876 public function testAutoblockCookieNoSecretKey() {
877 // Set up the bits of global configuration that we use.
878 $this->setMwGlobals( [
879 'wgCookieSetOnAutoblock' => true,
880 'wgCookiePrefix' => 'wmsitetitle',
881 'wgSecretKey' => null,
882 ] );
883
884 // Unregister the hooks for proper unit testing
885 $this->mergeMwGlobalArrayValue( 'wgHooks', [
886 'PerformRetroactiveAutoblock' => []
887 ] );
888
889 // 1. Log in a blocked test user.
890 $userBlocker = $this->getTestSysop()->getUser();
891 $user1tmp = $this->getTestUser()->getUser();
892 $request1 = new FauxRequest();
893 $request1->getSession()->setUser( $user1tmp );
894 $block = new Block( [ 'enableAutoblock' => true ] );
895 $block->setBlocker( $this->getTestSysop()->getUser() );
896 $block->setTarget( $user1tmp );
897 $block->setBlocker( $userBlocker );
898 $res = $block->insert();
899 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
900 $user1 = User::newFromSession( $request1 );
901 $user1->mBlock = $block;
902 $user1->load();
903 $this->assertTrue( $user1->isBlocked() );
904
905 // 2. Create a new request, set the cookie to just the block ID, and the user should
906 // still get blocked when they log in again.
907 $request2 = new FauxRequest();
908 $request2->setCookie( 'BlockID', $block->getId() );
909 $user2 = User::newFromSession( $request2 );
910 $user2->load();
911 $this->assertNotEquals( $user1->getId(), $user2->getId() );
912 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
913 $this->assertTrue( $user2->isAnon() );
914 $this->assertFalse( $user2->isLoggedIn() );
915 $this->assertTrue( $user2->isBlocked() );
916 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
917
918 // Clean up.
919 $block->delete();
920 }
921
922 /**
923 * @covers User::isPingLimitable
924 */
925 public function testIsPingLimitable() {
926 $request = new FauxRequest();
927 $request->setIP( '1.2.3.4' );
928 $user = User::newFromSession( $request );
929
930 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
931 $this->assertTrue( $user->isPingLimitable() );
932
933 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
934 $this->assertFalse( $user->isPingLimitable() );
935
936 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
937 $this->assertFalse( $user->isPingLimitable() );
938
939 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
940 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
941 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
942 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
943 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
944 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
945 }
946
947 public function provideExperienceLevel() {
948 return [
949 [ 2, 2, 'newcomer' ],
950 [ 12, 3, 'newcomer' ],
951 [ 8, 5, 'newcomer' ],
952 [ 15, 10, 'learner' ],
953 [ 450, 20, 'learner' ],
954 [ 460, 33, 'learner' ],
955 [ 525, 28, 'learner' ],
956 [ 538, 33, 'experienced' ],
957 ];
958 }
959
960 /**
961 * @covers User::getExperienceLevel
962 * @dataProvider provideExperienceLevel
963 */
964 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
965 $this->setMwGlobals( [
966 'wgLearnerEdits' => 10,
967 'wgLearnerMemberSince' => 4,
968 'wgExperiencedUserEdits' => 500,
969 'wgExperiencedUserMemberSince' => 30,
970 ] );
971
972 $db = wfGetDB( DB_MASTER );
973 $userQuery = User::getQueryInfo();
974 $row = $db->selectRow(
975 $userQuery['tables'],
976 $userQuery['fields'],
977 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
978 __METHOD__,
979 [],
980 $userQuery['joins']
981 );
982 $row->user_editcount = $editCount;
983 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
984 $user = User::newFromRow( $row );
985
986 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
987 }
988
989 /**
990 * @covers User::getExperienceLevel
991 */
992 public function testExperienceLevelAnon() {
993 $user = User::newFromName( '10.11.12.13', false );
994
995 $this->assertFalse( $user->getExperienceLevel() );
996 }
997
998 public static function provideIsLocallBlockedProxy() {
999 return [
1000 [ '1.2.3.4', '1.2.3.4' ],
1001 [ '1.2.3.4', '1.2.3.0/16' ],
1002 ];
1003 }
1004
1005 /**
1006 * @dataProvider provideIsLocallBlockedProxy
1007 * @covers User::isLocallyBlockedProxy
1008 */
1009 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1010 $this->setMwGlobals(
1011 'wgProxyList', []
1012 );
1013 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
1014
1015 $this->setMwGlobals(
1016 'wgProxyList',
1017 [
1018 $blockListEntry
1019 ]
1020 );
1021 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1022
1023 $this->setMwGlobals(
1024 'wgProxyList',
1025 [
1026 'test' => $blockListEntry
1027 ]
1028 );
1029 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1030
1031 $this->hideDeprecated(
1032 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1033 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1034 );
1035 $this->setMwGlobals(
1036 'wgProxyList',
1037 [
1038 $blockListEntry => 'test'
1039 ]
1040 );
1041 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1042 }
1043
1044 public function testActorId() {
1045 $this->hideDeprecated( 'User::selectFields' );
1046
1047 // Newly-created user has an actor ID
1048 $user = User::createNew( 'UserTestActorId1' );
1049 $id = $user->getId();
1050 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1051
1052 $user = User::newFromName( 'UserTestActorId2' );
1053 $user->addToDatabase();
1054 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1055
1056 $user = User::newFromName( 'UserTestActorId1' );
1057 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1058
1059 $user = User::newFromId( $id );
1060 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1061
1062 $user2 = User::newFromActorId( $user->getActorId() );
1063 $this->assertEquals( $user->getId(), $user2->getId(),
1064 'User::newFromActorId works for an existing user' );
1065
1066 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1067 $user = User::newFromRow( $row );
1068 $this->assertTrue( $user->getActorId() > 0,
1069 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1070
1071 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1072 User::purge( wfWikiId(), $id );
1073 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1074 ObjectCache::getMainWANInstance()->clearProcessCache();
1075
1076 $user = User::newFromId( $id );
1077 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1078 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1079
1080 $user->setName( 'UserTestActorId4-renamed' );
1081 $user->saveSettings();
1082 $this->assertEquals(
1083 $user->getName(),
1084 $this->db->selectField(
1085 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1086 ),
1087 'User::saveSettings updates actor table for name change'
1088 );
1089
1090 // For sanity
1091 $ip = '192.168.12.34';
1092 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1093
1094 $user = User::newFromName( $ip, false );
1095 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1096 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1097 'Actor ID can be created for an anonymous user' );
1098
1099 $user = User::newFromName( $ip, false );
1100 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1101 $user2 = User::newFromActorId( $user->getActorId() );
1102 $this->assertEquals( $user->getName(), $user2->getName(),
1103 'User::newFromActorId works for an anonymous user' );
1104 }
1105
1106 public function testNewFromAnyId() {
1107 // Registered user
1108 $user = $this->getTestUser()->getUser();
1109 for ( $i = 1; $i <= 7; $i++ ) {
1110 $test = User::newFromAnyId(
1111 ( $i & 1 ) ? $user->getId() : null,
1112 ( $i & 2 ) ? $user->getName() : null,
1113 ( $i & 4 ) ? $user->getActorId() : null
1114 );
1115 $this->assertSame( $user->getId(), $test->getId() );
1116 $this->assertSame( $user->getName(), $test->getName() );
1117 $this->assertSame( $user->getActorId(), $test->getActorId() );
1118 }
1119
1120 // Anon user. Can't load by only user ID when that's 0.
1121 $user = User::newFromName( '192.168.12.34', false );
1122 $user->getActorId( $this->db ); // Make sure an actor ID exists
1123
1124 $test = User::newFromAnyId( null, '192.168.12.34', null );
1125 $this->assertSame( $user->getId(), $test->getId() );
1126 $this->assertSame( $user->getName(), $test->getName() );
1127 $this->assertSame( $user->getActorId(), $test->getActorId() );
1128 $test = User::newFromAnyId( null, null, $user->getActorId() );
1129 $this->assertSame( $user->getId(), $test->getId() );
1130 $this->assertSame( $user->getName(), $test->getName() );
1131 $this->assertSame( $user->getActorId(), $test->getActorId() );
1132
1133 // Bogus data should still "work" as long as nothing triggers a ->load(),
1134 // and accessing the specified data shouldn't do that.
1135 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1136 $this->assertSame( 123456, $test->getId() );
1137 $this->assertSame( 'Bogus', $test->getName() );
1138 $this->assertSame( 654321, $test->getActorId() );
1139
1140 // Exceptional cases
1141 try {
1142 User::newFromAnyId( null, null, null );
1143 $this->fail( 'Expected exception not thrown' );
1144 } catch ( InvalidArgumentException $ex ) {
1145 }
1146 try {
1147 User::newFromAnyId( 0, null, 0 );
1148 $this->fail( 'Expected exception not thrown' );
1149 } catch ( InvalidArgumentException $ex ) {
1150 }
1151 }
1152
1153 /**
1154 * @covers User::newFromIdentity
1155 */
1156 public function testNewFromIdentity() {
1157 // Registered user
1158 $user = $this->getTestUser()->getUser();
1159
1160 $this->assertSame( $user, User::newFromIdentity( $user ) );
1161
1162 // ID only
1163 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1164 $result = User::newFromIdentity( $identity );
1165 $this->assertInstanceOf( User::class, $result );
1166 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1167 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1168 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1169
1170 // Name only
1171 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1172 $result = User::newFromIdentity( $identity );
1173 $this->assertInstanceOf( User::class, $result );
1174 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1175 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1176 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1177
1178 // Actor only
1179 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1180 $result = User::newFromIdentity( $identity );
1181 $this->assertInstanceOf( User::class, $result );
1182 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1183 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1184 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1185 }
1186
1187 /**
1188 * @covers User::getBlockedStatus
1189 * @covers User::getBlock
1190 * @covers User::blockedBy
1191 * @covers User::blockedFor
1192 * @covers User::isHidden
1193 * @covers User::isBlockedFrom
1194 */
1195 public function testBlockInstanceCache() {
1196 // First, check the user isn't blocked
1197 $user = $this->getMutableTestUser()->getUser();
1198 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1199 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1200 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1201 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1202 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1203 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1204
1205 // Block the user
1206 $blocker = $this->getTestSysop()->getUser();
1207 $block = new Block( [
1208 'hideName' => true,
1209 'allowUsertalk' => false,
1210 'reason' => 'Because',
1211 ] );
1212 $block->setTarget( $user );
1213 $block->setBlocker( $blocker );
1214 $res = $block->insert();
1215 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1216
1217 // Clear cache and confirm it loaded the block properly
1218 $user->clearInstanceCache();
1219 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1220 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1221 $this->assertSame( 'Because', $user->blockedFor() );
1222 $this->assertTrue( (bool)$user->isHidden() );
1223 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1224
1225 // Unblock
1226 $block->delete();
1227
1228 // Clear cache and confirm it loaded the not-blocked properly
1229 $user->clearInstanceCache();
1230 $this->assertNull( $user->getBlock( false ) );
1231 $this->assertSame( '', $user->blockedBy() );
1232 $this->assertSame( '', $user->blockedFor() );
1233 $this->assertFalse( (bool)$user->isHidden() );
1234 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1235 }
1236
1237 /**
1238 * Block cookie should be set for IP Blocks if
1239 * wgCookieSetOnIpBlock is set to true
1240 */
1241 public function testIpBlockCookieSet() {
1242 $this->setMwGlobals( [
1243 'wgCookieSetOnIpBlock' => true,
1244 'wgCookiePrefix' => 'wiki',
1245 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1246 ] );
1247
1248 // setup block
1249 $block = new Block( [
1250 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1251 ] );
1252 $block->setTarget( '1.2.3.4' );
1253 $block->setBlocker( $this->getTestSysop()->getUser() );
1254 $block->insert();
1255
1256 // setup request
1257 $request = new FauxRequest();
1258 $request->setIP( '1.2.3.4' );
1259
1260 // get user
1261 $user = User::newFromSession( $request );
1262 $user->trackBlockWithCookie();
1263
1264 // test cookie was set
1265 $cookies = $request->response()->getCookies();
1266 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1267
1268 // clean up
1269 $block->delete();
1270 }
1271
1272 /**
1273 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1274 * is disabled
1275 */
1276 public function testIpBlockCookieNotSet() {
1277 $this->setMwGlobals( [
1278 'wgCookieSetOnIpBlock' => false,
1279 'wgCookiePrefix' => 'wiki',
1280 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1281 ] );
1282
1283 // setup block
1284 $block = new Block( [
1285 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1286 ] );
1287 $block->setTarget( '1.2.3.4' );
1288 $block->setBlocker( $this->getTestSysop()->getUser() );
1289 $block->insert();
1290
1291 // setup request
1292 $request = new FauxRequest();
1293 $request->setIP( '1.2.3.4' );
1294
1295 // get user
1296 $user = User::newFromSession( $request );
1297 $user->trackBlockWithCookie();
1298
1299 // test cookie was not set
1300 $cookies = $request->response()->getCookies();
1301 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1302
1303 // clean up
1304 $block->delete();
1305 }
1306
1307 /**
1308 * When an ip user is blocked and then they log in, cookie block
1309 * should be invalid and the cookie removed.
1310 */
1311 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1312 $this->setMwGlobals( [
1313 'wgAutoblockExpiry' => 8000,
1314 'wgCookieSetOnIpBlock' => true,
1315 'wgCookiePrefix' => 'wiki',
1316 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1317 ] );
1318
1319 // setup block
1320 $block = new Block( [
1321 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1322 ] );
1323 $block->setTarget( '1.2.3.4' );
1324 $block->setBlocker( $this->getTestSysop()->getUser() );
1325 $block->insert();
1326
1327 // setup request
1328 $request = new FauxRequest();
1329 $request->setIP( '1.2.3.4' );
1330 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1331 $request->setCookie( 'BlockID', $block->getCookieValue() );
1332
1333 // setup user
1334 $user = User::newFromSession( $request );
1335
1336 // logged in users should be inmune to cookie block of type ip/range
1337 $this->assertFalse( $user->isBlocked() );
1338
1339 // cookie is being cleared
1340 $cookies = $request->response()->getCookies();
1341 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1342
1343 // clean up
1344 $block->delete();
1345 }
1346 }