84ca07007b065d86b4a99400bfb3d6f37921c942
[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\MediaWikiServices;
7 use Wikimedia\TestingAccessWrapper;
8
9 /**
10 * @group Database
11 */
12 class UserTest extends MediaWikiTestCase {
13 /**
14 * @var User
15 */
16 protected $user;
17
18 protected function setUp() {
19 parent::setUp();
20
21 $this->setMwGlobals( [
22 'wgGroupPermissions' => [],
23 'wgRevokePermissions' => [],
24 'wgActorTableSchemaMigrationStage' => MIGRATION_WRITE_BOTH,
25 ] );
26 $this->overrideMwServices();
27
28 $this->setUpPermissionGlobals();
29
30 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
31 }
32
33 private function setUpPermissionGlobals() {
34 global $wgGroupPermissions, $wgRevokePermissions;
35
36 # Data for regular $wgGroupPermissions test
37 $wgGroupPermissions['unittesters'] = [
38 'test' => true,
39 'runtest' => true,
40 'writetest' => false,
41 'nukeworld' => false,
42 ];
43 $wgGroupPermissions['testwriters'] = [
44 'test' => true,
45 'writetest' => true,
46 'modifytest' => true,
47 ];
48
49 # Data for regular $wgRevokePermissions test
50 $wgRevokePermissions['formertesters'] = [
51 'runtest' => true,
52 ];
53
54 # For the options test
55 $wgGroupPermissions['*'] = [
56 'editmyoptions' => true,
57 ];
58 }
59
60 /**
61 * @covers User::getGroupPermissions
62 */
63 public function testGroupPermissions() {
64 $rights = User::getGroupPermissions( [ 'unittesters' ] );
65 $this->assertContains( 'runtest', $rights );
66 $this->assertNotContains( 'writetest', $rights );
67 $this->assertNotContains( 'modifytest', $rights );
68 $this->assertNotContains( 'nukeworld', $rights );
69
70 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
71 $this->assertContains( 'runtest', $rights );
72 $this->assertContains( 'writetest', $rights );
73 $this->assertContains( 'modifytest', $rights );
74 $this->assertNotContains( 'nukeworld', $rights );
75 }
76
77 /**
78 * @covers User::getGroupPermissions
79 */
80 public function testRevokePermissions() {
81 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
82 $this->assertNotContains( 'runtest', $rights );
83 $this->assertNotContains( 'writetest', $rights );
84 $this->assertNotContains( 'modifytest', $rights );
85 $this->assertNotContains( 'nukeworld', $rights );
86 }
87
88 /**
89 * @covers User::getRights
90 */
91 public function testUserPermissions() {
92 $rights = $this->user->getRights();
93 $this->assertContains( 'runtest', $rights );
94 $this->assertNotContains( 'writetest', $rights );
95 $this->assertNotContains( 'modifytest', $rights );
96 $this->assertNotContains( 'nukeworld', $rights );
97 }
98
99 /**
100 * @covers User::getRights
101 */
102 public function testUserGetRightsHooks() {
103 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
104 $userWrapper = TestingAccessWrapper::newFromObject( $user );
105
106 $rights = $user->getRights();
107 $this->assertContains( 'test', $rights, 'sanity check' );
108 $this->assertContains( 'runtest', $rights, 'sanity check' );
109 $this->assertContains( 'writetest', $rights, 'sanity check' );
110 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
111
112 // Add a hook manipluating the rights
113 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
114 $rights[] = 'nukeworld';
115 $rights = array_diff( $rights, [ 'writetest' ] );
116 } ] ] );
117
118 $userWrapper->mRights = null;
119 $rights = $user->getRights();
120 $this->assertContains( 'test', $rights );
121 $this->assertContains( 'runtest', $rights );
122 $this->assertNotContains( 'writetest', $rights );
123 $this->assertContains( 'nukeworld', $rights );
124
125 // Add a Session that limits rights
126 $mock = $this->getMockBuilder( stdClass::class )
127 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
128 ->getMock();
129 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
130 $mock->method( 'getSessionId' )->willReturn(
131 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
132 );
133 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
134 $mockRequest = $this->getMockBuilder( FauxRequest::class )
135 ->setMethods( [ 'getSession' ] )
136 ->getMock();
137 $mockRequest->method( 'getSession' )->willReturn( $session );
138 $userWrapper->mRequest = $mockRequest;
139
140 $userWrapper->mRights = null;
141 $rights = $user->getRights();
142 $this->assertContains( 'test', $rights );
143 $this->assertNotContains( 'runtest', $rights );
144 $this->assertNotContains( 'writetest', $rights );
145 $this->assertNotContains( 'nukeworld', $rights );
146 }
147
148 /**
149 * @dataProvider provideGetGroupsWithPermission
150 * @covers User::getGroupsWithPermission
151 */
152 public function testGetGroupsWithPermission( $expected, $right ) {
153 $result = User::getGroupsWithPermission( $right );
154 sort( $result );
155 sort( $expected );
156
157 $this->assertEquals( $expected, $result, "Groups with permission $right" );
158 }
159
160 public static function provideGetGroupsWithPermission() {
161 return [
162 [
163 [ 'unittesters', 'testwriters' ],
164 'test'
165 ],
166 [
167 [ 'unittesters' ],
168 'runtest'
169 ],
170 [
171 [ 'testwriters' ],
172 'writetest'
173 ],
174 [
175 [ 'testwriters' ],
176 'modifytest'
177 ],
178 ];
179 }
180
181 /**
182 * @dataProvider provideIPs
183 * @covers User::isIP
184 */
185 public function testIsIP( $value, $result, $message ) {
186 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
187 }
188
189 public static function provideIPs() {
190 return [
191 [ '', false, 'Empty string' ],
192 [ ' ', false, 'Blank space' ],
193 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
194 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
195 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
196 [ '203.0.113.0', true, 'IPv4 example' ],
197 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
198 // Not valid IPs but classified as such by MediaWiki for negated asserting
199 // of whether this might be the identifier of a logged-out user or whether
200 // to allow usernames like it.
201 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
202 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
203 ];
204 }
205
206 /**
207 * @dataProvider provideUserNames
208 * @covers User::isValidUserName
209 */
210 public function testIsValidUserName( $username, $result, $message ) {
211 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
212 }
213
214 public static function provideUserNames() {
215 return [
216 [ '', false, 'Empty string' ],
217 [ ' ', false, 'Blank space' ],
218 [ 'abcd', false, 'Starts with small letter' ],
219 [ 'Ab/cd', false, 'Contains slash' ],
220 [ 'Ab cd', true, 'Whitespace' ],
221 [ '192.168.1.1', false, 'IP' ],
222 [ '116.17.184.5/32', false, 'IP range' ],
223 [ '::e:f:2001/96', false, 'IPv6 range' ],
224 [ 'User:Abcd', false, 'Reserved Namespace' ],
225 [ '12abcd232', true, 'Starts with Numbers' ],
226 [ '?abcd', true, 'Start with ? mark' ],
227 [ '#abcd', false, 'Start with #' ],
228 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
229 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
230 [ 'Ab cd', false, ' Ideographic space' ],
231 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
232 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
233 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
234 ];
235 }
236
237 /**
238 * Test, if for all rights a right- message exist,
239 * which is used on Special:ListGroupRights as help text
240 * Extensions and core
241 *
242 * @coversNothing
243 */
244 public function testAllRightsWithMessage() {
245 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
246 $allRights = User::getAllRights();
247 $allMessageKeys = Language::getMessageKeysFor( 'en' );
248
249 $rightsWithMessage = [];
250 foreach ( $allMessageKeys as $message ) {
251 // === 0: must be at beginning of string (position 0)
252 if ( strpos( $message, 'right-' ) === 0 ) {
253 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
254 }
255 }
256
257 sort( $allRights );
258 sort( $rightsWithMessage );
259
260 $this->assertEquals(
261 $allRights,
262 $rightsWithMessage,
263 'Each user rights (core/extensions) has a corresponding right- message.'
264 );
265 }
266
267 /**
268 * Test User::editCount
269 * @group medium
270 * @covers User::getEditCount
271 */
272 public function testGetEditCount() {
273 $user = $this->getMutableTestUser()->getUser();
274
275 // let the user have a few (3) edits
276 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
277 for ( $i = 0; $i < 3; $i++ ) {
278 $page->doEditContent(
279 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
280 'test',
281 0,
282 false,
283 $user
284 );
285 }
286
287 $this->assertEquals(
288 3,
289 $user->getEditCount(),
290 'After three edits, the user edit count should be 3'
291 );
292
293 // increase the edit count
294 $user->incEditCount();
295
296 $this->assertEquals(
297 4,
298 $user->getEditCount(),
299 'After increasing the edit count manually, the user edit count should be 4'
300 );
301 }
302
303 /**
304 * Test User::editCount
305 * @group medium
306 * @covers User::getEditCount
307 */
308 public function testGetEditCountForAnons() {
309 $user = User::newFromName( 'Anonymous' );
310
311 $this->assertNull(
312 $user->getEditCount(),
313 'Edit count starts null for anonymous users.'
314 );
315
316 $user->incEditCount();
317
318 $this->assertNull(
319 $user->getEditCount(),
320 'Edit count remains null for anonymous users despite calls to increase it.'
321 );
322 }
323
324 /**
325 * Test User::editCount
326 * @group medium
327 * @covers User::incEditCount
328 */
329 public function testIncEditCount() {
330 $user = $this->getMutableTestUser()->getUser();
331 $user->incEditCount();
332
333 $reloadedUser = User::newFromId( $user->getId() );
334 $reloadedUser->incEditCount();
335
336 $this->assertEquals(
337 2,
338 $reloadedUser->getEditCount(),
339 'Increasing the edit count after a fresh load leaves the object up to date.'
340 );
341 }
342
343 /**
344 * Test changing user options.
345 * @covers User::setOption
346 * @covers User::getOption
347 */
348 public function testOptions() {
349 $user = $this->getMutableTestUser()->getUser();
350
351 $user->setOption( 'userjs-someoption', 'test' );
352 $user->setOption( 'rclimit', 200 );
353 $user->setOption( 'wpwatchlistdays', '0' );
354 $user->saveSettings();
355
356 $user = User::newFromName( $user->getName() );
357 $user->load( User::READ_LATEST );
358 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
359 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
360
361 $user = User::newFromName( $user->getName() );
362 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
363 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
364 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
365
366 // Check that an option saved as a string '0' is returned as an integer.
367 $user = User::newFromName( $user->getName() );
368 $user->load( User::READ_LATEST );
369 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
370 }
371
372 /**
373 * T39963
374 * Make sure defaults are loaded when setOption is called.
375 * @covers User::loadOptions
376 */
377 public function testAnonOptions() {
378 global $wgDefaultUserOptions;
379 $this->user->setOption( 'userjs-someoption', 'test' );
380 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
381 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
382 }
383
384 /**
385 * Test password validity checks. There are 3 checks in core,
386 * - ensure the password meets the minimal length
387 * - ensure the password is not the same as the username
388 * - ensure the username/password combo isn't forbidden
389 * @covers User::checkPasswordValidity()
390 * @covers User::getPasswordValidity()
391 * @covers User::isValidPassword()
392 */
393 public function testCheckPasswordValidity() {
394 $this->setMwGlobals( [
395 'wgPasswordPolicy' => [
396 'policies' => [
397 'sysop' => [
398 'MinimalPasswordLength' => 8,
399 'MinimumPasswordLengthToLogin' => 1,
400 'PasswordCannotMatchUsername' => 1,
401 ],
402 'default' => [
403 'MinimalPasswordLength' => 6,
404 'PasswordCannotMatchUsername' => true,
405 'PasswordCannotMatchBlacklist' => true,
406 'MaximalPasswordLength' => 40,
407 ],
408 ],
409 'checks' => [
410 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
411 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
412 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
413 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
414 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
415 ],
416 ],
417 ] );
418
419 $user = static::getTestUser()->getUser();
420
421 // Sanity
422 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
423
424 // Minimum length
425 $this->assertFalse( $user->isValidPassword( 'a' ) );
426 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
427 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
428 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
429
430 // Maximum length
431 $longPass = str_repeat( 'a', 41 );
432 $this->assertFalse( $user->isValidPassword( $longPass ) );
433 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
434 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
435 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
436
437 // Matches username
438 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
439 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
440 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
441
442 // On the forbidden list
443 $user = User::newFromName( 'Useruser' );
444 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
445 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
446 }
447
448 /**
449 * @covers User::getCanonicalName()
450 * @dataProvider provideGetCanonicalName
451 */
452 public function testGetCanonicalName( $name, $expectedArray ) {
453 // fake interwiki map for the 'Interwiki prefix' testcase
454 $this->mergeMwGlobalArrayValue( 'wgHooks', [
455 'InterwikiLoadPrefix' => [
456 function ( $prefix, &$iwdata ) {
457 if ( $prefix === 'interwiki' ) {
458 $iwdata = [
459 'iw_url' => 'http://example.com/',
460 'iw_local' => 0,
461 'iw_trans' => 0,
462 ];
463 return false;
464 }
465 },
466 ],
467 ] );
468
469 foreach ( $expectedArray as $validate => $expected ) {
470 $this->assertEquals(
471 $expected,
472 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
473 }
474 }
475
476 public static function provideGetCanonicalName() {
477 return [
478 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
479 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
480 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
481 'valid' => false, 'false' => 'Talk:Username' ] ],
482 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
483 'valid' => false, 'false' => 'Interwiki:Username' ] ],
484 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
485 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
486 'usable' => 'Multi spaces' ] ],
487 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
488 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
489 'valid' => false, 'false' => 'In[]valid' ] ],
490 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
491 'false' => 'With / slash' ] ],
492 ];
493 }
494
495 /**
496 * @covers User::equals
497 */
498 public function testEquals() {
499 $first = $this->getMutableTestUser()->getUser();
500 $second = User::newFromName( $first->getName() );
501
502 $this->assertTrue( $first->equals( $first ) );
503 $this->assertTrue( $first->equals( $second ) );
504 $this->assertTrue( $second->equals( $first ) );
505
506 $third = $this->getMutableTestUser()->getUser();
507 $fourth = $this->getMutableTestUser()->getUser();
508
509 $this->assertFalse( $third->equals( $fourth ) );
510 $this->assertFalse( $fourth->equals( $third ) );
511
512 // Test users loaded from db with id
513 $user = $this->getMutableTestUser()->getUser();
514 $fifth = User::newFromId( $user->getId() );
515 $sixth = User::newFromName( $user->getName() );
516 $this->assertTrue( $fifth->equals( $sixth ) );
517 }
518
519 /**
520 * @covers User::getId
521 */
522 public function testGetId() {
523 $user = static::getTestUser()->getUser();
524 $this->assertTrue( $user->getId() > 0 );
525 }
526
527 /**
528 * @covers User::isLoggedIn
529 * @covers User::isAnon
530 */
531 public function testLoggedIn() {
532 $user = $this->getMutableTestUser()->getUser();
533 $this->assertTrue( $user->isLoggedIn() );
534 $this->assertFalse( $user->isAnon() );
535
536 // Non-existent users are perceived as anonymous
537 $user = User::newFromName( 'UTNonexistent' );
538 $this->assertFalse( $user->isLoggedIn() );
539 $this->assertTrue( $user->isAnon() );
540
541 $user = new User;
542 $this->assertFalse( $user->isLoggedIn() );
543 $this->assertTrue( $user->isAnon() );
544 }
545
546 /**
547 * @covers User::checkAndSetTouched
548 */
549 public function testCheckAndSetTouched() {
550 $user = $this->getMutableTestUser()->getUser();
551 $user = TestingAccessWrapper::newFromObject( $user );
552 $this->assertTrue( $user->isLoggedIn() );
553
554 $touched = $user->getDBTouched();
555 $this->assertTrue(
556 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
557 $this->assertGreaterThan(
558 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
559
560 $touched = $user->getDBTouched();
561 $this->assertTrue(
562 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
563 $this->assertGreaterThan(
564 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
565 }
566
567 /**
568 * @covers User::findUsersByGroup
569 */
570 public function testFindUsersByGroup() {
571 $users = User::findUsersByGroup( [] );
572 $this->assertEquals( 0, iterator_count( $users ) );
573
574 $users = User::findUsersByGroup( 'foo' );
575 $this->assertEquals( 0, iterator_count( $users ) );
576
577 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
578 $users = User::findUsersByGroup( 'foo' );
579 $this->assertEquals( 1, iterator_count( $users ) );
580 $users->rewind();
581 $this->assertTrue( $user->equals( $users->current() ) );
582
583 // arguments have OR relationship
584 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
585 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
586 $this->assertEquals( 2, iterator_count( $users ) );
587 $users->rewind();
588 $this->assertTrue( $user->equals( $users->current() ) );
589 $users->next();
590 $this->assertTrue( $user2->equals( $users->current() ) );
591
592 // users are not duplicated
593 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
594 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
595 $this->assertEquals( 1, iterator_count( $users ) );
596 $users->rewind();
597 $this->assertTrue( $user->equals( $users->current() ) );
598 }
599
600 /**
601 * When a user is autoblocked a cookie is set with which to track them
602 * in case they log out and change IP addresses.
603 * @link https://phabricator.wikimedia.org/T5233
604 */
605 public function testAutoblockCookies() {
606 // Set up the bits of global configuration that we use.
607 $this->setMwGlobals( [
608 'wgCookieSetOnAutoblock' => true,
609 'wgCookiePrefix' => 'wmsitetitle',
610 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
611 ] );
612
613 // Unregister the hooks for proper unit testing
614 $this->mergeMwGlobalArrayValue( 'wgHooks', [
615 'PerformRetroactiveAutoblock' => []
616 ] );
617
618 // 1. Log in a test user, and block them.
619 $userBlocker = $this->getTestSysop()->getUser();
620 $user1tmp = $this->getTestUser()->getUser();
621 $request1 = new FauxRequest();
622 $request1->getSession()->setUser( $user1tmp );
623 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
624 $block = new Block( [
625 'enableAutoblock' => true,
626 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
627 ] );
628 $block->setBlocker( $this->getTestSysop()->getUser() );
629 $block->setTarget( $user1tmp );
630 $block->setBlocker( $userBlocker );
631 $res = $block->insert();
632 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
633 $user1 = User::newFromSession( $request1 );
634 $user1->mBlock = $block;
635 $user1->load();
636
637 // Confirm that the block has been applied as required.
638 $this->assertTrue( $user1->isLoggedIn() );
639 $this->assertTrue( $user1->isBlocked() );
640 $this->assertEquals( Block::TYPE_USER, $block->getType() );
641 $this->assertTrue( $block->isAutoblocking() );
642 $this->assertGreaterThanOrEqual( 1, $block->getId() );
643
644 // Test for the desired cookie name, value, and expiry.
645 $cookies = $request1->response()->getCookies();
646 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
647 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
648 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
649 $this->assertEquals( $block->getId(), $cookieValue );
650
651 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
652 $request2 = new FauxRequest();
653 $request2->setCookie( 'BlockID', $block->getCookieValue() );
654 $user2 = User::newFromSession( $request2 );
655 $user2->load();
656 $this->assertNotEquals( $user1->getId(), $user2->getId() );
657 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
658 $this->assertTrue( $user2->isAnon() );
659 $this->assertFalse( $user2->isLoggedIn() );
660 $this->assertTrue( $user2->isBlocked() );
661 // Non-strict type-check.
662 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
663 // Can't directly compare the objects becuase of member type differences.
664 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
665 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
666 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
667
668 // 3. Finally, set up a request as a new user, and the block should still be applied.
669 $user3tmp = $this->getTestUser()->getUser();
670 $request3 = new FauxRequest();
671 $request3->getSession()->setUser( $user3tmp );
672 $request3->setCookie( 'BlockID', $block->getId() );
673 $user3 = User::newFromSession( $request3 );
674 $user3->load();
675 $this->assertTrue( $user3->isLoggedIn() );
676 $this->assertTrue( $user3->isBlocked() );
677 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
678
679 // Clean up.
680 $block->delete();
681 }
682
683 /**
684 * Make sure that no cookie is set to track autoblocked users
685 * when $wgCookieSetOnAutoblock is false.
686 */
687 public function testAutoblockCookiesDisabled() {
688 // Set up the bits of global configuration that we use.
689 $this->setMwGlobals( [
690 'wgCookieSetOnAutoblock' => false,
691 'wgCookiePrefix' => 'wm_no_cookies',
692 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
693 ] );
694
695 // Unregister the hooks for proper unit testing
696 $this->mergeMwGlobalArrayValue( 'wgHooks', [
697 'PerformRetroactiveAutoblock' => []
698 ] );
699
700 // 1. Log in a test user, and block them.
701 $userBlocker = $this->getTestSysop()->getUser();
702 $testUser = $this->getTestUser()->getUser();
703 $request1 = new FauxRequest();
704 $request1->getSession()->setUser( $testUser );
705 $block = new Block( [ 'enableAutoblock' => true ] );
706 $block->setBlocker( $this->getTestSysop()->getUser() );
707 $block->setTarget( $testUser );
708 $block->setBlocker( $userBlocker );
709 $res = $block->insert();
710 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
711 $user = User::newFromSession( $request1 );
712 $user->mBlock = $block;
713 $user->load();
714
715 // 2. Test that the cookie IS NOT present.
716 $this->assertTrue( $user->isLoggedIn() );
717 $this->assertTrue( $user->isBlocked() );
718 $this->assertEquals( Block::TYPE_USER, $block->getType() );
719 $this->assertTrue( $block->isAutoblocking() );
720 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
721 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
722 $cookies = $request1->response()->getCookies();
723 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
724
725 // Clean up.
726 $block->delete();
727 }
728
729 /**
730 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
731 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
732 * the cookie's should change with it.
733 */
734 public function testAutoblockCookieInfiniteExpiry() {
735 $this->setMwGlobals( [
736 'wgCookieSetOnAutoblock' => true,
737 'wgCookiePrefix' => 'wm_infinite_block',
738 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
739 ] );
740
741 // Unregister the hooks for proper unit testing
742 $this->mergeMwGlobalArrayValue( 'wgHooks', [
743 'PerformRetroactiveAutoblock' => []
744 ] );
745
746 // 1. Log in a test user, and block them indefinitely.
747 $userBlocker = $this->getTestSysop()->getUser();
748 $user1Tmp = $this->getTestUser()->getUser();
749 $request1 = new FauxRequest();
750 $request1->getSession()->setUser( $user1Tmp );
751 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
752 $block->setBlocker( $this->getTestSysop()->getUser() );
753 $block->setTarget( $user1Tmp );
754 $block->setBlocker( $userBlocker );
755 $res = $block->insert();
756 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
757 $user1 = User::newFromSession( $request1 );
758 $user1->mBlock = $block;
759 $user1->load();
760
761 // 2. Test the cookie's expiry timestamp.
762 $this->assertTrue( $user1->isLoggedIn() );
763 $this->assertTrue( $user1->isBlocked() );
764 $this->assertEquals( Block::TYPE_USER, $block->getType() );
765 $this->assertTrue( $block->isAutoblocking() );
766 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
767 $cookies = $request1->response()->getCookies();
768 // Test the cookie's expiry to the nearest minute.
769 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
770 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
771 // Check for expiry dates in a 10-second window, to account for slow testing.
772 $this->assertEquals(
773 $expOneDay,
774 $cookies['wm_infinite_blockBlockID']['expire'],
775 'Expiry date',
776 5.0
777 );
778
779 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
780 $newExpiry = wfTimestamp() + 2 * 60 * 60;
781 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
782 $block->update();
783 $user2tmp = $this->getTestUser()->getUser();
784 $request2 = new FauxRequest();
785 $request2->getSession()->setUser( $user2tmp );
786 $user2 = User::newFromSession( $request2 );
787 $user2->mBlock = $block;
788 $user2->load();
789 $cookies = $request2->response()->getCookies();
790 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
791 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
792
793 // Clean up.
794 $block->delete();
795 }
796
797 public function testSoftBlockRanges() {
798 global $wgUser;
799
800 $this->setMwGlobals( [
801 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
802 'wgUser' => null,
803 ] );
804
805 // IP isn't in $wgSoftBlockRanges
806 $request = new FauxRequest();
807 $request->setIP( '192.168.0.1' );
808 $wgUser = User::newFromSession( $request );
809 $this->assertNull( $wgUser->getBlock() );
810
811 // IP is in $wgSoftBlockRanges
812 $request = new FauxRequest();
813 $request->setIP( '10.20.30.40' );
814 $wgUser = User::newFromSession( $request );
815 $block = $wgUser->getBlock();
816 $this->assertInstanceOf( Block::class, $block );
817 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
818
819 // Make sure the block is really soft
820 $request->getSession()->setUser( $this->getTestUser()->getUser() );
821 $wgUser = User::newFromSession( $request );
822 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
823 $this->assertNull( $wgUser->getBlock() );
824 }
825
826 /**
827 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
828 */
829 public function testAutoblockCookieInauthentic() {
830 // Set up the bits of global configuration that we use.
831 $this->setMwGlobals( [
832 'wgCookieSetOnAutoblock' => true,
833 'wgCookiePrefix' => 'wmsitetitle',
834 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
835 ] );
836
837 // Unregister the hooks for proper unit testing
838 $this->mergeMwGlobalArrayValue( 'wgHooks', [
839 'PerformRetroactiveAutoblock' => []
840 ] );
841
842 // 1. Log in a blocked test user.
843 $userBlocker = $this->getTestSysop()->getUser();
844 $user1tmp = $this->getTestUser()->getUser();
845 $request1 = new FauxRequest();
846 $request1->getSession()->setUser( $user1tmp );
847 $block = new Block( [ 'enableAutoblock' => true ] );
848 $block->setBlocker( $this->getTestSysop()->getUser() );
849 $block->setTarget( $user1tmp );
850 $block->setBlocker( $userBlocker );
851 $res = $block->insert();
852 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
853 $user1 = User::newFromSession( $request1 );
854 $user1->mBlock = $block;
855 $user1->load();
856
857 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
858 // user not blocked.
859 $request2 = new FauxRequest();
860 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
861 $user2 = User::newFromSession( $request2 );
862 $user2->load();
863 $this->assertTrue( $user2->isAnon() );
864 $this->assertFalse( $user2->isLoggedIn() );
865 $this->assertFalse( $user2->isBlocked() );
866
867 // Clean up.
868 $block->delete();
869 }
870
871 /**
872 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
873 * This checks that a non-authenticated cookie still works.
874 */
875 public function testAutoblockCookieNoSecretKey() {
876 // Set up the bits of global configuration that we use.
877 $this->setMwGlobals( [
878 'wgCookieSetOnAutoblock' => true,
879 'wgCookiePrefix' => 'wmsitetitle',
880 'wgSecretKey' => null,
881 ] );
882
883 // Unregister the hooks for proper unit testing
884 $this->mergeMwGlobalArrayValue( 'wgHooks', [
885 'PerformRetroactiveAutoblock' => []
886 ] );
887
888 // 1. Log in a blocked test user.
889 $userBlocker = $this->getTestSysop()->getUser();
890 $user1tmp = $this->getTestUser()->getUser();
891 $request1 = new FauxRequest();
892 $request1->getSession()->setUser( $user1tmp );
893 $block = new Block( [ 'enableAutoblock' => true ] );
894 $block->setBlocker( $this->getTestSysop()->getUser() );
895 $block->setTarget( $user1tmp );
896 $block->setBlocker( $userBlocker );
897 $res = $block->insert();
898 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
899 $user1 = User::newFromSession( $request1 );
900 $user1->mBlock = $block;
901 $user1->load();
902 $this->assertTrue( $user1->isBlocked() );
903
904 // 2. Create a new request, set the cookie to just the block ID, and the user should
905 // still get blocked when they log in again.
906 $request2 = new FauxRequest();
907 $request2->setCookie( 'BlockID', $block->getId() );
908 $user2 = User::newFromSession( $request2 );
909 $user2->load();
910 $this->assertNotEquals( $user1->getId(), $user2->getId() );
911 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
912 $this->assertTrue( $user2->isAnon() );
913 $this->assertFalse( $user2->isLoggedIn() );
914 $this->assertTrue( $user2->isBlocked() );
915 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
916
917 // Clean up.
918 $block->delete();
919 }
920
921 /**
922 * @covers User::isPingLimitable
923 */
924 public function testIsPingLimitable() {
925 $request = new FauxRequest();
926 $request->setIP( '1.2.3.4' );
927 $user = User::newFromSession( $request );
928
929 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
930 $this->assertTrue( $user->isPingLimitable() );
931
932 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
933 $this->assertFalse( $user->isPingLimitable() );
934
935 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
936 $this->assertFalse( $user->isPingLimitable() );
937
938 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
939 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
940 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
941 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
942 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
943 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
944 }
945
946 public function provideExperienceLevel() {
947 return [
948 [ 2, 2, 'newcomer' ],
949 [ 12, 3, 'newcomer' ],
950 [ 8, 5, 'newcomer' ],
951 [ 15, 10, 'learner' ],
952 [ 450, 20, 'learner' ],
953 [ 460, 33, 'learner' ],
954 [ 525, 28, 'learner' ],
955 [ 538, 33, 'experienced' ],
956 ];
957 }
958
959 /**
960 * @covers User::getExperienceLevel
961 * @dataProvider provideExperienceLevel
962 */
963 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
964 $this->setMwGlobals( [
965 'wgLearnerEdits' => 10,
966 'wgLearnerMemberSince' => 4,
967 'wgExperiencedUserEdits' => 500,
968 'wgExperiencedUserMemberSince' => 30,
969 ] );
970
971 $db = wfGetDB( DB_MASTER );
972 $userQuery = User::getQueryInfo();
973 $row = $db->selectRow(
974 $userQuery['tables'],
975 $userQuery['fields'],
976 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
977 __METHOD__,
978 [],
979 $userQuery['joins']
980 );
981 $row->user_editcount = $editCount;
982 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
983 $user = User::newFromRow( $row );
984
985 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
986 }
987
988 /**
989 * @covers User::getExperienceLevel
990 */
991 public function testExperienceLevelAnon() {
992 $user = User::newFromName( '10.11.12.13', false );
993
994 $this->assertFalse( $user->getExperienceLevel() );
995 }
996
997 public static function provideIsLocallBlockedProxy() {
998 return [
999 [ '1.2.3.4', '1.2.3.4' ],
1000 [ '1.2.3.4', '1.2.3.0/16' ],
1001 ];
1002 }
1003
1004 /**
1005 * @dataProvider provideIsLocallBlockedProxy
1006 * @covers User::isLocallyBlockedProxy
1007 */
1008 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1009 $this->setMwGlobals(
1010 'wgProxyList', []
1011 );
1012 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
1013
1014 $this->setMwGlobals(
1015 'wgProxyList',
1016 [
1017 $blockListEntry
1018 ]
1019 );
1020 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1021
1022 $this->setMwGlobals(
1023 'wgProxyList',
1024 [
1025 'test' => $blockListEntry
1026 ]
1027 );
1028 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1029
1030 $this->hideDeprecated(
1031 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1032 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1033 );
1034 $this->setMwGlobals(
1035 'wgProxyList',
1036 [
1037 $blockListEntry => 'test'
1038 ]
1039 );
1040 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1041 }
1042
1043 public function testActorId() {
1044 $this->hideDeprecated( 'User::selectFields' );
1045
1046 // Newly-created user has an actor ID
1047 $user = User::createNew( 'UserTestActorId1' );
1048 $id = $user->getId();
1049 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1050
1051 $user = User::newFromName( 'UserTestActorId2' );
1052 $user->addToDatabase();
1053 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1054
1055 $user = User::newFromName( 'UserTestActorId1' );
1056 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1057
1058 $user = User::newFromId( $id );
1059 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1060
1061 $user2 = User::newFromActorId( $user->getActorId() );
1062 $this->assertEquals( $user->getId(), $user2->getId(),
1063 'User::newFromActorId works for an existing user' );
1064
1065 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1066 $user = User::newFromRow( $row );
1067 $this->assertTrue( $user->getActorId() > 0,
1068 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1069
1070 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1071 User::purge( wfWikiId(), $id );
1072 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1073 ObjectCache::getMainWANInstance()->clearProcessCache();
1074
1075 $user = User::newFromId( $id );
1076 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1077 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1078
1079 $user->setName( 'UserTestActorId4-renamed' );
1080 $user->saveSettings();
1081 $this->assertEquals(
1082 $user->getName(),
1083 $this->db->selectField(
1084 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1085 ),
1086 'User::saveSettings updates actor table for name change'
1087 );
1088
1089 // For sanity
1090 $ip = '192.168.12.34';
1091 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1092
1093 $user = User::newFromName( $ip, false );
1094 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1095 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1096 'Actor ID can be created for an anonymous user' );
1097
1098 $user = User::newFromName( $ip, false );
1099 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1100 $user2 = User::newFromActorId( $user->getActorId() );
1101 $this->assertEquals( $user->getName(), $user2->getName(),
1102 'User::newFromActorId works for an anonymous user' );
1103 }
1104
1105 public function testNewFromAnyId() {
1106 // Registered user
1107 $user = $this->getTestUser()->getUser();
1108 for ( $i = 1; $i <= 7; $i++ ) {
1109 $test = User::newFromAnyId(
1110 ( $i & 1 ) ? $user->getId() : null,
1111 ( $i & 2 ) ? $user->getName() : null,
1112 ( $i & 4 ) ? $user->getActorId() : null
1113 );
1114 $this->assertSame( $user->getId(), $test->getId() );
1115 $this->assertSame( $user->getName(), $test->getName() );
1116 $this->assertSame( $user->getActorId(), $test->getActorId() );
1117 }
1118
1119 // Anon user. Can't load by only user ID when that's 0.
1120 $user = User::newFromName( '192.168.12.34', false );
1121 $user->getActorId( $this->db ); // Make sure an actor ID exists
1122
1123 $test = User::newFromAnyId( null, '192.168.12.34', null );
1124 $this->assertSame( $user->getId(), $test->getId() );
1125 $this->assertSame( $user->getName(), $test->getName() );
1126 $this->assertSame( $user->getActorId(), $test->getActorId() );
1127 $test = User::newFromAnyId( null, null, $user->getActorId() );
1128 $this->assertSame( $user->getId(), $test->getId() );
1129 $this->assertSame( $user->getName(), $test->getName() );
1130 $this->assertSame( $user->getActorId(), $test->getActorId() );
1131
1132 // Bogus data should still "work" as long as nothing triggers a ->load(),
1133 // and accessing the specified data shouldn't do that.
1134 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1135 $this->assertSame( 123456, $test->getId() );
1136 $this->assertSame( 'Bogus', $test->getName() );
1137 $this->assertSame( 654321, $test->getActorId() );
1138
1139 // Exceptional cases
1140 try {
1141 User::newFromAnyId( null, null, null );
1142 $this->fail( 'Expected exception not thrown' );
1143 } catch ( InvalidArgumentException $ex ) {
1144 }
1145 try {
1146 User::newFromAnyId( 0, null, 0 );
1147 $this->fail( 'Expected exception not thrown' );
1148 } catch ( InvalidArgumentException $ex ) {
1149 }
1150 }
1151 }