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