Hard deprecate $wgTidyConfig['driver'] = 'disabled'
[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' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD,
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 User::editCount
240 * @group medium
241 * @covers User::getEditCount
242 */
243 public function testGetEditCount() {
244 $user = $this->getMutableTestUser()->getUser();
245
246 // let the user have a few (3) edits
247 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
248 for ( $i = 0; $i < 3; $i++ ) {
249 $page->doEditContent(
250 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
251 'test',
252 0,
253 false,
254 $user
255 );
256 }
257
258 $this->assertEquals(
259 3,
260 $user->getEditCount(),
261 'After three edits, the user edit count should be 3'
262 );
263
264 // increase the edit count
265 $user->incEditCount();
266
267 $this->assertEquals(
268 4,
269 $user->getEditCount(),
270 'After increasing the edit count manually, the user edit count should be 4'
271 );
272 }
273
274 /**
275 * Test User::editCount
276 * @group medium
277 * @covers User::getEditCount
278 */
279 public function testGetEditCountForAnons() {
280 $user = User::newFromName( 'Anonymous' );
281
282 $this->assertNull(
283 $user->getEditCount(),
284 'Edit count starts null for anonymous users.'
285 );
286
287 $user->incEditCount();
288
289 $this->assertNull(
290 $user->getEditCount(),
291 'Edit count remains null for anonymous users despite calls to increase it.'
292 );
293 }
294
295 /**
296 * Test User::editCount
297 * @group medium
298 * @covers User::incEditCount
299 */
300 public function testIncEditCount() {
301 $user = $this->getMutableTestUser()->getUser();
302 $user->incEditCount();
303
304 $reloadedUser = User::newFromId( $user->getId() );
305 $reloadedUser->incEditCount();
306
307 $this->assertEquals(
308 2,
309 $reloadedUser->getEditCount(),
310 'Increasing the edit count after a fresh load leaves the object up to date.'
311 );
312 }
313
314 /**
315 * Test changing user options.
316 * @covers User::setOption
317 * @covers User::getOption
318 */
319 public function testOptions() {
320 $user = $this->getMutableTestUser()->getUser();
321
322 $user->setOption( 'userjs-someoption', 'test' );
323 $user->setOption( 'rclimit', 200 );
324 $user->setOption( 'wpwatchlistdays', '0' );
325 $user->saveSettings();
326
327 $user = User::newFromName( $user->getName() );
328 $user->load( User::READ_LATEST );
329 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
330 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
331
332 $user = User::newFromName( $user->getName() );
333 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
334 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
335 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
336
337 // Check that an option saved as a string '0' is returned as an integer.
338 $user = User::newFromName( $user->getName() );
339 $user->load( User::READ_LATEST );
340 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
341 }
342
343 /**
344 * T39963
345 * Make sure defaults are loaded when setOption is called.
346 * @covers User::loadOptions
347 */
348 public function testAnonOptions() {
349 global $wgDefaultUserOptions;
350 $this->user->setOption( 'userjs-someoption', 'test' );
351 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
352 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
353 }
354
355 /**
356 * Test password validity checks. There are 3 checks in core,
357 * - ensure the password meets the minimal length
358 * - ensure the password is not the same as the username
359 * - ensure the username/password combo isn't forbidden
360 * @covers User::checkPasswordValidity()
361 * @covers User::getPasswordValidity()
362 * @covers User::isValidPassword()
363 */
364 public function testCheckPasswordValidity() {
365 $this->setMwGlobals( [
366 'wgPasswordPolicy' => [
367 'policies' => [
368 'sysop' => [
369 'MinimalPasswordLength' => 8,
370 'MinimumPasswordLengthToLogin' => 1,
371 'PasswordCannotMatchUsername' => 1,
372 ],
373 'default' => [
374 'MinimalPasswordLength' => 6,
375 'PasswordCannotMatchUsername' => true,
376 'PasswordCannotMatchBlacklist' => true,
377 'MaximalPasswordLength' => 40,
378 ],
379 ],
380 'checks' => [
381 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
382 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
383 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
384 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
385 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
386 ],
387 ],
388 ] );
389
390 $user = static::getTestUser()->getUser();
391
392 // Sanity
393 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
394
395 // Minimum length
396 $this->assertFalse( $user->isValidPassword( 'a' ) );
397 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
398 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
399 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
400
401 // Maximum length
402 $longPass = str_repeat( 'a', 41 );
403 $this->assertFalse( $user->isValidPassword( $longPass ) );
404 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
405 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
406 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
407
408 // Matches username
409 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
410 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
411 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
412
413 // On the forbidden list
414 $user = User::newFromName( 'Useruser' );
415 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
416 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
417 }
418
419 /**
420 * @covers User::getCanonicalName()
421 * @dataProvider provideGetCanonicalName
422 */
423 public function testGetCanonicalName( $name, $expectedArray ) {
424 // fake interwiki map for the 'Interwiki prefix' testcase
425 $this->mergeMwGlobalArrayValue( 'wgHooks', [
426 'InterwikiLoadPrefix' => [
427 function ( $prefix, &$iwdata ) {
428 if ( $prefix === 'interwiki' ) {
429 $iwdata = [
430 'iw_url' => 'http://example.com/',
431 'iw_local' => 0,
432 'iw_trans' => 0,
433 ];
434 return false;
435 }
436 },
437 ],
438 ] );
439
440 foreach ( $expectedArray as $validate => $expected ) {
441 $this->assertEquals(
442 $expected,
443 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
444 }
445 }
446
447 public static function provideGetCanonicalName() {
448 return [
449 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
450 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
451 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
452 'valid' => false, 'false' => 'Talk:Username' ] ],
453 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
454 'valid' => false, 'false' => 'Interwiki:Username' ] ],
455 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
456 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
457 'usable' => 'Multi spaces' ] ],
458 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
459 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
460 'valid' => false, 'false' => 'In[]valid' ] ],
461 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
462 'false' => 'With / slash' ] ],
463 ];
464 }
465
466 /**
467 * @covers User::equals
468 */
469 public function testEquals() {
470 $first = $this->getMutableTestUser()->getUser();
471 $second = User::newFromName( $first->getName() );
472
473 $this->assertTrue( $first->equals( $first ) );
474 $this->assertTrue( $first->equals( $second ) );
475 $this->assertTrue( $second->equals( $first ) );
476
477 $third = $this->getMutableTestUser()->getUser();
478 $fourth = $this->getMutableTestUser()->getUser();
479
480 $this->assertFalse( $third->equals( $fourth ) );
481 $this->assertFalse( $fourth->equals( $third ) );
482
483 // Test users loaded from db with id
484 $user = $this->getMutableTestUser()->getUser();
485 $fifth = User::newFromId( $user->getId() );
486 $sixth = User::newFromName( $user->getName() );
487 $this->assertTrue( $fifth->equals( $sixth ) );
488 }
489
490 /**
491 * @covers User::getId
492 */
493 public function testGetId() {
494 $user = static::getTestUser()->getUser();
495 $this->assertTrue( $user->getId() > 0 );
496 }
497
498 /**
499 * @covers User::isLoggedIn
500 * @covers User::isAnon
501 */
502 public function testLoggedIn() {
503 $user = $this->getMutableTestUser()->getUser();
504 $this->assertTrue( $user->isLoggedIn() );
505 $this->assertFalse( $user->isAnon() );
506
507 // Non-existent users are perceived as anonymous
508 $user = User::newFromName( 'UTNonexistent' );
509 $this->assertFalse( $user->isLoggedIn() );
510 $this->assertTrue( $user->isAnon() );
511
512 $user = new User;
513 $this->assertFalse( $user->isLoggedIn() );
514 $this->assertTrue( $user->isAnon() );
515 }
516
517 /**
518 * @covers User::checkAndSetTouched
519 */
520 public function testCheckAndSetTouched() {
521 $user = $this->getMutableTestUser()->getUser();
522 $user = TestingAccessWrapper::newFromObject( $user );
523 $this->assertTrue( $user->isLoggedIn() );
524
525 $touched = $user->getDBTouched();
526 $this->assertTrue(
527 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
528 $this->assertGreaterThan(
529 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
530
531 $touched = $user->getDBTouched();
532 $this->assertTrue(
533 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
534 $this->assertGreaterThan(
535 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
536 }
537
538 /**
539 * @covers User::findUsersByGroup
540 */
541 public function testFindUsersByGroup() {
542 // FIXME: fails under postgres
543 $this->markTestSkippedIfDbType( 'postgres' );
544
545 $users = User::findUsersByGroup( [] );
546 $this->assertEquals( 0, iterator_count( $users ) );
547
548 $users = User::findUsersByGroup( 'foo' );
549 $this->assertEquals( 0, iterator_count( $users ) );
550
551 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
552 $users = User::findUsersByGroup( 'foo' );
553 $this->assertEquals( 1, iterator_count( $users ) );
554 $users->rewind();
555 $this->assertTrue( $user->equals( $users->current() ) );
556
557 // arguments have OR relationship
558 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
559 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
560 $this->assertEquals( 2, iterator_count( $users ) );
561 $users->rewind();
562 $this->assertTrue( $user->equals( $users->current() ) );
563 $users->next();
564 $this->assertTrue( $user2->equals( $users->current() ) );
565
566 // users are not duplicated
567 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
568 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
569 $this->assertEquals( 1, iterator_count( $users ) );
570 $users->rewind();
571 $this->assertTrue( $user->equals( $users->current() ) );
572 }
573
574 /**
575 * When a user is autoblocked a cookie is set with which to track them
576 * in case they log out and change IP addresses.
577 * @link https://phabricator.wikimedia.org/T5233
578 */
579 public function testAutoblockCookies() {
580 // Set up the bits of global configuration that we use.
581 $this->setMwGlobals( [
582 'wgCookieSetOnAutoblock' => true,
583 'wgCookiePrefix' => 'wmsitetitle',
584 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
585 ] );
586
587 // Unregister the hooks for proper unit testing
588 $this->mergeMwGlobalArrayValue( 'wgHooks', [
589 'PerformRetroactiveAutoblock' => []
590 ] );
591
592 // 1. Log in a test user, and block them.
593 $userBlocker = $this->getTestSysop()->getUser();
594 $user1tmp = $this->getTestUser()->getUser();
595 $request1 = new FauxRequest();
596 $request1->getSession()->setUser( $user1tmp );
597 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
598 $block = new Block( [
599 'enableAutoblock' => true,
600 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
601 ] );
602 $block->setBlocker( $this->getTestSysop()->getUser() );
603 $block->setTarget( $user1tmp );
604 $block->setBlocker( $userBlocker );
605 $res = $block->insert();
606 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
607 $user1 = User::newFromSession( $request1 );
608 $user1->mBlock = $block;
609 $user1->load();
610
611 // Confirm that the block has been applied as required.
612 $this->assertTrue( $user1->isLoggedIn() );
613 $this->assertTrue( $user1->isBlocked() );
614 $this->assertEquals( Block::TYPE_USER, $block->getType() );
615 $this->assertTrue( $block->isAutoblocking() );
616 $this->assertGreaterThanOrEqual( 1, $block->getId() );
617
618 // Test for the desired cookie name, value, and expiry.
619 $cookies = $request1->response()->getCookies();
620 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
621 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
622 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
623 $this->assertEquals( $block->getId(), $cookieValue );
624
625 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
626 $request2 = new FauxRequest();
627 $request2->setCookie( 'BlockID', $block->getCookieValue() );
628 $user2 = User::newFromSession( $request2 );
629 $user2->load();
630 $this->assertNotEquals( $user1->getId(), $user2->getId() );
631 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
632 $this->assertTrue( $user2->isAnon() );
633 $this->assertFalse( $user2->isLoggedIn() );
634 $this->assertTrue( $user2->isBlocked() );
635 // Non-strict type-check.
636 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
637 // Can't directly compare the objects because of member type differences.
638 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
639 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
640 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
641
642 // 3. Finally, set up a request as a new user, and the block should still be applied.
643 $user3tmp = $this->getTestUser()->getUser();
644 $request3 = new FauxRequest();
645 $request3->getSession()->setUser( $user3tmp );
646 $request3->setCookie( 'BlockID', $block->getId() );
647 $user3 = User::newFromSession( $request3 );
648 $user3->load();
649 $this->assertTrue( $user3->isLoggedIn() );
650 $this->assertTrue( $user3->isBlocked() );
651 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
652
653 // Clean up.
654 $block->delete();
655 }
656
657 /**
658 * Make sure that no cookie is set to track autoblocked users
659 * when $wgCookieSetOnAutoblock is false.
660 */
661 public function testAutoblockCookiesDisabled() {
662 // Set up the bits of global configuration that we use.
663 $this->setMwGlobals( [
664 'wgCookieSetOnAutoblock' => false,
665 'wgCookiePrefix' => 'wm_no_cookies',
666 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
667 ] );
668
669 // Unregister the hooks for proper unit testing
670 $this->mergeMwGlobalArrayValue( 'wgHooks', [
671 'PerformRetroactiveAutoblock' => []
672 ] );
673
674 // 1. Log in a test user, and block them.
675 $userBlocker = $this->getTestSysop()->getUser();
676 $testUser = $this->getTestUser()->getUser();
677 $request1 = new FauxRequest();
678 $request1->getSession()->setUser( $testUser );
679 $block = new Block( [ 'enableAutoblock' => true ] );
680 $block->setBlocker( $this->getTestSysop()->getUser() );
681 $block->setTarget( $testUser );
682 $block->setBlocker( $userBlocker );
683 $res = $block->insert();
684 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
685 $user = User::newFromSession( $request1 );
686 $user->mBlock = $block;
687 $user->load();
688
689 // 2. Test that the cookie IS NOT present.
690 $this->assertTrue( $user->isLoggedIn() );
691 $this->assertTrue( $user->isBlocked() );
692 $this->assertEquals( Block::TYPE_USER, $block->getType() );
693 $this->assertTrue( $block->isAutoblocking() );
694 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
695 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
696 $cookies = $request1->response()->getCookies();
697 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
698
699 // Clean up.
700 $block->delete();
701 }
702
703 /**
704 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
705 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
706 * the cookie's should change with it.
707 */
708 public function testAutoblockCookieInfiniteExpiry() {
709 $this->setMwGlobals( [
710 'wgCookieSetOnAutoblock' => true,
711 'wgCookiePrefix' => 'wm_infinite_block',
712 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
713 ] );
714
715 // Unregister the hooks for proper unit testing
716 $this->mergeMwGlobalArrayValue( 'wgHooks', [
717 'PerformRetroactiveAutoblock' => []
718 ] );
719
720 // 1. Log in a test user, and block them indefinitely.
721 $userBlocker = $this->getTestSysop()->getUser();
722 $user1Tmp = $this->getTestUser()->getUser();
723 $request1 = new FauxRequest();
724 $request1->getSession()->setUser( $user1Tmp );
725 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
726 $block->setBlocker( $this->getTestSysop()->getUser() );
727 $block->setTarget( $user1Tmp );
728 $block->setBlocker( $userBlocker );
729 $res = $block->insert();
730 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
731 $user1 = User::newFromSession( $request1 );
732 $user1->mBlock = $block;
733 $user1->load();
734
735 // 2. Test the cookie's expiry timestamp.
736 $this->assertTrue( $user1->isLoggedIn() );
737 $this->assertTrue( $user1->isBlocked() );
738 $this->assertEquals( Block::TYPE_USER, $block->getType() );
739 $this->assertTrue( $block->isAutoblocking() );
740 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
741 $cookies = $request1->response()->getCookies();
742 // Test the cookie's expiry to the nearest minute.
743 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
744 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
745 // Check for expiry dates in a 10-second window, to account for slow testing.
746 $this->assertEquals(
747 $expOneDay,
748 $cookies['wm_infinite_blockBlockID']['expire'],
749 'Expiry date',
750 5.0
751 );
752
753 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
754 $newExpiry = wfTimestamp() + 2 * 60 * 60;
755 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
756 $block->update();
757 $user2tmp = $this->getTestUser()->getUser();
758 $request2 = new FauxRequest();
759 $request2->getSession()->setUser( $user2tmp );
760 $user2 = User::newFromSession( $request2 );
761 $user2->mBlock = $block;
762 $user2->load();
763 $cookies = $request2->response()->getCookies();
764 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
765 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
766
767 // Clean up.
768 $block->delete();
769 }
770
771 public function testSoftBlockRanges() {
772 global $wgUser;
773
774 $this->setMwGlobals( [
775 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
776 'wgUser' => null,
777 ] );
778
779 // IP isn't in $wgSoftBlockRanges
780 $request = new FauxRequest();
781 $request->setIP( '192.168.0.1' );
782 $wgUser = User::newFromSession( $request );
783 $this->assertNull( $wgUser->getBlock() );
784
785 // IP is in $wgSoftBlockRanges
786 $request = new FauxRequest();
787 $request->setIP( '10.20.30.40' );
788 $wgUser = User::newFromSession( $request );
789 $block = $wgUser->getBlock();
790 $this->assertInstanceOf( Block::class, $block );
791 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
792
793 // Make sure the block is really soft
794 $request->getSession()->setUser( $this->getTestUser()->getUser() );
795 $wgUser = User::newFromSession( $request );
796 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
797 $this->assertNull( $wgUser->getBlock() );
798 }
799
800 /**
801 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
802 */
803 public function testAutoblockCookieInauthentic() {
804 // Set up the bits of global configuration that we use.
805 $this->setMwGlobals( [
806 'wgCookieSetOnAutoblock' => true,
807 'wgCookiePrefix' => 'wmsitetitle',
808 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
809 ] );
810
811 // Unregister the hooks for proper unit testing
812 $this->mergeMwGlobalArrayValue( 'wgHooks', [
813 'PerformRetroactiveAutoblock' => []
814 ] );
815
816 // 1. Log in a blocked test user.
817 $userBlocker = $this->getTestSysop()->getUser();
818 $user1tmp = $this->getTestUser()->getUser();
819 $request1 = new FauxRequest();
820 $request1->getSession()->setUser( $user1tmp );
821 $block = new Block( [ 'enableAutoblock' => true ] );
822 $block->setBlocker( $this->getTestSysop()->getUser() );
823 $block->setTarget( $user1tmp );
824 $block->setBlocker( $userBlocker );
825 $res = $block->insert();
826 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
827 $user1 = User::newFromSession( $request1 );
828 $user1->mBlock = $block;
829 $user1->load();
830
831 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
832 // user not blocked.
833 $request2 = new FauxRequest();
834 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
835 $user2 = User::newFromSession( $request2 );
836 $user2->load();
837 $this->assertTrue( $user2->isAnon() );
838 $this->assertFalse( $user2->isLoggedIn() );
839 $this->assertFalse( $user2->isBlocked() );
840
841 // Clean up.
842 $block->delete();
843 }
844
845 /**
846 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
847 * This checks that a non-authenticated cookie still works.
848 */
849 public function testAutoblockCookieNoSecretKey() {
850 // Set up the bits of global configuration that we use.
851 $this->setMwGlobals( [
852 'wgCookieSetOnAutoblock' => true,
853 'wgCookiePrefix' => 'wmsitetitle',
854 'wgSecretKey' => null,
855 ] );
856
857 // Unregister the hooks for proper unit testing
858 $this->mergeMwGlobalArrayValue( 'wgHooks', [
859 'PerformRetroactiveAutoblock' => []
860 ] );
861
862 // 1. Log in a blocked test user.
863 $userBlocker = $this->getTestSysop()->getUser();
864 $user1tmp = $this->getTestUser()->getUser();
865 $request1 = new FauxRequest();
866 $request1->getSession()->setUser( $user1tmp );
867 $block = new Block( [ 'enableAutoblock' => true ] );
868 $block->setBlocker( $this->getTestSysop()->getUser() );
869 $block->setTarget( $user1tmp );
870 $block->setBlocker( $userBlocker );
871 $res = $block->insert();
872 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
873 $user1 = User::newFromSession( $request1 );
874 $user1->mBlock = $block;
875 $user1->load();
876 $this->assertTrue( $user1->isBlocked() );
877
878 // 2. Create a new request, set the cookie to just the block ID, and the user should
879 // still get blocked when they log in again.
880 $request2 = new FauxRequest();
881 $request2->setCookie( 'BlockID', $block->getId() );
882 $user2 = User::newFromSession( $request2 );
883 $user2->load();
884 $this->assertNotEquals( $user1->getId(), $user2->getId() );
885 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
886 $this->assertTrue( $user2->isAnon() );
887 $this->assertFalse( $user2->isLoggedIn() );
888 $this->assertTrue( $user2->isBlocked() );
889 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
890
891 // Clean up.
892 $block->delete();
893 }
894
895 /**
896 * @covers User::isPingLimitable
897 */
898 public function testIsPingLimitable() {
899 $request = new FauxRequest();
900 $request->setIP( '1.2.3.4' );
901 $user = User::newFromSession( $request );
902
903 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
904 $this->assertTrue( $user->isPingLimitable() );
905
906 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
907 $this->assertFalse( $user->isPingLimitable() );
908
909 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
910 $this->assertFalse( $user->isPingLimitable() );
911
912 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
913 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
914 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
915 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
916 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
917 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
918 }
919
920 public function provideExperienceLevel() {
921 return [
922 [ 2, 2, 'newcomer' ],
923 [ 12, 3, 'newcomer' ],
924 [ 8, 5, 'newcomer' ],
925 [ 15, 10, 'learner' ],
926 [ 450, 20, 'learner' ],
927 [ 460, 33, 'learner' ],
928 [ 525, 28, 'learner' ],
929 [ 538, 33, 'experienced' ],
930 ];
931 }
932
933 /**
934 * @covers User::getExperienceLevel
935 * @dataProvider provideExperienceLevel
936 */
937 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
938 $this->setMwGlobals( [
939 'wgLearnerEdits' => 10,
940 'wgLearnerMemberSince' => 4,
941 'wgExperiencedUserEdits' => 500,
942 'wgExperiencedUserMemberSince' => 30,
943 ] );
944
945 $db = wfGetDB( DB_MASTER );
946 $userQuery = User::getQueryInfo();
947 $row = $db->selectRow(
948 $userQuery['tables'],
949 $userQuery['fields'],
950 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
951 __METHOD__,
952 [],
953 $userQuery['joins']
954 );
955 $row->user_editcount = $editCount;
956 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
957 $user = User::newFromRow( $row );
958
959 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
960 }
961
962 /**
963 * @covers User::getExperienceLevel
964 */
965 public function testExperienceLevelAnon() {
966 $user = User::newFromName( '10.11.12.13', false );
967
968 $this->assertFalse( $user->getExperienceLevel() );
969 }
970
971 public static function provideIsLocallBlockedProxy() {
972 return [
973 [ '1.2.3.4', '1.2.3.4' ],
974 [ '1.2.3.4', '1.2.3.0/16' ],
975 ];
976 }
977
978 /**
979 * @dataProvider provideIsLocallBlockedProxy
980 * @covers User::isLocallyBlockedProxy
981 */
982 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
983 $this->setMwGlobals(
984 'wgProxyList', []
985 );
986 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
987
988 $this->setMwGlobals(
989 'wgProxyList',
990 [
991 $blockListEntry
992 ]
993 );
994 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
995
996 $this->setMwGlobals(
997 'wgProxyList',
998 [
999 'test' => $blockListEntry
1000 ]
1001 );
1002 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1003
1004 $this->hideDeprecated(
1005 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1006 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1007 );
1008 $this->setMwGlobals(
1009 'wgProxyList',
1010 [
1011 $blockListEntry => 'test'
1012 ]
1013 );
1014 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1015 }
1016
1017 public function testActorId() {
1018 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1019 $this->hideDeprecated( 'User::selectFields' );
1020
1021 // Newly-created user has an actor ID
1022 $user = User::createNew( 'UserTestActorId1' );
1023 $id = $user->getId();
1024 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1025
1026 $user = User::newFromName( 'UserTestActorId2' );
1027 $user->addToDatabase();
1028 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1029
1030 $user = User::newFromName( 'UserTestActorId1' );
1031 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1032
1033 $user = User::newFromId( $id );
1034 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1035
1036 $user2 = User::newFromActorId( $user->getActorId() );
1037 $this->assertEquals( $user->getId(), $user2->getId(),
1038 'User::newFromActorId works for an existing user' );
1039
1040 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1041 $user = User::newFromRow( $row );
1042 $this->assertTrue( $user->getActorId() > 0,
1043 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1044
1045 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1046 User::purge( $domain, $id );
1047 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1048 ObjectCache::getMainWANInstance()->clearProcessCache();
1049
1050 $user = User::newFromId( $id );
1051 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1052 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1053
1054 $user->setName( 'UserTestActorId4-renamed' );
1055 $user->saveSettings();
1056 $this->assertEquals(
1057 $user->getName(),
1058 $this->db->selectField(
1059 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1060 ),
1061 'User::saveSettings updates actor table for name change'
1062 );
1063
1064 // For sanity
1065 $ip = '192.168.12.34';
1066 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1067
1068 $user = User::newFromName( $ip, false );
1069 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1070 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1071 'Actor ID can be created for an anonymous user' );
1072
1073 $user = User::newFromName( $ip, false );
1074 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1075 $user2 = User::newFromActorId( $user->getActorId() );
1076 $this->assertEquals( $user->getName(), $user2->getName(),
1077 'User::newFromActorId works for an anonymous user' );
1078 }
1079
1080 public function testNewFromAnyId() {
1081 // Registered user
1082 $user = $this->getTestUser()->getUser();
1083 for ( $i = 1; $i <= 7; $i++ ) {
1084 $test = User::newFromAnyId(
1085 ( $i & 1 ) ? $user->getId() : null,
1086 ( $i & 2 ) ? $user->getName() : null,
1087 ( $i & 4 ) ? $user->getActorId() : null
1088 );
1089 $this->assertSame( $user->getId(), $test->getId() );
1090 $this->assertSame( $user->getName(), $test->getName() );
1091 $this->assertSame( $user->getActorId(), $test->getActorId() );
1092 }
1093
1094 // Anon user. Can't load by only user ID when that's 0.
1095 $user = User::newFromName( '192.168.12.34', false );
1096 $user->getActorId( $this->db ); // Make sure an actor ID exists
1097
1098 $test = User::newFromAnyId( null, '192.168.12.34', null );
1099 $this->assertSame( $user->getId(), $test->getId() );
1100 $this->assertSame( $user->getName(), $test->getName() );
1101 $this->assertSame( $user->getActorId(), $test->getActorId() );
1102 $test = User::newFromAnyId( null, null, $user->getActorId() );
1103 $this->assertSame( $user->getId(), $test->getId() );
1104 $this->assertSame( $user->getName(), $test->getName() );
1105 $this->assertSame( $user->getActorId(), $test->getActorId() );
1106
1107 // Bogus data should still "work" as long as nothing triggers a ->load(),
1108 // and accessing the specified data shouldn't do that.
1109 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1110 $this->assertSame( 123456, $test->getId() );
1111 $this->assertSame( 'Bogus', $test->getName() );
1112 $this->assertSame( 654321, $test->getActorId() );
1113
1114 // Exceptional cases
1115 try {
1116 User::newFromAnyId( null, null, null );
1117 $this->fail( 'Expected exception not thrown' );
1118 } catch ( InvalidArgumentException $ex ) {
1119 }
1120 try {
1121 User::newFromAnyId( 0, null, 0 );
1122 $this->fail( 'Expected exception not thrown' );
1123 } catch ( InvalidArgumentException $ex ) {
1124 }
1125 }
1126
1127 /**
1128 * @covers User::newFromIdentity
1129 */
1130 public function testNewFromIdentity() {
1131 // Registered user
1132 $user = $this->getTestUser()->getUser();
1133
1134 $this->assertSame( $user, User::newFromIdentity( $user ) );
1135
1136 // ID only
1137 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1138 $result = User::newFromIdentity( $identity );
1139 $this->assertInstanceOf( User::class, $result );
1140 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1141 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1142 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1143
1144 // Name only
1145 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1146 $result = User::newFromIdentity( $identity );
1147 $this->assertInstanceOf( User::class, $result );
1148 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1149 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1150 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1151
1152 // Actor only
1153 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1154 $result = User::newFromIdentity( $identity );
1155 $this->assertInstanceOf( User::class, $result );
1156 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1157 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1158 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1159 }
1160
1161 /**
1162 * @covers User::getBlockedStatus
1163 * @covers User::getBlock
1164 * @covers User::blockedBy
1165 * @covers User::blockedFor
1166 * @covers User::isHidden
1167 * @covers User::isBlockedFrom
1168 */
1169 public function testBlockInstanceCache() {
1170 // First, check the user isn't blocked
1171 $user = $this->getMutableTestUser()->getUser();
1172 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1173 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1174 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1175 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1176 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1177 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1178
1179 // Block the user
1180 $blocker = $this->getTestSysop()->getUser();
1181 $block = new Block( [
1182 'hideName' => true,
1183 'allowUsertalk' => false,
1184 'reason' => 'Because',
1185 ] );
1186 $block->setTarget( $user );
1187 $block->setBlocker( $blocker );
1188 $res = $block->insert();
1189 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1190
1191 // Clear cache and confirm it loaded the block properly
1192 $user->clearInstanceCache();
1193 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1194 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1195 $this->assertSame( 'Because', $user->blockedFor() );
1196 $this->assertTrue( (bool)$user->isHidden() );
1197 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1198
1199 // Unblock
1200 $block->delete();
1201
1202 // Clear cache and confirm it loaded the not-blocked properly
1203 $user->clearInstanceCache();
1204 $this->assertNull( $user->getBlock( false ) );
1205 $this->assertSame( '', $user->blockedBy() );
1206 $this->assertSame( '', $user->blockedFor() );
1207 $this->assertFalse( (bool)$user->isHidden() );
1208 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1209 }
1210
1211 /**
1212 * Block cookie should be set for IP Blocks if
1213 * wgCookieSetOnIpBlock is set to true
1214 */
1215 public function testIpBlockCookieSet() {
1216 $this->setMwGlobals( [
1217 'wgCookieSetOnIpBlock' => true,
1218 'wgCookiePrefix' => 'wiki',
1219 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1220 ] );
1221
1222 // setup block
1223 $block = new Block( [
1224 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1225 ] );
1226 $block->setTarget( '1.2.3.4' );
1227 $block->setBlocker( $this->getTestSysop()->getUser() );
1228 $block->insert();
1229
1230 // setup request
1231 $request = new FauxRequest();
1232 $request->setIP( '1.2.3.4' );
1233
1234 // get user
1235 $user = User::newFromSession( $request );
1236 $user->trackBlockWithCookie();
1237
1238 // test cookie was set
1239 $cookies = $request->response()->getCookies();
1240 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1241
1242 // clean up
1243 $block->delete();
1244 }
1245
1246 /**
1247 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1248 * is disabled
1249 */
1250 public function testIpBlockCookieNotSet() {
1251 $this->setMwGlobals( [
1252 'wgCookieSetOnIpBlock' => false,
1253 'wgCookiePrefix' => 'wiki',
1254 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1255 ] );
1256
1257 // setup block
1258 $block = new Block( [
1259 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1260 ] );
1261 $block->setTarget( '1.2.3.4' );
1262 $block->setBlocker( $this->getTestSysop()->getUser() );
1263 $block->insert();
1264
1265 // setup request
1266 $request = new FauxRequest();
1267 $request->setIP( '1.2.3.4' );
1268
1269 // get user
1270 $user = User::newFromSession( $request );
1271 $user->trackBlockWithCookie();
1272
1273 // test cookie was not set
1274 $cookies = $request->response()->getCookies();
1275 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1276
1277 // clean up
1278 $block->delete();
1279 }
1280
1281 /**
1282 * When an ip user is blocked and then they log in, cookie block
1283 * should be invalid and the cookie removed.
1284 */
1285 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1286 $this->setMwGlobals( [
1287 'wgAutoblockExpiry' => 8000,
1288 'wgCookieSetOnIpBlock' => true,
1289 'wgCookiePrefix' => 'wiki',
1290 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1291 ] );
1292
1293 // setup block
1294 $block = new Block( [
1295 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1296 ] );
1297 $block->setTarget( '1.2.3.4' );
1298 $block->setBlocker( $this->getTestSysop()->getUser() );
1299 $block->insert();
1300
1301 // setup request
1302 $request = new FauxRequest();
1303 $request->setIP( '1.2.3.4' );
1304 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1305 $request->setCookie( 'BlockID', $block->getCookieValue() );
1306
1307 // setup user
1308 $user = User::newFromSession( $request );
1309
1310 // logged in users should be inmune to cookie block of type ip/range
1311 $this->assertFalse( $user->isBlocked() );
1312
1313 // cookie is being cleared
1314 $cookies = $request->response()->getCookies();
1315 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1316
1317 // clean up
1318 $block->delete();
1319 }
1320 }