MediaWiki REL1_33
BotPasswordTest.php
Go to the documentation of this file.
1<?php
2
5use Wikimedia\ScopedCallback;
6use Wikimedia\TestingAccessWrapper;
7
13
15 private $testUser;
16
19
20 protected function setUp() {
21 parent::setUp();
22
23 $this->setMwGlobals( [
24 'wgEnableBotPasswords' => true,
25 'wgBotPasswordsDatabase' => false,
26 'wgCentralIdLookupProvider' => 'BotPasswordTest OkMock',
27 'wgGrantPermissions' => [
28 'test' => [ 'read' => true ],
29 ],
30 'wgUserrightsInterwikiDelimiter' => '@',
31 ] );
32
33 $this->testUser = $this->getMutableTestUser();
34 $this->testUserName = $this->testUser->getUser()->getName();
35
36 $mock1 = $this->getMockForAbstractClass( CentralIdLookup::class );
37 $mock1->expects( $this->any() )->method( 'isAttached' )
38 ->will( $this->returnValue( true ) );
39 $mock1->expects( $this->any() )->method( 'lookupUserNames' )
40 ->will( $this->returnValue( [ $this->testUserName => 42, 'UTDummy' => 43, 'UTInvalid' => 0 ] ) );
41 $mock1->expects( $this->never() )->method( 'lookupCentralIds' );
42
43 $mock2 = $this->getMockForAbstractClass( CentralIdLookup::class );
44 $mock2->expects( $this->any() )->method( 'isAttached' )
45 ->will( $this->returnValue( false ) );
46 $mock2->expects( $this->any() )->method( 'lookupUserNames' )
47 ->will( $this->returnArgument( 0 ) );
48 $mock2->expects( $this->never() )->method( 'lookupCentralIds' );
49
50 $this->mergeMwGlobalArrayValue( 'wgCentralIdLookupProviders', [
51 'BotPasswordTest OkMock' => [ 'factory' => function () use ( $mock1 ) {
52 return $mock1;
53 } ],
54 'BotPasswordTest FailMock' => [ 'factory' => function () use ( $mock2 ) {
55 return $mock2;
56 } ],
57 ] );
58
59 CentralIdLookup::resetCache();
60 }
61
62 public function addDBData() {
63 $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
64 $passwordHash = $passwordFactory->newFromPlaintext( 'foobaz' );
65
66 $dbw = wfGetDB( DB_MASTER );
67 $dbw->delete(
68 'bot_passwords',
69 [ 'bp_user' => [ 42, 43 ], 'bp_app_id' => 'BotPassword' ],
70 __METHOD__
71 );
72 $dbw->insert(
73 'bot_passwords',
74 [
75 [
76 'bp_user' => 42,
77 'bp_app_id' => 'BotPassword',
78 'bp_password' => $passwordHash->toString(),
79 'bp_token' => 'token!',
80 'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
81 'bp_grants' => '["test"]',
82 ],
83 [
84 'bp_user' => 43,
85 'bp_app_id' => 'BotPassword',
86 'bp_password' => $passwordHash->toString(),
87 'bp_token' => 'token!',
88 'bp_restrictions' => '{"IPAddresses":["127.0.0.0/8"]}',
89 'bp_grants' => '["test"]',
90 ],
91 ],
92 __METHOD__
93 );
94 }
95
96 public function testBasics() {
97 $user = $this->testUser->getUser();
98 $bp = BotPassword::newFromUser( $user, 'BotPassword' );
99 $this->assertInstanceOf( BotPassword::class, $bp );
100 $this->assertTrue( $bp->isSaved() );
101 $this->assertSame( 42, $bp->getUserCentralId() );
102 $this->assertSame( 'BotPassword', $bp->getAppId() );
103 $this->assertSame( 'token!', trim( $bp->getToken(), " \0" ) );
104 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
105 $this->assertSame( [ 'test' ], $bp->getGrants() );
106
107 $this->assertNull( BotPassword::newFromUser( $user, 'DoesNotExist' ) );
108
109 $this->setMwGlobals( [
110 'wgCentralIdLookupProvider' => 'BotPasswordTest FailMock'
111 ] );
112 $this->assertNull( BotPassword::newFromUser( $user, 'BotPassword' ) );
113
114 $this->assertSame( '@', BotPassword::getSeparator() );
115 $this->setMwGlobals( [
116 'wgUserrightsInterwikiDelimiter' => '#',
117 ] );
118 $this->assertSame( '#', BotPassword::getSeparator() );
119 }
120
121 public function testUnsaved() {
122 $user = $this->testUser->getUser();
123 $bp = BotPassword::newUnsaved( [
124 'user' => $user,
125 'appId' => 'DoesNotExist'
126 ] );
127 $this->assertInstanceOf( BotPassword::class, $bp );
128 $this->assertFalse( $bp->isSaved() );
129 $this->assertSame( 42, $bp->getUserCentralId() );
130 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
131 $this->assertEquals( MWRestrictions::newDefault(), $bp->getRestrictions() );
132 $this->assertSame( [], $bp->getGrants() );
133
134 $bp = BotPassword::newUnsaved( [
135 'username' => 'UTDummy',
136 'appId' => 'DoesNotExist2',
137 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
138 'grants' => [ 'test' ],
139 ] );
140 $this->assertInstanceOf( BotPassword::class, $bp );
141 $this->assertFalse( $bp->isSaved() );
142 $this->assertSame( 43, $bp->getUserCentralId() );
143 $this->assertSame( 'DoesNotExist2', $bp->getAppId() );
144 $this->assertEquals( '{"IPAddresses":["127.0.0.0/8"]}', $bp->getRestrictions()->toJson() );
145 $this->assertSame( [ 'test' ], $bp->getGrants() );
146
147 $user = $this->testUser->getUser();
148 $bp = BotPassword::newUnsaved( [
149 'centralId' => 45,
150 'appId' => 'DoesNotExist'
151 ] );
152 $this->assertInstanceOf( BotPassword::class, $bp );
153 $this->assertFalse( $bp->isSaved() );
154 $this->assertSame( 45, $bp->getUserCentralId() );
155 $this->assertSame( 'DoesNotExist', $bp->getAppId() );
156
157 $user = $this->testUser->getUser();
158 $bp = BotPassword::newUnsaved( [
159 'user' => $user,
160 'appId' => 'BotPassword'
161 ] );
162 $this->assertInstanceOf( BotPassword::class, $bp );
163 $this->assertFalse( $bp->isSaved() );
164
165 $this->assertNull( BotPassword::newUnsaved( [
166 'user' => $user,
167 'appId' => '',
168 ] ) );
169 $this->assertNull( BotPassword::newUnsaved( [
170 'user' => $user,
171 'appId' => str_repeat( 'X', BotPassword::APPID_MAXLENGTH + 1 ),
172 ] ) );
173 $this->assertNull( BotPassword::newUnsaved( [
174 'user' => $this->testUserName,
175 'appId' => 'Ok',
176 ] ) );
177 $this->assertNull( BotPassword::newUnsaved( [
178 'username' => 'UTInvalid',
179 'appId' => 'Ok',
180 ] ) );
181 $this->assertNull( BotPassword::newUnsaved( [
182 'appId' => 'Ok',
183 ] ) );
184 }
185
186 public function testGetPassword() {
187 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
188
189 $password = $bp->getPassword();
190 $this->assertInstanceOf( Password::class, $password );
191 $this->assertTrue( $password->equals( 'foobaz' ) );
192
193 $bp->centralId = 44;
194 $password = $bp->getPassword();
195 $this->assertInstanceOf( InvalidPassword::class, $password );
196
197 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
198 $dbw = wfGetDB( DB_MASTER );
199 $dbw->update(
200 'bot_passwords',
201 [ 'bp_password' => 'garbage' ],
202 [ 'bp_user' => 42, 'bp_app_id' => 'BotPassword' ],
203 __METHOD__
204 );
205 $password = $bp->getPassword();
206 $this->assertInstanceOf( InvalidPassword::class, $password );
207 }
208
210 $bp1 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
211 $bp2 = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
212
213 $this->assertNotInstanceOf( InvalidPassword::class, $bp1->getPassword(), 'sanity check' );
214 $this->assertNotInstanceOf( InvalidPassword::class, $bp2->getPassword(), 'sanity check' );
215 BotPassword::invalidateAllPasswordsForUser( $this->testUserName );
216 $this->assertInstanceOf( InvalidPassword::class, $bp1->getPassword() );
217 $this->assertNotInstanceOf( InvalidPassword::class, $bp2->getPassword() );
218
219 $bp = TestingAccessWrapper::newFromObject( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
220 $this->assertInstanceOf( InvalidPassword::class, $bp->getPassword() );
221 }
222
224 $this->assertNotNull( BotPassword::newFromCentralId( 42, 'BotPassword' ), 'sanity check' );
225 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ), 'sanity check' );
226
227 BotPassword::removeAllPasswordsForUser( $this->testUserName );
228
229 $this->assertNull( BotPassword::newFromCentralId( 42, 'BotPassword' ) );
230 $this->assertNotNull( BotPassword::newFromCentralId( 43, 'BotPassword' ) );
231 }
232
236 public function testCanonicalizeLoginData( $username, $password, $expectedResult ) {
237 $result = BotPassword::canonicalizeLoginData( $username, $password );
238 if ( is_array( $expectedResult ) ) {
239 $this->assertArrayEquals( $expectedResult, $result, true, true );
240 } else {
241 $this->assertSame( $expectedResult, $result );
242 }
243 }
244
246 return [
247 [ 'user', 'pass', false ],
248 [ 'user', 'abc@def', false ],
249 [ 'legacy@user', 'pass', false ],
250 [ 'user@bot', '12345678901234567890123456789012',
251 [ 'user@bot', '12345678901234567890123456789012' ] ],
252 [ 'user', 'bot@12345678901234567890123456789012',
253 [ 'user@bot', '12345678901234567890123456789012' ] ],
254 [ 'user', 'bot@12345678901234567890123456789012345',
255 [ 'user@bot', '12345678901234567890123456789012345' ] ],
256 [ 'user', 'bot@x@12345678901234567890123456789012',
257 [ 'user@bot@x', '12345678901234567890123456789012' ] ],
258 ];
259 }
260
261 public function testLogin() {
262 // Test failure when bot passwords aren't enabled
263 $this->setMwGlobals( 'wgEnableBotPasswords', false );
264 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
265 $this->assertEquals( Status::newFatal( 'botpasswords-disabled' ), $status );
266 $this->setMwGlobals( 'wgEnableBotPasswords', true );
267
268 // Test failure when BotPasswordSessionProvider isn't configured
269 $manager = new SessionManager( [
270 'logger' => new Psr\Log\NullLogger,
271 'store' => new EmptyBagOStuff,
272 ] );
273 $reset = MediaWiki\Session\TestUtils::setSessionManagerSingleton( $manager );
274 $this->assertNull(
275 $manager->getProvider( MediaWiki\Session\BotPasswordSessionProvider::class ),
276 'sanity check'
277 );
278 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', new FauxRequest );
279 $this->assertEquals( Status::newFatal( 'botpasswords-no-provider' ), $status );
280 ScopedCallback::consume( $reset );
281
282 // Now configure BotPasswordSessionProvider for further tests...
283 $mainConfig = RequestContext::getMain()->getConfig();
284 $config = new HashConfig( [
285 'SessionProviders' => $mainConfig->get( 'SessionProviders' ) + [
286 MediaWiki\Session\BotPasswordSessionProvider::class => [
287 'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
288 'args' => [ [ 'priority' => 40 ] ],
289 ]
290 ],
291 ] );
292 $manager = new SessionManager( [
293 'config' => new MultiConfig( [ $config, RequestContext::getMain()->getConfig() ] ),
294 'logger' => new Psr\Log\NullLogger,
295 'store' => new EmptyBagOStuff,
296 ] );
297 $reset = MediaWiki\Session\TestUtils::setSessionManagerSingleton( $manager );
298
299 // No "@"-thing in the username
300 $status = BotPassword::login( $this->testUserName, 'foobaz', new FauxRequest );
301 $this->assertEquals( Status::newFatal( 'botpasswords-invalid-name', '@' ), $status );
302
303 // No base user
304 $status = BotPassword::login( 'UTDummy@BotPassword', 'foobaz', new FauxRequest );
305 $this->assertEquals( Status::newFatal( 'nosuchuser', 'UTDummy' ), $status );
306
307 // No bot password
308 $status = BotPassword::login( "{$this->testUserName}@DoesNotExist", 'foobaz', new FauxRequest );
309 $this->assertEquals(
310 Status::newFatal( 'botpasswords-not-exist', $this->testUserName, 'DoesNotExist' ),
311 $status
312 );
313
314 // Failed restriction
315 $request = $this->getMockBuilder( FauxRequest::class )
316 ->setMethods( [ 'getIP' ] )
317 ->getMock();
318 $request->expects( $this->any() )->method( 'getIP' )
319 ->will( $this->returnValue( '10.0.0.1' ) );
320 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
321 $this->assertEquals( Status::newFatal( 'botpasswords-restriction-failed' ), $status );
322
323 // Wrong password
324 $status = BotPassword::login(
325 "{$this->testUserName}@BotPassword", $this->testUser->getPassword(), new FauxRequest );
326 $this->assertEquals( Status::newFatal( 'wrongpassword' ), $status );
327
328 // Success!
329 $request = new FauxRequest;
330 $this->assertNotInstanceOf(
331 MediaWiki\Session\BotPasswordSessionProvider::class,
332 $request->getSession()->getProvider(),
333 'sanity check'
334 );
335 $status = BotPassword::login( "{$this->testUserName}@BotPassword", 'foobaz', $request );
336 $this->assertInstanceOf( Status::class, $status );
337 $this->assertTrue( $status->isGood() );
338 $session = $status->getValue();
339 $this->assertInstanceOf( MediaWiki\Session\Session::class, $session );
340 $this->assertInstanceOf(
341 MediaWiki\Session\BotPasswordSessionProvider::class, $session->getProvider()
342 );
343 $this->assertSame( $session->getId(), $request->getSession()->getId() );
344
345 ScopedCallback::consume( $reset );
346 }
347
352 public function testSave( $password ) {
353 $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
354
355 $bp = BotPassword::newUnsaved( [
356 'centralId' => 42,
357 'appId' => 'TestSave',
358 'restrictions' => MWRestrictions::newFromJson( '{"IPAddresses":["127.0.0.0/8"]}' ),
359 'grants' => [ 'test' ],
360 ] );
361 $this->assertFalse( $bp->isSaved(), 'sanity check' );
362 $this->assertNull(
363 BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ), 'sanity check'
364 );
365
366 $passwordHash = $password ? $passwordFactory->newFromPlaintext( $password ) : null;
367 $this->assertFalse( $bp->save( 'update', $passwordHash ) );
368 $this->assertTrue( $bp->save( 'insert', $passwordHash ) );
369 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST );
370 $this->assertInstanceOf( BotPassword::class, $bp2 );
371 $this->assertEquals( $bp->getUserCentralId(), $bp2->getUserCentralId() );
372 $this->assertEquals( $bp->getAppId(), $bp2->getAppId() );
373 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
374 $this->assertEquals( $bp->getRestrictions(), $bp2->getRestrictions() );
375 $this->assertEquals( $bp->getGrants(), $bp2->getGrants() );
376 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
377 if ( $password === null ) {
378 $this->assertInstanceOf( InvalidPassword::class, $pw );
379 } else {
380 $this->assertTrue( $pw->equals( $password ) );
381 }
382
383 $token = $bp->getToken();
384 $this->assertEquals( 42, $bp->getUserCentralId() );
385 $this->assertEquals( 'TestSave', $bp->getAppId() );
386 $this->assertFalse( $bp->save( 'insert' ) );
387 $this->assertTrue( $bp->save( 'update' ) );
388 $this->assertNotEquals( $token, $bp->getToken() );
389 $bp2 = BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST );
390 $this->assertInstanceOf( BotPassword::class, $bp2 );
391 $this->assertEquals( $bp->getToken(), $bp2->getToken() );
392 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
393 if ( $password === null ) {
394 $this->assertInstanceOf( InvalidPassword::class, $pw );
395 } else {
396 $this->assertTrue( $pw->equals( $password ) );
397 }
398
399 $passwordHash = $passwordFactory->newFromPlaintext( 'XXX' );
400 $token = $bp->getToken();
401 $this->assertTrue( $bp->save( 'update', $passwordHash ) );
402 $this->assertNotEquals( $token, $bp->getToken() );
403 $pw = TestingAccessWrapper::newFromObject( $bp )->getPassword();
404 $this->assertTrue( $pw->equals( 'XXX' ) );
405
406 $this->assertTrue( $bp->delete() );
407 $this->assertFalse( $bp->isSaved() );
408 $this->assertNull( BotPassword::newFromCentralId( 42, 'TestSave', BotPassword::READ_LATEST ) );
409
410 $this->assertFalse( $bp->save( 'foobar' ) );
411 }
412
413 public static function provideSave() {
414 return [
415 [ null ],
416 [ 'foobar' ],
417 ];
418 }
419}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
BotPassword Database.
testCanonicalizeLoginData( $username, $password, $expectedResult)
provideCanonicalizeLoginData
testSave( $password)
provideSave
A BagOStuff object with no objects in it.
WebRequest clone which takes values from a provided array.
A Config instance which stores all settings as a member variable.
static newFromJson( $json)
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
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.
assertArrayEquals(array $expected, array $actual, $ordered=false, $named=false)
Assert that two arrays are equal.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This serves as the entry point to the MediaWiki session handling system.
Provides a fallback sequence for Config objects.
Wraps the user object, so we can also retain full access to properties like password if we log in via...
Definition TestUser.php:9
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:2843
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
Definition hooks.txt:1991
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1266
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
Definition hooks.txt:783
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:782
return true to allow those checks to and false if checking is done & $user
Definition hooks.txt:1510
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
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
Definition injection.txt:37
A helper class for throttling authentication attempts.
const DB_MASTER
Definition defines.php:26