Go to the documentation of this file.
267 $this->mMainModule = $mainModule;
268 $this->mModuleName = $moduleName;
269 $this->mModulePrefix = $modulePrefix;
338 if ( !is_array( $examples ) ) {
339 $examples = [ $examples ];
340 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
341 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
342 !preg_match(
'/^\s*api\.php\?/', $examples[0] )
347 $examplesCount = count( $examples );
348 for ( $i = 0; $i < $examplesCount; $i += 2 ) {
349 $tmp[$examples[$i + 1]] = $examples[$i];
354 foreach ( $examples
as $k => $v ) {
355 if ( is_numeric( $k ) ) {
361 if ( is_array( $msg ) ) {
362 $msg = implode(
' ', $msg );
366 $qs = preg_replace(
'/^\s*api\.php\?/',
'', $qs );
367 $ret[$qs] = $this->
msg(
'api-help-fallback-example', [ $msg ] );
573 self::dieDebug( __METHOD__,
'base method was called on main module.' );
576 return $this->
getMain()->lacksSameOriginSecurity();
605 if (
$path ===
'main' ) {
609 $parts = explode(
'+',
$path );
610 if ( count( $parts ) === 1 ) {
612 $parts = explode(
' ',
$path );
615 $count = count( $parts );
616 for ( $i = 0; $i < $count; $i++ ) {
618 $manager = $parent->getModuleManager();
619 if ( $manager ===
null ) {
620 $errorPath = implode(
'+', array_slice( $parts, 0, $i ) );
621 $this->
dieWithError( [
'apierror-badmodule-nosubmodules', $errorPath ],
'badmodule' );
623 $module = $manager->getModule( $parts[$i] );
625 if ( $module ===
null ) {
626 $errorPath = $i ? implode(
'+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
628 [
'apierror-badmodule-badsubmodule', $errorPath,
wfEscapeWikiText( $parts[$i] ) ],
645 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
648 return $this->
getMain()->getResult();
659 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
662 return $this->
getMain()->getErrorFormatter();
670 if ( !isset( $this->mSlaveDB ) ) {
685 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
688 return $this->
getMain()->getContinuationManager();
699 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
702 $this->
getMain()->setContinuationManager( $manager );
731 if ( is_array( $paramName ) ) {
732 return array_map(
function (
$name ) {
733 return $this->mModulePrefix .
$name;
736 return $this->mModulePrefix . $paramName;
751 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
756 foreach (
$params as $paramName => $paramSettings ) {
758 $paramName, $paramSettings, $parseLimit );
761 $this->mParamCache[$parseLimit] = $results;
764 return $this->mParamCache[$parseLimit];
786 $required = func_get_args();
787 array_shift( $required );
789 $intersection = array_intersect( array_keys( array_filter(
$params,
790 [ $this,
'parameterNotEmpty' ] ) ), $required );
792 if ( count( $intersection ) > 1 ) {
794 'apierror-invalidparammix',
799 array_values( $intersection )
801 count( $intersection ),
803 } elseif ( count( $intersection ) == 0 ) {
805 'apierror-missingparam-one-of',
810 array_values( $required )
824 $required = func_get_args();
825 array_shift( $required );
827 $intersection = array_intersect( array_keys( array_filter(
$params,
828 [ $this,
'parameterNotEmpty' ] ) ), $required );
830 if ( count( $intersection ) > 1 ) {
832 'apierror-invalidparammix',
837 array_values( $intersection )
839 count( $intersection ),
852 $required = func_get_args();
853 array_shift( $required );
855 $intersection = array_intersect(
856 array_keys( array_filter(
$params, [ $this,
'parameterNotEmpty' ] ) ),
860 if ( count( $intersection ) == 0 ) {
862 'apierror-missingparam-at-least-one-of',
867 array_values( $required )
883 if ( $this->
getConfig()->
get(
'DebugAPI' ) || $this->
getMain()->isInternalMode() ) {
887 $queryValues = $this->
getRequest()->getQueryValues();
890 if ( $prefix !==
'noprefix' ) {
893 if ( array_key_exists( $param, $queryValues ) ) {
894 $badParams[] = $param;
900 [
'apierror-mustpostparams', implode(
', ', $badParams ), count( $badParams ) ]
912 return !is_null( $x ) && $x !==
false;
930 if ( isset(
$params[
'title'] ) ) {
932 if ( !$titleObj || $titleObj->isExternal() ) {
935 if ( !$titleObj->canExist() ) {
939 if ( $load !==
false ) {
940 $pageObj->loadPageData( $load );
942 } elseif ( isset(
$params[
'pageid'] ) ) {
943 if ( $load ===
false ) {
967 if ( isset(
$params[
'title'] ) ) {
969 if ( !$titleObj || $titleObj->isExternal() ) {
973 } elseif ( isset(
$params[
'pageid'] ) ) {
994 switch ( $watchlist ) {
1002 # If the user is already watching, don't bother checking
1003 if ( $userWatching ) {
1006 # If no user option was passed, use watchdefault and watchcreations
1007 if ( is_null( $userOption ) ) {
1008 return $this->
getUser()->getBoolOption(
'watchdefault' ) ||
1009 $this->
getUser()->getBoolOption(
'watchcreations' ) && !$titleObj->exists();
1012 # Watch the article based on the user preference
1013 return $this->
getUser()->getBoolOption( $userOption );
1016 return $userWatching;
1019 return $userWatching;
1037 if ( !is_array( $paramSettings ) ) {
1039 self::PARAM_DFLT => $paramSettings,
1043 $default = isset( $paramSettings[self::PARAM_DFLT] )
1046 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1049 $multiLimit1 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT1] )
1052 $multiLimit2 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT2] )
1055 $type = isset( $paramSettings[self::PARAM_TYPE] )
1058 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1061 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1064 $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] )
1067 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1070 $allowAll = isset( $paramSettings[self::PARAM_ALL] )
1075 if ( !isset(
$type ) ) {
1076 if ( isset( $default ) ) {
1077 $type = gettype( $default );
1083 if (
$type ==
'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
1084 $this->
getMain()->markParamsSensitive( $encParamName );
1087 if (
$type ==
'boolean' ) {
1088 if ( isset( $default ) && $default !==
false ) {
1092 "Boolean param $encParamName's default is set to '$default'. " .
1093 'Boolean parameters must default to false.'
1098 } elseif (
$type ==
'upload' ) {
1099 if ( isset( $default ) ) {
1103 "File upload param $encParamName's default is set to " .
1104 "'$default'. File upload parameters may not have a default." );
1107 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1110 if ( !
$value->exists() ) {
1114 $value = $this->
getMain()->getRequest()->unsetVal( $encParamName );
1117 [
'apierror-badupload', $encParamName ],
1118 "badupload_{$encParamName}"
1123 $value = $this->
getMain()->getVal( $encParamName, $default );
1127 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1128 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1130 $type = array_merge(
$type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1137 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1138 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1145 $rawValue =
$request->getRawVal( $encParamName );
1146 if ( $rawValue ===
null ) {
1147 $rawValue = $default;
1151 if ( isset(
$value ) && substr( $rawValue, 0, 1 ) ===
"\x1f" ) {
1155 $value = implode(
"\x1f",
$request->normalizeUnicode( explode(
"\x1f", $rawValue ) ) );
1157 $this->
dieWithError(
'apierror-badvalue-notmultivalue',
'badvalue_notmultivalue' );
1162 if ( $rawValue !==
$value ) {
1168 if ( $allowAll && $multi && is_array(
$type ) && in_array( $allSpecifier,
$type,
true ) ) {
1171 "For param $encParamName, PARAM_ALL collides with a possible value" );
1173 if ( isset(
$value ) && ( $multi || is_array(
$type ) ) ) {
1179 $allowAll ? $allSpecifier :
null,
1188 if ( !is_array(
$type ) ) {
1195 if ( $required &&
$value ===
'' ) {
1196 $this->
dieWithError( [
'apierror-missingparam', $paramName ] );
1200 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[
self::PARAM_MIN] :
null;
1201 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[
self::PARAM_MAX] :
null;
1202 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1205 if ( is_array(
$value ) ) {
1207 if ( !is_null( $min ) || !is_null( $max ) ) {
1209 $this->
validateLimit( $paramName, $v, $min, $max,
null, $enforceLimits );
1214 if ( !is_null( $min ) || !is_null( $max ) ) {
1220 if ( !$parseLimit ) {
1224 if ( !isset( $paramSettings[self::PARAM_MAX] )
1225 || !isset( $paramSettings[self::PARAM_MAX2] )
1229 "MAX1 or MAX2 are not defined for the limit $encParamName"
1233 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1235 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[
self::PARAM_MIN] : 0;
1247 $paramSettings[self::PARAM_MAX],
1248 $paramSettings[self::PARAM_MAX2]
1254 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1258 if ( is_array(
$value ) ) {
1259 foreach (
$value as $key => $val ) {
1267 if ( is_array(
$value ) ) {
1268 foreach (
$value as $key => $val ) {
1279 if ( !is_array(
$value ) && !$multi ) {
1283 if ( !$tagsStatus->isGood() ) {
1288 self::dieDebug( __METHOD__,
"Param $encParamName's type is unknown - $type" );
1293 if ( !$dupes && is_array(
$value ) ) {
1297 if ( in_array(
$type, [
'NULL',
'string',
'text',
'password' ],
true ) ) {
1299 if ( isset( $paramSettings[self::PARAM_MAX_BYTES] )
1300 && strlen( $val ) > $paramSettings[self::PARAM_MAX_BYTES]
1302 $this->
dieWithError( [
'apierror-maxbytes', $encParamName,
1303 $paramSettings[self::PARAM_MAX_BYTES] ] );
1305 if ( isset( $paramSettings[self::PARAM_MAX_CHARS] )
1306 && mb_strlen( $val,
'UTF-8' ) > $paramSettings[self::PARAM_MAX_CHARS]
1308 $this->
dieWithError( [
'apierror-maxchars', $encParamName,
1309 $paramSettings[self::PARAM_MAX_CHARS] ] );
1315 if ( $deprecated &&
$value !==
false ) {
1316 $feature = $encParamName;
1318 while ( !$m->isMain() ) {
1319 $p = $m->getParent();
1320 $name = $m->getModuleName();
1321 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup(
$name ) );
1322 $feature =
"{$param}={$name}&{$feature}";
1325 $this->
addDeprecation( [
'apiwarn-deprecation-parameter', $encParamName ], $feature );
1329 $usedDeprecatedValues = $deprecatedValues &&
$value !==
false
1330 ? array_intersect( array_keys( $deprecatedValues ), (
array)
$value )
1332 if ( $usedDeprecatedValues ) {
1333 $feature =
"$encParamName=";
1335 while ( !$m->isMain() ) {
1336 $p = $m->getParent();
1337 $name = $m->getModuleName();
1338 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup(
$name ) );
1339 $feature =
"{$param}={$name}&{$feature}";
1342 foreach ( $usedDeprecatedValues
as $v ) {
1343 $msg = $deprecatedValues[$v];
1344 if ( $msg ===
true ) {
1345 $msg = [
'apiwarn-deprecation-parameter',
"$encParamName=$v" ];
1350 } elseif ( $required ) {
1351 $this->
dieWithError( [
'apierror-missingparam', $paramName ] );
1366 $this->
addWarning( [
'apiwarn-badutf8', $encParamName ] );
1377 if ( substr(
$value, 0, 1 ) ===
"\x1f" ) {
1384 return explode( $sep,
$value, $limit );
1405 $allSpecifier =
null, $limit1 =
null, $limit2 =
null
1407 if ( (
$value ===
'' ||
$value ===
"\x1f" ) && $allowMultiple ) {
1416 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
1420 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1421 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1423 return $allowedValues;
1426 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1428 [
'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1429 "too-many-$valueName-for-{$this->getModulePath()}"
1433 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1435 if ( in_array(
$value, $allowedValues,
true ) ) {
1439 $values = array_map(
function ( $v ) {
1441 }, $allowedValues );
1443 'apierror-multival-only-one-of',
1447 ],
"multival_$valueName" );
1450 if ( is_array( $allowedValues ) ) {
1452 $unknown = array_map(
'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1453 if ( count( $unknown ) ) {
1454 if ( $allowMultiple ) {
1456 'apiwarn-unrecognizedvalues',
1463 [
'apierror-unrecognizedvalue', $valueName,
wfEscapeWikiText( $valuesList[0] ) ],
1464 "unknown_$valueName"
1469 $valuesList = array_intersect( $valuesList, $allowedValues );
1472 return $allowMultiple ? $valuesList : $valuesList[0];
1486 $enforceLimits =
false
1488 if ( !is_null( $min ) &&
$value < $min ) {
1490 [
'apierror-integeroutofrange-belowminimum',
1492 'integeroutofrange',
1493 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1495 $this->
warnOrDie( $msg, $enforceLimits );
1501 if ( $this->
getMain()->isInternalMode() ) {
1507 if ( !is_null( $max ) &&
$value > $max ) {
1508 if ( !is_null( $botMax ) && $this->
getMain()->canApiHighLimits() ) {
1509 if (
$value > $botMax ) {
1511 [
'apierror-integeroutofrange-abovebotmax',
1513 'integeroutofrange',
1514 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1516 $this->
warnOrDie( $msg, $enforceLimits );
1521 [
'apierror-integeroutofrange-abovemax',
1523 'integeroutofrange',
1524 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1526 $this->
warnOrDie( $msg, $enforceLimits );
1545 'unclear-"now"-timestamp'
1551 if (
$value ===
'now' ) {
1556 if ( $timestamp ===
false ) {
1559 "badtimestamp_{$encParamName}"
1578 if ( !isset( $salts[$tokenType] ) ) {
1580 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1581 'without registering it'
1588 if ( $tokenObj->match( $token ) ) {
1593 if ( $webUiSalt !==
null && $this->
getUser()->matchEditToken(
1618 $value = $titleObj->getText();
1636 "baduser_{$encParamName}"
1656 protected function setWatch( $watch, $titleObj, $userOption =
null ) {
1673 while ( count( $arr ) > $limit ) {
1688 if ( !is_null(
$params[
'owner'] ) && !is_null(
$params[
'token'] ) ) {
1695 $token =
$user->getOption(
'watchlisttoken' );
1696 if ( $token ==
'' || !hash_equals( $token,
$params[
'token'] ) ) {
1697 $this->
dieWithError(
'apierror-bad-watchlist-token',
'bad_wltoken' );
1700 if ( !$this->
getUser()->isLoggedIn() ) {
1701 $this->
dieWithError(
'watchlistanontext',
'notloggedin' );
1718 if ( is_array( $v ) ) {
1719 return array_map(
'self::escapeWikiText', $v );
1722 '__' =>
'__',
'{' =>
'{',
'}' =>
'}',
1723 '[[Category:' =>
'[[:Category:',
1724 '[[File:' =>
'[[:File:',
'[[Image:' =>
'[[:Image:',
1742 if ( is_string( $msg ) ) {
1744 } elseif ( is_array( $msg ) ) {
1745 $msg = call_user_func_array(
'wfMessage', $msg );
1747 if ( !$msg instanceof
Message ) {
1767 if (
$user ===
null ) {
1772 foreach ( $errors
as $error ) {
1773 if ( is_array( $error ) && $error[0] ===
'blockedtext' &&
$user->getBlock() ) {
1779 } elseif ( is_array( $error ) && $error[0] ===
'autoblockedtext' &&
$user->getBlock() ) {
1781 'apierror-autoblocked',
1785 } elseif ( is_array( $error ) && $error[0] ===
'systemblockedtext' &&
$user->getBlock() ) {
1787 'apierror-systemblocked',
1792 call_user_func_array( [
$status,
'fatal' ], (
array)$error );
1834 $data = (
array)$data;
1835 if ( $feature !==
null ) {
1836 $data[
'feature'] = $feature;
1839 $this->
addWarning( $msg,
'deprecation', $data );
1843 $msgs = [ $this->
msg(
'api-usage-mailinglist-ref' ) ];
1844 Hooks::run(
'ApiDeprecationHelp', [ &$msgs ] );
1845 if ( count( $msgs ) > 1 ) {
1846 $key =
'$' . implode(
' $', range( 1, count( $msgs ) ) );
1847 $msg = (
new RawMessage( $key ) )->params( $msgs );
1849 $msg = reset( $msgs );
1851 $this->
getMain()->addWarning( $msg,
'deprecation-help' );
1920 if ( $enforceLimits ) {
1939 'apierror-autoblocked',
1962 throw new MWException(
'Successful status passed to ApiBase::dieStatus' );
1968 if ( !
$status->getErrorsByType(
'error' ) ) {
1970 foreach (
$status->getErrorsByType(
'warning' )
as $err ) {
1971 call_user_func_array(
1972 [ $newStatus,
'fatal' ],
1973 array_merge( [ $err[
'message'] ], $err[
'params'] )
1976 if ( !$newStatus->getErrorsByType(
'error' ) ) {
1977 $newStatus->fatal(
'unknownerror-nocode' );
1992 'apierror-readonly',
2010 $rights = (
array)$rights;
2011 if ( !call_user_func_array( [
$user,
'isAllowedAny' ], $rights ) ) {
2012 $this->
dieWithError( [
'apierror-permissiondenied', $this->
msg(
"action-{$rights[0]}" ) ] );
2030 foreach ( (
array)$actions
as $action ) {
2031 $errors = array_merge( $errors,
$title->getUserPermissionsErrors( $action,
$user ) );
2050 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
true ) {
2078 protected static function dieDebug( $method, $message ) {
2079 throw new MWException(
"Internal error in $method: $message" );
2090 $s =
'"' . addslashes( $feature ) .
'"' .
2093 ' "' . addslashes(
$request->getHeader(
'Referer' ) ) .
'"' .
2094 ' "' . addslashes( $this->
getMain()->getUserAgent() ) .
'"';
2115 return "apihelp-{$this->getModulePath()}-summary";
2129 "apihelp-{$this->getModulePath()}-extended-description",
2130 'api-help-no-extended-description',
2150 if ( !$msg->exists() ) {
2151 wfDeprecated(
'API help "description" messages',
'1.30' );
2158 preg_replace(
'/\n.*/s',
'', $msg->text() )
2176 Hooks::run(
'APIGetDescription', [ &$apiModule, &$desc ] );
2178 if ( is_array( $desc ) ) {
2179 $desc = implode(
"\n", $desc );
2197 if ( $summary->exists() ) {
2198 $msgs = [ $summary, $extendedDescription ];
2200 wfDeprecated(
'API help "description" messages',
'1.30' );
2206 if ( !$description->exists() ) {
2207 $description = $this->
msg(
'api-help-fallback-description', $desc );
2209 $msgs = [ $description ];
2212 Hooks::run(
'APIGetDescriptionMessages', [ $this, &$msgs ] );
2233 self::PARAM_TYPE =>
'string',
2234 self::PARAM_REQUIRED =>
true,
2235 self::PARAM_SENSITIVE =>
true,
2236 self::PARAM_HELP_MSG => [
2237 'api-help-param-token',
2266 Hooks::run(
'APIGetParamDescription', [ &$apiModule, &$desc ] );
2275 foreach (
$params as $param => $settings ) {
2276 if ( !is_array( $settings ) ) {
2280 $d = isset( $desc[$param] ) ? $desc[$param] :
'';
2281 if ( is_array( $d ) ) {
2283 $d = array_map(
function (
$line ) {
2284 if ( preg_match(
'/^\s+(\S+)\s+-\s+(.+)$/',
$line, $m ) ) {
2285 $line =
"\n;{$m[1]}:{$m[2]}";
2289 $d = implode(
' ', $d );
2292 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2295 $msg = $this->
msg(
"apihelp-{$path}-param-{$param}" );
2296 if ( !$msg->exists() ) {
2297 $msg = $this->
msg(
'api-help-fallback-parameter', $d );
2304 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2306 $msgs[$param] = [ $msg ];
2308 if ( isset( $settings[self::PARAM_TYPE] ) &&
2309 $settings[self::PARAM_TYPE] ===
'submodule'
2311 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2317 $map[$submoduleName] = $prefix . $submoduleName;
2322 $deprecatedSubmodules = [];
2323 foreach ( $map
as $v => $m ) {
2324 $arr = &$submodules;
2325 $isDeprecated =
false;
2330 $summary = $submod->getFinalSummary();
2331 $isDeprecated = $submod->isDeprecated();
2332 if ( $isDeprecated ) {
2333 $arr = &$deprecatedSubmodules;
2340 $key = $summary->getKey();
2341 $params = $summary->getParams();
2343 $key =
'api-help-undocumented-module';
2347 $arr[] = $m->setContext( $this->
getContext() );
2349 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2350 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2351 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2353 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2355 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2357 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2358 'ApiBase::PARAM_TYPE is an array' );
2362 $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
2366 foreach ( $settings[self::PARAM_TYPE]
as $value ) {
2367 if ( isset( $valueMsgs[
$value] ) ) {
2368 $msg = $valueMsgs[
$value];
2370 $msg =
"apihelp-{$path}-paramvalue-{$param}-{$value}";
2377 [ $m->getKey(),
'api-help-param-no-description' ],
2379 isset( $deprecatedValues[
$value] )
2381 $msgs[$param][] = $m->setContext( $this->
getContext() );
2384 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2389 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2390 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2392 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2394 foreach ( $settings[self::PARAM_HELP_MSG_APPEND]
as $m ) {
2398 $msgs[$param][] = $m;
2401 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2407 Hooks::run(
'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2425 $flags[] =
'deprecated';
2428 $flags[] =
'internal';
2431 $flags[] =
'readrights';
2434 $flags[] =
'writerights';
2437 $flags[] =
'mustbeposted';
2457 if ( $this->mModuleSource !==
false ) {
2462 $rClass =
new ReflectionClass( $this );
2463 $path = $rClass->getFileName();
2466 $this->mModuleSource =
null;
2472 if ( self::$extensionInfo ===
null ) {
2473 $extDir = $this->
getConfig()->get(
'ExtensionDirectory' );
2474 self::$extensionInfo = [
2475 realpath( __DIR__ ) ?: __DIR__ => [
2477 'name' =>
'MediaWiki',
2478 'license-name' =>
'GPL-2.0-or-later',
2480 realpath(
"$IP/extensions" ) ?:
"$IP/extensions" =>
null,
2481 realpath( $extDir ) ?: $extDir =>
null,
2487 'license-name' =>
null,
2489 foreach ( $this->
getConfig()->
get(
'ExtensionCredits' )
as $group ) {
2490 foreach ( $group
as $ext ) {
2491 if ( !isset(
$ext[
'path'] ) || !isset(
$ext[
'name'] ) ) {
2496 $extpath =
$ext[
'path'];
2497 if ( !is_dir( $extpath ) ) {
2498 $extpath = dirname( $extpath );
2500 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2501 array_intersect_key(
$ext, $keep );
2505 $extpath =
$ext[
'path'];
2506 if ( !is_dir( $extpath ) ) {
2507 $extpath = dirname( $extpath );
2509 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2510 array_intersect_key(
$ext, $keep );
2517 if ( array_key_exists(
$path, self::$extensionInfo ) ) {
2519 $this->mModuleSource = self::$extensionInfo[
$path];
2525 }
while (
$path !== $oldpath );
2528 $this->mModuleSource =
null;
2672 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata =
null ) {
2695 throw new MWException(
'Successful status passed to ApiBase::dieStatus' );
2698 $errors =
$status->getErrorsByType(
'error' );
2701 $errors =
$status->getErrorsByType(
'warning' );
2705 $errors = [ [
'message' =>
'unknownerror-nocode',
'params' => [] ] ];
2709 $msg = $errors[0][
'message'];
2711 $msg =
new Message( $errors[0][
'message'], $errors[0][
'params'] );
2714 $key = $msg->getKey();
2716 array_unshift(
$params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2735 'unknownerror' =>
'apierror-unknownerror',
2736 'unknownerror-nocode' =>
'apierror-unknownerror-nocode',
2737 'ns-specialprotected' =>
'ns-specialprotected',
2738 'protectedinterface' =>
'protectedinterface',
2739 'namespaceprotected' =>
'namespaceprotected',
2740 'customcssprotected' =>
'customcssprotected',
2741 'customjsprotected' =>
'customjsprotected',
2742 'cascadeprotected' =>
'cascadeprotected',
2743 'protectedpagetext' =>
'protectedpagetext',
2744 'protect-cantedit' =>
'protect-cantedit',
2745 'deleteprotected' =>
'deleteprotected',
2746 'badaccess-group0' =>
'badaccess-group0',
2747 'badaccess-groups' =>
'badaccess-groups',
2748 'titleprotected' =>
'titleprotected',
2749 'nocreate-loggedin' =>
'nocreate-loggedin',
2750 'nocreatetext' =>
'nocreatetext',
2751 'movenologintext' =>
'movenologintext',
2752 'movenotallowed' =>
'movenotallowed',
2753 'confirmedittext' =>
'confirmedittext',
2754 'blockedtext' =>
'apierror-blocked',
2755 'autoblockedtext' =>
'apierror-autoblocked',
2756 'systemblockedtext' =>
'apierror-systemblocked',
2757 'actionthrottledtext' =>
'apierror-ratelimited',
2758 'alreadyrolled' =>
'alreadyrolled',
2759 'cantrollback' =>
'cantrollback',
2760 'readonlytext' =>
'readonlytext',
2761 'sessionfailure' =>
'sessionfailure',
2762 'cannotdelete' =>
'cannotdelete',
2763 'notanarticle' =>
'apierror-missingtitle',
2764 'selfmove' =>
'selfmove',
2765 'immobile_namespace' =>
'apierror-immobilenamespace',
2766 'articleexists' =>
'articleexists',
2767 'hookaborted' =>
'hookaborted',
2768 'cantmove-titleprotected' =>
'cantmove-titleprotected',
2769 'imagenocrossnamespace' =>
'imagenocrossnamespace',
2770 'imagetypemismatch' =>
'imagetypemismatch',
2771 'ip_range_invalid' =>
'ip_range_invalid',
2772 'range_block_disabled' =>
'range_block_disabled',
2773 'nosuchusershort' =>
'nosuchusershort',
2774 'badipaddress' =>
'badipaddress',
2775 'ipb_expiry_invalid' =>
'ipb_expiry_invalid',
2776 'ipb_already_blocked' =>
'ipb_already_blocked',
2777 'ipb_blocked_as_range' =>
'ipb_blocked_as_range',
2778 'ipb_cant_unblock' =>
'ipb_cant_unblock',
2779 'mailnologin' =>
'apierror-cantsend',
2780 'ipbblocked' =>
'ipbblocked',
2781 'ipbnounblockself' =>
'ipbnounblockself',
2782 'usermaildisabled' =>
'usermaildisabled',
2783 'blockedemailuser' =>
'apierror-blockedfrommail',
2784 'notarget' =>
'apierror-notarget',
2785 'noemail' =>
'noemail',
2786 'rcpatroldisabled' =>
'rcpatroldisabled',
2787 'markedaspatrollederror-noautopatrol' =>
'markedaspatrollederror-noautopatrol',
2788 'delete-toobig' =>
'delete-toobig',
2789 'movenotallowedfile' =>
'movenotallowedfile',
2790 'userrights-no-interwiki' =>
'userrights-no-interwiki',
2791 'userrights-nodatabase' =>
'userrights-nodatabase',
2792 'nouserspecified' =>
'nouserspecified',
2793 'noname' =>
'noname',
2794 'summaryrequired' =>
'apierror-summaryrequired',
2795 'import-rootpage-invalid' =>
'import-rootpage-invalid',
2796 'import-rootpage-nosubpage' =>
'import-rootpage-nosubpage',
2797 'readrequired' =>
'apierror-readapidenied',
2798 'writedisabled' =>
'apierror-noapiwrite',
2799 'writerequired' =>
'apierror-writeapidenied',
2800 'missingparam' =>
'apierror-missingparam',
2801 'invalidtitle' =>
'apierror-invalidtitle',
2802 'nosuchpageid' =>
'apierror-nosuchpageid',
2803 'nosuchrevid' =>
'apierror-nosuchrevid',
2804 'nosuchuser' =>
'nosuchusershort',
2805 'invaliduser' =>
'apierror-invaliduser',
2806 'invalidexpiry' =>
'apierror-invalidexpiry',
2807 'pastexpiry' =>
'apierror-pastexpiry',
2808 'create-titleexists' =>
'apierror-create-titleexists',
2809 'missingtitle-createonly' =>
'apierror-missingtitle-createonly',
2810 'cantblock' =>
'apierror-cantblock',
2811 'canthide' =>
'apierror-canthide',
2812 'cantblock-email' =>
'apierror-cantblock-email',
2813 'cantunblock' =>
'apierror-permissiondenied-generic',
2814 'cannotundelete' =>
'cannotundelete',
2815 'permdenied-undelete' =>
'apierror-permissiondenied-generic',
2816 'createonly-exists' =>
'apierror-articleexists',
2817 'nocreate-missing' =>
'apierror-missingtitle',
2818 'cantchangecontentmodel' =>
'apierror-cantchangecontentmodel',
2819 'nosuchrcid' =>
'apierror-nosuchrcid',
2820 'nosuchlogid' =>
'apierror-nosuchlogid',
2821 'protect-invalidaction' =>
'apierror-protect-invalidaction',
2822 'protect-invalidlevel' =>
'apierror-protect-invalidlevel',
2823 'toofewexpiries' =>
'apierror-toofewexpiries',
2824 'cantimport' =>
'apierror-cantimport',
2825 'cantimport-upload' =>
'apierror-cantimport-upload',
2826 'importnofile' =>
'importnofile',
2827 'importuploaderrorsize' =>
'importuploaderrorsize',
2828 'importuploaderrorpartial' =>
'importuploaderrorpartial',
2829 'importuploaderrortemp' =>
'importuploaderrortemp',
2830 'importcantopen' =>
'importcantopen',
2831 'import-noarticle' =>
'import-noarticle',
2832 'importbadinterwiki' =>
'importbadinterwiki',
2833 'import-unknownerror' =>
'apierror-import-unknownerror',
2834 'cantoverwrite-sharedfile' =>
'apierror-cantoverwrite-sharedfile',
2835 'sharedfile-exists' =>
'apierror-fileexists-sharedrepo-perm',
2836 'mustbeposted' =>
'apierror-mustbeposted',
2837 'show' =>
'apierror-show',
2838 'specialpage-cantexecute' =>
'apierror-specialpage-cantexecute',
2839 'invalidoldimage' =>
'apierror-invalidoldimage',
2840 'nodeleteablefile' =>
'apierror-nodeleteablefile',
2841 'fileexists-forbidden' =>
'fileexists-forbidden',
2842 'fileexists-shared-forbidden' =>
'fileexists-shared-forbidden',
2843 'filerevert-badversion' =>
'filerevert-badversion',
2844 'noimageredirect-anon' =>
'apierror-noimageredirect-anon',
2845 'noimageredirect-logged' =>
'apierror-noimageredirect',
2846 'spamdetected' =>
'apierror-spamdetected',
2847 'contenttoobig' =>
'apierror-contenttoobig',
2848 'noedit-anon' =>
'apierror-noedit-anon',
2849 'noedit' =>
'apierror-noedit',
2850 'wasdeleted' =>
'apierror-pagedeleted',
2851 'blankpage' =>
'apierror-emptypage',
2852 'editconflict' =>
'editconflict',
2853 'hashcheckfailed' =>
'apierror-badmd5',
2854 'missingtext' =>
'apierror-notext',
2855 'emptynewsection' =>
'apierror-emptynewsection',
2856 'revwrongpage' =>
'apierror-revwrongpage',
2857 'undo-failure' =>
'undo-failure',
2858 'content-not-allowed-here' =>
'content-not-allowed-here',
2859 'edit-hook-aborted' =>
'edit-hook-aborted',
2860 'edit-gone-missing' =>
'edit-gone-missing',
2861 'edit-conflict' =>
'edit-conflict',
2862 'edit-already-exists' =>
'edit-already-exists',
2863 'invalid-file-key' =>
'apierror-invalid-file-key',
2864 'nouploadmodule' =>
'apierror-nouploadmodule',
2865 'uploaddisabled' =>
'uploaddisabled',
2866 'copyuploaddisabled' =>
'copyuploaddisabled',
2867 'copyuploadbaddomain' =>
'apierror-copyuploadbaddomain',
2868 'copyuploadbadurl' =>
'apierror-copyuploadbadurl',
2869 'filename-tooshort' =>
'filename-tooshort',
2870 'filename-toolong' =>
'filename-toolong',
2871 'illegal-filename' =>
'illegal-filename',
2872 'filetype-missing' =>
'filetype-missing',
2873 'mustbeloggedin' =>
'apierror-mustbeloggedin',
2884 $key = $msg->getKey();
2885 if ( isset( self::$messageMap[$key] ) ) {
2887 array_unshift(
$params, self::$messageMap[$key] );
2908 if ( is_array( $error ) ) {
2909 $first = reset( $error );
2910 if ( is_array( $first ) ) {
2918 'code' => $msg->getApiCode(),
2920 $msg->inLanguage(
'en' )->useDatabase(
false )->text()
2922 'data' => $msg->getApiData()
2960 "apihelp-{$this->getModulePath()}-description",
2961 "apihelp-{$this->getModulePath()}-summary",
dieUsageMsgOrDebug( $error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
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
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.
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Exception used to abort API execution with an error.
getContext()
Get the base IContextSource object.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
getParent()
Get the parent of this module.
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
getType()
Get the type of target for this particular block.
getSummaryMessage()
Return the summary message.
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getFinalParams( $flags=0)
Get final list of parameters, after hooks have had a chance to tweak it as needed.
const PARAM_REQUIRED
(boolean) Is the parameter required?
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<
the array() calling protocol came about after MediaWiki 1.4rc1.
parseMsg( $error)
Return the error message related to a certain array.
parameterNotEmpty( $x)
Callback function used in requireOnlyOneParameter to check whether required parameters are set.
array null bool $mModuleSource
validateToken( $token, array $params)
Validate the supplied token.
This manages continuation state.
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
getExamplesMessages()
Returns usage examples for this module.
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,...
validateTimestamp( $value, $encParamName)
Validate and normalize parameters of type 'timestamp'.
dieUsageMsg( $error)
Output the error message related to a certain array.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static array $extensionInfo
Maps extension paths to info arrays.
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
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 & $ret
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
getResult()
Get the result object.
getDescriptionMessage()
Return the description message.
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
mustBePosted()
Indicates whether this module must be called with a POST request.
logFeatureUsage( $feature)
Write logging information for API features to a debug log, for usage analysis.
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
getExtendedDescription()
Return the extended help text message.
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
static escapeWikiText( $v)
A subset of wfEscapeWikiText for BC texts.
getDB()
Gets a default replica DB connection object.
static makeMessage( $msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'])
Add warnings and/or errors from a Status.
dynamicParameterDocumentation()
Indicate if the module supports dynamically-determined parameters that cannot be included in self::ge...
static isValidUserName( $name)
Is the input a valid username?
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Interface for messages with machine-readable data for use by the API.
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
getWebUITokenSalt(array $params)
Fetch the salt used in the Web UI corresponding to this module.
static listParam(array $list, $type='text')
isMain()
Returns true if this module is the main module ($this === $this->mMainModule), false otherwise.
isReadMode()
Indicates whether this module requires read rights.
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
This abstract class implements many basic API functions, and is the base of all API classes.
Extension of RawMessage implementing IApiMessage.
getModuleFromPath( $path)
Get a module from its module path.
getFinalParamDescription()
Get final parameter descriptions, after hooks have had a chance to tweak it as needed.
Extension of Message implementing IApiMessage.
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note 'password'-type fields are always sensitive regardless of ...
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
getParamDescription()
Returns an array of parameter descriptions.
getFinalSummary()
Get final module summary.
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
explodeMultiValue( $value, $limit)
Split a multi-valued parameter string, like explode()
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
warnOrDie(ApiMessage $msg, $enforceLimits=false)
Adds a warning to the output, else dies.
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
getFinalDescription()
Get final module description, after hooks have had a chance to tweak it as needed.
wfTransactionalTimeLimit()
Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
getModulePath()
Get the path to this module.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
const LIMIT_BIG1
Fast query, standard limit.
getDescription()
Returns the description string for this module.
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
static getTokenTypeSalts()
Get the salts for known token types.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
parseMsgInternal( $error)
namespace and then decline to actually register it file or subcat img or subcat $title
handleParamNormalization( $paramName, $value, $rawValue)
Handle when a parameter was Unicode-normalized.
when a variable name is used in a it is silently declared as a new masking the global
isDeprecated()
Indicates whether this module is deprecated.
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.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
setContext(IContextSource $context)
getHelpUrls()
Return links to more detailed help pages about the module.
validateUser( $value, $encParamName)
Validate and normalize parameters of type 'user'.
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
needsToken()
Returns the token type this module requires in order to execute.
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
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
setWatch( $watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
getContinuationManager()
Get the continuation manager.
addError( $msg, $code=null, $data=null)
Add an error for this module without aborting.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
getWatchlistUser( $params)
Gets the user for whom to get the watchlist.
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
static newGood( $value=null)
Factory function for good results.
const LIMIT_SML2
Slow query, apihighlimits limit.
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
dieUsage( $description, $errorCode, $httpRespCode=0, $extradata=null)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
dieReadOnly()
Helper function for readonly errors.
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
checkTitleUserPermissions(Title $title, $actions, $user=null)
Helper function for permission-denied errors.
static newFromID( $id, $from='fromdb')
Constructor from a page id.
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
getConditionalRequestData( $condition)
Returns data for HTTP conditional request mechanisms.
isWriteMode()
Indicates whether this module requires write mode.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false.
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
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. '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
static truncateArray(&$arr, $limit)
Truncate an array to a certain length.
Interface for objects which can provide a MediaWiki context on request.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
const PARAM_VALUE_LINKS
(string[]) When PARAM_TYPE is an array, this may be an array mapping those values to page titles whic...
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
Represents a title within MediaWiki.
Allows to change the fields on the form that will be generated $name
const LIMIT_BIG2
Fast query, apihighlimits limit.
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
getModuleSourceInfo()
Returns information about the source of this module, if known.
validateLimit( $paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
Validate the value against the minimum and user/bot maximum limits.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
getParameter( $paramName, $parseLimit=true)
Get a value for the given 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
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
getModuleName()
Get the name of the module being executed by this instance.
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
The Message class provides methods which fulfil two basic services:
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues, $allSpecifier=null, $limit1=null, $limit2=null)
Return an array of values that were given in a 'a|b|c' notation, after it optionally validates them a...
getMain()
Get the main module.
getParameterFromSettings( $paramName, $paramSettings, $parseLimit)
Using the settings determine the value for the given parameter.
const PARAM_MAX_CHARS
(integer) Maximum length of a string in characters (unicode codepoints).
getTitleFromTitleOrPageId( $params)
Get a Title object from a title or pageid param, if possible.
getExamples()
Returns usage examples for this module.
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
Variant of the Message class.
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
const PARAM_SUBMODULE_PARAM_PREFIX
(string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix added by ApiQueryGeneratorBa...
const PARAM_MAX_BYTES
(integer) Maximum length of a string in bytes (in UTF-8 encoding).
Message subclass that prepends wikitext for API help.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
static isExternal( $username)
Tells whether the username is external or not.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
getErrorFormatter()
Get the error formatter.
requirePostedParameters( $params, $prefix='prefix')
Die if any of the specified parameters were found in the query part of the URL rather than the post b...
static getBlockInfo(Block $block)
Get basic info about a given block.
static isIPAddress( $ip)
Determine if a string is as valid IP address or network (CIDR prefix).
getErrorFromStatus( $status, &$extraData=null)
Get error (as code, string) from a Status object.
const LIMIT_SML1
Slow query, standard limit.
getHelpFlags()
Generates the list of flags for the help screen and for action=paraminfo.