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