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