3define(
'NS_UNITTEST', 5600 );
4define(
'NS_UNITTEST_TALK', 5601 );
10use Wikimedia\TestingAccessWrapper;
29 'wgGroupPermissions' => [],
30 'wgRevokePermissions' => [],
43 # Data for regular $wgGroupPermissions test
56 # Data for regular $wgRevokePermissions test
61 # For the options test
63 'editmyoptions' =>
true,
72 $this->assertContains(
'runtest', $rights );
73 $this->assertNotContains(
'writetest', $rights );
74 $this->assertNotContains(
'modifytest', $rights );
75 $this->assertNotContains(
'nukeworld', $rights );
78 $this->assertContains(
'runtest', $rights );
79 $this->assertContains(
'writetest', $rights );
80 $this->assertContains(
'modifytest', $rights );
81 $this->assertNotContains(
'nukeworld', $rights );
89 $this->assertNotContains(
'runtest', $rights );
90 $this->assertNotContains(
'writetest', $rights );
91 $this->assertNotContains(
'modifytest', $rights );
92 $this->assertNotContains(
'nukeworld', $rights );
99 $rights = $this->
user->getRights();
100 $this->assertContains(
'runtest', $rights );
101 $this->assertNotContains(
'writetest', $rights );
102 $this->assertNotContains(
'modifytest', $rights );
103 $this->assertNotContains(
'nukeworld', $rights );
111 $userWrapper = TestingAccessWrapper::newFromObject(
$user );
114 $this->assertContains(
'test', $rights,
'sanity check' );
115 $this->assertContains(
'runtest', $rights,
'sanity check' );
116 $this->assertContains(
'writetest', $rights,
'sanity check' );
117 $this->assertNotContains(
'nukeworld', $rights,
'sanity check' );
121 $rights[] =
'nukeworld';
122 $rights = array_diff( $rights, [
'writetest' ] );
125 $userWrapper->mRights =
null;
127 $this->assertContains(
'test', $rights );
128 $this->assertContains(
'runtest', $rights );
129 $this->assertNotContains(
'writetest', $rights );
130 $this->assertContains(
'nukeworld', $rights );
133 $mock = $this->getMockBuilder( stdClass::class )
134 ->setMethods( [
'getAllowedUserRights',
'deregisterSession',
'getSessionId' ] )
136 $mock->method(
'getAllowedUserRights' )->willReturn( [
'test',
'writetest' ] );
137 $mock->method(
'getSessionId' )->willReturn(
138 new MediaWiki\Session\SessionId( str_repeat(
'X', 32 ) )
140 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
141 $mockRequest = $this->getMockBuilder( FauxRequest::class )
142 ->setMethods( [
'getSession' ] )
144 $mockRequest->method(
'getSession' )->willReturn( $session );
145 $userWrapper->mRequest = $mockRequest;
147 $userWrapper->mRights =
null;
149 $this->assertContains(
'test', $rights );
150 $this->assertNotContains(
'runtest', $rights );
151 $this->assertNotContains(
'writetest', $rights );
152 $this->assertNotContains(
'nukeworld', $rights );
164 $this->assertEquals( $expected,
$result,
"Groups with permission $right" );
170 [
'unittesters',
'testwriters' ],
198 [
'',
false,
'Empty string' ],
199 [
' ',
false,
'Blank space' ],
200 [
'10.0.0.0',
true,
'IPv4 private 10/8' ],
201 [
'10.255.255.255',
true,
'IPv4 private 10/8' ],
202 [
'192.168.1.1',
true,
'IPv4 private 192.168/16' ],
203 [
'203.0.113.0',
true,
'IPv4 example' ],
204 [
'2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
true,
'IPv6 example' ],
208 [
'300.300.300.300',
true,
'Looks too much like an IPv4 address' ],
209 [
'203.0.113.xxx',
true,
'Assigned by UseMod to cloaked logged-out users' ],
223 [
'',
false,
'Empty string' ],
224 [
' ',
false,
'Blank space' ],
225 [
'abcd',
false,
'Starts with small letter' ],
226 [
'Ab/cd',
false,
'Contains slash' ],
227 [
'Ab cd',
true,
'Whitespace' ],
228 [
'192.168.1.1',
false,
'IP' ],
229 [
'116.17.184.5/32',
false,
'IP range' ],
230 [
'::e:f:2001/96',
false,
'IPv6 range' ],
231 [
'User:Abcd',
false,
'Reserved Namespace' ],
232 [
'12abcd232',
true,
'Starts with Numbers' ],
233 [
'?abcd',
true,
'Start with ? mark' ],
234 [
'#abcd',
false,
'Start with #' ],
235 [
'Abcdകഖഗഘ',
true,
' Mixed scripts' ],
236 [
'ജോസ്തോമസ്',
false,
'ZWNJ- Format control character' ],
237 [
'Ab cd',
false,
' Ideographic space' ],
238 [
'300.300.300.300',
false,
'Looks too much like an IPv4 address' ],
239 [
'302.113.311.900',
false,
'Looks too much like an IPv4 address' ],
240 [
'203.0.113.xxx',
false,
'Reserved for usage by UseMod for cloaked logged-out users' ],
253 $page = WikiPage::factory( Title::newFromText(
'Help:UserTest_EditCount' ) );
254 for ( $i = 0; $i < 3; $i++ ) {
255 $page->doEditContent(
256 ContentHandler::makeContent( (
string)$i, $page->getTitle() ),
267 'After three edits, the user edit count should be 3'
277 'After increasing the edit count manually, the user edit count should be 4'
291 'Edit count starts null for anonymous users.'
298 'Edit count remains null for anonymous users despite calls to increase it.'
312 $reloadedUser->incEditCount();
316 $reloadedUser->getEditCount(),
317 'Increasing the edit count after a fresh load leaves the object up to date.'
336 $this->assertEquals(
'test',
$user->
getOption(
'userjs-someoption' ) );
340 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
341 $this->assertEquals(
'test',
$user->
getOption(
'userjs-someoption' ) );
357 $this->
user->setOption(
'userjs-someoption',
'test' );
359 $this->assertEquals(
'test', $this->
user->getOption(
'userjs-someoption' ) );
373 'wgPasswordPolicy' => [
376 'MinimalPasswordLength' => 8,
377 'MinimumPasswordLengthToLogin' => 1,
378 'PasswordCannotMatchUsername' => 1,
381 'MinimalPasswordLength' => 6,
382 'PasswordCannotMatchUsername' =>
true,
383 'PasswordCannotMatchBlacklist' =>
true,
384 'MaximalPasswordLength' => 40,
388 'MinimalPasswordLength' =>
'PasswordPolicyChecks::checkMinimalPasswordLength',
389 'MinimumPasswordLengthToLogin' =>
'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
390 'PasswordCannotMatchUsername' =>
'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
391 'PasswordCannotMatchBlacklist' =>
'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
392 'MaximalPasswordLength' =>
'PasswordPolicyChecks::checkMaximalPasswordLength',
398 $user = static::getTestUser()->getUser();
410 $longPass = str_repeat(
'a', 41 );
434 'InterwikiLoadPrefix' => [
435 function ( $prefix, &$iwdata ) {
436 if ( $prefix ===
'interwiki' ) {
438 'iw_url' =>
'http://example.com/',
448 foreach ( $expectedArray
as $validate => $expected ) {
457 'Leading space' => [
' Leading space', [
'creatable' =>
'Leading space' ] ],
458 'Trailing space ' => [
'Trailing space ', [
'creatable' =>
'Trailing space' ] ],
459 'Namespace prefix' => [
'Talk:Username', [
'creatable' =>
false,
'usable' =>
false,
460 'valid' =>
false,
'false' =>
'Talk:Username' ] ],
461 'Interwiki prefix' => [
'interwiki:Username', [
'creatable' =>
false,
'usable' =>
false,
462 'valid' =>
false,
'false' =>
'Interwiki:Username' ] ],
463 'With hash' => [
'name with # hash', [
'creatable' =>
false,
'usable' =>
false ] ],
464 'Multi spaces' => [
'Multi spaces', [
'creatable' =>
'Multi spaces',
465 'usable' =>
'Multi spaces' ] ],
466 'Lowercase' => [
'lowercase', [
'creatable' =>
'Lowercase' ] ],
467 'Invalid character' => [
'in[]valid', [
'creatable' =>
false,
'usable' =>
false,
468 'valid' =>
false,
'false' =>
'In[]valid' ] ],
469 'With slash' => [
'with / slash', [
'creatable' =>
false,
'usable' =>
false,
'valid' =>
false,
470 'false' =>
'With / slash' ] ],
481 $this->assertTrue( $first->equals( $first ) );
482 $this->assertTrue( $first->equals( $second ) );
483 $this->assertTrue( $second->equals( $first ) );
488 $this->assertFalse( $third->equals( $fourth ) );
489 $this->assertFalse( $fourth->equals( $third ) );
495 $this->assertTrue( $fifth->equals( $sixth ) );
502 $user = static::getTestUser()->getUser();
530 $user = TestingAccessWrapper::newFromObject(
$user );
536 $this->assertGreaterThan(
542 $this->assertGreaterThan(
543 $touched,
$user->
getDBTouched(),
"user_touched increased with casOnTouched() #2" );
554 $this->assertEquals( 0, iterator_count(
$users ) );
557 $this->assertEquals( 0, iterator_count(
$users ) );
561 $this->assertEquals( 1, iterator_count(
$users ) );
568 $this->assertEquals( 2, iterator_count(
$users ) );
572 $this->assertTrue( $user2->equals(
$users->current() ) );
577 $this->assertEquals( 1, iterator_count(
$users ) );
591 'wgCookieSetOnAutoblock' =>
true,
592 'wgCookiePrefix' =>
'wmsitetitle',
598 'PerformRetroactiveAutoblock' => []
604 $request1->getSession()->setUser( $user1tmp );
605 $expiryFiveHours =
wfTimestamp() + ( 5 * 60 * 60 );
606 $block =
new Block( [
607 'enableAutoblock' =>
true,
608 'expiry' =>
wfTimestamp( TS_MW, $expiryFiveHours ),
611 $block->setTarget( $user1tmp );
612 $res = $block->insert();
613 $this->assertTrue( (
bool)
$res[
'id'],
'Failed to insert block' );
615 $user1->mBlock = $block;
619 $this->assertTrue( $user1->isLoggedIn() );
620 $this->assertTrue( $user1->isBlocked() );
622 $this->assertTrue( $block->isAutoblocking() );
623 $this->assertGreaterThanOrEqual( 1, $block->getId() );
626 $cookies = $request1->response()->getCookies();
627 $this->assertArrayHasKey(
'wmsitetitleBlockID', $cookies );
628 $this->assertEquals( $expiryFiveHours, $cookies[
'wmsitetitleBlockID'][
'expire'] );
630 $this->assertEquals( $block->getId(), $cookieValue );
634 $request2->setCookie(
'BlockID', $block->getCookieValue() );
637 $this->assertNotEquals( $user1->getId(), $user2->getId() );
638 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
639 $this->assertTrue( $user2->isAnon() );
640 $this->assertFalse( $user2->isLoggedIn() );
641 $this->assertTrue( $user2->isBlocked() );
643 $this->assertEquals(
true, $user2->getBlock()->isAutoblocking(),
'Autoblock does not work' );
646 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
647 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
652 $request3->getSession()->setUser( $user3tmp );
653 $request3->setCookie(
'BlockID', $block->getId() );
656 $this->assertTrue( $user3->isLoggedIn() );
657 $this->assertTrue( $user3->isBlocked() );
658 $this->assertEquals(
true, $user3->getBlock()->isAutoblocking() );
672 'wgCookieSetOnAutoblock' =>
false,
673 'wgCookiePrefix' =>
'wm_no_cookies',
679 'PerformRetroactiveAutoblock' => []
685 $request1->getSession()->setUser( $testUser );
686 $block =
new Block( [
'enableAutoblock' =>
true ] );
688 $block->setTarget( $testUser );
689 $res = $block->insert();
690 $this->assertTrue( (
bool)
$res[
'id'],
'Failed to insert block' );
692 $user->mBlock = $block;
699 $this->assertTrue( $block->isAutoblocking() );
701 $this->assertGreaterThanOrEqual( $block->getId(),
$user->
getBlockId() );
702 $cookies = $request1->response()->getCookies();
703 $this->assertArrayNotHasKey(
'wm_no_cookiesBlockID', $cookies );
717 'wgCookieSetOnAutoblock' =>
true,
718 'wgCookiePrefix' =>
'wm_infinite_block',
724 'PerformRetroactiveAutoblock' => []
730 $request1->getSession()->setUser( $user1Tmp );
731 $block =
new Block( [
'enableAutoblock' =>
true,
'expiry' =>
'infinity' ] );
733 $block->setTarget( $user1Tmp );
734 $res = $block->insert();
735 $this->assertTrue( (
bool)
$res[
'id'],
'Failed to insert block' );
737 $user1->mBlock = $block;
741 $this->assertTrue( $user1->isLoggedIn() );
742 $this->assertTrue( $user1->isBlocked() );
744 $this->assertTrue( $block->isAutoblocking() );
745 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
746 $cookies = $request1->response()->getCookies();
748 $this->assertArrayHasKey(
'wm_infinite_blockBlockID', $cookies );
753 $cookies[
'wm_infinite_blockBlockID'][
'expire'],
760 $block->setExpiry(
wfTimestamp( TS_MW, $newExpiry ) );
764 $request2->getSession()->setUser( $user2tmp );
766 $user2->mBlock = $block;
768 $cookies = $request2->response()->getCookies();
769 $this->assertEquals(
wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
770 $this->assertEquals( $newExpiry, $cookies[
'wm_infinite_blockBlockID'][
'expire'] );
782 RequestContext::getMain()->setUser(
$user );
783 RequestContext::getMain()->setRequest(
$request );
784 TestingAccessWrapper::newFromObject(
$user )->mRequest =
$request;
787 $this->
setMwGlobals(
'wgSoftBlockRanges', [
'10.0.0.0/8' ] );
790 $wgUser =
new User();
793 $setSessionUser( $wgUser,
$request );
794 $this->assertNull( $wgUser->getBlock() );
797 $wgUser =
new User();
800 $setSessionUser( $wgUser,
$request );
801 $block = $wgUser->getBlock();
802 $this->assertInstanceOf( Block::class, $block );
803 $this->assertSame(
'wgSoftBlockRanges', $block->getSystemBlockType() );
809 $setSessionUser( $wgUser,
$request );
810 $this->assertFalse( $wgUser->isAnon(),
'sanity check' );
811 $this->assertNull( $wgUser->getBlock() );
821 'wgCookieSetOnAutoblock' =>
true,
822 'wgCookiePrefix' =>
'wmsitetitle',
828 'PerformRetroactiveAutoblock' => []
834 $request1->getSession()->setUser( $user1tmp );
835 $block =
new Block( [
'enableAutoblock' =>
true ] );
837 $block->setTarget( $user1tmp );
838 $res = $block->insert();
839 $this->assertTrue( (
bool)
$res[
'id'],
'Failed to insert block' );
841 $user1->mBlock = $block;
847 $request2->setCookie(
'BlockID', $block->getId() .
'!zzzzzzz' );
850 $this->assertTrue( $user2->isAnon() );
851 $this->assertFalse( $user2->isLoggedIn() );
852 $this->assertFalse( $user2->isBlocked() );
866 'wgCookieSetOnAutoblock' =>
true,
867 'wgCookiePrefix' =>
'wmsitetitle',
868 'wgSecretKey' =>
null,
873 'PerformRetroactiveAutoblock' => []
879 $request1->getSession()->setUser( $user1tmp );
880 $block =
new Block( [
'enableAutoblock' =>
true ] );
882 $block->setTarget( $user1tmp );
883 $res = $block->insert();
884 $this->assertTrue( (
bool)
$res[
'id'],
'Failed to insert block' );
886 $user1->mBlock = $block;
888 $this->assertTrue( $user1->isBlocked() );
893 $request2->setCookie(
'BlockID', $block->getId() );
896 $this->assertNotEquals( $user1->getId(), $user2->getId() );
897 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
898 $this->assertTrue( $user2->isAnon() );
899 $this->assertFalse( $user2->isLoggedIn() );
900 $this->assertTrue( $user2->isBlocked() );
901 $this->assertEquals(
true, $user2->getBlock()->isAutoblocking() );
918 $this->
setMwGlobals(
'wgRateLimitsExcludedIPs', [
'1.2.3.4' ] );
921 $this->
setMwGlobals(
'wgRateLimitsExcludedIPs', [
'1.2.3.0/8' ] );
925 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
926 ->setMethods( [
'getIP',
'getRights' ] )->getMock();
927 $noRateLimitUser->expects( $this->any() )->method(
'getIP' )->willReturn(
'1.2.3.4' );
928 $noRateLimitUser->expects( $this->any() )->method(
'getRights' )->willReturn( [
'noratelimit' ] );
929 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
934 [ 2, 2,
'newcomer' ],
935 [ 12, 3,
'newcomer' ],
936 [ 8, 5,
'newcomer' ],
937 [ 15, 10,
'learner' ],
938 [ 450, 20,
'learner' ],
939 [ 460, 33,
'learner' ],
940 [ 525, 28,
'learner' ],
941 [ 538, 33,
'experienced' ],
951 'wgLearnerEdits' => 10,
952 'wgLearnerMemberSince' => 4,
953 'wgExperiencedUserEdits' => 500,
954 'wgExperiencedUserMemberSince' => 30,
960 $userQuery[
'tables'],
961 $userQuery[
'fields'],
962 [
'user_id' => $this->
getTestUser()->getUser()->getId() ],
967 $row->user_editcount = $editCount;
968 $row->user_registration =
$db->
timestamp( time() - $memberSince * 86400 );
985 [
'1.2.3.4',
'1.2.3.4' ],
986 [
'1.2.3.4',
'1.2.3.0/16' ],
1011 'test' => $blockListEntry
1017 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1018 'addresses in keys: ' . $blockListEntry .
', please move them to values)'
1023 $blockListEntry =>
'test'
1033 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1039 $this->assertTrue(
$user->
getActorId() > 0,
'User::createNew sets an actor ID' );
1043 $this->assertTrue(
$user->
getActorId() > 0,
'User::addToDatabase sets an actor ID' );
1046 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be retrieved for user loaded by name' );
1049 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be retrieved for user loaded by ID' );
1052 $this->assertEquals(
$user->
getId(), $user2->getId(),
1053 'User::newFromActorId works for an existing user' );
1055 $row = $this->db->selectRow(
'user',
User::selectFields(), [
'user_id' => $id ], __METHOD__ );
1058 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1063 $this->assertEquals(
1065 $this->db->selectField(
1066 'actor',
'actor_name', [
'actor_id' =>
$user->
getActorId() ], __METHOD__
1068 'User::saveSettings updates actor table for name change'
1072 $ip =
'192.168.12.34';
1073 $this->db->delete(
'actor', [
'actor_name' => $ip ], __METHOD__ );
1076 $this->assertFalse(
$user->
getActorId() > 0,
'Anonymous user has no actor ID by default' );
1078 'Actor ID can be created for an anonymous user' );
1081 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be loaded for an anonymous user' );
1083 $this->assertEquals(
$user->
getName(), $user2->getName(),
1084 'User::newFromActorId works for an anonymous user' );
1102 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1108 $this->assertTrue(
$user->
getActorId() > 0,
'User::createNew sets an actor ID' );
1112 $this->assertTrue(
$user->
getActorId() > 0,
'User::addToDatabase sets an actor ID' );
1115 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be retrieved for user loaded by name' );
1118 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be retrieved for user loaded by ID' );
1121 $this->assertEquals(
$user->
getId(), $user2->getId(),
1122 'User::newFromActorId works for an existing user' );
1124 $row = $this->db->selectRow(
'user',
User::selectFields(), [
'user_id' => $id ], __METHOD__ );
1127 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1129 $this->db->delete(
'actor', [
'actor_user' => $id ], __METHOD__ );
1132 ObjectCache::getMainWANInstance()->clearProcessCache();
1135 $this->assertFalse(
$user->
getActorId() > 0,
'No Actor ID by default if none in database' );
1136 $this->assertTrue(
$user->
getActorId( $this->db ) > 0,
'Actor ID can be created if none in db' );
1140 $this->assertEquals(
1142 $this->db->selectField(
1143 'actor',
'actor_name', [
'actor_id' =>
$user->
getActorId() ], __METHOD__
1145 'User::saveSettings updates actor table for name change'
1149 $ip =
'192.168.12.34';
1150 $this->db->delete(
'actor', [
'actor_name' => $ip ], __METHOD__ );
1153 $this->assertFalse(
$user->
getActorId() > 0,
'Anonymous user has no actor ID by default' );
1155 'Actor ID can be created for an anonymous user' );
1158 $this->assertTrue(
$user->
getActorId() > 0,
'Actor ID can be loaded for an anonymous user' );
1160 $this->assertEquals(
$user->
getName(), $user2->getName(),
1161 'User::newFromActorId works for an anonymous user' );
1170 for ( $i = 1; $i <= 7; $i++ ) {
1176 $this->assertSame(
$user->
getId(), $test->getId() );
1177 $this->assertSame(
$user->
getName(), $test->getName() );
1186 $this->assertSame(
$user->
getId(), $test->getId() );
1187 $this->assertSame(
$user->
getName(), $test->getName() );
1190 $this->assertSame(
$user->
getId(), $test->getId() );
1191 $this->assertSame(
$user->
getName(), $test->getName() );
1197 $this->assertSame( 123456, $test->getId() );
1198 $this->assertSame(
'Bogus', $test->getName() );
1199 $this->assertSame( 654321, $test->getActorId() );
1204 $this->fail(
'Expected exception not thrown' );
1205 }
catch ( InvalidArgumentException $ex ) {
1209 $this->fail(
'Expected exception not thrown' );
1210 }
catch ( InvalidArgumentException $ex ) {
1226 $this->assertInstanceOf( User::class,
$result );
1234 $this->assertInstanceOf( User::class,
$result );
1242 $this->assertInstanceOf( User::class,
$result );
1260 $this->assertNull(
$user->
getBlock(
false ),
'sanity check' );
1263 $this->assertFalse( (
bool)
$user->
isHidden(),
'sanity check' );
1268 $block =
new Block( [
1270 'allowUsertalk' =>
false,
1271 'reason' =>
'Because',
1273 $block->setTarget(
$user );
1274 $block->setBlocker( $blocker );
1275 $res = $block->insert();
1276 $this->assertTrue( (
bool)
$res[
'id'],
'sanity check: Failed to insert block' );
1280 $this->assertInstanceOf( Block::class,
$user->
getBlock(
false ) );
1310 'wgBlockAllowsUTEdit' =>
$options[
'blockAllowsUTEdit'] ??
true,
1315 if (
$title === self::USER_TALK_PAGE ) {
1322 foreach (
$options[
'pageRestrictions'] ?? []
as $pagestr ) {
1328 foreach (
$options[
'namespaceRestrictions'] ?? []
as $ns ) {
1332 $block =
new Block( [
1334 'allowUsertalk' =>
$options[
'allowUsertalk'] ??
false,
1335 'sitewide' => !$restrictions,
1337 $block->setTarget(
$user );
1338 $block->setBlocker( $this->
getTestSysop()->getUser() );
1339 if ( $restrictions ) {
1340 $block->setRestrictions( $restrictions );
1353 'Sitewide block, basic operation' => [
'Test page',
true ],
1354 'Sitewide block, not allowing user talk' => [
1356 'allowUsertalk' =>
false,
1359 'Sitewide block, allowing user talk' => [
1361 'allowUsertalk' =>
true,
1364 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1366 'allowUsertalk' =>
true,
1367 'blockAllowsUTEdit' =>
false,
1370 'Partial block, blocking the page' => [
1371 'Test page',
true, [
1372 'pageRestrictions' => [
'Test page' ],
1375 'Partial block, not blocking the page' => [
1376 'Test page 2',
false, [
1377 'pageRestrictions' => [
'Test page' ],
1380 'Partial block, not allowing user talk but user talk page is not blocked' => [
1382 'allowUsertalk' =>
false,
1383 'pageRestrictions' => [
'Test page' ],
1386 'Partial block, allowing user talk but user talk page is blocked' => [
1388 'allowUsertalk' =>
true,
1392 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1394 'allowUsertalk' =>
false,
1395 'pageRestrictions' => [
'Test page' ],
1396 'blockAllowsUTEdit' =>
false,
1399 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1401 'allowUsertalk' =>
true,
1403 'blockAllowsUTEdit' =>
false,
1406 'Partial user talk namespace block, not allowing user talk' => [
1408 'allowUsertalk' =>
false,
1412 'Partial user talk namespace block, allowing user talk' => [
1414 'allowUsertalk' =>
true,
1418 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1420 'allowUsertalk' =>
true,
1422 'blockAllowsUTEdit' =>
false,
1435 'wgCookieSetOnIpBlock' =>
true,
1436 'wgCookiePrefix' =>
'wiki',
1441 $block =
new Block( [
1444 $block->setTarget(
'1.2.3.4' );
1445 $block->setBlocker( $this->
getTestSysop()->getUser() );
1457 $cookies =
$request->response()->getCookies();
1458 $this->assertArrayHasKey(
'wikiBlockID', $cookies );
1471 'wgCookieSetOnIpBlock' =>
false,
1472 'wgCookiePrefix' =>
'wiki',
1477 $block =
new Block( [
1480 $block->setTarget(
'1.2.3.4' );
1481 $block->setBlocker( $this->
getTestSysop()->getUser() );
1493 $cookies =
$request->response()->getCookies();
1494 $this->assertArrayNotHasKey(
'wikiBlockID', $cookies );
1507 'wgAutoblockExpiry' => 8000,
1508 'wgCookieSetOnIpBlock' =>
true,
1509 'wgCookiePrefix' =>
'wiki',
1514 $block =
new Block( [
1517 $block->setTarget(
'1.2.3.4' );
1518 $block->setBlocker( $this->
getTestSysop()->getUser() );
1525 $request->setCookie(
'BlockID', $block->getCookieValue() );
1534 $cookies =
$request->response()->getCookies();
1535 $this->assertEquals(
'', $cookies[
'wikiBlockID'][
'value'] );
1546 $clock = MWTimestamp::convert( TS_UNIX,
'20100101000000' );
1547 MWTimestamp::setFakeTime(
function ()
use ( &$clock ) {
1548 return $clock += 1000;
1552 $firstRevision =
self::makeEdit(
$user,
'Help:UserTest_GetEditTimestamp',
'one',
'test' );
1553 $secondRevision =
self::makeEdit(
$user,
'Help:UserTest_GetEditTimestamp',
'two',
'test' );
1555 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1560 MWTimestamp::setFakeTime(
false );
1572 $page = WikiPage::factory( Title::newFromText(
$title ) );
1576 return $updater->saveRevision( CommentStoreComment::newUnsavedComment( $comment ) );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
$wgGroupPermissions
Permission keys given to users in each group.
$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.
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
WebRequest clone which takes values from a provided array.
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
testUserPermissions()
User::getRights.
testGetGroupsWithPermission( $expected, $right)
provideGetGroupsWithPermission User::getGroupsWithPermission
testIpBlockCookieSet()
Block cookie should be set for IP Blocks if wgCookieSetOnIpBlock is set to true User::trackBlockWithC...
testActorId_old()
Actor tests with SCHEMA_COMPAT_READ_OLD.
testExperienceLevelAnon()
User::getExperienceLevel.
testUserGetRightsHooks()
User::getRights.
testOptions()
Test changing user options.
const USER_TALK_PAGE
Constant for self::testIsBlockedFrom.
testGetFirstLatestEditTimestamp()
User::getFirstEditTimestamp User::getLatestEditTimestamp.
testGetCanonicalName( $name, $expectedArray)
User::getCanonicalName() provideGetCanonicalName.
testNewFromAnyId()
User::newFromAnyId.
testAutoblockCookies()
When a user is autoblocked a cookie is set with which to track them in case they log out and change I...
static makeEdit(User $user, $title, $content, $comment)
testAutoblockCookieInfiniteExpiry()
When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie should ma...
testAutoblockCookieInauthentic()
Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
testExperienceLevel( $editCount, $memberSince, $expLevel)
User::getExperienceLevel provideExperienceLevel.
testIsPingLimitable()
User::isPingLimitable.
static provideGetGroupsWithPermission()
testIsValidUserName( $username, $result, $message)
provideUserNames User::isValidUserName
testIsIP( $value, $result, $message)
provideIPs User::isIP
testGetEditCount()
Test User::editCount medium User::getEditCount.
testAutoblockCookieNoSecretKey()
The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
testSoftBlockRanges()
User::getBlockedStatus.
static provideGetCanonicalName()
testAnonOptions()
T39963 Make sure defaults are loaded when setOption is called.
testIncEditCount()
Test User::editCount medium User::incEditCount.
testIpBlockCookieIgnoredWhenUserLoggedIn()
When an ip user is blocked and then they log in, cookie block should be invalid and the cookie remove...
testIpBlockCookieNotSet()
Block cookie should NOT be set when wgCookieSetOnIpBlock is disabled User::trackBlockWithCookie.
testGetEditCountForAnons()
Test User::editCount medium User::getEditCount.
testRevokePermissions()
User::getGroupPermissions.
static provideIsLocallBlockedProxy()
testNewFromIdentity()
User::newFromIdentity.
testEquals()
User::equals.
static provideIsBlockedFrom()
testCheckPasswordValidity()
Test password validity checks.
testIsLocallyBlockedProxy( $ip, $blockListEntry)
provideIsLocallBlockedProxy User::isLocallyBlockedProxy
testBlockInstanceCache()
User::getBlockedStatus User::getBlock User::blockedBy User::blockedFor User::isHidden User::isBlocked...
testCheckAndSetTouched()
User::checkAndSetTouched.
testLoggedIn()
User::isLoggedIn User::isAnon.
testAutoblockCookiesDisabled()
Make sure that no cookie is set to track autoblocked users when $wgCookieSetOnAutoblock is false.
testGroupPermissions()
User::getGroupPermissions.
testFindUsersByGroup()
User::findUsersByGroup.
testIsBlockedFrom( $title, $expect, array $options=[])
User::isBlockedFrom provideIsBlockedFrom.
testActorId()
User::newFromActorId.
static provideUserNames()
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
getPasswordValidity( $password)
Given unvalidated password input, return error message on failure.
getName()
Get the user name, or the IP of an anonymous user.
addToDatabase()
Add this existing user object to the database.
getExperienceLevel()
Compute experienced level based on edit count and registration date.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
getFirstEditTimestamp()
Get the timestamp of the first edit.
equals(UserIdentity $user)
Checks if two user objects point to the same user.
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
setName( $str)
Set the user name.
getId()
Get the user's ID.
static isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
static purge( $wikiId, $userId)
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
trackBlockWithCookie()
Set the 'BlockID' cookie depending on block type and user authentication status.
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
isPingLimitable()
Is this user subject to rate limiting?
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
static newFromRow( $row, $data=null)
Create a new user object from a user row.
static newFromId( $id)
Static factory method for creation from a given user ID.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
static selectFields()
Return the list of user fields that should be selected to create a new user object.
isHidden()
Check if user account is hidden.
checkPasswordValidity( $password)
Check if this is a valid password for this user.
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
setOption( $oname, $val)
Set the given option for a user.
getEditCount()
Get the user's edit count.
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
isValidPassword( $password)
Is the input a valid password for this user?
getLatestEditTimestamp()
Get the timestamp of the latest edit.
static newFromIdentity(UserIdentity $identity)
Returns a User object corresponding to the given UserIdentity.
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
getBlockId()
If user is blocked, return the ID for the block.
getTalkPage()
Get this user's talk page title.
isLoggedIn()
Get whether the user is logged in.
saveSettings()
Save this user's settings into the database.
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
blockedBy()
If user is blocked, return the name of the user who placed the block.
getRights()
Get the permissions this user has.
static createNew( $name, $params=[])
Add a user to the database, return the user object.
incEditCount()
Schedule a deferred update to update the user's edit count.
blockedFor()
If user is blocked, return the specified reason for the block.
getBlock( $fromReplica=true)
Get the block affecting the user, or null if the user is not blocked.
isBlocked( $fromReplica=true)
Check if user is blocked.
isAnon()
Get whether the user is anonymous.
isBlockedFrom( $title, $fromReplica=false)
Check if user is blocked from editing a particular article.
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
const SCHEMA_COMPAT_WRITE_BOTH
const SCHEMA_COMPAT_READ_OLD
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
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
namespace and then decline to actually register it file or subcat img or subcat $title
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Allows to change the fields on the form that will be generated $name
this hook is for auditing only or null if authentication failed before getting that far $username
processing should stop and the error should be shown to the user * false
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$page->newPageUpdater($user) $updater