Go to the documentation of this file.
3 use Wikimedia\TestingAccessWrapper;
23 $mock = TestingAccessWrapper::newFromObject(
new MockApi() );
24 $result = call_user_func_array( [ $mock, $method ],
$args );
25 $this->assertSame( $expected,
$result );
30 [
null,
'getModuleManager' ],
31 [
null,
'getCustomPrinter' ],
32 [ [],
'getHelpUrls' ],
35 [
true,
'shouldCheckMaxLag' ],
36 [
true,
'isReadMode' ],
37 [
false,
'isWriteMode' ],
38 [
false,
'mustBePosted' ],
39 [
false,
'isDeprecated' ],
40 [
false,
'isInternal' ],
41 [
false,
'needsToken' ],
42 [
null,
'getWebUITokenSalt', [ [] ] ],
43 [
null,
'getConditionalRequestData', [
'etag' ] ],
44 [
null,
'dynamicParameterDocumentation' ],
50 $mock->requireOnlyOneParameter(
51 [
"filename" =>
"foo.txt",
"enablechunks" =>
false ],
52 "filename",
"enablechunks"
54 $this->assertTrue(
true );
62 $mock->requireOnlyOneParameter(
63 [
"filename" =>
"foo.txt",
"enablechunks" => 0 ],
64 "filename",
"enablechunks"
73 $mock->requireOnlyOneParameter(
74 [
"filename" =>
"foo.txt",
"enablechunks" =>
true ],
75 "filename",
"enablechunks"
81 'One of the parameters "foo" and "bar" is required.' );
83 $mock->requireOnlyOneParameter(
84 [
"filename" =>
"foo.txt",
"enablechunks" =>
false ],
90 $mock->requireMaxOneParameter(
91 [
'foo' =>
'bar',
'baz' =>
'quz' ],
93 $this->assertTrue(
true );
98 $mock->requireMaxOneParameter(
99 [
'foo' =>
'bar',
'baz' =>
'quz' ],
101 $this->assertTrue(
true );
106 'The parameters "foo" and "baz" can not be used together.' );
108 $mock->requireMaxOneParameter(
109 [
'foo' =>
'bar',
'baz' =>
'quz' ],
115 'At least one of the parameters "foo" and "bar" is required.' );
117 $mock->requireAtLeastOneParameter(
118 [
'a' =>
'b',
'c' =>
'd' ],
124 $mock->requireAtLeastOneParameter(
125 [
'a' =>
'b',
'c' =>
'd' ],
127 $this->assertTrue(
true );
132 $mock->requireAtLeastOneParameter(
133 [
'a' =>
'b',
'c' =>
'd' ],
135 $this->assertTrue(
true );
140 'The parameters "title" and "pageid" can not be used together.' );
142 $mock->getTitleOrPageId( [
'title' =>
'a',
'pageid' => 7 ] );
147 $result = $mock->getTitleOrPageId( [
'title' =>
'Foo' ] );
149 $this->assertSame(
'Foo',
$result->getTitle()->getPrefixedText() );
156 $mock->getTitleOrPageId( [
'title' =>
'|' ] );
161 "Namespace doesn't allow actual pages." );
163 $mock->getTitleOrPageId( [
'title' =>
'Special:RandomPage' ] );
169 [
'pageid' => $page->getId() ] );
172 $page->getTitle()->getPrefixedText(),
173 $result->getTitle()->getPrefixedText()
182 'There is no page with ID 2147483648.' );
184 $mock->getTitleOrPageId( [
'pageid' => 2147483648 ] );
189 'The parameters "title" and "pageid" can not be used together.' );
191 $mock->getTitleFromTitleOrPageId( [
'title' =>
'a',
'pageid' => 7 ] );
196 $result = $mock->getTitleFromTitleOrPageId( [
'title' =>
'Foo' ] );
198 $this->assertSame(
'Foo',
$result->getPrefixedText() );
205 $mock->getTitleFromTitleOrPageId( [
'title' =>
'|' ] );
211 [
'pageid' => $page->getId() ] );
213 $this->assertSame( $page->getTitle()->getPrefixedText(),
$result->getPrefixedText() );
218 'There is no page with ID 298401643.' );
220 $mock->getTitleFromTitleOrPageId( [
'pageid' => 298401643 ] );
225 ->setMethods( [
'getAllowedParams' ] )
227 $mock->method(
'getAllowedParams' )->willReturn( [
235 $wrapper = TestingAccessWrapper::newFromObject( $mock );
242 $this->assertSame(
'value', $wrapper->getParameter(
'bar' ) );
246 $wrapper->getParameter(
'foo' );
247 $this->fail(
'Expected exception not thrown' );
254 $mock->extractRequestParams();
255 $this->fail(
'Expected exception not thrown' );
276 $wrapper = TestingAccessWrapper::newFromObject( $mock );
278 $wrapper->mModulePrefix =
'my';
279 $paramName =
'Param';
281 $paramName =
'myParam';
289 $parseLimits =
$options[
'parseLimits'] ??
true;
291 if ( !empty(
$options[
'apihighlimits'] ) ) {
292 $context->setUser( self::$users[
'sysop']->getUser() );
296 $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->mMainModule );
297 $mainWrapper->mInternalMode =
false;
308 if ( $expected instanceof Exception ) {
310 $wrapper->getParameterFromSettings( $paramName, $paramSettings,
312 $this->fail(
'No exception thrown' );
313 }
catch ( Exception $ex ) {
314 $this->assertEquals( $expected, $ex );
317 $result = $wrapper->getParameterFromSettings( $paramName,
318 $paramSettings, $parseLimits );
325 $this->assertRegExp(
'/^\d{14}$/',
$result );
326 $this->assertLessThanOrEqual( 1,
328 "Result $result differs from expected $expected by " .
329 'more than one second' );
331 $this->assertSame( $expected,
$result );
333 $actualWarnings = array_map(
function ( $warn ) {
334 return $warn instanceof Message
335 ? array_merge( [ $warn->getKey() ], $warn->getParams() )
337 }, $mock->warnings );
338 $this->assertSame( $warnings, $actualWarnings );
345 $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->getMain() );
346 $this->assertSame( [
'myParam' ],
347 $mainWrapper->getSensitiveParams() );
375 [
'apiwarn-badutf8',
'myParam' ],
380 for ( $i = 0; $i < 32; $i++ ) {
382 $enc .= ( $i === 9 || $i === 10 || $i === 13 )
388 'Basic param' => [
'bar',
null,
'bar', [] ],
389 'Basic param, C0 controls' => [ $c0,
null, $enc, $warnings ],
390 'String param' => [
'bar',
'',
'bar', [] ],
391 'String param, defaulted' => [
null,
'',
'', [] ],
392 'String param, empty' => [
'',
'default',
'', [] ],
393 'String param, required, empty' => [
397 [
'apierror-missingparam',
'myParam' ] ),
400 'Multi-valued parameter' => [
406 'Multi-valued parameter, alternative separator' => [
412 'Multi-valued parameter, other C0 controls' => [
418 'Multi-valued parameter, other C0 controls (2)' => [
421 [ substr( $enc, 0, -3 ),
'' ],
424 'Multi-valued parameter with limits' => [
433 'Multi-valued parameter with exceeded limits' => [
440 null, [
'apierror-toomanyvalues',
'myParam', 2 ],
'too-many-myParam'
444 'Multi-valued parameter with exceeded limits for non-bot' => [
452 null, [
'apierror-toomanyvalues',
'myParam', 2 ],
'too-many-myParam'
456 'Multi-valued parameter with non-exceeded limits for bot' => [
465 [
'apihighlimits' =>
true ],
467 'Multi-valued parameter with prohibited duplicates' => [
472 [ 0 =>
'a', 1 =>
'b', 3 =>
'c' ],
475 'Multi-valued parameter with allowed duplicates' => [
484 'Empty boolean param' => [
490 'Boolean param 0' => [
496 'Boolean param false' => [
502 'Boolean multi-param' => [
509 'Internal error in ApiBase::getParameterFromSettings: ' .
510 'Multi-values not supported for myParam'
514 'Empty boolean param with non-false default' => [
521 'Internal error in ApiBase::getParameterFromSettings: ' .
522 "Boolean param myParam's default is set to '1'. " .
523 'Boolean parameters must default to false.' ),
526 'Deprecated parameter' => [
530 [ [
'apiwarn-deprecation-parameter',
'myParam' ] ],
532 'Deprecated parameter value' => [
536 [ [
'apiwarn-deprecation-parameter',
'myParam=a' ] ],
538 'Multiple deprecated parameter values' => [
541 [
'b' =>
true,
'd' =>
true ],
543 [
'a',
'b',
'c',
'd' ],
545 [
'apiwarn-deprecation-parameter',
'myParam=b' ],
546 [
'apiwarn-deprecation-parameter',
'myParam=d' ],
549 'Deprecated parameter value with custom warning' => [
555 '"*" when wildcard not allowed' => [
560 [ [
'apiwarn-unrecognizedvalues',
'myParam',
561 [
'list' => [
'*' ],
'type' =>
'comma' ], 1 ] ],
573 'Wildcard "*" with multiples not allowed' => [
580 [
'apierror-unrecognizedvalue',
'myParam',
'*' ],
584 'Wildcard "*" with unrestricted type' => [
603 'Wildcard conflicting with allowed value' => [
611 'Internal error in ApiBase::getParameterFromSettings: ' .
612 'For param myParam, PARAM_ALL collides with a possible ' .
616 'Namespace with wildcard' => [
626 'Namespace with wildcard suppressed' => [
636 'Namespace with wildcard "x"' => [
644 [ [
'apiwarn-unrecognizedvalues',
'myParam',
645 [
'list' => [
'x' ],
'type' =>
'comma' ], 1 ] ],
648 'dDy+G?e?txnr.1:(@[Ru',
650 'dDy+G?e?txnr.1:(@[Ru',
653 'Sensitive field' => [
654 'I am fond of pineapples',
656 'I am fond of pineapples',
659 'Upload with default' => [
666 'Internal error in ApiBase::getParameterFromSettings: ' .
667 "File upload param myParam's default is set to ''. " .
668 'File upload parameters may not have a default.' ),
671 'Multiple upload' => [
678 'Internal error in ApiBase::getParameterFromSettings: ' .
679 'Multi-values not supported for myParam' ),
687 [
'apierror-unrecognizedvalue',
'myParam',
'-1' ],
691 'Extra namespace -1' => [
702 'Nonexistent module' => [
707 [
'foo' =>
'foo',
'bar' =>
'foo+bar' ],
712 'apierror-unrecognizedvalue',
720 '\\x1f with multiples not allowed' => [
724 'apierror-badvalue-notmultivalue',
725 'badvalue_notmultivalue' ),
728 'Integer with unenforced min' => [
735 [ [
'apierror-integeroutofrange-belowminimum',
'myParam', -1,
738 'Integer with enforced min' => [
746 [
'apierror-integeroutofrange-belowminimum',
'myParam',
747 '-1',
'-2' ],
'integeroutofrange',
748 [
'min' => -1,
'max' =>
null,
'botMax' =>
null ] ),
751 'Integer with unenforced max (internal mode)' => [
760 'Integer with enforced max (internal mode)' => [
770 'Integer with unenforced max (non-internal mode)' => [
777 [ [
'apierror-integeroutofrange-abovemax',
'myParam', 7, 8 ] ],
778 [
'internalmode' =>
false ],
780 'Integer with enforced max (non-internal mode)' => [
789 [
'apierror-integeroutofrange-abovemax',
'myParam',
'7',
'8' ],
791 [
'min' =>
null,
'max' => 7,
'botMax' => 7 ]
794 [
'internalmode' =>
false ],
796 'Array of integers' => [
805 'Array of integers with unenforced min/max (internal mode)' => [
814 [ [
'apierror-integeroutofrange-belowminimum',
'myParam', 0, -1 ] ],
816 'Array of integers with enforced min/max (internal mode)' => [
827 [
'apierror-integeroutofrange-belowminimum',
'myParam', 0, -1 ],
829 [
'min' => 0,
'max' => 100,
'botMax' => 100 ]
833 'Array of integers with unenforced min/max (non-internal mode)' => [
843 [
'apierror-integeroutofrange-abovemax',
'myParam', 100, 966 ],
844 [
'apierror-integeroutofrange-belowminimum',
'myParam', 0, -1 ]
846 [
'internalmode' =>
false ],
848 'Array of integers with enforced min/max (non-internal mode)' => [
859 [
'apierror-integeroutofrange-abovemax',
'myParam', 100, 966 ],
861 [
'min' => 0,
'max' => 100,
'botMax' => 100 ]
864 [
'internalmode' =>
false ],
866 'Limit with parseLimits false' => [
871 [
'parseLimits' =>
false ],
873 'Limit with no max' => [
881 'Internal error in ApiBase::getParameterFromSettings: ' .
882 'MAX1 or MAX2 are not defined for the limit myParam' ),
885 'Limit with no max2' => [
893 'Internal error in ApiBase::getParameterFromSettings: ' .
894 'MAX1 or MAX2 are not defined for the limit myParam' ),
897 'Limit with multi-value' => [
906 'Internal error in ApiBase::getParameterFromSettings: ' .
907 'Multi-values not supported for myParam' ),
930 'Limit max for apihighlimits' => [
939 [
'apihighlimits' =>
true ],
941 'Limit too large (internal mode)' => [
951 'Limit okay for apihighlimits (internal mode)' => [
960 [
'apihighlimits' =>
true ],
962 'Limit too large for apihighlimits (internal mode)' => [
971 [
'apihighlimits' =>
true ],
973 'Limit too large (non-internal mode)' => [
981 [ [
'apierror-integeroutofrange-abovemax',
'myParam', 100, 101 ] ],
982 [
'internalmode' =>
false ],
984 'Limit okay for apihighlimits (non-internal mode)' => [
993 [
'internalmode' =>
false,
'apihighlimits' =>
true ],
995 'Limit too large for apihighlimits (non-internal mode)' => [
1003 [ [
'apierror-integeroutofrange-abovebotmax',
'myParam', 101, 102 ] ],
1004 [
'internalmode' =>
false,
'apihighlimits' =>
true ],
1006 'Limit too small' => [
1015 [ [
'apierror-integeroutofrange-belowminimum',
'myParam', -1,
1029 [ [
'apiwarn-unclearnowtimestamp',
'myParam',
'0' ] ],
1031 'Timestamp empty' => [
1035 [ [
'apiwarn-unclearnowtimestamp',
'myParam',
'' ] ],
1044 'Timestamp now' => [
1050 'Invalid timestamp' => [
1055 [
'apierror-badtimestamp',
'myParam',
'a potato' ],
1056 'badtimestamp_myParam'
1060 'Timestamp array' => [
1075 'User prefixed with "User:"' => [
1081 'Invalid username "|"' => [
1085 [
'apierror-baduser',
'myParam',
'|' ],
1086 'baduser_myParam' ),
1089 'Invalid username "300.300.300.300"' => [
1093 [
'apierror-baduser',
'myParam',
'300.300.300.300' ],
1094 'baduser_myParam' ),
1097 'IP range as username' => [
1103 'IPv6 as username' => [
1109 'Obsolete cloaked usemod IP address as username' => [
1115 'Invalid username containing IP address' => [
1116 'This is [not] valid 1.2.3.xxx, ha!',
1120 [
'apierror-baduser',
'myParam',
'This is [not] valid 1.2.3.xxx, ha!' ],
1125 'External username' => [
1131 'Array of usernames' => [
1146 'Array of one tag' => [
1155 'Array of tags' => [
1169 'invalid tag', 1 ) ),
1172 'Unrecognized type' => [
1176 'Internal error in ApiBase::getParameterFromSettings: ' .
1177 "Param myParam's type is unknown - nonexistenttype" ),
1180 'Too many bytes' => [
1187 [
'apierror-maxbytes',
'myParam', 0 ] ),
1190 'Too many chars' => [
1197 [
'apierror-maxchars',
'myParam', 1 ] ),
1200 'Omitted required param' => [
1204 [
'apierror-missingparam',
'myParam' ] ),
1207 'Empty multi-value' => [
1213 'Multi-value \x1f' => [
1219 'Allowed non-multi-value with "|"' => [
1225 'Prohibited multi-value' => [
1230 'apierror-multival-only-one-of',
1232 Message::listParam( [
'<kbd>a</kbd>',
'<kbd>b</kbd>' ] ),
1249 [
"\t1", 1,
'\t1' ],
1250 [
"\r1", 1,
'\r1' ],
1251 [
"\f1", 0,
'\f1',
'badutf-8' ],
1252 [
"\n1", 1,
'\n1' ],
1253 [
"\v1", 0,
'\v1',
'badutf-8' ],
1254 [
"\e1", 0,
'\e1',
'badutf-8' ],
1255 [
"\x001", 0,
'\x001',
'badutf-8' ],
1258 foreach ( $integerTests
as $test ) {
1259 $desc = $test[2] ?? $test[0];
1260 $warnings = isset( $test[3] ) ?
1261 [ [
'apiwarn-badutf8',
'myParam' ] ] : [];
1262 $returnArray[
"\"$desc\" as integer"] = [
1270 return $returnArray;
1278 $this->assertEquals( $expect, $mock->errorArrayToStatus( [] ) );
1282 $expect->fatal(
'blockedtext' );
1283 $expect->fatal(
'autoblockedtext' );
1284 $expect->fatal(
'systemblockedtext' );
1285 $expect->fatal(
'mainpage' );
1286 $expect->fatal(
'parentheses',
'foobar' );
1287 $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1289 [
'autoblockedtext' ],
1290 [
'systemblockedtext' ],
1292 [
'parentheses',
'foobar' ],
1297 $block = new \Block( [
1298 'address' =>
$user->getName(),
1299 'user' =>
$user->getID(),
1301 'reason' => __METHOD__,
1302 'expiry' => time() + 100500,
1309 $expect->fatal(
ApiMessage::create(
'apierror-autoblocked',
'autoblocked', $blockinfo ) );
1310 $expect->fatal(
ApiMessage::create(
'apierror-systemblocked',
'blocked', $blockinfo ) );
1311 $expect->fatal(
'mainpage' );
1312 $expect->fatal(
'parentheses',
'foobar' );
1313 $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1315 [
'autoblockedtext' ],
1316 [
'systemblockedtext' ],
1318 [
'parentheses',
'foobar' ],
1330 $this->fail(
'Expected exception not thrown' );
1341 $this->fail(
'Expected exception not thrown' );
1351 $this->fail(
'Expected exception not thrown' );
1354 'Exception has "unknownerror-nocode"' );
1363 'xxexists' =>
'exists!',
1364 'xxmulti' =>
'a|b|c|d|{bad}',
1366 'xxtemplate-a' =>
'A!',
1367 'xxtemplate-b' =>
'B1|B2|B3',
1368 'xxtemplate-c' =>
'',
1369 'xxrecursivetemplate-b-B1' =>
'X',
1370 'xxrecursivetemplate-b-B3' =>
'Y',
1371 'xxrecursivetemplate-b-B4' =>
'?',
1372 'xxemptytemplate-' =>
'nope',
1375 'errorformat' =>
'raw',
1382 ->setConstructorArgs( [ $main,
'test',
'xx' ] )
1383 ->setMethods( [
'getAllowedParams' ] )
1384 ->getMockForAbstractClass();
1385 $mock->method(
'getAllowedParams' )->willReturn( [
1386 'notexists' =>
null,
1398 'recursivetemplate-{m}-{t}' => [
1401 'emptytemplate-{m}' => [
1405 'badtemplate-{e}' => [
1408 'badtemplate2-{e}' => [
1411 'badtemplate3-{x}' => [
1416 $this->assertEquals( [
1417 'notexists' =>
null,
1418 'exists' =>
'exists!',
1419 'multi' => [
'a',
'b',
'c',
'd',
'{bad}' ],
1421 'template-a' => [
'A!' ],
1422 'template-b' => [
'B1',
'B2',
'B3' ],
1424 'template-d' =>
null,
1425 'recursivetemplate-a-A!' =>
null,
1426 'recursivetemplate-b-B1' =>
'X',
1427 'recursivetemplate-b-B2' =>
null,
1428 'recursivetemplate-b-B3' =>
'Y',
1429 ], $mock->extractRequestParams() );
1431 $used = TestingAccessWrapper::newFromObject( $main )->getParamsUsed();
1433 $this->assertEquals( [
1438 'xxrecursivetemplate-a-A!',
1439 'xxrecursivetemplate-b-B1',
1440 'xxrecursivetemplate-b-B2',
1441 'xxrecursivetemplate-b-B3',
1448 $warnings = $mock->getResult()->getResultData(
'warnings', [
'Strip' =>
'all' ] );
1449 $this->assertCount( 1, $warnings );
1450 $this->assertSame(
'ignoring-invalid-templated-value', $warnings[0][
'code'] );
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
This is the main API class, used for both external and internal processing.
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
WebRequest clone which takes values from a provided array.
testGetTitleOrPageIdBadParams()
Exception used to abort API execution with an error.
testGetTitleFromTitleOrPageIdInvalidTitle()
processing should stop and the error should be shown to the user * false
testRequireOnlyOneParameterZero()
ApiUsageException.
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
const PARAM_REQUIRED
(boolean) Is the parameter required?
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 and they can depend only on the ResourceLoaderContext $context
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,...
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. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
testGetTitleFromTitleOrPageIdPageId()
testRequireAtLeastOneParameterTwo()
static newFatal( $message)
Factory function for fatal errors.
testGetTitleOrPageIdTitle()
testRequireOnlyOneParameterDefault()
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
testExtractRequestParams()
ApiBase::extractRequestParams.
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
doGetParameterFromSettings( $input, $paramSettings, $expected, $warnings, $options=[])
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
testGetTitleOrPageIdPageId()
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
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note 'password'-type fields are always sensitive regardless of ...
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
testRequireMaxOneParameterZero()
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
An IContextSource implementation which will inherit context from another source but allow individual ...
testRequireAtLeastOneParameterOne()
testRequireOnlyOneParameterTrue()
ApiUsageException.
if(is_array( $mode)) switch( $mode) $input
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
testRequireMaxOneParameterOne()
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
testStubMethods( $expected, $method, $args=[])
This covers a variety of stub methods that return a fixed value.
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
testRequireOnlyOneParameterMissing()
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
testRequireAtLeastOneParameterZero()
static newGood( $value=null)
Factory function for good results.
testGetTitleFromTitleOrPageIdInvalidPageId()
testGetParameterFromSettings_prefix( $input, $paramSettings, $expected, $warnings, $options=[])
provideGetParameterFromSettings
testGetTitleOrPageIdInvalidPageId()
static getMain()
Get the RequestContext object associated with the main request.
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
testGetTitleFromTitleOrPageIdBadParams()
const PARAM_TEMPLATE_VARS
(array) Indicate that this is a templated parameter, and specify replacements.
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
static provideGetParameterFromSettings()
static apiExceptionHasCode(ApiUsageException $ex, $code)
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
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
testRequireMaxOneParameterTwo()
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
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
const PARAM_MAX_CHARS
(integer) Maximum length of a string in characters (unicode codepoints).
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
testGetParameterFromSettings_noprefix( $input, $paramSettings, $expected, $warnings, $options=[])
provideGetParameterFromSettings
testGetTitleOrPageIdSpecialTitle()
const PARAM_MAX_BYTES
(integer) Maximum length of a string in bytes (in UTF-8 encoding).
testGetTitleOrPageIdInvalidTitle()
testGetTitleFromTitleOrPageIdTitle()
static getBlockInfo(Block $block)
Get basic info about a given block.