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