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