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