Merge "objectcache: Fixes WinCache increment losing TTL."
[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 * @covers User::trackBlockWithCookie
587 */
588 public function testAutoblockCookies() {
589 // Set up the bits of global configuration that we use.
590 $this->setMwGlobals( [
591 'wgCookieSetOnAutoblock' => true,
592 'wgCookiePrefix' => 'wmsitetitle',
593 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
594 ] );
595
596 // Unregister the hooks for proper unit testing
597 $this->mergeMwGlobalArrayValue( 'wgHooks', [
598 'PerformRetroactiveAutoblock' => []
599 ] );
600
601 // 1. Log in a test user, and block them.
602 $userBlocker = $this->getTestSysop()->getUser();
603 $user1tmp = $this->getTestUser()->getUser();
604 $request1 = new FauxRequest();
605 $request1->getSession()->setUser( $user1tmp );
606 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
607 $block = new Block( [
608 'enableAutoblock' => true,
609 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
610 ] );
611 $block->setBlocker( $this->getTestSysop()->getUser() );
612 $block->setTarget( $user1tmp );
613 $block->setBlocker( $userBlocker );
614 $res = $block->insert();
615 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
616 $user1 = User::newFromSession( $request1 );
617 $user1->mBlock = $block;
618 $user1->load();
619
620 // Confirm that the block has been applied as required.
621 $this->assertTrue( $user1->isLoggedIn() );
622 $this->assertTrue( $user1->isBlocked() );
623 $this->assertEquals( Block::TYPE_USER, $block->getType() );
624 $this->assertTrue( $block->isAutoblocking() );
625 $this->assertGreaterThanOrEqual( 1, $block->getId() );
626
627 // Test for the desired cookie name, value, and expiry.
628 $cookies = $request1->response()->getCookies();
629 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
630 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
631 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
632 $this->assertEquals( $block->getId(), $cookieValue );
633
634 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
635 $request2 = new FauxRequest();
636 $request2->setCookie( 'BlockID', $block->getCookieValue() );
637 $user2 = User::newFromSession( $request2 );
638 $user2->load();
639 $this->assertNotEquals( $user1->getId(), $user2->getId() );
640 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
641 $this->assertTrue( $user2->isAnon() );
642 $this->assertFalse( $user2->isLoggedIn() );
643 $this->assertTrue( $user2->isBlocked() );
644 // Non-strict type-check.
645 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
646 // Can't directly compare the objects because of member type differences.
647 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
648 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
649 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
650
651 // 3. Finally, set up a request as a new user, and the block should still be applied.
652 $user3tmp = $this->getTestUser()->getUser();
653 $request3 = new FauxRequest();
654 $request3->getSession()->setUser( $user3tmp );
655 $request3->setCookie( 'BlockID', $block->getId() );
656 $user3 = User::newFromSession( $request3 );
657 $user3->load();
658 $this->assertTrue( $user3->isLoggedIn() );
659 $this->assertTrue( $user3->isBlocked() );
660 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
661
662 // Clean up.
663 $block->delete();
664 }
665
666 /**
667 * Make sure that no cookie is set to track autoblocked users
668 * when $wgCookieSetOnAutoblock is false.
669 * @covers User::trackBlockWithCookie
670 */
671 public function testAutoblockCookiesDisabled() {
672 // Set up the bits of global configuration that we use.
673 $this->setMwGlobals( [
674 'wgCookieSetOnAutoblock' => false,
675 'wgCookiePrefix' => 'wm_no_cookies',
676 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
677 ] );
678
679 // Unregister the hooks for proper unit testing
680 $this->mergeMwGlobalArrayValue( 'wgHooks', [
681 'PerformRetroactiveAutoblock' => []
682 ] );
683
684 // 1. Log in a test user, and block them.
685 $userBlocker = $this->getTestSysop()->getUser();
686 $testUser = $this->getTestUser()->getUser();
687 $request1 = new FauxRequest();
688 $request1->getSession()->setUser( $testUser );
689 $block = new Block( [ 'enableAutoblock' => true ] );
690 $block->setBlocker( $this->getTestSysop()->getUser() );
691 $block->setTarget( $testUser );
692 $block->setBlocker( $userBlocker );
693 $res = $block->insert();
694 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
695 $user = User::newFromSession( $request1 );
696 $user->mBlock = $block;
697 $user->load();
698
699 // 2. Test that the cookie IS NOT present.
700 $this->assertTrue( $user->isLoggedIn() );
701 $this->assertTrue( $user->isBlocked() );
702 $this->assertEquals( Block::TYPE_USER, $block->getType() );
703 $this->assertTrue( $block->isAutoblocking() );
704 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
705 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
706 $cookies = $request1->response()->getCookies();
707 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
708
709 // Clean up.
710 $block->delete();
711 }
712
713 /**
714 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
715 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
716 * the cookie's should change with it.
717 * @covers User::trackBlockWithCookie
718 */
719 public function testAutoblockCookieInfiniteExpiry() {
720 $this->setMwGlobals( [
721 'wgCookieSetOnAutoblock' => true,
722 'wgCookiePrefix' => 'wm_infinite_block',
723 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
724 ] );
725
726 // Unregister the hooks for proper unit testing
727 $this->mergeMwGlobalArrayValue( 'wgHooks', [
728 'PerformRetroactiveAutoblock' => []
729 ] );
730
731 // 1. Log in a test user, and block them indefinitely.
732 $userBlocker = $this->getTestSysop()->getUser();
733 $user1Tmp = $this->getTestUser()->getUser();
734 $request1 = new FauxRequest();
735 $request1->getSession()->setUser( $user1Tmp );
736 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
737 $block->setBlocker( $this->getTestSysop()->getUser() );
738 $block->setTarget( $user1Tmp );
739 $block->setBlocker( $userBlocker );
740 $res = $block->insert();
741 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
742 $user1 = User::newFromSession( $request1 );
743 $user1->mBlock = $block;
744 $user1->load();
745
746 // 2. Test the cookie's expiry timestamp.
747 $this->assertTrue( $user1->isLoggedIn() );
748 $this->assertTrue( $user1->isBlocked() );
749 $this->assertEquals( Block::TYPE_USER, $block->getType() );
750 $this->assertTrue( $block->isAutoblocking() );
751 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
752 $cookies = $request1->response()->getCookies();
753 // Test the cookie's expiry to the nearest minute.
754 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
755 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
756 // Check for expiry dates in a 10-second window, to account for slow testing.
757 $this->assertEquals(
758 $expOneDay,
759 $cookies['wm_infinite_blockBlockID']['expire'],
760 'Expiry date',
761 5.0
762 );
763
764 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
765 $newExpiry = wfTimestamp() + 2 * 60 * 60;
766 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
767 $block->update();
768 $user2tmp = $this->getTestUser()->getUser();
769 $request2 = new FauxRequest();
770 $request2->getSession()->setUser( $user2tmp );
771 $user2 = User::newFromSession( $request2 );
772 $user2->mBlock = $block;
773 $user2->load();
774 $cookies = $request2->response()->getCookies();
775 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
776 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
777
778 // Clean up.
779 $block->delete();
780 }
781
782 /**
783 * @covers User::getBlockedStatus
784 */
785 public function testSoftBlockRanges() {
786 global $wgUser;
787
788 $this->setMwGlobals( [
789 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
790 'wgUser' => null,
791 ] );
792
793 // IP isn't in $wgSoftBlockRanges
794 $request = new FauxRequest();
795 $request->setIP( '192.168.0.1' );
796 $wgUser = User::newFromSession( $request );
797 $this->assertNull( $wgUser->getBlock() );
798
799 // IP is in $wgSoftBlockRanges
800 $request = new FauxRequest();
801 $request->setIP( '10.20.30.40' );
802 $wgUser = User::newFromSession( $request );
803 $block = $wgUser->getBlock();
804 $this->assertInstanceOf( Block::class, $block );
805 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
806
807 // Make sure the block is really soft
808 $request->getSession()->setUser( $this->getTestUser()->getUser() );
809 $wgUser = User::newFromSession( $request );
810 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
811 $this->assertNull( $wgUser->getBlock() );
812 }
813
814 /**
815 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
816 * @covers User::trackBlockWithCookie
817 */
818 public function testAutoblockCookieInauthentic() {
819 // Set up the bits of global configuration that we use.
820 $this->setMwGlobals( [
821 'wgCookieSetOnAutoblock' => true,
822 'wgCookiePrefix' => 'wmsitetitle',
823 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
824 ] );
825
826 // Unregister the hooks for proper unit testing
827 $this->mergeMwGlobalArrayValue( 'wgHooks', [
828 'PerformRetroactiveAutoblock' => []
829 ] );
830
831 // 1. Log in a blocked test user.
832 $userBlocker = $this->getTestSysop()->getUser();
833 $user1tmp = $this->getTestUser()->getUser();
834 $request1 = new FauxRequest();
835 $request1->getSession()->setUser( $user1tmp );
836 $block = new Block( [ 'enableAutoblock' => true ] );
837 $block->setBlocker( $this->getTestSysop()->getUser() );
838 $block->setTarget( $user1tmp );
839 $block->setBlocker( $userBlocker );
840 $res = $block->insert();
841 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
842 $user1 = User::newFromSession( $request1 );
843 $user1->mBlock = $block;
844 $user1->load();
845
846 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
847 // user not blocked.
848 $request2 = new FauxRequest();
849 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
850 $user2 = User::newFromSession( $request2 );
851 $user2->load();
852 $this->assertTrue( $user2->isAnon() );
853 $this->assertFalse( $user2->isLoggedIn() );
854 $this->assertFalse( $user2->isBlocked() );
855
856 // Clean up.
857 $block->delete();
858 }
859
860 /**
861 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
862 * This checks that a non-authenticated cookie still works.
863 * @covers User::trackBlockWithCookie
864 */
865 public function testAutoblockCookieNoSecretKey() {
866 // Set up the bits of global configuration that we use.
867 $this->setMwGlobals( [
868 'wgCookieSetOnAutoblock' => true,
869 'wgCookiePrefix' => 'wmsitetitle',
870 'wgSecretKey' => null,
871 ] );
872
873 // Unregister the hooks for proper unit testing
874 $this->mergeMwGlobalArrayValue( 'wgHooks', [
875 'PerformRetroactiveAutoblock' => []
876 ] );
877
878 // 1. Log in a blocked test user.
879 $userBlocker = $this->getTestSysop()->getUser();
880 $user1tmp = $this->getTestUser()->getUser();
881 $request1 = new FauxRequest();
882 $request1->getSession()->setUser( $user1tmp );
883 $block = new Block( [ 'enableAutoblock' => true ] );
884 $block->setBlocker( $this->getTestSysop()->getUser() );
885 $block->setTarget( $user1tmp );
886 $block->setBlocker( $userBlocker );
887 $res = $block->insert();
888 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
889 $user1 = User::newFromSession( $request1 );
890 $user1->mBlock = $block;
891 $user1->load();
892 $this->assertTrue( $user1->isBlocked() );
893
894 // 2. Create a new request, set the cookie to just the block ID, and the user should
895 // still get blocked when they log in again.
896 $request2 = new FauxRequest();
897 $request2->setCookie( 'BlockID', $block->getId() );
898 $user2 = User::newFromSession( $request2 );
899 $user2->load();
900 $this->assertNotEquals( $user1->getId(), $user2->getId() );
901 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
902 $this->assertTrue( $user2->isAnon() );
903 $this->assertFalse( $user2->isLoggedIn() );
904 $this->assertTrue( $user2->isBlocked() );
905 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
906
907 // Clean up.
908 $block->delete();
909 }
910
911 /**
912 * @covers User::isPingLimitable
913 */
914 public function testIsPingLimitable() {
915 $request = new FauxRequest();
916 $request->setIP( '1.2.3.4' );
917 $user = User::newFromSession( $request );
918
919 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
920 $this->assertTrue( $user->isPingLimitable() );
921
922 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
923 $this->assertFalse( $user->isPingLimitable() );
924
925 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
926 $this->assertFalse( $user->isPingLimitable() );
927
928 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
929 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
930 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
931 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
932 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
933 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
934 }
935
936 public function provideExperienceLevel() {
937 return [
938 [ 2, 2, 'newcomer' ],
939 [ 12, 3, 'newcomer' ],
940 [ 8, 5, 'newcomer' ],
941 [ 15, 10, 'learner' ],
942 [ 450, 20, 'learner' ],
943 [ 460, 33, 'learner' ],
944 [ 525, 28, 'learner' ],
945 [ 538, 33, 'experienced' ],
946 ];
947 }
948
949 /**
950 * @covers User::getExperienceLevel
951 * @dataProvider provideExperienceLevel
952 */
953 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
954 $this->setMwGlobals( [
955 'wgLearnerEdits' => 10,
956 'wgLearnerMemberSince' => 4,
957 'wgExperiencedUserEdits' => 500,
958 'wgExperiencedUserMemberSince' => 30,
959 ] );
960
961 $db = wfGetDB( DB_MASTER );
962 $userQuery = User::getQueryInfo();
963 $row = $db->selectRow(
964 $userQuery['tables'],
965 $userQuery['fields'],
966 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
967 __METHOD__,
968 [],
969 $userQuery['joins']
970 );
971 $row->user_editcount = $editCount;
972 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
973 $user = User::newFromRow( $row );
974
975 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
976 }
977
978 /**
979 * @covers User::getExperienceLevel
980 */
981 public function testExperienceLevelAnon() {
982 $user = User::newFromName( '10.11.12.13', false );
983
984 $this->assertFalse( $user->getExperienceLevel() );
985 }
986
987 public static function provideIsLocallBlockedProxy() {
988 return [
989 [ '1.2.3.4', '1.2.3.4' ],
990 [ '1.2.3.4', '1.2.3.0/16' ],
991 ];
992 }
993
994 /**
995 * @dataProvider provideIsLocallBlockedProxy
996 * @covers User::isLocallyBlockedProxy
997 */
998 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
999 $this->setMwGlobals(
1000 'wgProxyList', []
1001 );
1002 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
1003
1004 $this->setMwGlobals(
1005 'wgProxyList',
1006 [
1007 $blockListEntry
1008 ]
1009 );
1010 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1011
1012 $this->setMwGlobals(
1013 'wgProxyList',
1014 [
1015 'test' => $blockListEntry
1016 ]
1017 );
1018 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1019
1020 $this->hideDeprecated(
1021 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1022 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1023 );
1024 $this->setMwGlobals(
1025 'wgProxyList',
1026 [
1027 $blockListEntry => 'test'
1028 ]
1029 );
1030 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1031 }
1032
1033 /**
1034 * @covers User::newFromActorId
1035 */
1036 public function testActorId() {
1037 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1038 $this->hideDeprecated( 'User::selectFields' );
1039
1040 // Newly-created user has an actor ID
1041 $user = User::createNew( 'UserTestActorId1' );
1042 $id = $user->getId();
1043 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1044
1045 $user = User::newFromName( 'UserTestActorId2' );
1046 $user->addToDatabase();
1047 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1048
1049 $user = User::newFromName( 'UserTestActorId1' );
1050 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1051
1052 $user = User::newFromId( $id );
1053 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1054
1055 $user2 = User::newFromActorId( $user->getActorId() );
1056 $this->assertEquals( $user->getId(), $user2->getId(),
1057 'User::newFromActorId works for an existing user' );
1058
1059 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1060 $user = User::newFromRow( $row );
1061 $this->assertTrue( $user->getActorId() > 0,
1062 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1063
1064 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1065 User::purge( $domain, $id );
1066 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1067 ObjectCache::getMainWANInstance()->clearProcessCache();
1068
1069 $user = User::newFromId( $id );
1070 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1071 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1072
1073 $user->setName( 'UserTestActorId4-renamed' );
1074 $user->saveSettings();
1075 $this->assertEquals(
1076 $user->getName(),
1077 $this->db->selectField(
1078 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1079 ),
1080 'User::saveSettings updates actor table for name change'
1081 );
1082
1083 // For sanity
1084 $ip = '192.168.12.34';
1085 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1086
1087 $user = User::newFromName( $ip, false );
1088 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1089 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1090 'Actor ID can be created for an anonymous user' );
1091
1092 $user = User::newFromName( $ip, false );
1093 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1094 $user2 = User::newFromActorId( $user->getActorId() );
1095 $this->assertEquals( $user->getName(), $user2->getName(),
1096 'User::newFromActorId works for an anonymous user' );
1097 }
1098
1099 /**
1100 * @covers User::newFromAnyId
1101 */
1102 public function testNewFromAnyId() {
1103 // Registered user
1104 $user = $this->getTestUser()->getUser();
1105 for ( $i = 1; $i <= 7; $i++ ) {
1106 $test = User::newFromAnyId(
1107 ( $i & 1 ) ? $user->getId() : null,
1108 ( $i & 2 ) ? $user->getName() : null,
1109 ( $i & 4 ) ? $user->getActorId() : null
1110 );
1111 $this->assertSame( $user->getId(), $test->getId() );
1112 $this->assertSame( $user->getName(), $test->getName() );
1113 $this->assertSame( $user->getActorId(), $test->getActorId() );
1114 }
1115
1116 // Anon user. Can't load by only user ID when that's 0.
1117 $user = User::newFromName( '192.168.12.34', false );
1118 $user->getActorId( $this->db ); // Make sure an actor ID exists
1119
1120 $test = User::newFromAnyId( null, '192.168.12.34', null );
1121 $this->assertSame( $user->getId(), $test->getId() );
1122 $this->assertSame( $user->getName(), $test->getName() );
1123 $this->assertSame( $user->getActorId(), $test->getActorId() );
1124 $test = User::newFromAnyId( null, null, $user->getActorId() );
1125 $this->assertSame( $user->getId(), $test->getId() );
1126 $this->assertSame( $user->getName(), $test->getName() );
1127 $this->assertSame( $user->getActorId(), $test->getActorId() );
1128
1129 // Bogus data should still "work" as long as nothing triggers a ->load(),
1130 // and accessing the specified data shouldn't do that.
1131 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1132 $this->assertSame( 123456, $test->getId() );
1133 $this->assertSame( 'Bogus', $test->getName() );
1134 $this->assertSame( 654321, $test->getActorId() );
1135
1136 // Exceptional cases
1137 try {
1138 User::newFromAnyId( null, null, null );
1139 $this->fail( 'Expected exception not thrown' );
1140 } catch ( InvalidArgumentException $ex ) {
1141 }
1142 try {
1143 User::newFromAnyId( 0, null, 0 );
1144 $this->fail( 'Expected exception not thrown' );
1145 } catch ( InvalidArgumentException $ex ) {
1146 }
1147 }
1148
1149 /**
1150 * @covers User::newFromIdentity
1151 */
1152 public function testNewFromIdentity() {
1153 // Registered user
1154 $user = $this->getTestUser()->getUser();
1155
1156 $this->assertSame( $user, User::newFromIdentity( $user ) );
1157
1158 // ID only
1159 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1160 $result = User::newFromIdentity( $identity );
1161 $this->assertInstanceOf( User::class, $result );
1162 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1163 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1164 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1165
1166 // Name only
1167 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1168 $result = User::newFromIdentity( $identity );
1169 $this->assertInstanceOf( User::class, $result );
1170 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1171 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1172 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1173
1174 // Actor only
1175 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1176 $result = User::newFromIdentity( $identity );
1177 $this->assertInstanceOf( User::class, $result );
1178 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1179 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1180 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1181 }
1182
1183 /**
1184 * @covers User::getBlockedStatus
1185 * @covers User::getBlock
1186 * @covers User::blockedBy
1187 * @covers User::blockedFor
1188 * @covers User::isHidden
1189 * @covers User::isBlockedFrom
1190 */
1191 public function testBlockInstanceCache() {
1192 // First, check the user isn't blocked
1193 $user = $this->getMutableTestUser()->getUser();
1194 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1195 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1196 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1197 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1198 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1199 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1200
1201 // Block the user
1202 $blocker = $this->getTestSysop()->getUser();
1203 $block = new Block( [
1204 'hideName' => true,
1205 'allowUsertalk' => false,
1206 'reason' => 'Because',
1207 ] );
1208 $block->setTarget( $user );
1209 $block->setBlocker( $blocker );
1210 $res = $block->insert();
1211 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1212
1213 // Clear cache and confirm it loaded the block properly
1214 $user->clearInstanceCache();
1215 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1216 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1217 $this->assertSame( 'Because', $user->blockedFor() );
1218 $this->assertTrue( (bool)$user->isHidden() );
1219 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1220
1221 // Unblock
1222 $block->delete();
1223
1224 // Clear cache and confirm it loaded the not-blocked properly
1225 $user->clearInstanceCache();
1226 $this->assertNull( $user->getBlock( false ) );
1227 $this->assertSame( '', $user->blockedBy() );
1228 $this->assertSame( '', $user->blockedFor() );
1229 $this->assertFalse( (bool)$user->isHidden() );
1230 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1231 }
1232
1233 /**
1234 * @covers User::isBlockedFrom
1235 * @dataProvider provideIsBlockedFrom
1236 * @param string|null $title Title to test.
1237 * @param bool $expect Expected result from User::isBlockedFrom()
1238 * @param array $options Additional test options:
1239 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1240 * - 'allowUsertalk': (bool, default false) Passed to Block::__construct()
1241 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1242 */
1243 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1244 $this->setMwGlobals( [
1245 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ?? true,
1246 ] );
1247
1248 $user = $this->getTestUser()->getUser();
1249
1250 if ( $title === self::USER_TALK_PAGE ) {
1251 $title = $user->getTalkPage();
1252 } else {
1253 $title = Title::newFromText( $title );
1254 }
1255
1256 $restrictions = [];
1257 foreach ( $options['pageRestrictions'] ?? [] as $pagestr ) {
1258 $page = $this->getExistingTestPage(
1259 $pagestr === self::USER_TALK_PAGE ? $user->getTalkPage() : $pagestr
1260 );
1261 $restrictions[] = new PageRestriction( 0, $page->getId() );
1262 }
1263 foreach ( $options['namespaceRestrictions'] ?? [] as $ns ) {
1264 $restrictions[] = new NamespaceRestriction( 0, $ns );
1265 }
1266
1267 $block = new Block( [
1268 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1269 'allowUsertalk' => $options['allowUsertalk'] ?? false,
1270 'sitewide' => !$restrictions,
1271 ] );
1272 $block->setTarget( $user );
1273 $block->setBlocker( $this->getTestSysop()->getUser() );
1274 if ( $restrictions ) {
1275 $block->setRestrictions( $restrictions );
1276 }
1277 $block->insert();
1278
1279 try {
1280 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1281 } finally {
1282 $block->delete();
1283 }
1284 }
1285
1286 public static function provideIsBlockedFrom() {
1287 return [
1288 'Sitewide block, basic operation' => [ 'Test page', true ],
1289 'Sitewide block, not allowing user talk' => [
1290 self::USER_TALK_PAGE, true, [
1291 'allowUsertalk' => false,
1292 ]
1293 ],
1294 'Sitewide block, allowing user talk' => [
1295 self::USER_TALK_PAGE, false, [
1296 'allowUsertalk' => true,
1297 ]
1298 ],
1299 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1300 self::USER_TALK_PAGE, true, [
1301 'allowUsertalk' => true,
1302 'blockAllowsUTEdit' => false,
1303 ]
1304 ],
1305 'Partial block, blocking the page' => [
1306 'Test page', true, [
1307 'pageRestrictions' => [ 'Test page' ],
1308 ]
1309 ],
1310 'Partial block, not blocking the page' => [
1311 'Test page 2', false, [
1312 'pageRestrictions' => [ 'Test page' ],
1313 ]
1314 ],
1315 'Partial block, not allowing user talk but user talk page is not blocked' => [
1316 self::USER_TALK_PAGE, false, [
1317 'allowUsertalk' => false,
1318 'pageRestrictions' => [ 'Test page' ],
1319 ]
1320 ],
1321 'Partial block, allowing user talk but user talk page is blocked' => [
1322 self::USER_TALK_PAGE, true, [
1323 'allowUsertalk' => true,
1324 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1325 ]
1326 ],
1327 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1328 self::USER_TALK_PAGE, false, [
1329 'allowUsertalk' => false,
1330 'pageRestrictions' => [ 'Test page' ],
1331 'blockAllowsUTEdit' => false,
1332 ]
1333 ],
1334 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1335 self::USER_TALK_PAGE, true, [
1336 'allowUsertalk' => true,
1337 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1338 'blockAllowsUTEdit' => false,
1339 ]
1340 ],
1341 'Partial user talk namespace block, not allowing user talk' => [
1342 self::USER_TALK_PAGE, true, [
1343 'allowUsertalk' => false,
1344 'namespaceRestrictions' => [ NS_USER_TALK ],
1345 ]
1346 ],
1347 'Partial user talk namespace block, allowing user talk' => [
1348 self::USER_TALK_PAGE, false, [
1349 'allowUsertalk' => true,
1350 'namespaceRestrictions' => [ NS_USER_TALK ],
1351 ]
1352 ],
1353 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1354 self::USER_TALK_PAGE, true, [
1355 'allowUsertalk' => true,
1356 'namespaceRestrictions' => [ NS_USER_TALK ],
1357 'blockAllowsUTEdit' => false,
1358 ]
1359 ],
1360 ];
1361 }
1362
1363 /**
1364 * Block cookie should be set for IP Blocks if
1365 * wgCookieSetOnIpBlock is set to true
1366 * @covers User::trackBlockWithCookie
1367 */
1368 public function testIpBlockCookieSet() {
1369 $this->setMwGlobals( [
1370 'wgCookieSetOnIpBlock' => true,
1371 'wgCookiePrefix' => 'wiki',
1372 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1373 ] );
1374
1375 // setup block
1376 $block = new Block( [
1377 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1378 ] );
1379 $block->setTarget( '1.2.3.4' );
1380 $block->setBlocker( $this->getTestSysop()->getUser() );
1381 $block->insert();
1382
1383 // setup request
1384 $request = new FauxRequest();
1385 $request->setIP( '1.2.3.4' );
1386
1387 // get user
1388 $user = User::newFromSession( $request );
1389 $user->trackBlockWithCookie();
1390
1391 // test cookie was set
1392 $cookies = $request->response()->getCookies();
1393 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1394
1395 // clean up
1396 $block->delete();
1397 }
1398
1399 /**
1400 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1401 * is disabled
1402 * @covers User::trackBlockWithCookie
1403 */
1404 public function testIpBlockCookieNotSet() {
1405 $this->setMwGlobals( [
1406 'wgCookieSetOnIpBlock' => false,
1407 'wgCookiePrefix' => 'wiki',
1408 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1409 ] );
1410
1411 // setup block
1412 $block = new Block( [
1413 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1414 ] );
1415 $block->setTarget( '1.2.3.4' );
1416 $block->setBlocker( $this->getTestSysop()->getUser() );
1417 $block->insert();
1418
1419 // setup request
1420 $request = new FauxRequest();
1421 $request->setIP( '1.2.3.4' );
1422
1423 // get user
1424 $user = User::newFromSession( $request );
1425 $user->trackBlockWithCookie();
1426
1427 // test cookie was not set
1428 $cookies = $request->response()->getCookies();
1429 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1430
1431 // clean up
1432 $block->delete();
1433 }
1434
1435 /**
1436 * When an ip user is blocked and then they log in, cookie block
1437 * should be invalid and the cookie removed.
1438 * @covers User::trackBlockWithCookie
1439 */
1440 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1441 $this->setMwGlobals( [
1442 'wgAutoblockExpiry' => 8000,
1443 'wgCookieSetOnIpBlock' => true,
1444 'wgCookiePrefix' => 'wiki',
1445 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1446 ] );
1447
1448 // setup block
1449 $block = new Block( [
1450 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1451 ] );
1452 $block->setTarget( '1.2.3.4' );
1453 $block->setBlocker( $this->getTestSysop()->getUser() );
1454 $block->insert();
1455
1456 // setup request
1457 $request = new FauxRequest();
1458 $request->setIP( '1.2.3.4' );
1459 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1460 $request->setCookie( 'BlockID', $block->getCookieValue() );
1461
1462 // setup user
1463 $user = User::newFromSession( $request );
1464
1465 // logged in users should be inmune to cookie block of type ip/range
1466 $this->assertFalse( $user->isBlocked() );
1467
1468 // cookie is being cleared
1469 $cookies = $request->response()->getCookies();
1470 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1471
1472 // clean up
1473 $block->delete();
1474 }
1475 }