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