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