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