MediaWiki REL1_31
UserTest.php
Go to the documentation of this file.
1<?php
2
3define( 'NS_UNITTEST', 5600 );
4define( 'NS_UNITTEST_TALK', 5601 );
5
7use Wikimedia\TestingAccessWrapper;
8
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
29
30 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
31 }
32
33 private function setUpPermissionGlobals() {
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
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
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
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
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
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
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
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
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
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
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
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
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
377 public function testAnonOptions() {
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
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
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
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
522 public function testGetId() {
523 $user = static::getTestUser()->getUser();
524 $this->assertTrue( $user->getId() > 0 );
525 }
526
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
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
570 public function testFindUsersByGroup() {
572 $this->assertEquals( 0, iterator_count( $users ) );
573
575 $this->assertEquals( 0, iterator_count( $users ) );
576
577 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
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
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
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
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 $setSessionUser = function ( User $user, WebRequest $request ) {
799 $this->setMwGlobals( 'wgUser', $user );
800 RequestContext::getMain()->setUser( $user );
801 RequestContext::getMain()->setRequest( $request );
802 TestingAccessWrapper::newFromObject( $user )->mRequest = $request;
803 $request->getSession()->setUser( $user );
804 };
805 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
806
807 // IP isn't in $wgSoftBlockRanges
808 $wgUser = new User();
809 $request = new FauxRequest();
810 $request->setIP( '192.168.0.1' );
811 $setSessionUser( $wgUser, $request );
812 $this->assertNull( $wgUser->getBlock() );
813
814 // IP is in $wgSoftBlockRanges
815 $wgUser = new User();
816 $request = new FauxRequest();
817 $request->setIP( '10.20.30.40' );
818 $setSessionUser( $wgUser, $request );
819 $block = $wgUser->getBlock();
820 $this->assertInstanceOf( Block::class, $block );
821 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
822
823 // Make sure the block is really soft
824 $wgUser = $this->getTestUser()->getUser();
825 $request = new FauxRequest();
826 $request->setIP( '10.20.30.40' );
827 $setSessionUser( $wgUser, $request );
828 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
829 $this->assertNull( $wgUser->getBlock() );
830 }
831
836 // Set up the bits of global configuration that we use.
837 $this->setMwGlobals( [
838 'wgCookieSetOnAutoblock' => true,
839 'wgCookiePrefix' => 'wmsitetitle',
840 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
841 ] );
842
843 // Unregister the hooks for proper unit testing
844 $this->mergeMwGlobalArrayValue( 'wgHooks', [
845 'PerformRetroactiveAutoblock' => []
846 ] );
847
848 // 1. Log in a blocked test user.
849 $userBlocker = $this->getTestSysop()->getUser();
850 $user1tmp = $this->getTestUser()->getUser();
851 $request1 = new FauxRequest();
852 $request1->getSession()->setUser( $user1tmp );
853 $block = new Block( [ 'enableAutoblock' => true ] );
854 $block->setBlocker( $this->getTestSysop()->getUser() );
855 $block->setTarget( $user1tmp );
856 $block->setBlocker( $userBlocker );
857 $res = $block->insert();
858 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
859 $user1 = User::newFromSession( $request1 );
860 $user1->mBlock = $block;
861 $user1->load();
862
863 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
864 // user not blocked.
865 $request2 = new FauxRequest();
866 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
867 $user2 = User::newFromSession( $request2 );
868 $user2->load();
869 $this->assertTrue( $user2->isAnon() );
870 $this->assertFalse( $user2->isLoggedIn() );
871 $this->assertFalse( $user2->isBlocked() );
872
873 // Clean up.
874 $block->delete();
875 }
876
882 // Set up the bits of global configuration that we use.
883 $this->setMwGlobals( [
884 'wgCookieSetOnAutoblock' => true,
885 'wgCookiePrefix' => 'wmsitetitle',
886 'wgSecretKey' => null,
887 ] );
888
889 // Unregister the hooks for proper unit testing
890 $this->mergeMwGlobalArrayValue( 'wgHooks', [
891 'PerformRetroactiveAutoblock' => []
892 ] );
893
894 // 1. Log in a blocked test user.
895 $userBlocker = $this->getTestSysop()->getUser();
896 $user1tmp = $this->getTestUser()->getUser();
897 $request1 = new FauxRequest();
898 $request1->getSession()->setUser( $user1tmp );
899 $block = new Block( [ 'enableAutoblock' => true ] );
900 $block->setBlocker( $this->getTestSysop()->getUser() );
901 $block->setTarget( $user1tmp );
902 $block->setBlocker( $userBlocker );
903 $res = $block->insert();
904 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
905 $user1 = User::newFromSession( $request1 );
906 $user1->mBlock = $block;
907 $user1->load();
908 $this->assertTrue( $user1->isBlocked() );
909
910 // 2. Create a new request, set the cookie to just the block ID, and the user should
911 // still get blocked when they log in again.
912 $request2 = new FauxRequest();
913 $request2->setCookie( 'BlockID', $block->getId() );
914 $user2 = User::newFromSession( $request2 );
915 $user2->load();
916 $this->assertNotEquals( $user1->getId(), $user2->getId() );
917 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
918 $this->assertTrue( $user2->isAnon() );
919 $this->assertFalse( $user2->isLoggedIn() );
920 $this->assertTrue( $user2->isBlocked() );
921 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
922
923 // Clean up.
924 $block->delete();
925 }
926
930 public function testIsPingLimitable() {
931 $request = new FauxRequest();
932 $request->setIP( '1.2.3.4' );
934
935 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
936 $this->assertTrue( $user->isPingLimitable() );
937
938 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
939 $this->assertFalse( $user->isPingLimitable() );
940
941 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
942 $this->assertFalse( $user->isPingLimitable() );
943
944 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
945 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
946 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
947 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
948 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
949 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
950 }
951
952 public function provideExperienceLevel() {
953 return [
954 [ 2, 2, 'newcomer' ],
955 [ 12, 3, 'newcomer' ],
956 [ 8, 5, 'newcomer' ],
957 [ 15, 10, 'learner' ],
958 [ 450, 20, 'learner' ],
959 [ 460, 33, 'learner' ],
960 [ 525, 28, 'learner' ],
961 [ 538, 33, 'experienced' ],
962 ];
963 }
964
969 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
970 $this->setMwGlobals( [
971 'wgLearnerEdits' => 10,
972 'wgLearnerMemberSince' => 4,
973 'wgExperiencedUserEdits' => 500,
974 'wgExperiencedUserMemberSince' => 30,
975 ] );
976
977 $db = wfGetDB( DB_MASTER );
978 $userQuery = User::getQueryInfo();
979 $row = $db->selectRow(
980 $userQuery['tables'],
981 $userQuery['fields'],
982 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
983 __METHOD__,
984 [],
985 $userQuery['joins']
986 );
987 $row->user_editcount = $editCount;
988 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
989 $user = User::newFromRow( $row );
990
991 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
992 }
993
997 public function testExperienceLevelAnon() {
998 $user = User::newFromName( '10.11.12.13', false );
999
1000 $this->assertFalse( $user->getExperienceLevel() );
1001 }
1002
1003 public static function provideIsLocallBlockedProxy() {
1004 return [
1005 [ '1.2.3.4', '1.2.3.4' ],
1006 [ '1.2.3.4', '1.2.3.0/16' ],
1007 ];
1008 }
1009
1014 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1015 $this->setMwGlobals(
1016 'wgProxyList', []
1017 );
1018 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
1019
1020 $this->setMwGlobals(
1021 'wgProxyList',
1022 [
1023 $blockListEntry
1024 ]
1025 );
1026 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1027
1028 $this->setMwGlobals(
1029 'wgProxyList',
1030 [
1031 'test' => $blockListEntry
1032 ]
1033 );
1034 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1035
1036 $this->hideDeprecated(
1037 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1038 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1039 );
1040 $this->setMwGlobals(
1041 'wgProxyList',
1042 [
1043 $blockListEntry => 'test'
1044 ]
1045 );
1046 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1047 }
1048
1049 public function testActorId() {
1050 $this->hideDeprecated( 'User::selectFields' );
1051
1052 // Newly-created user has an actor ID
1053 $user = User::createNew( 'UserTestActorId1' );
1054 $id = $user->getId();
1055 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1056
1057 $user = User::newFromName( 'UserTestActorId2' );
1058 $user->addToDatabase();
1059 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1060
1061 $user = User::newFromName( 'UserTestActorId1' );
1062 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1063
1064 $user = User::newFromId( $id );
1065 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1066
1067 $user2 = User::newFromActorId( $user->getActorId() );
1068 $this->assertEquals( $user->getId(), $user2->getId(),
1069 'User::newFromActorId works for an existing user' );
1070
1071 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1072 $user = User::newFromRow( $row );
1073 $this->assertTrue( $user->getActorId() > 0,
1074 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1075
1076 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1077 User::purge( wfWikiId(), $id );
1078 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1079 ObjectCache::getMainWANInstance()->clearProcessCache();
1080
1081 $user = User::newFromId( $id );
1082 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1083 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1084
1085 $user->setName( 'UserTestActorId4-renamed' );
1086 $user->saveSettings();
1087 $this->assertEquals(
1088 $user->getName(),
1089 $this->db->selectField(
1090 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1091 ),
1092 'User::saveSettings updates actor table for name change'
1093 );
1094
1095 // For sanity
1096 $ip = '192.168.12.34';
1097 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1098
1099 $user = User::newFromName( $ip, false );
1100 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1101 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1102 'Actor ID can be created for an anonymous user' );
1103
1104 $user = User::newFromName( $ip, false );
1105 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1106 $user2 = User::newFromActorId( $user->getActorId() );
1107 $this->assertEquals( $user->getName(), $user2->getName(),
1108 'User::newFromActorId works for an anonymous user' );
1109 }
1110
1111 public function testNewFromAnyId() {
1112 // Registered user
1113 $user = $this->getTestUser()->getUser();
1114 for ( $i = 1; $i <= 7; $i++ ) {
1115 $test = User::newFromAnyId(
1116 ( $i & 1 ) ? $user->getId() : null,
1117 ( $i & 2 ) ? $user->getName() : null,
1118 ( $i & 4 ) ? $user->getActorId() : null
1119 );
1120 $this->assertSame( $user->getId(), $test->getId() );
1121 $this->assertSame( $user->getName(), $test->getName() );
1122 $this->assertSame( $user->getActorId(), $test->getActorId() );
1123 }
1124
1125 // Anon user. Can't load by only user ID when that's 0.
1126 $user = User::newFromName( '192.168.12.34', false );
1127 $user->getActorId( $this->db ); // Make sure an actor ID exists
1128
1129 $test = User::newFromAnyId( null, '192.168.12.34', null );
1130 $this->assertSame( $user->getId(), $test->getId() );
1131 $this->assertSame( $user->getName(), $test->getName() );
1132 $this->assertSame( $user->getActorId(), $test->getActorId() );
1133 $test = User::newFromAnyId( null, null, $user->getActorId() );
1134 $this->assertSame( $user->getId(), $test->getId() );
1135 $this->assertSame( $user->getName(), $test->getName() );
1136 $this->assertSame( $user->getActorId(), $test->getActorId() );
1137
1138 // Bogus data should still "work" as long as nothing triggers a ->load(),
1139 // and accessing the specified data shouldn't do that.
1140 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1141 $this->assertSame( 123456, $test->getId() );
1142 $this->assertSame( 'Bogus', $test->getName() );
1143 $this->assertSame( 654321, $test->getActorId() );
1144
1145 // Exceptional cases
1146 try {
1147 User::newFromAnyId( null, null, null );
1148 $this->fail( 'Expected exception not thrown' );
1149 } catch ( InvalidArgumentException $ex ) {
1150 }
1151 try {
1152 User::newFromAnyId( 0, null, 0 );
1153 $this->fail( 'Expected exception not thrown' );
1154 } catch ( InvalidArgumentException $ex ) {
1155 }
1156 }
1157
1166 public function testBlockInstanceCache() {
1167 // First, check the user isn't blocked
1168 $user = $this->getMutableTestUser()->getUser();
1169 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1170 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1171 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1172 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1173 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1174 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1175
1176 // Block the user
1177 $blocker = $this->getTestSysop()->getUser();
1178 $block = new Block( [
1179 'hideName' => true,
1180 'allowUsertalk' => false,
1181 'reason' => 'Because',
1182 ] );
1183 $block->setTarget( $user );
1184 $block->setBlocker( $blocker );
1185 $res = $block->insert();
1186 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1187
1188 // Clear cache and confirm it loaded the block properly
1189 $user->clearInstanceCache();
1190 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1191 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1192 $this->assertSame( 'Because', $user->blockedFor() );
1193 $this->assertTrue( (bool)$user->isHidden() );
1194 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1195
1196 // Unblock
1197 $block->delete();
1198
1199 // Clear cache and confirm it loaded the not-blocked properly
1200 $user->clearInstanceCache();
1201 $this->assertNull( $user->getBlock( false ) );
1202 $this->assertSame( '', $user->blockedBy() );
1203 $this->assertSame( '', $user->blockedFor() );
1204 $this->assertFalse( (bool)$user->isHidden() );
1205 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1206 }
1207
1208 private function newFakeUser( $name, $ip, $id ) {
1209 $req = new FauxRequest();
1210 $req->setIP( $ip );
1211
1212 $user = $this->getMockBuilder( User::class )
1213 ->setMethods( [ 'getId', 'getName', 'getRequest', 'getGroups' ] )
1214 ->getMock();
1215
1216 $user->method( 'getId' )->willReturn( $id );
1217 $user->method( 'getName' )->willReturn( $name );
1218 $user->method( 'getRequest' )->willReturn( $req );
1219 $user->method( 'getGroups' )->willReturn( [ 'user' ] );
1220
1221 $this->overrideUserPermissions( $user, [
1222 'noratelimit' => false,
1223 ] );
1224
1225 return $user;
1226 }
1227
1228 private function newFakeAnon( $ip ) {
1229 return $this->newFakeUser( $ip, $ip, 0 );
1230 }
1231
1235 public function testPingLimiterGlobal() {
1236 $this->setMwGlobals( [
1237 'wgRateLimits' => [
1238 'edit' => [
1239 'anon' => [ 1, 60 ],
1240 ],
1241 'purge' => [
1242 'ip' => [ 1, 60 ],
1243 'subnet' => [ 1, 60 ],
1244 ],
1245 'rollback' => [
1246 'user' => [ 1, 60 ],
1247 ],
1248 'move' => [
1249 'user-global' => [ 1, 60 ],
1250 ],
1251 'delete' => [
1252 'ip-all' => [ 1, 60 ],
1253 'subnet-all' => [ 1, 60 ],
1254 ],
1255 ],
1256 ] );
1257
1258 // Set up a fake cache for storing limits
1259 $cache = new HashBagOStuff( [ 'keyspace' => 'xwiki' ] );
1260
1261 global $wgMainCacheType;
1262 ObjectCache::$instances[$wgMainCacheType] = $cache;
1263
1264 $cacheAccess = TestingAccessWrapper::newFromObject( $cache );
1265 $cacheAccess->keyspace = 'xwiki';
1266
1268
1269 // Set up some fake users
1270 $anon1 = $this->newFakeAnon( '1.2.3.4' );
1271 $anon2 = $this->newFakeAnon( '1.2.3.8' );
1272 $anon3 = $this->newFakeAnon( '6.7.8.9' );
1273 $anon4 = $this->newFakeAnon( '6.7.8.1' );
1274
1275 // The mock ContralIdProvider uses the local id MOD 10 as the global ID.
1276 // So Frank has global ID 11, and Jane has global ID 56.
1277 // Kara's global ID is 0, which means no global ID.
1278 $frankX1 = $this->newFakeUser( 'Frank', '1.2.3.4', 111 );
1279 $frankX2 = $this->newFakeUser( 'Frank', '1.2.3.8', 111 );
1280 $frankY1 = $this->newFakeUser( 'Frank', '1.2.3.4', 211 );
1281 $janeX1 = $this->newFakeUser( 'Jane', '1.2.3.4', 456 );
1282 $janeX3 = $this->newFakeUser( 'Jane', '6.7.8.9', 456 );
1283 $janeY1 = $this->newFakeUser( 'Jane', '1.2.3.4', 756 );
1284 $karaX1 = $this->newFakeUser( 'Kara', '5.5.5.5', 100 );
1285 $karaY1 = $this->newFakeUser( 'Kara', '5.5.5.5', 200 );
1286
1287 // Test limits on wiki X
1288 $this->assertFalse( $anon1->pingLimiter( 'edit' ), 'First anon edit' );
1289 $this->assertTrue( $anon2->pingLimiter( 'edit' ), 'Second anon edit' );
1290
1291 $this->assertFalse( $anon1->pingLimiter( 'purge' ), 'Anon purge' );
1292 $this->assertTrue( $anon1->pingLimiter( 'purge' ), 'Anon purge via same IP' );
1293
1294 $this->assertFalse( $anon3->pingLimiter( 'purge' ), 'Anon purge via different subnet' );
1295 $this->assertTrue( $anon2->pingLimiter( 'purge' ), 'Anon purge via same subnet' );
1296
1297 $this->assertFalse( $frankX1->pingLimiter( 'rollback' ), 'First rollback' );
1298 $this->assertTrue( $frankX2->pingLimiter( 'rollback' ), 'Second rollback via different IP' );
1299 $this->assertFalse( $janeX1->pingLimiter( 'rollback' ), 'Rlbk by different user, same IP' );
1300
1301 $this->assertFalse( $frankX1->pingLimiter( 'move' ), 'First move' );
1302 $this->assertTrue( $frankX2->pingLimiter( 'move' ), 'Second move via different IP' );
1303 $this->assertFalse( $janeX1->pingLimiter( 'move' ), 'Move by different user, same IP' );
1304 $this->assertFalse( $karaX1->pingLimiter( 'move' ), 'Move by another user' );
1305 $this->assertTrue( $karaX1->pingLimiter( 'move' ), 'Second move by another user' );
1306
1307 $this->assertFalse( $frankX1->pingLimiter( 'delete' ), 'First delete' );
1308 $this->assertTrue( $janeX1->pingLimiter( 'delete' ), 'Delete via same IP' );
1309
1310 $this->assertTrue( $frankX2->pingLimiter( 'delete' ), 'Delete via same subnet' );
1311 $this->assertFalse( $janeX3->pingLimiter( 'delete' ), 'Delete via different subnet' );
1312
1313 // Now test how limits carry over to wiki Y
1314 $cacheAccess->keyspace = 'ywiki';
1315
1316 $this->assertFalse( $anon3->pingLimiter( 'edit' ), 'Anon edit on wiki Y' );
1317 $this->assertTrue( $anon4->pingLimiter( 'purge' ), 'Anon purge on wiki Y, same subnet' );
1318 $this->assertFalse( $frankY1->pingLimiter( 'rollback' ), 'Rollback on wiki Y, same name' );
1319 $this->assertTrue( $frankY1->pingLimiter( 'move' ), 'Move on wiki Y, same name' );
1320 $this->assertTrue( $janeY1->pingLimiter( 'move' ), 'Move on wiki Y, different user' );
1321 $this->assertTrue( $frankY1->pingLimiter( 'delete' ), 'Delete on wiki Y, same IP' );
1322
1323 // For a user without a global ID, user-global acts as a local restriction
1324 $this->assertFalse( $karaY1->pingLimiter( 'move' ), 'Move by another user' );
1325 $this->assertTrue( $karaY1->pingLimiter( 'move' ), 'Second move by another user' );
1326 }
1327
1328 private function installMockContralIdProvider() {
1329 $mockCentralIdLookup = $this->createMock( CentralIdLookup::class );
1330
1331 $mockCentralIdLookup->method( 'centralIdFromLocalUser' )
1332 ->willReturnCallback( function ( User $user ) {
1333 return $user->getId() % 100;
1334 } );
1335 $mockCentralIdLookup->method( 'getProviderId' )
1336 ->willReturn( 'test' );
1337
1338 $this->setMwGlobals( [
1339 'wgCentralIdLookupProvider' => 'test',
1340 'wgCentralIdLookupProviders' => [
1341 'test' => [
1342 'factory' => function () use ( $mockCentralIdLookup ) {
1343 return $mockCentralIdLookup;
1344 }
1345 ]
1346 ]
1347 ] );
1348 }
1349
1350 // Backported functions for supporting backported tests
1351
1358 public function overrideUserPermissions( $user, $permissions = [] ) {
1359 $user->mRights = $permissions;
1360 }
1361}
they could even be mouse clicks or menu items whatever suits your program You should also get your if any
Definition COPYING.txt:326
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
$wgRevokePermissions
Permission keys revoked from users in each group.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgGroupPermissions['sysop']['replacetext']
$wgUser
Definition Setup.php:902
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition Block.php:1588
const TYPE_USER
Definition Block.php:83
WebRequest clone which takes values from a provided array.
Simple store for keeping values in an associative array for the current process.
static generateHex( $chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format.
static TestUser[] $users
Database $db
Primary database.
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
static getTestSysop()
Convenience method for getting an immutable admin test user.
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static getMain()
Get the RequestContext object associated with the main request.
Database.
Definition UserTest.php:12
testUserPermissions()
User::getRights.
Definition UserTest.php:91
testGetGroupsWithPermission( $expected, $right)
provideGetGroupsWithPermission User::getGroupsWithPermission
Definition UserTest.php:152
testExperienceLevelAnon()
User::getExperienceLevel.
Definition UserTest.php:997
testUserGetRightsHooks()
User::getRights.
Definition UserTest.php:102
testOptions()
Test changing user options.
Definition UserTest.php:348
newFakeAnon( $ip)
newFakeUser( $name, $ip, $id)
testGetCanonicalName( $name, $expectedArray)
User::getCanonicalName() provideGetCanonicalName.
Definition UserTest.php:452
User $user
Definition UserTest.php:16
testNewFromAnyId()
testAutoblockCookies()
When a user is autoblocked a cookie is set with which to track them in case they log out and change I...
Definition UserTest.php:605
testAutoblockCookieInfiniteExpiry()
When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie should ma...
Definition UserTest.php:734
testAutoblockCookieInauthentic()
Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
Definition UserTest.php:835
testExperienceLevel( $editCount, $memberSince, $expLevel)
User::getExperienceLevel provideExperienceLevel.
Definition UserTest.php:969
testIsPingLimitable()
User::isPingLimitable.
Definition UserTest.php:930
static provideGetGroupsWithPermission()
Definition UserTest.php:160
testIsValidUserName( $username, $result, $message)
provideUserNames User::isValidUserName
Definition UserTest.php:210
testIsIP( $value, $result, $message)
provideIPs User::isIP
Definition UserTest.php:185
testGetEditCount()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:272
testAutoblockCookieNoSecretKey()
The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
Definition UserTest.php:881
testSoftBlockRanges()
Definition UserTest.php:797
static provideGetCanonicalName()
Definition UserTest.php:476
testAnonOptions()
T39963 Make sure defaults are loaded when setOption is called.
Definition UserTest.php:377
setUpPermissionGlobals()
Definition UserTest.php:33
testIncEditCount()
Test User::editCount medium User::incEditCount.
Definition UserTest.php:329
testGetEditCountForAnons()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:308
testRevokePermissions()
User::getGroupPermissions.
Definition UserTest.php:80
static provideIsLocallBlockedProxy()
installMockContralIdProvider()
provideExperienceLevel()
Definition UserTest.php:952
testGetId()
User::getId.
Definition UserTest.php:522
testEquals()
User::equals.
Definition UserTest.php:498
testCheckPasswordValidity()
Test password validity checks.
Definition UserTest.php:393
testIsLocallyBlockedProxy( $ip, $blockListEntry)
provideIsLocallBlockedProxy User::isLocallyBlockedProxy
testBlockInstanceCache()
User::getBlockedStatus User::getBlock User::blockedBy User::blockedFor User::isHidden User::isBlocked...
testAllRightsWithMessage()
Test, if for all rights a right- message exist, which is used on Special:ListGroupRights as help text...
Definition UserTest.php:244
testCheckAndSetTouched()
User::checkAndSetTouched.
Definition UserTest.php:549
testPingLimiterGlobal()
User::pingLimiter.
testLoggedIn()
User::isLoggedIn User::isAnon.
Definition UserTest.php:531
testAutoblockCookiesDisabled()
Make sure that no cookie is set to track autoblocked users when $wgCookieSetOnAutoblock is false.
Definition UserTest.php:687
testGroupPermissions()
User::getGroupPermissions.
Definition UserTest.php:63
static provideIPs()
Definition UserTest.php:189
testFindUsersByGroup()
User::findUsersByGroup.
Definition UserTest.php:570
overrideUserPermissions( $user, $permissions=[])
Overrides specific user permissions.
static provideUserNames()
Definition UserTest.php:214
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition User.php:591
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
Definition User.php:5672
static isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
Definition User.php:1999
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition User.php:657
static purge( $wikiId, $userId)
Definition User.php:496
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition User.php:1210
static newFromRow( $row, $data=null)
Create a new user object from a user row.
Definition User.php:750
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition User.php:614
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition User.php:4982
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
Definition User.php:4955
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
Definition User.php:1053
static selectFields()
Return the list of user fields that should be selected to create a new user object.
Definition User.php:5646
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
Definition User.php:729
static getAllRights()
Get a list of all available permissions.
Definition User.php:5111
setOption( $oname, $val)
Set the given option for a user.
Definition User.php:3241
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition User.php:4297
incEditCount()
Deferred version of incEditCountImmediate()
Definition User.php:5324
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
Definition User.php:629
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
$res
Definition database.txt:21
this hook is for auditing only $req
Definition hooks.txt:990
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2806
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:785
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
const MIGRATION_WRITE_BOTH
Definition Defines.php:303
const NS_USER_TALK
Definition Defines.php:77
$cache
Definition mcc.php:33
CACHE_MEMCACHED $wgMainCacheType
Definition memcached.txt:63
A helper class for throttling authentication attempts.
const DB_MASTER
Definition defines.php:29