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