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