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