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